Monday, April 25, 2016

Prediction - 3

Hello, welcome back to my blog about automated trading. Last week I have presented how to use neural network for prediction. This week I will present algorithm which is using neural network predictor.

For the source code, please download repository and update to branch 12-prediction-3, changeset 079ca8d735d9.

What is there

The main code is in the classes Algo2 and Algo2TestApp. To make it run you will have to set up username and password for MbTrading account (Algo2TestApp line 44). I can't publish my own. Other way is to implement different historical provider which supports intraday data.

Algorithm works with pre computed network which is in file Algo2-nn-predictor.txt. I had to do it in this way, because it takes hours on my computer to calculate the network. Note that for network calculation I have used only historical data which are not the part of the backtest. The way how algorithm works is pretty straightforward. It builds up the observations which are then exposed to the network and network says whether to buy or not. So let's see the result.

Results

Backtest was done from 2015/10/26 till 2016/04/22 with initial capital 30.000 USD and 10 USD per transaction cost. Final result was 27.000 USD. This means I would not bet my money on this version. On the other hand the risk was managed well. All trades were open and closed within the same day and stop and target prices were known at the time of opening. This gave me fuel to think agbout the improvements - e.g. add another factors to the neural networks.

That's it for today. Next week I will look to some of the traditional technical indicators and see how I can connect them with what I have. Thank you for reading!

Monday, April 18, 2016

Prediction - 2

Hello, welcome back to my blog about automated trading. Last week I have started with prediction and presented K nearest neighborhood method. This week have promissed to introduce neural networks.

For the source code, please download repository and update to branch 11-prediction-2, changeset 0dff22e2031f.

Background

Neural networks are a big topic. Just DuckDuckGo them, or here are 2 links I personally like.
Then there are available plenty of books and scientific articles. I personally read through some of them.

Now for the practical usage let's focus only on feed forward networks with single hidden layer. They are good in classification and identifying relations (see previous post). What does it mean? At first there must be a fundamental reason for relation between observed values and class. Once it is there, then there is no need to know what kind of relation is it. This is the job for network. Example of what it can mean in the stock trading? Question is whether price will tomorrow go up or not. And believe is that this depends on the price change in the past few days. And this leads to the refined question.

Refined question

In the previous post I have deined question whether stock price during next 5 trading days will drop under the today's low or not. This was supposed to define the stop loss. Now let's improve it, short prediction window to 1 trading day and define it in the more appropriate way.

Let's say today is the last trading day where open, high, low and close prices are know. Let's say tomorrow is the next trading day (it might be really tomorrow or for example next Monday if today is a Friday). Let's set the convention that today.open, tomorrow.high... are shortcusts for today open price, tomorrow high price and so on.
Now for the prediction. Task is to buy stocks tomorrow after market opens. So tomorrow.open is known at the time of buying. Then the prediction model should find stocks which will satisfy the following criteria.
  1. tomorrow.low > today.low (for stop loss)
  2. tomorrow.high - tomorrow.open > 2 * (tomorrow.open - today.low) (for risk/reward ratio and target price)
Knowing this the algorithm would buy the predicted stocks right after the open, set up stop loass at today.low, set up target at tomorrow.open + 2 * (tomorrow.open - today.low) and finally limit position holding time to sell eveything before market closes. Then the only thing which left is to calculate the position size based on the acceptable risk. This I will do next week. Also note that if tomorrow.open < today.low, then it doesn't make sense to do this prediction, because the first constraint is already broken. These records are excluded.

Coding

There is more coding for today. At first I have implemented inerface for neural networks, back propagation and black box supervised training. All this includes technique for dealing with local minimas (although no one can be sure). Everything is in the package com.enterprisemath.math.nn.

Then second part is adaptor to the original prediction API. This is done by the classes NNCaterogyPredictorEstimator and NNCaterogyPredictor. Estimator estimates the category predictor and this predictor is used as before. I have made few renamings in this package as well. KNeighbourhoodCategoryPredictor is now called KNNCategoryPredictor.

Finally the test application is renamed from HistoricalQuoteKNPredictionTestApp to PricePredictionTestApp. Structure is the same as in the previous post. One important point is variable predictorType on line 77. This allows to choose the predictor. Allowed values are:
  • NN - neural networks
  • KNN - k-nearest neighrbour model
Please note that neural networks are compute expensive and it takes a long long time. This is a known problem with neural networks. Therefore I have reduced the data size for this demonstration. For the real usage I am storing the network once it is successfully trained. If you have any idea how to speed up the process of NN training, please let me know.

Results

Here are my results from program running today as I am writing this post.

Data

Downloaded data have the following properties.
  • Symbols: ACAD, CLDX, HK, THLD
  • Number of training records: 1467
  • Number of test records: 369
  • Number of true in training records: 153
  • Number of false in training records: 1314
  • Number of true in test records: 23
  • Number of false in test records: 346
As before data are divided to the training records and test records (80% / 20%) to make sure prediction model applies to the unknown records.  In the test data, there are 32 opportunities to buy according strategy discussed above (Number of true in test records). So let's see how many predictions can find.

K-nearest neighborhood method

This method gave me following results.
  • Number of not sure: 48
  • Number of true when true: 0
  • Number of true when false: 0
  • Number of false when true: 19
  • Number of false when false: 302
  • Total success rate: 0.818
From this I can see this prediction method would not generate any trading opportunity (labeled as 'Number of true...'). So it's useless. This is probably caused, because most majority of cases are not considered as a buy oportunity. And therefore there is higher probability that these will take the allowed K places.

Neural network

This method gave me following results.
  • Number of not sure: 46
  • Number of true when true: 4
  • Number of true when false: 16
  • Number of false when true: 13
  • Number of false when false: 290
  • Total success rate: 0.796
This model would open 20 positions in total and 4 of them would reach the target. The other 16 would not - they might go sideways, little bit up or drop. Definitely there is a space for improvements (e.g. add volume or day of the week into the equation). And definitely I am going to create a trading algorithm to see NN in action (of course I will include there more than just 4 stocks (; ).

That's it for today. Next week I will show the trading algorithm which is using prediction. Thank you for reading!

Monday, April 11, 2016

Prediction - 1

Hello, welcome back to my blog about automated trading. Last week I have presented code for one of the trading algorithm. This week I am going to start talking about predisions.

For the source code, please download repository and update to branch 10-prediction-1, changeset 42db394a0d6b.

Background

Recently term prediction is becoming popular across industries. Companies like Google (Google prediction API), Microsoft (Microsoft Azure Essentials) and many others offering cloud service for prediction. There are many articles and books explaining the terminology. For example wikipedia or book named 'Microsoft Azure Essentials Azure Machine Learning'. This book is available on Amazon (right now it is free). From now on I expect basic knowledge about prediction.

Now, let's set the prediction goal. I want to trade long position and therefore buy low and sell high. This means I need to predict which stocks will go up in the near future, or at least will not fall in the near future. For the moment I choose to work with the latter and I might revise this later. Now let's look at the indicators which are available. Historical data, news, financial reports, call logs and others. Right now I need  (there are more sources like news, financial reports or call logs, but I haven't integrated them yet). Can it help? I believe yes.

That was nice theory. Now more concrete. The most important is to define task. Knowing all historical data up to today's close price and volume. Task is to select stocks which will NOT go below today's low in the next 5 days. These are the ones to buy tomorrow morning and there is a known stop loss. This is task for classification with 2 possible outcomes.

Next step is to organize the training data and build the prediction model. Each training row contains observed values (known values) and result (will be unknown in the next step). Observed values are percent changes of the price compare to the today's closed for past X days. And result is simply whether price will stay above today's low for the next 5 days or not (true / false). Now pulling historical data for 2 years this will create one row of data for every day for every stock contributing to the model. For model construction, please look to the code.

Final step is to make the prediction. This is simply using the model. Knowing only the observed values, what is the result? Model will provide more or less accurate answer. Let's look to the code how everything works.

Coding

For this article I have implemented K-nearest neighbors algorithm, version for classification. To get more information, please go to this article on wikipedia. Source code class is KNeighbourhoodCategoryPredictor. And this class implements interface CategoryPredictor to be able to switch it to better implementation later. Right now I am taking this just as a benchmark.

Then there is an application HistoricalQuoteKNPredictionTestApp. This app does following:
  1. Downloads list of stocks according fundamental criteria from finviz.com
  2. For each stock builds the data bank (observations, result) from past 2 years
  3. For each stock splits data bank into 2 groups - 80% goes to training data bank, 20% of most recent records goes to test data bank
  4. Trains KNeighbourhoodCategoryPredictor from training data bank
  5. Compares predicted results with actual results for each record in the test data bank
  6. Prints the info out
Now lets's discuss it. At first I choosed 80/20 data splitting, because I want test my model on the data that are not used to train the model. After running the program right now I get the following results:
  • Number of symbols - 92
  • Number of training records  - 36061
  • Number of test records - 9016
  • Number of not sure predictions - 4136
  • Number of true when true - 88
  • Number of false when false - 3906
  • Number of true when false - 80
  • Number of false when true - 806
  • Total success rate - 0.4429902395740905
The most important numbers are 'Number of true when true' and 'Number of true when false'. These are the ones where algorithm would trigger a buy signal. As a result - 80 positions would be closed by stop loss and 86 would be closed in different way. I don't have answer yet whether this would be profitable or not. For now let's take this as a benchmark for further improvement.

Now you can play with the program. For example try to select different stocks, change parameters or refine the original question. Then please send me your result.

Considering outsourcing through API

Now I will give you some of my thoughts regarding the various prediction APIS. Typically they work in the way that client upload data to the cloud disk and invokes training. Once training is done, then url for making prediction is exposed. I haven no doubt that these companies are doing great job. If I don't have math background then I would probably ended up with one of these. Fortunately I have it and therefore I have a choice.

Pros:
  • Quick start
  • Good results right away
Cons:
  • Payments
  • Network overhead
  • Data transformation overhead
  • Account maintanence overhead
  • Dependency & conditions
  • Unable to build my own IP
  • Black box (in some cases)
Based on this list I decided to develop my prediction software. Do you have opinion? Please let me know.

That's it for today. Next week I will try to improve quality of the prediction by using neural networks. Thank you for reading!

Monday, April 4, 2016

Trading algorithm

Hello, welcome back to my blog about automated trading. Last week I was talking about technologies. This week I am going to introduce you an trading algorithm.

For the source code example, please download repository and update to branch 9-algo_implementation-1, changeset c9c8928026ad.

Algo code

Looking for the implementation. The main classes to look at are Algo1 and Algo1TestApp. And you can run the Algo1TestApp and see the result of the backtest for the past year. On top of these I have made improved the whole framework. Next let's go throug the algorithm itself.

Algorithm works in the long term and can hold positions for weeks. Basics ideas are following. DoTraining method makes decisions of entry / exit every day and processEvent method simply just executes orders. I decided to buy stocks according these rules:
  • Must follow the fundamental criteria (part with finviz filter)
  • Price must be low enough (part with price check)
  • Must be in discount (part with pattern check)

Why I did this. Fundamental criteria should at least some confidence that company is not going to bancrupt. Price is important for me, because my budget is limited. I am using only cash account and I want to be able to buy reasonable volume. And finally I want buy stocks which are on low price now, expecting they willl return to the original price later. That's it.

Real system example

I want to show you how looks my real system. I can definitely imagine prettier design, but functional wise it works great.
Trading platform screenshot
This is screenshot from my trading platform. On the left side I wrote code. The only thing I need to do is implement 2 methods I described in the chapter Algo interface. Everything else is handled automatically by system. On the right side there is panel where you can manage the code revisions, backtests and deployme the code for the real trading. This is that simple.

That's it for today. Next week I will talk about prediction API. Thank you for reading!