Monday, February 22, 2016

Backtesting - part 2

Hello, welcome back to my blog about automated trading. Last week I have made preparation for the back testing. Now I am going to finish it.

For the source code, please download repository and update to branch 6-backtest-2, changeset 7fef89d5a3a5.

There was enough theory last week. Now let's go straight to the coding.

Coding

The entry class to look at is BacktestRunnerBean. This class depends on data providers which are then called from the Algo implementation. Method runBacktest does all the fun in it. For better understanding of how it works, please look to the accompanying test.
Now there is available an application called BacktestRunnerBeanTestApp. This is standalone application which creates all the whole environment and runs test. You can find there also very bad trading strategy (Algo) implementation. Please note that this strategy is good only to show the process. Data providers are implemented in the minimalistic way. So have fun!!!

That's it for today. Next week I will take a holiday. After that I will talk about the fix protocol. Thank you for reading!

Monday, February 15, 2016

Backtesting - part 1

Hello, welcome back to my blog about automated trading. Last week I have covered the topic about real time quotes. This week I start talking about back testing. This topic is long enough so I will split it into 2 parts. Today there will be an introduction and next week I will present simple standalone backtest unit.

For the source code, please download repository and update to branch 6-backtest-1, changeset 29fc2509e9a9.

Background

Without doubt backtesting is important part for automated trading although there are many inaccuracies and biases (there are already plenty of articles, just search for backtest). I am not going into these details. This post is about the implementation of back test framework. And I would like to mentione the following issues I had to go through.
  1. How to cook real time quotes
  2. How to prevent future prediction
  3. Searching according finviz criteria
  4. Speed
  5. What about market impact 
For some of them I have solution. For some not. If you have any better one, please let me know. Now let's go through them.

First issue was how to cook real time quotes. Obviously they have to come somehow from the historical quotes as these are the only one available. I sorted this out simply by translating the average price of historical quote to the bid and ask of real time quote. Limitation is that the maximum amount of real time quotes is same as the number of historical quotes. I just live with that.

Second issue was how to prevent future prediction. This is solved by implementation of HistoricalProvider which acts like a proxy. Then the request date is simply repaired as the test progresses. Here let me mention one point about TrainingDataProvider. There is a method called today. Algo implementations have to use is to get current date. This makes date operations within the backtest possible.

Third issue is tricky and I don't have perfect solution yet. This issue appears when Algo implementation relies on the data from Finviz page. In the real daily cycle the implementation gets up to date date every day. But this page doesn't reflect the backtest, so data might be incorrect. Probably daily crawling and storing would solve it, but this is too early. For the moment I live with the wrong data, nothing is perfect.

Fourth issue is speed. According my experience most time is spend by querying the remote services. Solution to this is caching. Now using the cheap cloud there is a need to find balance between available memory and speed. Please refer to the coding part.

And finally fifth issue is market impact. Every transaction has some cost. One part of the cost is broker comission. Another part is market impact. And there might be more. To simulate this I introduced transaction cost function which is associated with all transactions. Please refer to the coding part.

And what about you? Do you know about other issues? Do you have better solutions? Please let me know in the comments.

Coding

This chapter is just preparaion. So here are the prepared units. Next time I will put them into the framework. There is an implementation of VariableContext called InMemoryVariableContext. This is used to suply variable persistence for the backtest lifetime. Then there are 2 implementations of HistoricalProvider called CachedHistoricalProvider and EndDateLimitedHistoricalProvider. These are used as a guarantee for the future prediction problem and as a one part of speed optimization. And finally there is object called TransactionCostFunction obviously used for simulating transaction cost.

That's it for today. Next week I will finish this chapter. Thank you for reading!

Monday, February 8, 2016

Algo interface

Hello, welcome back to my blog about automated trading. Last week I have covered the topic about real time quotes. This week I will introduce the interface which allows to plug in various trading strategies into the system.

For the source code example, please download repository and update to branch 5-algo, changeset 61bfc9e57423.

Background

In the chapter Daily cycle I have split the day into 2 parts - overnight and trading session. For better imagination, please see the image below.



As it was stated there is planty of computing time available over night and there is a need to make processing very fast during the trading session. This gives need for interface to have 2 different methods. Let's call them doTraining and processEvent. Both of them need to have access to the data sources and both of them have to tell to platform what to do. However their needs and responses are different. So let's go through it.

Method doTraining is used for crwaling through stocks, finding the best deals and so on. This method needs to have access to the stock screener, currently open positions and historical data. Result of the call tells to the platform what to prepare for the trading session. Currently the supported command is  subscription request for real time quotes during next trading session.

Method processEvent is used for processing event which happenes during the trading session (e.g. price change). Anytime this happens the method is called. Therefore this method is called many times per trading session. Input to the metod contains the event which triggered the call. Available data sources are all the one which works in real time during trading session (e.g. real time quotes). Result of the call tells to the platform what to do. Currently strategy can ask platform to send orders for buy or sell.

What about sharing data between calls? Each method has another parameter called variables of the type VariableContext. This is interface used exactly for this. Client can persists variables in one call and use them in another call. Please note that another call might happen on the different computer so using of this interface is the only guaranteed way to keep everything consistent.

Coding

As for coding, please refer to the interface called Algo. This is the entry point to everything. There is a different data provider for each of the method and each of the method returns different result. Finally both methods have variables which are used as a point for data sharing between the calls (trading cloud persist this into the database).

That's it for today. Next week I will show how to make backtesting. Thank you for reading!

Monday, February 1, 2016

Real time quotes

Hello, welcome back to my blog about automated trading. Last week I have made example for the stocks screening. This week I will write about the quotes during trading session.

For the source code example, please download repository and update to branch 4-real-time-quotes, changeset f33d07def714.

Background

Realtime quotes are another essential part of the system for the automated trading. As historical quotes are used during the night for heavy computing, real time quotes are used during the trading session for knowing immediate price (and others). In my system real time quotes has the following data.
  • Symbol - company identification
  • Timestamp
  • Previous close - close price from the previous trading day
  • Open - price at the open
  • Bid
  • Ask
  • Volume
Now regarding the speed. In short, speed matters. Every symbol produces several messages per second. Now multiply it by the number of symbols you want to track (50 or 100) and it ends up as a thousands messages per hour. Trading system has to be able to consume them and process them. This is not that trvivial task on the free (or cheap) cloud. Therefore here I will introduce the speed test. Next let's look to the actual code.

Coding

On the broker side, typically there is exposed very simplistic API. Client needs to log in and subscribe or unsubscribe quotes. Then there are few administrative messages (e.g. heartbeat, error, logout). That's it. So let's look to the source code. I have implemented solution which works with MbTrading.

First there are 2 interfaces - QuoteConnector and QuoteReceiver. QuoteConnector is the actual class which allows QuoteReceiver to register for subscription. QuoteReceiver then receives the subscribed quotes. Then the actual implementation is done through MbTradingQuoteConnector with unit test MbTradingQuoteConnectorTest. Now if you have trading account with MbTrading, then you can fill in credentials into MbTradingQuoteConnectorTestInternetApp and connect it with the actual broker. And finally as I have talked about the speed, then there is example for performance testing - MbTradingQuoteUtilsPerformanceTestApp. This is application which measures how fast I am able to parse broker message received. I personally use this style for any optimization, knowing that unit test will cover the correct functionality. So play with that and have fun!

That's it for today. Next week I will introduce the generic interface for the trading algorithms. Thank you for reading!