Playground
Pair Trading Cointegration Tester
Engle-Granger cointegration test: OLS hedge ratio, ADF on residuals, OU half-life, rolling z-score with entry/exit bands.
Runs in your browser. Nothing you enter is uploaded, and no account or API key is needed.
1. Upload two price series
Format: date,asset_a,asset_b. The first numeric column is treated as A, the second as B. Prices are log-transformed internally; the regression is log A = α + β · log B + ε. Needs ≥ 60 aligned observations.
2. Parameters
What this tool computes
Full Engle-Granger cointegration test on a price pair, plus Ornstein-Uhlenbeck mean-reversion half-life and rolling z-score of the spread for entry/exit simulation. Load the cointegrated synthetic demo or upload your own two-column price CSV.
How to use it
- The page opens with a synthetic cointegrated pair. Upload your own date,asset_a,asset_b CSV with at least 60 aligned prices.
- Set the ADF lag count (0 to 10) and the rolling z-score window (default 60 observations).
- Read the cointegration result: the ADF t-statistic on the residuals of log A = α + β·log B, judged against the Engle-Granger (MacKinnon 2010) critical values.
- Check the spread's mean-reversion half-life and the verdict: tradable, borderline or not cointegrated.
- Set entry and exit z-scores and read how many entries and exits the rolling z-score triggers on the chart.
The method, step by step
Test a pair for cointegration with the Engle-Granger method: regress one price series on the other to get the hedge ratio, run an Augmented Dickey-Fuller test on the regression residual to check the spread is stationary, and estimate the Ornstein-Uhlenbeck half-life to see how fast it mean-reverts. A low ADF p-value plus a tradeable half-life is the signal; confirm it holds out of sample before trading.
-
Start from an economic reason, not a screen
Before testing, have a reason the two instruments should be linked: same sector, same supply chain, a hedging relationship, or an index-and-constituent tie. Screening thousands of pairs for cointegration guarantees false positives, because some will pass by chance just like any large multiple-comparison search. A prior reason constrains the search and makes a passing test meaningful rather than a coincidence you will trade until it breaks.
If you screened many pairs, the ones that pass are partly selection luck. Treat a data-mined cointegration result with the same suspicion as any over-searched backtest.
-
Estimate the hedge ratio
Regress one price series on the other using ordinary least squares. The slope coefficient is the hedge ratio: how many units of the second instrument offset one unit of the first to form the spread. This ratio defines the spread you will test and trade. Getting it right matters, because a mis-estimated hedge ratio produces a spread that is not actually balanced and will not mean-revert the way the test suggests.
The hedge ratio can drift over time. Re-estimate it periodically rather than fixing it once, since a stale ratio quietly unbalances the spread.
-
Run an ADF test on the residual
Take the residual of the regression, which is the spread, and run an Augmented Dickey-Fuller test on it. The ADF test checks whether the spread is stationary, meaning it reverts to a stable mean rather than wandering. A low p-value rejects the null of a non-stationary, drifting spread, which is the evidence that the pair is cointegrated. A high p-value means the spread can wander indefinitely and the pair is not safe to trade as a mean-reverting spread.
Cointegration, not correlation, is the property that matters. Two highly correlated series can still have a non-stationary spread that drifts apart and never comes back.
Cointegration Half-Life Solver -
Measure the mean-reversion half-life
A stationary spread is necessary but not sufficient; it also has to revert fast enough to trade. Fit an Ornstein-Uhlenbeck process to the spread and compute the half-life, the expected time for a deviation to decay halfway back to the mean. A half-life of a few days suits a short-horizon strategy; a half-life of many months means your capital is tied up too long for the spread to be useful. The half-life turns a yes-or-no test into a tradeability assessment.
Match the half-life to your holding horizon and capital cost. A statistically perfect spread with a six-month half-life is not tradeable for a strategy that needs to turn capital over weekly.
Cointegration Half-Life Solver -
Validate out of sample and monitor for breaks
Cointegration relationships break, often when a structural change hits one of the instruments. Confirm the relationship holds on data after the period you estimated it on, and once live, monitor the spread for signs the cointegration has broken: a spread that stops reverting and trends away is the warning. A pair that cointegrated historically but has broken is a trap that looks like an opportunity. Build the break check in from the start.
Have a rule for when a pair has broken and you exit, decided before you enter. The most dangerous pair is one that used to cointegrate and quietly stopped.
Sources: Co-Integration and Error Correction: Representation, Estimation, and Testing (Engle and Granger, Econometrica (1987)) ; Pairs Trading: Performance of a Relative-Value Arbitrage Rule (Gatev, Goetzmann, Rouwenhorst, Review of Financial Studies (2006))
Mistakes that undo the result
Trading correlation instead of cointegration
Correlated series can still have a spread that drifts apart forever. Only cointegration guarantees a mean-reverting spread, and trading correlation alone risks holding a divergence that never reverts.
Screening many pairs and trading the best
Testing thousands of pairs guarantees some pass by chance. Without an economic reason, a passing cointegration test from a large screen is largely selection luck and tends to break soon after you start trading it.
Ignoring the half-life
A stationary spread that reverts over many months ties up capital far too long to be tradeable for a short-horizon strategy. Cointegration without a workable half-life is a statistical curiosity, not a trade.
Questions people ask
What does the tester actually test?
The Engle-Granger two-step test: an OLS regression of log A on log B for the hedge ratio, then an augmented Dickey-Fuller test on the residuals judged against MacKinnon's cointegration critical values (about −3.34 at 5% for two series, stricter than the plain Dickey-Fuller −1.94). It also estimates the spread's Ornstein-Uhlenbeck half-life and counts z-score entry and exit crossings. It does not backtest P&L, Sharpe or drawdown.
Why isn't the cointegration test built in?
It is the core of the tool: every upload runs Engle-Granger first, and the verdict reads not cointegrated when the residual ADF statistic does not clear the 5% critical value. The z-score chart is shown either way so you can see what the spread did. The Cointegration Half-Life Solver covers the half-life side in more depth.
What's the difference between this and the order-book replayer?
This tool works on two price series (daily or other bars) and asks whether their spread mean-reverts. The order-book replayer displays Level-2 snapshots of one book. Neither simulates fills; for execution cost use the Execution Simulator.
How do I set the entry threshold?
Common starting points are entry at |z| = 2 and exit between 0 and 0.5. A higher entry threshold triggers fewer entries; the entry and exit counts under the chart update as you change the thresholds.
Why is pair trading notoriously hard to make work?
Three common reasons: cointegration breaks during regime changes and leaves a diverging pair, execution costs eat the edge on tight spreads, and the strategy is well known and crowded. Passing the test on one sample is not evidence the relationship will hold.
Related tools
- Calculators Portfolio Correlation Matrix
Paste a multi-asset returns CSV. See the Pearson correlation heatmap, condition number, average absolute correlation, and eigenvalue concentration — the diagnostics for detecting redundant strategies before you allocate capital.
- Playgrounds Walk-Forward Validator
Upload a returns CSV. Rolling or expanding IS/OOS windows, per-window Sharpe, walk-forward efficiency, and a concatenated OOS equity curve. Catches regime decay that PBO alone misses.
- Calculators Risk-Adjusted Returns Calculator
Paste a returns CSV. Sharpe, Sortino, Calmar, Omega, alpha, beta, tracking error, information ratio, max drawdown, and tail moments — plus a benchmark-relative block when you include one.
Articles
- 8 min read Best Sentiment & News APIs for Trading 2026
Best news and sentiment APIs for trading in 2026: Finnhub's free news at 60 calls a minute, Massive's free sentiment labels, Alpha Vantage and Benzinga.
Use it from code
The same calculation as a JavaScript module you can import. It runs where you import it, with no request, key or rate limit.
import { compute } from "https://aifinhub.io/engines/pair-trading-tester.js";