Calculator in Markets and quant
Cointegration half-life
Tests two raw price series for cointegration and gives the hedge ratio and the spread's half-life.
- Changed 4 Dec 2026
- 10 test cases pass
- Version 1
- About 5,300 tokens
- Needed by both models tested, 4 Dec 2026
In short
| Formula | With lookback, keep the last lookback rows; n = rows kept.beta = Σ(a−ā)(b−b̄) ÷ Σ(b−b̄)^2; intercept = ā − beta×b̄; rSquared = (Σ(a−ā)(b−b̄))^2 ÷ (Σ(a−ā)^2 × Σ(b−b̄)^2)spread s_t = a_t − intercept − beta×b_tDickey-Fuller, no constant: x = s_1…s_(n−1), d_t = s_(t+1) − s_t; gamma = Σx×d ÷ Σx^2se = √(Σ(d − gamma×x)^2 ÷ (n−2) ÷ Σx^2); adfStat = gamma ÷ sear1 = 1 + gamma; if gamma < 0 and |ar1| < 1: halfLifeDays = ln 2 ÷ −ln|ar1| (0 when ar1 = 0); else none |
| Units | Prices in; half-life in rows (days for daily prices). |
| Defaults | lookback none (all rows). At least 6 rows; lookback 6 to 1000000. |
| Worked example | a = 25.5, 26.6, 29.3, 26.5, 31.4, 32.7, 31.5, 35.4, 37.3, 34.5, 39.4, 40.7; b = 10, 11, 12, 11, 13, 14, 13, 15, 16, 15, 17, 18; lookback 12 (all rows). beta = 140.4 ÷ 70.25 = 1.999intercept = 32.5667 − beta×13.75 = 5.086Σx×d = −2.95015, Σx^2 = 1.81648, gamma = −1.62410, ar1 = -0.624se = √(1.05582 ÷ 10 ÷ 1.81648) = 0.241090, adfStat = -6.736halfLifeDays = ln 2 ÷ −ln 0.624101 = 1.47 |
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/cointegration-half-life-solver/ to test these two price series for cointegration and give the spread's half-life. 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 cointegration_half_life_solver_check() first, then call cointegration_half_life_solver() with your numbers. Give the answer with the cite line.
"""Cointegration half-life: Engle-Granger two-step test on two price series. Regresses a on b by
least squares, runs the Dickey-Fuller test on the residual spread, and gives the spread's
mean-reversion half-life from its AR(1) coefficient.
Inputs: a, b (lists of prices, oldest first, same length, at least 6), lookback (optional:
use only the last N rows, 6 to 1000000; default all rows).
Returns: beta, intercept, rSquared, observations, ar1, adfStat, halfLifeDays (None when the
spread does not revert).
mysi, Cointegration half-life, mysi.dev/cointegration-half-life-solver, version 1,
changed 2026-12-04. MIT.
"""
import math
def _cointegration_half_life_solver_series(name, xs):
if not isinstance(xs, list) or len(xs) < 6 or not all(
isinstance(x, (int, float)) and not isinstance(x, bool) and math.isfinite(x)
for x in xs):
raise ValueError(f"{name} must be a list of at least 6 numbers")
return [float(x) for x in xs]
def cointegration_half_life_solver(a, b, lookback=None):
a = _cointegration_half_life_solver_series("a", a)
b = _cointegration_half_life_solver_series("b", b)
if len(a) != len(b):
raise ValueError("a and b must be lists of the same length")
if lookback is not None:
if isinstance(lookback, bool) or not isinstance(lookback, int) or not \
6 <= lookback <= 1000000:
raise ValueError("lookback must be a whole number of rows from 6 to 1000000")
a, b = a[-lookback:], b[-lookback:]
n = len(a)
ma, mb = sum(a) / n, sum(b) / n
sab = sum((x - ma) * (y - mb) for x, y in zip(a, b))
sbb = sum((y - mb) ** 2 for y in b)
saa = sum((x - ma) ** 2 for x in a)
beta = sab / sbb if sbb else 0.0
intercept = ma - beta * mb
r2 = sab * sab / (saa * sbb) if saa and sbb else 0.0
s = [x - intercept - beta * y for x, y in zip(a, b)] # the spread
lag, ds = s[:-1], [s[i + 1] - s[i] for i in range(n - 1)]
sxx = sum(x * x for x in lag)
gamma = sum(x * d for x, d in zip(lag, ds)) / sxx if sxx else 0.0 # ds = gamma x lag
sse = sum((d - gamma * x) ** 2 for x, d in zip(lag, ds))
se = math.sqrt(sse / (n - 2) / sxx) if sxx else math.inf
adf = gamma / se if se else 0.0 # Dickey-Fuller t
phi = 1 + gamma
if gamma >= 0 or abs(phi) >= 1:
half_life = None
elif phi == 0:
half_life = 0.0 # the gap closes in one row
else:
half_life = math.log(2) / -math.log(abs(phi))
return {
"beta": beta, "intercept": intercept, "rSquared": r2, "observations": n,
"ar1": phi, "adfStat": adf, "halfLifeDays": half_life,
}
_COINTEGRATION_HALF_LIFE_SOLVER_A = [25.5, 26.6, 29.3, 26.5, 31.4, 32.7,
31.5, 35.4, 37.3, 34.5, 39.4, 40.7]
_COINTEGRATION_HALF_LIFE_SOLVER_B = [10, 11, 12, 11, 13, 14, 13, 15, 16, 15, 17, 18]
COINTEGRATION_HALF_LIFE_SOLVER_CASES = [
({"a": _COINTEGRATION_HALF_LIFE_SOLVER_A, "b": _COINTEGRATION_HALF_LIFE_SOLVER_B,
"lookback": 12}, {"beta": 1.99858, "adfStat": -6.73648, "halfLifeDays": 1.47027}),
({"a": [3, 5, 7, 9, 11, 13], "b": [1, 2, 3, 4, 5, 6]}, {"beta": 2.0, "intercept": 1.0}),
({"a": [10, 12, 9, 11, 10, 8], "b": [5, 5, 5, 5, 5, 5]},
{"ar1": -0.5, "adfStat": -2.52051, "halfLifeDays": 1.0}),
]
def cointegration_half_life_solver_check(tolerance=1e-3):
for given, want in COINTEGRATION_HALF_LIFE_SOLVER_CASES:
got = cointegration_half_life_solver(**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
cointegration_half_life_solver_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(cointegration_half_life_solver(**given))) A statistical test on past prices, not a trading recommendation.
What it takes
| Input | Meaning | Default | Allowed |
|---|---|---|---|
| a | Prices of asset A, oldest first, at least 6 numbers; the dependent leg | required | a list |
| b | Prices of asset B, same length as a; the hedge leg | required | a list |
| lookback | Use only the most recent N rows; leave it out to use all rows | required | 6 to 1,000,000 |
What it returns
| Output | Meaning |
|---|---|
| beta, intercept, rSquared | The regression a = intercept + beta × b + spread; beta is the hedge ratio (units of b per unit of a) |
| observations | Rows used |
| ar1 | AR(1) coefficient of the spread, 1 + gamma |
| adfStat | Dickey-Fuller t-statistic on the spread; more negative is stronger evidence |
| halfLifeDays | Rows for a gap in the spread to halve; null when the spread does not revert |
Where the method comes from
Engle and Granger (1987) test whether two price series are cointegrated in two steps: regress one on the other by least squares, then test the residual spread for a unit root. The unit-root test here is the Dickey-Fuller regression of the spread's change on its previous level, without a constant or lags (Dickey and Fuller 1979). Because the hedge ratio was estimated first, the statistic is read against the Engle-Granger critical values for two variables with a constant, not the plain Dickey-Fuller ones: MacKinnon (2010, Table 2) gives them for T = n − 1 rows as −3.89644 − 10.9519/T − 22.527/T² (1%), −3.33613 − 6.1101/T − 6.823/T² (5%) and −3.04445 − 4.2412/T − 2.720/T² (10%). This function returns the statistic, not a verdict.
The half-life is the exact AR(1) mapping: a gap shrinks by the factor |ar1| each row, so it halves after ln 2 ÷ −ln|ar1| rows. With few rows the test has little power; MacKinnon's response surfaces were fitted from 20 rows up. Inputs are price levels, not returns.
Sources
- Engle and Granger, Co-integration and error correction: representation, estimation, and testing, Econometrica 55(2)published 1987
- Dickey and Fuller, Distribution of the estimators for autoregressive time series with a unit root, Journal of the American Statistical Association 74(366)published 1979
- 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 2 of 3 with it; claude-fable-5-2 was right on 0 of 3 questions without this page and 3 of 3 with it.
Changes
- Moved from aifinhub.io as Python. Answers unchanged for price series. Dropped the approximate p-value (interpolated through anchor points with no source), the meanReverting verdict (it compared adfStat with the large-sample 10% value at any sample size, not MacKinnon's value for the rows given), theta (it used an unpublished floor when ar1 is 0), the fixed critical-value table, the spread series, and the guess that a series near zero is returns (now always read as prices). The minimum is 6 rows instead of 30.4 Dec 2026
Cite as: mysi, Cointegration half-life, mysi.dev/cointegration-half-life-solver, version 1, changed 2026-12-04. Code MIT.