Calculator in Markets and quant
Pair trading test
Tests a pair on log prices with a chosen ADF lag, and gives MacKinnon's critical values and the half-life.
- Changed 4 Dec 2026
- 9 test cases pass
- Version 1
- About 5,800 tokens
- Needed by the small model tested, 4 Dec 2026
In short
| Formula | x = ln b, y = ln a; beta = Σ(x−x̄)(y−ȳ)÷Σ(x−x̄)^2; alpha = ȳ−beta×x̄spread e = y−alpha−beta×x; residualStdev = √(Σe^2÷(n−2)); r2 = 1−Σe^2÷Σ(y−ȳ)^2d_t = e_t − e_(t−1); ADF over T rows, no constant: d_t = gamma×e_(t−1) + c_1×d_(t−1)+…+c_lags×d_(t−lags)tStat = gamma ÷ its standard error (residual variance ÷ (T−lags−1))critical1 = −3.89644−10.9519÷T−22.527÷T^2; critical5 = −3.33613−6.1101÷T−6.823÷T^2; critical10 = −3.04445−4.2412÷T−2.720÷T^2pValueBand = "< 1%", "< 5%", "< 10%" at the first critical value above tStat, else ">= 10%"; isStationary5 = tStat < critical5least squares d_t = c+slope×e_(t−1); theta = −slope; halfLifeDays = −ln 2 ÷ ln(1+slope) if −1 < slope < 0, else none |
| Units | Prices in; half-life in rows. |
| Defaults | lags 1 (0 to 10); at least max(6, 2×lags+3) rows. |
| Worked example | a = 17.16, 18.69, 19.98, 17.96, 20.8, 22.63, 21.43, 25.23, 27.18, 24.98, 27.47, 28.8; b = 10, 11, 12, 11, 13, 14, 13, 15, 16, 15, 17, 18; lags 0. beta = 0.356856 ÷ 0.378871 = 0.942T = 11: gamma = −0.0018379÷0.0050775 = −0.361976, tStat = −0.361976 ÷ 0.237688 = -1.523critical10 = −3.04445−0.38556−0.02248 = -3.452, pValueBand = >= 10%slope −0.353357: halfLifeDays = −ln 2 ÷ ln 0.646643 = 1.59 |
By hand: no, run the code. A small model did not get these answers from the formulas alone.
Say this to your agent
Use https://mysi.dev/pair-trading-tester/ to run an Engle-Granger test on these two price series with 0 ADF lags. Nothing to install, no key, no settings. An agent that can open web pages and run Python opens the page, runs the tested code in its own sandbox and gives you the answer.
The code
Copy this into your Python tool. Run pair_trading_tester_check() first, then call pair_trading_tester() with your numbers. Give the answer with the cite line.
"""Pair trading test: Engle-Granger test of two price series (least squares of log a on log b,
augmented Dickey-Fuller on the residuals, MacKinnon 2010 critical values), spread half-life.
Inputs: a, b (positive prices, oldest first, same length, at least 6 and 2 x lags + 3),
lags (lagged differences in the ADF regression, 0 to 10, default 1).
Returns: alpha, beta, residualStdev, r2, tStat, critical1, critical5, critical10, pValueBand,
isStationary5, halfLifeDays (None when not reverting), theta.
mysi, Pair trading test, mysi.dev/pair-trading-tester, version 1, changed 2026-12-04. MIT.
"""
import math
def _pair_trading_tester_ols(x, y):
n, mx, my = len(x), sum(x) / len(x), sum(y) / len(y)
sxx = sum((u - mx) ** 2 for u in x)
beta = sum((u - mx) * (v - my) for u, v in zip(x, y)) / sxx if sxx else 0.0
alpha = my - beta * mx
ss_res = sum((v - alpha - beta * u) ** 2 for u, v in zip(x, y))
ss_tot = sum((v - my) ** 2 for v in y)
return alpha, beta, math.sqrt(ss_res / max(1, n - 2)), 1 - ss_res / ss_tot if ss_tot else 0.0
def _pair_trading_tester_inverse(m):
k, g = len(m), [r[:] + [float(i == j) for j in range(len(m))] for i, r in enumerate(m)]
for c in range(k):
p = max(range(c, k), key=lambda r: abs(g[r][c]))
if abs(g[p][c]) < 1e-12:
raise ValueError("a and b give a singular ADF regression; use more or other prices")
g[c], g[p] = g[p], g[c]
g[c] = [v / g[c][c] for v in g[c]]
for r in range(k):
if r != c:
g[r] = [v - g[r][c] * w for v, w in zip(g[r], g[c])]
return [row[k:] for row in g]
def pair_trading_tester(a, b, lags=1):
if not isinstance(lags, int) or isinstance(lags, bool) or not 0 <= lags <= 10:
raise ValueError("lags must be a whole number from 0 to 10")
need = max(6, 2 * lags + 3)
for name, xs in (("a", a), ("b", b)):
if not isinstance(xs, list) or len(xs) < need or not all(
isinstance(x, (int, float)) and not isinstance(x, bool) and x > 0 for x in xs):
raise ValueError(f"{name} must be a list of at least {need} prices above 0")
if len(a) != len(b):
raise ValueError("a and b must be lists of the same length")
la, lb = [math.log(x) for x in a], [math.log(x) for x in b]
alpha, beta, res_sd, r2 = _pair_trading_tester_ols(lb, la)
e = [y - alpha - beta * x for x, y in zip(lb, la)] # the spread
d = [e[i] - e[i - 1] for i in range(1, len(e))]
rows = [[e[i]] + [d[i - j] for j in range(1, lags + 1)] for i in range(lags, len(d))]
ys, k = d[lags:], lags + 1 # ADF regression, no constant
xtx = [[sum(r[p] * r[q] for r in rows) for q in range(k)] for p in range(k)]
inv = _pair_trading_tester_inverse(xtx)
xty = [sum(r[p] * y for r, y in zip(rows, ys)) for p in range(k)]
coef = [sum(i * v for i, v in zip(inv[p], xty)) for p in range(k)]
rss = sum((y - sum(c * v for c, v in zip(coef, r))) ** 2 for r, y in zip(rows, ys))
se = math.sqrt(rss / max(1, len(ys) - k) * inv[0][0])
t_stat = coef[0] / se if se > 0 else 0.0
n = len(ys) # MacKinnon 2010, N = 2, c
cv = [-3.89644 - 10.9519 / n - 22.527 / n ** 2, -3.33613 - 6.1101 / n - 6.823 / n ** 2,
-3.04445 - 4.2412 / n - 2.720 / n ** 2]
band = ["< 1%", "< 5%", "< 10%", ">= 10%"][sum(t_stat >= c for c in cv)]
_, slope, _, _ = _pair_trading_tester_ols(e[:-1], d) # d = c + slope x e_prev
half_life = -math.log(2) / math.log(1 + slope) if slope < 0 and 1 + slope > 0 else None
return {"alpha": alpha, "beta": beta, "residualStdev": res_sd, "r2": r2, "tStat": t_stat,
"critical1": cv[0], "critical5": cv[1], "critical10": cv[2], "pValueBand": band,
"isStationary5": t_stat < cv[1], "halfLifeDays": half_life, "theta": -slope}
_PAIR_TRADING_TESTER_A = [17.16, 18.69, 19.98, 17.96, 20.8, 22.63, 21.43, 25.23, 27.18, 24.98,
27.47, 28.8]
_PAIR_TRADING_TESTER_B = [10, 11, 12, 11, 13, 14, 13, 15, 16, 15, 17, 18]
PAIR_TRADING_TESTER_CASES = [
({"a": _PAIR_TRADING_TESTER_A, "b": _PAIR_TRADING_TESTER_B, "lags": 0},
{"beta": 0.941892, "tStat": -1.52290, "halfLifeDays": 1.58993}),
({"a": _PAIR_TRADING_TESTER_A, "b": _PAIR_TRADING_TESTER_B, "lags": 1},
{"tStat": -4.69257, "critical5": -4.01537}),
({"a": [31.39, 30.44, 29.53, 30.96, 34.07, 30.74, 35.6, 34.64, 33.73, 36.11],
"b": [20, 21, 19, 22, 23, 21, 24, 25, 23, 26], "lags": 0},
{"beta": 0.673416, "tStat": -7.90804, "theta": 1.68078}),
]
def pair_trading_tester_check(tolerance=1e-3):
for given, want in PAIR_TRADING_TESTER_CASES:
got = pair_trading_tester(**given)
for name, value in want.items():
close = abs(got[name] - value) <= tolerance * max(1, abs(value))
assert close, (name, got[name], value)
return "ok"
if __name__ == "__main__":
import json, sys
pair_trading_tester_check()
given = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a)
js = lambda v: v.lstrip("-")[:1].isdigit() or v[:1] in '[{".' or v in ("true", "false", "null")
given = {k: json.loads(v) if js(v) else v for k, v in given.items()}
if given:
print(json.dumps(pair_trading_tester(**given))) A statistical test on past prices, not a trading recommendation.
What it takes
| Input | Meaning | Default | Allowed |
|---|---|---|---|
| a | Prices of asset A (the dependent leg), oldest first, all above 0 | required | a list |
| b | Prices of asset B, aligned with a and the same length | required | a list |
| lags | Lagged differences in the ADF regression (0 = plain Dickey-Fuller) | 1 | 0 to 10 |
What it returns
| Output | Meaning |
|---|---|
| alpha, beta | The regression ln a = alpha + beta × ln b; beta is the hedge ratio on log prices |
| residualStdev, r2 | Standard deviation of the spread and the regression's R squared |
| tStat | ADF t-statistic on the spread; more negative is stronger evidence of cointegration |
| critical1, critical5, critical10 | Engle-Granger critical values at 1%, 5% and 10% for this many rows |
| pValueBand | "< 1%", "< 5%", "< 10%" or ">= 10%": where tStat falls against the critical values |
| isStationary5 | True when tStat is below the 5% critical value |
| halfLifeDays | Rows for a gap in the spread to halve; null when it does not revert smoothly |
| theta | Minus the slope of the spread's change on its level, per row |
Where the method comes from
The Engle-Granger two-step test (Engle and Granger 1987) regresses the log price of one asset on the other by least squares and tests the residual spread for a unit root with the augmented Dickey-Fuller regression (Said and Dickey 1984), without a constant and with the chosen number of lagged differences. Because the hedge ratio is estimated first, the t-statistic is compared with the Engle-Granger critical values for two series with a constant, from MacKinnon's (2010) response surfaces, which adjust for T, the number of rows in the unit-root regression; they were fitted on simulations from 20 rows up, so shorter samples are an extrapolation. The spread's half-life comes from regressing its change on its previous level with a constant, the discrete form of an Ornstein-Uhlenbeck process.
The test has little power on short samples, so a few hundred rows are needed for a real decision. A significant result on past prices does not guarantee the relation will hold, and the hedge ratio is on log prices, so beta is an elasticity.
Sources
- Engle and Granger, Co-integration and error correction: representation, estimation, and testing, Econometrica 55(2)published 1987
- Said and Dickey, Testing for unit roots in autoregressive-moving average models of unknown order, Biometrika 71(3)published 1984
- MacKinnon, Critical values for cointegration tests, Queen's Economics Department Working Paper 1227, Table 2published 2010
Tested
Tested 4 Dec 2026: claude-haiku-5-5 was right on 0 of 3 questions without this page and 3 of 3 with it; claude-fable-5-2 was right on 3 of 3 questions without this page, so it was not tested with it.
Changes
- Moved from aifinhub.io as Python. Answers unchanged, returned flat (tStat instead of adf.tStat). Dropped the verdict (its 30- and 60-day cut-offs have no source), the residual and z-score series, and the rolling z-score entry and exit counts with their inputs z_window, entry_z and exit_z, to keep the main test within one short function. The minimum is 6 rows instead of 60, and the half-life is given for any length instead of from 30 rows.4 Dec 2026
Cite as: mysi, Pair trading test, mysi.dev/pair-trading-tester, version 1, changed 2026-12-04. Code MIT.