mysi Find

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.

In short

FormulaWith 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
UnitsPrices in; half-life in rows (days for daily prices).
Defaultslookback none (all rows). At least 6 rows; lookback 6 to 1000000.
Worked examplea = 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)))
Raw file

A statistical test on past prices, not a trading recommendation.

What it takes

InputMeaningDefaultAllowed
aPrices of asset A, oldest first, at least 6 numbers; the dependent legrequireda list
bPrices of asset B, same length as a; the hedge legrequireda list
lookbackUse only the most recent N rows; leave it out to use all rowsrequired6 to 1,000,000

What it returns

OutputMeaning
beta, intercept, rSquaredThe regression a = intercept + beta × b + spread; beta is the hedge ratio (units of b per unit of a)
observationsRows used
ar1AR(1) coefficient of the spread, 1 + gamma
adfStatDickey-Fuller t-statistic on the spread; more negative is stronger evidence
halfLifeDaysRows 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

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

Cite as: mysi, Cointegration half-life, mysi.dev/cointegration-half-life-solver, version 1, changed 2026-12-04. Code MIT.