FAQ · Getting systematic research right

How do I backtest a pairs trading strategy with cointegration in Python?

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.

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 z crosses 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_unit models 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.

Next questions

How do I backtest a portfolio of several tickers?Run every ticker in one backtest against one shared account, so positions compete for the same capital and margin. Process bars in time order across all tickers, act on each ticker only when it has a fresh bar, and size each position against total equity. Testing tickers one at a time and adding the results misses the shared capital constraint.How do I split data into in-sample and out-of-sample?Split by time, never at random. Use the earlier part of your history, often about 70%, to build and tune the strategy, and keep the later 30% untouched until you have stopped changing it. Test once on the held-out part; if you tune again after seeing it, it is no longer out-of-sample.What is look-ahead bias and how do I find it in my backtest?Look-ahead bias is a backtest using information that was not available when the decision was made, such as filling at the close of the bar that produced the signal or reading data published later. Find it by checking when each value was known, shifting signals by one bar, and seeing whether results collapse.Can I backtest futures with roll handling, or FX with swap costs?Yes, but only if the backtest handles two things a plain price series hides. In a continuous futures series, the price jump at each contract roll must not be counted as profit or loss. An FX position held overnight must be charged or credited swap every night it is held. A backtest that skips either can report a result the account would never have produced.

Every answer here restates the documents that ship in the kit, which are authoritative. All questions.

Reamer Research

Your first backtest in a minute

Backtesting and live trading in Python and C++. Free to install in Evaluation Mode, with no key or sign-up.

pip install reamer-research

A licence at $20 a month removes every limit. The same code runs unchanged.

Reamer Server

The order-management core for your firm

Your venues, your risk rules on every order, one strategy per CPU core, on your own Linux servers.

$24,000 / year

Or start with a 30-day trial at $2,000.