Pairs trading in Python: a cointegration screen and z-score backtest in 60 lines
This guide builds a minimal pairs trading research script in Python. It is meant for learning: it shows the moving parts and avoids the most common mistakes, but it is not production code and the output is not a trading recommendation.
Setup
pip install yfinance statsmodels pandas numpy
1. Prices
import numpy as np, pandas as pd, yfinance as yf from statsmodels.tsa.stattools import coint, adfuller import statsmodels.api as sm px = yf.download(["KO", "PEP"], start="2019-01-01", auto_adjust=True)["Close"].dropna() la, lb = np.log(px["KO"]), np.log(px["PEP"])
Use adjusted closes so dividends and splits do not create fake jumps, and work with log prices.
2. Test cointegration on a formation window
form = slice(0, 252) # first year only
t, p, _ = coint(la.iloc[form], lb.iloc[form])
print(f"Engle-Granger p-value: {p:.3f}")
X = sm.add_constant(lb.iloc[form])
beta = sm.OLS(la.iloc[form], X).fit().params.iloc[1]
spread = la.iloc[form] - beta * lb.iloc[form]
print(f"beta {beta:.3f}, ADF p {adfuller(spread)[1]:.3f}")
coint runs the full Engle–Granger procedure with the right critical values. Running adfuller on your own residuals gives a p-value that is too optimistic; it is shown here only for comparison.
3. Rolling hedge ratio and z-score, no look-ahead
W = 252
def rolling_beta(y, x, w):
cov = y.rolling(w).cov(x)
return cov / x.rolling(w).var()
b = rolling_beta(la, lb, W)
s = la - b * lb
z = (s - s.rolling(W).mean()) / s.rolling(W).std()
Every value on date t uses only data up to t. That is the property most hand-made backtests lose. More on the hedge ratio and the z-score.
4. Rules: enter at ±2, exit at ±0.5, stop at ±3.5
pos = np.zeros(len(z)) # +1 long spread, -1 short spread
for i in range(1, len(z)):
zi, p0 = z.iloc[i], pos[i - 1]
if np.isnan(zi): pos[i] = 0
elif p0 == 0 and zi <= -2: pos[i] = 1
elif p0 == 0 and zi >= 2: pos[i] = -1
elif p0 != 0 and (abs(zi) <= 0.5 or abs(zi) >= 3.5): pos[i] = 0
else: pos[i] = p0
pos = pd.Series(pos, index=z.index)
5. Returns with next-bar fills and costs
ra, rb = la.diff(), lb.diff() # log returns
held = pos.shift(1).fillna(0) # trade on the next bar
hedge = b.shift(1)
gross = held * (ra - hedge * rb) / (1 + hedge.abs())
cost = 0.0005 * pos.diff().abs().fillna(0) * 2 # 5 bp per leg per side
net = (gross - cost).fillna(0)
print("trades:", int((pos.diff().abs() > 0).sum() / 2))
print("total log return:", round(net.sum(), 3))
print("max drawdown:", round((net.cumsum() - net.cumsum().cummax()).min(), 3))
Dividing by 1 + |β| normalises returns to the total capital in both legs. Shifting the position by one bar means a signal seen at today's close is acted on at the next bar.
What this script still gets wrong
- It tests one pair chosen in advance. Screening many pairs needs a multiple-testing correction.
- The cointegration test runs once. A real system re-tests as data arrives and stops trading broken pairs.
- Borrow fees, slippage and position sizing are simplified.
Read backtesting without fooling yourself before drawing conclusions from any result.
Skip the plumbing
If you would rather study results than maintain data pipelines, Arbitrading runs this kind of screen daily for 276 pairs and has a walk-forward backtester for your own levels. The free plan includes the scanner and three backtests a day; KO vs PEP is a good place to start.