Test candidate pairs for cointegration on an in-sample period, estimate the hedge ratio there, then trade the spread out of sample. Go long the spread when its z-score falls below a threshold and short it when it rises above, closing near zero. Estimating the hedge ratio on the whole history is the most common way pairs backtests lie.
The idea
Two prices are cointegrated when some combination of them, spread = A - beta * B, tends to return to a stable mean even though each price wanders on its own. Pairs trading bets on that return: when the spread is unusually wide, sell A and buy B; when it is unusually narrow, do the opposite.
Correlation is not the same thing. Two prices can move together day to day and still drift apart for good. Cointegration is about the level of the spread, which is what the trade depends on.
Step 1: test for cointegration in sample
from statsmodels.tsa.stattools import coint
import statsmodels.api as sm
ins_a, ins_b = a[:'2021'], b[:'2021']
score, pvalue, _ = coint(ins_a, ins_b) # Engle-Granger test
beta = sm.OLS(ins_a, sm.add_constant(ins_b)).fit().params.iloc[1]
spread = ins_a - beta * ins_b
mean, std = spread.mean(), spread.std()
A p-value below 0.05 is the usual bar. Two cautions:
- Testing many pairs finds false ones. Test 1,000 pairs at 5% and about 50 will pass by chance. Prefer pairs with an economic reason to move together (two share classes, a company and its main competitor, an ETF and its largest holdings) and test them on a second period too.
- Cointegration breaks. Mergers, index changes and new business lines can end a relationship. Re-test regularly.
Step 2: trade it out of sample
Use beta, mean and std from the in-sample period, or update them with a rolling window that uses only past data. Then:
z = (spread - mean) / std- enter short the spread (sell A, buy beta × B) when
z > 2; - enter long the spread (buy A, sell beta × B) when
z < -2; - exit when
zcrosses back near 0, with a stop if|z|keeps widening, say past 4.
What to include in the backtest
- Both legs' costs. A pairs trade pays spread and commission twice on entry and twice on exit.
- Short borrow and financing. The short leg costs money to hold.
- Leg timing. Both legs should fill at the same moment. Using one leg's close and the other's next open is a hidden source of profit or loss.
- Shared capital. Both legs draw on one account's buying power.
How Reamer Research handles it
In Reamer Research both legs run in one backtest against one account, on one wall clock. The fitted values go in as settings on a configured object, so the out-of-sample run cannot re-fit them on the data it is testing:
import reamer_research as rr
class Pair:
lookback = 1
def __init__(self, a, b, beta, mean, std, qty=100, entry=2.0, exit=0.3):
self.a, self.b, self.beta, self.mean, self.std = a, b, beta, mean, std
self.qty, self.entry, self.exit = qty, entry, exit
def on_bar(self, d):
if not (d[self.a].valid and d[self.b].valid):
return None
z = (d[self.a].close[-1] - self.beta * d[self.b].close[-1] - self.mean) / self.std
hedge = round(self.qty * self.beta)
pos = d.position(self.a)
if pos == 0 and z > self.entry:
return rr.orders(rr.sell_market(self.qty, ticker=self.a), rr.buy_market(hedge, ticker=self.b))
if pos == 0 and z < -self.entry:
return rr.orders(rr.buy_market(self.qty, ticker=self.a), rr.sell_market(hedge, ticker=self.b))
if pos != 0 and abs(z) < self.exit:
return rr.close_all()
result = rr.backtest(Pair('KO', 'PEP', beta, mean, std), {'KO': 'KO.bin', 'PEP': 'PEP.bin'},
start=oos_start, spread=0.01, commission_per_unit=0.005)
The same rule runs as a function on_bar(data) or a class as well. Orders returned on the same bar fill from the next ticks of each ticker, so the two legs enter together. ticker_config sets spread, commission and slippage separately for each leg. The order log and the visual trade diagnostics tool show both legs of every trade.
Limits to know
- Fitting is yours. The cointegration test and the hedge ratio come from your own code, with statsmodels or any other library.
- Borrow fees are yours to add.
swap_per_unitmodels overnight financing as a charge on longs and a credit on shorts, so a stock borrow fee on the short leg is subtracted from the result in your own code. - Two tickers need a licence. Evaluation Mode runs one ticker.
A $20 month includes the full kit, so you can run your own pairs out of sample and cancel if it does not fit.