You don't need to keep chasing that one perfect strategy...

See how you can use algos to systematise your trading, remove emotions and finally __make your capital grow__!

Grab your FREE Guide to Algo Trading PDF:

Posted on Sep 25, 2019 by

1 Comment

148 Views

In our previous post, we looked into implementing a Kalman filter in R for calculating the hedge ratio in a pairs trading strategy.

You know, light reading…

We saw that while R makes it easy to implement a relatively advanced algorithm like the Kalman filter, there are drawbacks to using it as a backtesting tool.

Setting up anything more advanced than the *simplest* possible vectorised backtesting framework is tough going and error-prone. Plus, it certainly isn’t simple to experiment with strategy design – for instance, incorporating costs, trading at multiple levels, using a timed exit, or incorporating other trade filters.

To be fair, there are good native R backtesting solutions, such as Quantstrat. But in my experience none of them let you experiment as efficiently as the Zorro platform.

And as an independent trader, the ability to move fast – writing proof of concept backtests, invalidating bad ideas, exploring good ones in detail, and ultimately moving to production efficiently – is quite literally a superpower.

*I’ve already invalidated 3 ideas since starting this post*

The downside with Zorro is that it would be pretty nightmarish implementing a Kalman filter in its native Lite-C code. But thanks to Zorro’s R bridge, I can use the R code for the Kalman filter that I’ve already written, with literally only a couple of minor tweaks. *We can have the best of both worlds!*

This post presents a script for a pairs trading algorithm using Zorro. We’ll stick with a static hedge ratio and focus on the pairs trading logic itself. In the next post, I’ll show you how to configure Zorro to talk to R and thus make use of the Kalman filter algorithm.

*Let’s get to it. *

Even the briefest scan of the pairs trading literature reveals many approaches to constructing spreads. For example, using:

- Prices
- Log-prices
- Ratios
- Factors
- Cointegration
- Least squares regression
- Copulas
- State space models

Ultimately, the goal is to find a spread that is both mean-reverting and volatile enough to make money from.

In my view, *how* you do that is much less important than it’s ability to make money. From personal experience, I know that the tendency is to get hung up on the “correct” way to implement a pairs trade. Such a thing doesn’t exist — I’ve seen money-printing pairs trading books that younger me, being more hung up on “correctness”, would have scoffed at.

Instead, understand that pairs trading is ultimately a numbers game and that universe selection is more important than the specifics of the algorithm. Sure, you can tweak your implementation to squeeze a little more out of it, and even find pockets of conditional or seasonal mean-reversion, but the specifics of the implementation are unlikely to be the ultimate source of alpha.

Anyway, that’s for you to mull over and keep in mind as you read this series. Right now, we’re just going to present one version of a pairs trade in Zorro.

This is a pairs trade that uses a price-based spread for its signals. First, here’s the code that calculates the spread, given two tickers `Y`

and `X`

(lines 5 – 6) and a hedge ratio, `beta`

(line 39). The spread is simply \(Y – \beta X\)

Here’s the code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
/* Price-based spread in Zorro */ #define Y "GDX" #define X "GLD" var calculate_spread(var hedge_ratio) { var spread = 0; asset(Y); spread += priceClose(); asset(X); spread -= hedge_ratio*priceClose(); return spread; } function run() { set(PLOTNOW); StartDate = 20100101; EndDate = 20191231; BarPeriod = 1440; LookBack = 100; // load data from Alpha Vantage in INITRUN if(is(INITRUN)) { string Name; while(Name = loop(Y, X)) { assetHistory(Name, FROM_AV); } } // calculate spread var beta = 0.4; vars spread = series(calculate_spread(beta)); // plot asset(Y); var asset1Prices = priceClose(); asset(X); plot(strf("%s-LHS", Y), asset1Prices, MAIN, RED); plot(strf("%s-RHS", X), priceClose(), 0|AXIS2, BLUE); plot("spread", spread, NEW, BLACK); } |

Using GDX and GLD as our Y and X tickers respectively and a hedge ratio of 0.4, Zorro outputs the following plot:

The spread looks like it was reasonably stationary during certain subsets of the simulation, but between 2011 and 2013 it trended – not really a desirable property for a strategy based on mean-reversion.

Even this period in late 2013, where one could imagine profiting from a mean-reversion strategy, the spread hasn’t been very well behaved. The buy and sells levels are far from obvious in advance:

One way to tame the spread is to apply a rolling z-score transformation. That is, take a window of data, say 100 days, and calculate its mean and standard deviation. The z-score of the next point is the raw value less the window’s mean, divided by its standard deviation. Applying this in a rolling fashion is a one-liner in Zorro:

1 |
vars ZScore = series(zscore(spread[0], 100)); |

Our z-scored spread then looks like this:

The z-scored spread has some nice properties. In particular, it tends to oscillate between two extrema, eliminating the need to readjust buy and sell levels (although we’d need to decide on the actual values to use). On the other hand, it does introduce an additional parameter, namely the window length used in its calculation.

To implement the rest of our pairs trade, we need to decide the z-score levels at which to trade and implement the logic for buying and selling the spread.

Zorro makes that fairly easy for us. Here’s the complete backtesting framework code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
/* Price-based spread trading in Zorro */ #define Y "GDX" #define X "GLD" #define MaxTrades 5 #define Spacing 0.5 // #define COSTS int ZSLookback = 100; int Portfolio_Units = 100; //units of the portfolio to buy/sell (more --> better fidelity to dictates of hedge ratio) var calculate_spread(var hedge_ratio) { var spread = 0; asset(Y); #ifndef COSTS Spread = Commission = Slippage = 0; #endif spread += priceClose(); asset(X); #ifndef COSTS Spread = Commission = Slippage = 0; #endif spread -= hedge_ratio*priceClose(); return spread; } function run() { set(PLOTNOW); setf(PlotMode, PL_FINE); StartDate = 20100101; EndDate = 20191231; BarPeriod = 1440; LookBack = ZSLookback; MaxLong = MaxShort = MaxTrades; // load data from Alpha Vantage in INITRUN if(is(INITRUN)) { string Name; while(Name = loop(Y, X)) { assetHistory(Name, FROM_AV); } } // calculate spread var beta = 0.4; vars spread = series(calculate_spread(beta)); vars ZScore = series(zscore(spread[0], 100)); // set up trade levels var Levels[MaxTrades]; int i; for(i=0; i<MaxTrades; i++) { Levels[i] = (i+1)*Spacing; } // ------------------------------- // trade logic // ------------------------------- // exit on cross of zero line if(crossOver(ZScore, 0) or crossUnder(ZScore, 0)) { asset(X); exitLong(); exitShort(); asset(Y); exitLong(); exitShort(); } // entering positions at Levels for(i=0; i<=MaxTrades; i++) { if(crossUnder(ZScore, -Levels[i])) // buying the spread (long Y, short X) { asset(Y); Lots = Portfolio_Units; enterLong(); asset(X); Lots = Portfolio_Units * beta; enterShort(); } if(crossOver(ZScore, Levels[i])) // shorting the spread (short Y, long X) { asset(Y); Lots = Portfolio_Units; enterShort(); asset(X); Lots = Portfolio_Units * beta; enterLong(); } } // exiting positions at Levels for(i=1; i<=MaxTrades-1; i++) { if(crossOver(ZScore, -Levels[i])) // covering long spread (exiting long Y, exiting short X) { asset(Y); exitLong(0, 0, Portfolio_Units); asset(X); exitShort(0, 0, Portfolio_Units * beta); } if(crossUnder(ZScore, Levels[1])) // covering short spread (exiting short Y, exiting long X) { asset(Y); exitShort(0, 0, Portfolio_Units); asset(X); exitLong(0, 0, Portfolio_Units * beta); } } // plots if(!is(LOOKBACK)) { plot("zscore", ZScore, NEW, BLUE); int i; for(i=0; i<MaxTrades; i++) { plot(strf("#level_%d", i), Levels[i], 0, BLACK); plot(strf("#neglevel_%d", i), -Levels[i], 0, BLACK); } plot("spread", spread, NEW, BLUE); } } |

The trade levels are controlled by the `MaxTrades`

and `Spacing`

variables (lines 7 – 8). These are implemented as `#define`

statements to make it easy to change these values, enabling fast iteration.

As implemented here, with `MaxTrades`

equal to 5 and `Spacing`

equal to 0.5, Zorro will generate trade levels every 0.5 standard deviations above and below the zero line of our z-score.

The generation of the levels happens in lines 57 – 63.

The trade logic is quite simple:

- Buy the spread if the z-score crosses under a negative level
- Short the spread if the z-score crosses over a positive level
- If we’re long the spread, cover a position if the z-score crosses over a negative level
- If we’re short the spread, cover a position if the z-score crosses under a positive level
- Cover whenever z-score crosses the zero line

By default, we’re trading 100 units of the spread at each level. We’re trading in and out of the spread as the z-score moves around and crosses our levels. If the z-score crosses more than one level in a single period, we’d be entering positions for each crossed level at market.

Essentially, it’s a bet on the mean-reversion of the z-scored spread translating into profitable buy and sell signals in the underlyings.

The strategy returns a Sharpe ratio of about 0.6 before costs (you can enable costs by uncommenting `#define COSTS`

in line 9, but you’ll need to set up a Zorro assets list with cost details, or tell Zorro about costs via script) and the following equity curve:

There you have it – a Zorro framework for price-based pairs trading. More than this particular approach to pairs trading itself, I hope that I’ve demonstrated Zorro’s efficiency for implementing such frameworks quickly. And once they’re implemented, you can run experiments and iterate on the design, as well as the utility of the trading strategy, efficiently.

For instance, it’s trivial to:

- Add more price levels, tighten them up, or space them out
- Get feedback on the impact of changing the z-score window length
- Explore what happens when you change the hedge ratio
- Change the simulation period
- Swap out GLD and GDX for other tickers

You can even run Zorro on the command line and pass most of the parameters controlling these variables as command line arguments – which means you can write a batch file to run hundreds of backtests and really get into some serious data mining – if that’s your thing.

All that aside, in the next post I want to show you how to incorporate the dynamic estimate of the hedge ratio into our Zorro pairs trading framework by calling the Kalman filter implemented in R directly from our Zorro script.

**You can grab the code for the Kalman Filter we used in the previous post for free below:**

the Code

__Get the exact data and code__ we used in this blog post!

**Implement your own Kalman Filter — **download all the code you need for free

## Comment (1)

Thank you. I enjoy the post a lot. A very good introduction to Pair tradings.