Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Pairs Trading: What am I missing?

Hi everyone! I'm working on a pairs trading strategy (based on a Udemy course) and I can't figure out where I am going wrong? The premise of the strategy is simple. Calculate the z-score based on a moving average (of the pair ratio [stockprice1/stockprice2]), then either go long (zscore2) the pair. Then the exit strategy is to get out of the trade when the zscore crosses zero. It shouldn't be too hard to create, but I can't figure out where I am going wrong. I think my orders are being calculated wrong. Thanks in advance for any help.

5 responses

What are you questioning? I look at the daily positions you have your portfolio. It appears you have half your portfolio in AAPL and half in FB and at any given time. One is long and one is short.

What were you expecting?

For the first few months, my positions are half long and half short (depending on the current zscore, etc.). But somewhere the positions become different. The long and short positions are no longer 50/50. That is where I am getting caught up. Any advice is greatly appreciated!

Notice in your backtest results that the ratio between APPL and FB is pretty close to 50/50 until 2014-06-23. That happens to be the first time the code re-balances after 2014-06-09. What is special about 2014-06-09? APPL had a 7:1 stock split.

The algorithm stores what it thinks is the current number of shares held. However, it doesn't adjust those numbers for splits. Prices and Shares should never be stored and used across trading days. They will not be split adjusted. In your case, rather than storing the shares held, simply check 'context.portfolio.positions[s1].amount' for the current number of shares. That will automagically be adjusted for you. (the same is true for 'context.portfolio.positions[s1].cost_basis' which is the split adjusted price paid)

Thank you Dan. That fixed it!

Happy to help. BTW you may want to simply use the built in 'order_target_percent(long_stock, 0.5)' and 'order_target_percent(short_stock, -0.5)'. That will reduce several lines of your code and automatically readjust the correct quantity of shares to be long 50% and short 50% as desired.