Showing posts with label StockReader. Show all posts
Showing posts with label StockReader. Show all posts

Saturday, 24 October 2020

StockPredictor: Using Neural Networks to Try to Predict Stock Values

With the verified training data, I've been trying to predict stock performances, given some key numbers. 

I'm using the scikit toolbox for Python and the initial findings is that the neural network hasn't been able to predict the stock performances. The correlation between the predicted values and the target values is close to zero. 

Findings
I've run several iterations with different parameters, like alpha (learning rate), random state, batch size and whether to use historic data or not. They all point to the same conclusion - there is no easy-to-catch pattern that the neural network can find. 

These finding support the efficient market theory - the past information is already priced into the current stock prices. 

The distribution of the result data is hard to model using a neural network. Most of the data is small, but there are some few outliers that generates large losses for the training function.

The result distribution. 95% of the results are in the range -0.0143 up to 0.0166,
but some outliers are much bigger.


For reference, I trained a neural network for a dataset that is available in sklearn (load_diabetes). That network found a quite strong correlation between predictions and the results (75%). This means that I know how to set up and use data sets for machine learning. 

Summary of the project and the future
I have no plans to continue the project at this moment. The web scraper will keep recording stock records and I'll update the documentation.

Lessons learned:
  • Verify the data early in the project!
  • Use standard schemes for saving the data. Preferably CSV format, and/or a format that can easibly be imported into a database.
  • Add checks for inconsistent data that notifies the operator.
Unplanned future work:
  • Map the results into an machine-learning friendlier distribution. Maybe logarithmic scale?
  • Iterate over different prediction windows. Currently only 7 days is used.
  • Use other algorithms, like K-nearest neighbor.
For the end of the year, I'll explore Internet of Things (IOT) with Arduino and Raspberry PI. The train project will continue in 2021.

Saturday, 10 October 2020

StockPredictor: Exploring the MLPRegressor

I want to predict stock prices using existing data. Optionally, I'll convert the problem into a classification problem ("to buy or not to buy). With the training data in place, I'll explore the Python package scikit-learn.

This article discusses some machine learning algorithms that can be used to predict a numerical value. Neural networks and K-nearest neighbors seems promising. I suspect non-linear relations between features and results, so I don't expect linear regression to work. However, I'll give it a try later.

Multilayer Perceptron Regressor

I based my program on the examples above, with my data from StockReader. 
After training the neural network on ~210 000 examples, I test it on ~50 000 examples. I compare how the neural network is doing with an dart throwing monkey (a simple prediction that the stock performances will be the average daily price increase of the stocks).

The initial output from training the neural network together with verifying it on the test data shows no improvement compared to the monkey. The Median Average Error for the Neural network was 0.095, compared to the benchmark of 0.064. 

The next step will be to investigate other parameters for the neural network, along with other algoritms. Since I will compare different models, I will need to introduce cross validation data. This is important, since I need to make sure to verify the model selection itself.


Useful link:

Saturday, 12 September 2020

StockPredictor: Selecting Algorithm and Some Design Considerations

This is the third part of the stock project, where I will use the validated data to train a machine learning system to predict the performance of a stock based on the data that was available at the date of the stock record.

The first step is to make some design considerations for the algorithm. The earliest program will only look at the current stock record for features (X) and the results (y) will be the daily change of the stock.

If I select the prediction window to one week, one example of features and results would be:


The results from a query in the database will look like this:

The X data can consist of values of P, P/E, P/C, Yield, PMI, RSI and the time to/since the last dividend. The y data for the stock record of 2018-10-31 will be the change (%) divided by the days: 
The daily increase of ABB's stock price was 0,054% during one week in November, 2018.
It would have been more mathematically correct to take the seventh
root of the quota, but this time I'll prefer simplicity.

For training data to be useful, there must be a price record in the future that can be used ad y.

I'm saving the data to a huge panda dataframe (the process of populating it from the database (with some necessary processing) takes ~35 minutes. To avoid repeating this cumbersome process every time, I save the dataframe to a csv file, that can be used directly to train the machine learning algorithm. Loading that file takes less than a second.

The Data Set
I suspect that some of the data are highly correlated to each other. For example, Price, P/E and P/C are correlated in the short-term, since earnings and capital per share seldom changes. 

Sometimes, the data contains zeros or null values. 

Regression or Neural Networks

Both regression and neural networks has some pros for this dataset. 

Linear regression

A linear regression would be intuitive for predicting the change in stock price. But there are some zeros in the underlying data that I fear will skew the results. It also seems to be tricky to handle XOR relationships between features. 

Multi-Layer Neural Networks can model complex relationships such as XOR relations and zeroed records. I'll start with this one initially. The

SciKit-Learn

Sklearn has a neural-network-ish regressor that I will investigate.


Saturday, 25 July 2020

StockReader: Handling Broken Scaping

I've seen that the web scraper StockReader script sometimes halts due to various reasons. For example. it can be timeouts from the server.
The connection error is seen occasionally.

I'll handle this by running the script again and again until I get the data I need, while skipping the records that I've already collected.

The first step is to make StockReader check for existing files:

The second step is to acquire the stock names along with the stock ID's for the source web page. Using the names, I can tell whether the particular stock has a record or not. I did that using regular expressions in the script.



The third step is to open the file in read mode (if it exists), and store the contents of that file. After that, I'll close the file.

The fourth step is to open the file in append mode and iterate over all stock names, and fetch the stock data for the missing stock records.

The program works best if I run it some five times. Then it is likely that I'll catch most, if not all stock records for that day.

Issue:
For long stock names, the name is truncated in the web page that lists all stocks:
From the list of active stocks: A3 Allmänna IT- och..
From the in stock info web page: A3 Allmänna IT- och Telekomaktiebolaget
I resolved that issue by adding a second list of truncated stock names. If a stock was found in the truncated stock name list, I iterated over all stock names that already has a stock record. If one of those matched the stock name, the program didn't query that stock information.

Saturday, 11 July 2020

StockAnalyzer: Chasing errors

The work on Stock Analyzer will focus on two tracks in parallel:

  1. Fixing existing data to fit into the database (Scope of this blog post)
  2. Visual the data that is in the database
I see errors when the program is trying to parse values to the database. For example:


2017-06-05 - 2017-08-14: Unable to parse '2017-08-15'. 
2017-08-19 - 2017-11-01: Unable to parse '2017-11-07'
2017-11-06 and later: Unable to parse '2018-02-22'

The issue is that the program tries to parse a date into an integer since the date is on the wrong position in the file.

The first step is to check which stocks it could be that has the faulty data. I can easily do that using grep in my WSL2 environment on my Windows 10  computer.

The faulty data for June contains the string "2017-08-15".
This string is found in the following stocks:
Eniro, Concordia Maritime, Clavister Holding, MindMancer and Tethys Oil 
When importing the different stock records to a spread sheet to see which of the stocks are faulty.

Tethys Oil seems to have some missing data.
I did some maths on the remaining data to check if it is possible to recover the missing bits, but it wasn't. I'll simply remove the records for Tethys Oil for the missing period of time. A new grep instance gives:

This means that the stock records for the company Tethys Oil are corrupted between May 9th, 2017 and November  9th, 2017. Now, I want to remove those lines for the files ranging from 20170509.csv up to 20171109.csv.

For a given file, it is easy to remove lines containing "Tethys Oil":
sed '/Tethys Oil/d' -i file.txt
To identify the files in the desired age span, I tried to find a way to do lexicographic comparisons of the file names in the bash shell. It turned out not to be trivial, so created a Python script instead. 

The output are commands that removes all lines containing Tethys oil from the files in the interval. After pasting them to bash, the erroneous lines has been removed from the files.




Saturday, 13 June 2020

StockAnalyzer: Resuming Transmission

After focusing on global pandemics and relocations for the last months, I am able to resume focusing on my pet projects, but at a slower pace than before. I expect to post at least once per month.

I'll continue coding for the machine learning project StockAnalyzer.

Earlier this year, I explored NodeJS. I'll switch to Python instead, since it is more flexible and since I'm more familiar with it.

StockAnalyzer
I'll document the project in a separate page on the blog. The source code is available on my GitHub page.

StockAnalyzer will both present a number of graphs of how some key numbers are evolving over time.

StockAnalyzer will also perform an automated scan of all key numbers for all records over time in order to detect flawed data, where the data formats are OK, but the numeric values appear to be invalid. This will be done later.

Here, some key numbers are shown over time.
The graphs will help me find outliers and understand the data.
The first step is to present the data graphically - the vast amount of data will make it impossible to just look at the numbers.

Several of the curves appear to have identical shapes. The curves that relates the price to the earnings and capital will be similar to the price curve. This because the earnings and capital per share doesn't change very often. The yield is the dividend divided by the price and that is inversely correlated to the stock price.

In the next blog posts, I'll keep exploring the data.

In the following blog posts, I'll explore the data

Saturday, 22 February 2020

StockAnalyser NodeJS: Connecting to an Existing MSSQL database (1)

Important:
This blog shows my learning curve in different programming languages. Take my code with a large grain of salt.

The NodeJS script shall connect to an existing MS SQL database. This blog post summarizes some of the initial investigations to make this happen.

The connection string is:

The different components of the connection string are:
  • Integrated Security means that I am not using a username/password.
  • AttachDbFileName points to the file on the file system
  • Data Source refers to the MS SQL Server instance.
First step is to find and control the SQL Server software. Sometimes, it comes with the installation of Microsoft Visual studio. The software SQL Server Data Tools isn't included in my MSVC installation  (2017) and I need to add it using the MSVC installer.

The settings for my local database


Normally, the SQL Server Data Tools provides the server to other applications. For some reason I don't have it so I will install MS SQL Server on top of MSVC in the next blog post.

Saturday, 15 June 2019

StockAnalyzer: Selecting the Input Files

Now, it is time to interpret the input files. They are named in the form "YYYYMMDD.csv" and contain a header row that describes the contents.

I need to consider some possible issues for the input data:
  • The file headers has slightly different formats since I have added some information in the later versions. 
  • The early versions of StockReader had hard coded references to the stocks. Thus, some stock records has sometimes slightly different names of the stocks. Sometimes, the companies changed names too. I need to add checks for the stock names, and possibly add a second table that maps different names to the same stocks.
  • Sometimes, the data acquisition was interrupted.

I'll start by selecting which files to analyze, based on the file names and the time interval that the user has specified in the dateTimePickers.

In order to do that, I use a built in function for removing the file path and the file extension. The remaining string contains the year, month and date:
Now, I process only one file.
Now, I want to check whether the corresponding date is within the time interval. For that purpose, I need to convert the string 20101110 to a datetime format. This is done in three steps:
Step 1: Check the file format - I'm only interested in comma separate value files.
Step 2: Check the date - I'm only interested in files that are corresponding to plausible dates.
Step 3: Convert the date to dateTime format and check whether the date is between the start and end date that the user has specified.
If all these checks are OK, the program will analyze the file. I'll do that in the next blog post.

Special Characters - ÅÄÖ
Since I am collecting data from Swedish stocks, I will handle strings with Swedish characters. I solved that by adding a streamReader object that is configured for the Windows 1252 encoding that contains Swedish characters.

As a side note, I added an UNIQUE constraint to the database. There can be only one record for one company at a particular date.

Saturday, 8 June 2019

StockAnalyzer: Adding Code

Now, it is time to add some code to the program.

Database
The database is controlled from dbParser.
I added some code for printing the contents of the database to the console and also code for clearing all data from the database.
Code for printing contents of database to console.
Code for deleting all records of the database.
The first step is to delete all records from the StockTable.
The second step is to set the identity counter to zero.
Scanning for Files
I have saved my input data in a local folder on my computer. Thus, it is convenient for me to have that folder as the default folder. However, I want to avoid assuming that that folder exists - someone might fork my repo and install it on another system.

To handle this, the program will check whether my folder exists. If it doesn't, it will use the user's document folder instead.
I'll clean up this form soon.
When the user presses the "Scan to Database" button, the program will scan for the files in the class scanFolder. First, I need a list of all files in the current folder. Once I have that file list, I will iterate over it and scan only the files that are in the time interval.
In the next blog post, I'll make the program select which files to analyze and also start to add records to the database.

Saturday, 1 June 2019

StockAnalyzer: Creating a Structure of the Program

I've been able to populate my database with some dummy data and to read it from the database. That's an important step and now, I need to define the overall structure of the program.

Use Cases identifies some scenarios where an user is using the system:

  • User wants to delete all stock records from the database
  • User wants to scan all available files and add the data to the database
  • User wants to scan all files within a specified time range
  • User wants to update the database with the latest results from StockReader

The program will have three different modules:

  • User Interface - Collects the parameters and call methods/functions
  • FileScanner - Select which csv files to scan and determine whether the data in a row contains enough information so that it can be added to the database.
  • DBParser - Build SQL queries and launch them. Database error handling.
Now, I have a rough idea what the program should look like. I have added a couple of user interface widgets to my app. The code is stubbed right now:

I will clean up this form later.
In the "Time Interval to Scan" group box, the user will be able to limit the number of files that shall be loaded into the database.

In the "Directory to Scan" group box, the user will be able to select where the input files are. The text of the button shows the current folder.

The user will be able to clear the database and scan all files that matches the dates in the folder. The algorithm will look like this:

  • List all csv files in the current folder. 
  • For all files that are matching the time interval:
    • Check the headers in order to know how to interpret the data.
    • For all rows in the file: 
      • If the needed data is there for that stock, add the information to the database


I have also created two classes: FileScanner and DBParser. Those are instantiated when the program starts.

In the next blog post, I'll fill the classes and widgets with code.

Saturday, 25 May 2019

StockAnalyzer: Connecting to the Database and Designing It

As I have mentioned before, I will process the data in three steps:
  • A C#-app for Windows that will populate the database (ongoing)
  • A web app that will analyse the database and look for inconsistencies
  • A Python script (or possibly Matlab script) that will perform machine learning on the data set.
In the last blog post, I created the database that I will work with. Now. I'll start populating it.

The first step is to connect to the database. I'll use an example that I found:

The language setting is Swedish.
For non-Swedish speakers, the error message
says that the key attachdbfilename is invalid.
The key attachdbfilename is invalid. The DataDirectory needs to be changed to an actual library. I'll start by fixing the connectionString and using a standard SQL query:

I can now connect to the database and launch a simple query!

The First INSERT and SELECT to the Database
I extended the query to the database. First, I populated the database with some dummy data. After that, I selected all rows in the database and presented them as a message box:
It shouldn't be possible to add more than one record of a particular stock for a particular date. I will add a UNIQUE constraint. I will fix that soon.

Next, I need to plan how to design the application, with different classes and layouts for the user interface.

Side Note:
I added  the project to my GitHub account, using instructions on GitHub.



The updated code is available at https://github.com/cutetrains/StockToDatabase

Saturday, 11 May 2019

StockAnalyzer: Building the First C# Windows App and a Database

It's been a while since I used Visual Studio, so I had to install a lot of updated.
Updating the environment takes time but is crucial for development.
I have spent too much time debugging issues that were solved with an update.
Since my version of Qt is dependent on Visual Studio, I had to rebuild TrafficControl and verify that it still works. Fortunately, it worked like a charm.

To learn about Visual Studio, I opened a simple example app that simply contains a text field. a button and a hyperlink:
The code is very intuitive: The main thread shows the form and the Form1 designer sets up the user interface element. In Form1.cs. there are some listeners to events such as a mouse click or a click to a hyperlink.

Adding a Database and a Data Source
First, I need to create a database. It is possible to use the Azure platform to do that online, but I'll create a local Microsoft SQL database instead. I followed the steps from the documentation.



Step 1: Select a local Database

Step 2: The database model shall be a dataset.

Step 3: Name the database object to StockRecord
Now, there is an empty database that I can use in my project.

The next step is to design the database itself and connect to it.

In the next blog post, I'll connect to the database from the program and populate it with some dummy data.

Saturday, 27 April 2019

StockAnalyzer: Applying Machine Learning on Stock Information

After using some neural networks to analyse a small set of data for a friends pet project, I will focus on my own data.

I have a web scraper, StockReader, that collects some information about public stocks that are listed in Sweden. That has been in use for eight years and I have more than 1500 snapshots of a couple of hundreds of stocks.

It was originally written in C++ (the code was terrible, but it was essential for me to learn to build a more complex program) and I later ported that to a twenty-four line python script that is scheduled to run three times a week.

Now, I want to use the data to learn more about machine learning and analysis of time series. I also want to get experience from C#/Visual Studio and Angular JS.

I don't expect to find a magic algorithm  that helps me in stock-picking. The purpose of this project is to learn coding, machine learning, C#, Visual Studio and Angular JS.

The Different Technology Areas for the Project
The data is saved in csv files (comma separated values). The data includes stock price, earnings per share, dividends, profit margin, RSI and date for the quarterly reports.

I will create a Windows program based on C# in Visual Studio to populate a mySQL database with the stock data. It would probably be easier using Python but I want to explore new tools and programming languages.

After the data is in the database, I will build a web app using Angular JS, That program will check the data and search for possible stock splits and inconsistent data.

Once the data is corrected, I will analyse it. Since Python has very powerful AI packages, I will use Python to extend the web app above.

I will start by describing the data and some relevant topics for stock markets.

Saturday, 5 January 2019

2018 in Retrospect

The last year, I had quite some progress on my projects. A normal week, I spend two hours on coding, two hours on learning and two hours on blogging.

TrafficControl (C++/Qt):
  • I added locks for tracks in order to avoid trains to travel in opposite directions on the same track. I also added red and green circles to visualize the lock status of the tracks.
  • Further, I added an icon to the executable 
  • The Python script that parses the KML map to a network in TrafficControl was modified: Now, it ignores hidden tracks and the tracks/stations doesn't need to be in any specific folder.
  • Improving the model for acceleration of trains
  • User Interface Improvements: I added system load and simulated time to the user interface.
    • Adding buttons for the controls 
    • Adding menus and toolbars
    • Adding a Help menu that points to some Help sections on this blog.
  • NetworkDesigner is a new tool that helps the user design a network
StockReader (Was: C, now: Python):
  • I re-implemented the web scraper in Python. Now, it has only 24 lines of code, including a check of the robots.txt policy.
TravelTimeCalculator (Android/Java):
HouseReader (Python)
I've also started another blog that will discuss society-related issues.

In 2019, I'll make TravelTimeCalculator demo-able. After that, I'll continue with TrafficControl, adding passenger handling.

Saturday, 3 February 2018

StockReader: What Data I Want and the Final Script

I want to acquire the following data for stocks on Swedish markets:
  • Name, DI
  • Price, DI
  • Earning per share, DI
  • P/E, DI
  • Book value per share, DI
  • Price per adjusted equity, DI 
  • Yield, DI
  • Yield per share, DI
  • Profit margin, DI
  • RSI, DI
  • Date of next report, DI
  • Date of next yield, DI
(In Swedish: Namn;Kurs;Vinst per aktie;P E;Kapital per aktie;P JEK;Direktavkastning;Utdelning per aktie;Vinstmarginal;RSI;Nasta rapport;Utdelningsdatum;TA)

I'll start with fetching 

If that allows, I'll fetch the entire stock list:

For each stock in that list, I'll use the hyperlink to get the stocks unique id number:
https://trader.di.se/index.php/quote/kurs/730

This is done using re.findall("/index.php/quote/kurs/[0-9]{1,10}", stockListResponse)

I'll use that number to fetch the key numbers of that stock:
https://trader.di.se/index.php/quote/nyckeltal/730

The code is shown below:
The new script is 24 lines of code, compared with the original C program with 300+ lines of code.
The data is encapsulated in table tags. The regex command generates a list of all matches, and I cherry-pick the data I want.

The next step was to add StockReader to scheduled tasks in windows.

Saturday, 27 January 2018

StockReader: Respecting Robots.txt and Initial Scraping

Robots has some rules to follow, or break if they are nasty. Those rules are defined in the robots.txt file on the particular web site.

I'll start by creating a stub python script that will access a web page and print that to a console.

First, I need to install a module: requests. To do that, I need to install a Python package manager, PIP:
In https://bootstrap.pypa.io/, download and run getpip.py.

To install a package,
Navigate to the folder where pip.exe is located.
Run pip install requests

Now, requests can be imported and used

In my case, I'll use DI.se. The corresponding robots.txt file will be analyzed. If that page allows, I'll download the stock list and analyse the stocks in the list

Saturday, 13 January 2018

StockReader: Re-implement in Python

One of my first larger software projects was StockReader. That is a C++ web scraper for stocks.

The final result of StockReader
Now, I need to re-implement the program for four reasons: 
  1. My firewall doesn't like blocks executables that sends several get requests
  2. The source code is horrible and needs to be refactored completely in order to be more maintainable
  3. I should be able to use regular expressions.
  4. The program should be more automatic, selecting stocks automatically
I will not publish the program on Github, but I'll post some issues that I will discuss.

The first step will be to implement a script that gets a web page from an URL. From that html code, I'll extract the URLs for the key number sections for the stocks.

When creating code, it is crucial to understand what one is writing. It is important to resist the temptation to copy some code from stackoverflow and instead focus on really understand what one is writing.

In the Python documentation, there is a section about regular expressions.

Tuesday, 7 October 2014

Qt: Static and Dynamic linking for deployment of applications

Almost all software is developed using some pre-existing software, so that the developer doesn't need to invent the wheel again.

These pieces of software are imported in different manners to the final program. This may be:

  • Software that polls the keyboard and sends a corresponding character to the buffer/stdin,
  • Software that keeps track of the mouse pointer
  • Software that manages database connections
  • Software that sets up the user interface, such as the "Open file" window.
  • Software that handles networks
  • Software that handles databases
  • ...

In Windows, that code is compiled to DLL files (Dynamically Linked Library). Other operating systems such as Linux has similar libraries.

Put simply, In order to deploy  software and make it useful for others, there are two options: static and dynamic linking.

Static linking will bring the libraries into the exe file (~10-20 Mb). If many program files on a system will need the same libraries, there will be a lot of redundant code in the different executables.

Dynamic linking will make the program refer to DLL files for the needed external code. This results in a smaller exe files (~100kb), but that will be dependent on external DLL files. I'm sure that my readers has got their fair share of dll errors.

Text in Swedish, but the message is clear: 
spend hours chasing DLLs or consider another program.

The program Dependency Walker can be very helpful when finding what DLL files (and what versions) are needed for a program. Still, a lot of work and frustration lies ahead.

In the next blog post I'll describe what problems I saw when I tried building my program statically. Actually, I needed to recompile the entire Qt installation from its sources, and that's where I got the problems.

Until then, I can recommend VoidRealms/Bryan Cairns Youtube videos about DLL:s







Wednesday, 1 October 2014

|| AND &&: Why it is a good idea to quibble

I had to recover my Windows 8 installation one week ago, and in that process, I re-installed Qt. This time, I also included the Microsoft Visual Studio Express compiling option for Qt.

After doing that, I tried to rebuild my programs TrafficControl and StockReader. I got houndreds of strange compiler errors that I didn't expect since the programs compiled without warnings before.

The issue was that I used the keywords "and" and "or" in several if clauses. Those keywords are allowed by gcc/g++ (GNU Compiler Collection), but not by Microsoft Visual Studio 2013: http://msdn.microsoft.com/en-us/library/2e6a4at9.aspx

My personal preference would have been to use AND and OR for logical keywords - that would have kept my source code as similar to human language as possible. But I also want my source code to be portable between different operating systems and compilers. So from now on, I'll continue with using the ||, && and != operators instead of OR, AND and NOT.

I still have some problems making static builds for  my programs. More about that in future blog posts.

Saturday, 12 April 2014

StockReader: Bringing Hundreds of Stocks to one Spreadsheet

My other project is StockReader. That program scans key numbers from some three hundred Swedish stocks and makes that data accessible from a spread sheet program.

That program analyses stock data from some web pages, extracts the interesting information and arranges it in a comma-separated-value file that is linked to a spreadsheet, where I can rank the stocks after some criteria.

This way, I can assign different points/grades to stocks, depending on how they perform with regard to, for example the price/earnings value. Companies with big losses will get a "bad" grade, and companies with good earnings will get a "good" grade.

The final result of the program: Stock data collected to a Spreadsheet
After summing the grades for each key number, I can easily identify the companies with high dividends, good earnings, good net asset values, ... After having my computer doing all the dull work, I can continue with cherry-picking the best stocks.

Nowadays, I am advocating the efficient market hypothesis, meaning that all public information about assets will be reflected by the price. So stock-picking will be more of a hobby for me with no intentions of beating the market.

I've learnt a lot when creating the program and I want to share it with my readers in future posts.