"""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)))