LIVE
connecting to the live quote stream…
--:--:--UTC
mediumQuant○
#17

Half-life of mean reversion

mediumQuantacceptance —~25 min

Implement half_life(spread) — the mean-reversion half-life of a spread series. Regress Δs_t = s_t - s_{t-1} on s_{t-1} with an intercept by ordinary least squares to get the slope b. If b < 0 the spread reverts and the half-life is -ln(2) / ln(1 + b); if b >= 0 it does not revert, and there is no half-life — return None.

Half-life tells a pairs trader how long a divergence should take to close. Return it rounded to 4 decimal places.

example 1
input
spread=[1.0, 0.6, 0.3, 0.2, 0.1, 0.05, 0.02]
output
1.3207
example 2
input
spread=[1.0, 1.1, 1.25, 1.4, 1.6, 1.85]
output
None
note

A diverging spread — no half-life.

constraints
  • 4 ≤ len(spread) ≤ 5_000
  • spread is not constant
teacher · 2 hints · the first is free
↗ read the theory
the chapter this problem is cut from
▶ open in the workbench
run the same math on a real tape
●solution.py· utf-8 · spaces:4
ln 1, col 1tab indent · esc leave editor
python 3.13 · pyodide
+ 6 hidden on submit
input · keyword arguments to half_life()
spread=[1.0, 0.6, 0.3, 0.2, 0.1, 0.05, 0.02]
expected
1.3207

the judge calls half_life() with exactly these inputs · outputs are compared to 6 decimal places

● standing bypython 3.13 in your browser · pyodide 0.28.3 · judged on the server to 6 dp⌘↵ run · ⌘⇧↵ submit
paper only · educational · not advice