Quant research & trading·Python·Published
Pairs Trader
This is a cointegration-gated pairs backtester, and the gate is the part I care about most because most pairs screens skip it and then trade two series that merely look correlated. It runs an Engle-Granger test, OLS for the hedge ratio and an ADF test on the residuals, then estimates the half-life of mean reversion from an AR(1) fit on those residuals so I know whether the spread reverts in days or in months. The backtest is the classic construction: long the spread when z-score < -entry_z, short when z-score > +entry_z, take profit at |z| < exit_z, stop at |z| > stop_z, with the z-score computed over a configurable rolling window. The CLI downloads aligned yfinance data, runs the gate unless you pass --no-coint-test, prints trade count, total PnL, Sharpe, win rate and average PnL, and can write a trades CSV plus a three-panel chart of normalized prices, the spread and the z-score with thresholds and trade markers. Tests check the EG test on a synthetic cointegrated pair, half-life recovery, rejection of a random walk, and that the backtest skips when the pair fails the gate.



- Correlation is not cointegration: two trending series can correlate at 0.95 and still have a residual that wanders, which is why the ADF test on the residual has to gate the trade rather than a correlation threshold.
- The half-life from an AR(1) on the residual sets the holding period; if the z-window is much shorter than the half-life the signal fires before the spread has any reason to revert.
- A stop at |z| > stop_z is not a risk control in the usual sense, it is an admission that the cointegration relationship broke, and treating it as a normal stop-loss hides that distinction.
Scale 0–100: how much this project relied on each skill.