Ornstein-Uhlenbeck Half-Life: Measuring Mean-Reversion Speed for Spreads in Python

Ornstein-Uhlenbeck Half-Life: Measuring Mean-Reversion Speed for Spreads in Python

The Ornstein-Uhlenbeck process models a variable pulled toward a long-run mean at speed theta, with noise pushing it away. Its half-life is the time for a deviation from that mean to decay to half its size. It turns the vague question “how fast does this spread mean-revert?” into one number computed from a single regression.

The process is named for Uhlenbeck and Ornstein (1930), “On the Theory of the Brownian Motion,” Physical Review 36, 823.

Two things the half-life is not, and one thing it is:

  • It is: a time scale — the expected number of bars for a deviation to shrink by half.
  • It is not: a claim that reversion is tradeable.
  • It is not: a forecast of profit. Costs, borrow availability, and relationship stability sit outside the model entirely.

Why Half-Life Matters for Pairs and Spread Trading

A mean-reversion strategy needs a window length. The OU half-life gives a data-driven estimate of the reversion time scale instead of an arbitrary constant. For the statistical-arbitrage setting in which such spreads are traded, see Avellaneda and Lee (2010), who study model-driven statistical arbitrage in US equities (also indexed on IDEAS/RePEc).

Every z-score or Bollinger-style spread trader eventually picks a lookback: 20 bars, 50 bars, 100 bars. That choice encodes an implicit belief about reversion speed. If the window is far longer than the true half-life, the estimated mean is stale and signals blur. If it is far shorter, the mean tracks noise.

The half-life converts a modeling assumption into an estimate. Given the spread series, one regression gives the characteristic decay time. A common rule of thumb, not an empirical result from the sources here, is to size the window at one to two half-lives. For how the spread itself is formed before any of this applies, see pairs trading cointegration methodology.

The OU Model and Its Exact Discretization

The continuous-time OU stochastic differential equation is dX = theta(mu - X)dt + sigma dW, where theta is the reversion speed, mu the long-run mean, and sigma the volatility of the driving noise. Its exact solution over a step dt gives the discrete form used in estimation:

  • OU SDE: dX = theta(mu - X)dt + sigma dW
  • Exact discretization: y_t = mu(1 - e^{-theta dt}) + e^{-theta dt} y_{t-1} + eta_t
  • Estimating regression: dy_t = a + b*y_{t-1} + e_t, with dy_t = y_t - y_{t-1}
  • Coefficient mapping: b = e^{-theta dt} - 1
  • Solve for theta: theta = -ln(1 + b)/dt
  • Half-life: ln(2)/theta = -dt*ln(2)/ln(1 + b)

The key structural fact is the lag-1 coefficient. In the exact discretization it equals e^{-theta dt}, which is strictly positive and strictly less than one whenever theta is positive. Subtract one and you get b, the slope of a simple OLS regression. That is the bridge between the textbook SDE and a few lines of Python. The ln and exp operations are standard numpy.log calls.

The Regression That Estimates It

Regress the spread’s first difference on its own lagged level: dy_t = a + b*y_{t-1} + e_t, estimated by ordinary least squares. Because b = e^{-theta dt} - 1, solving yields theta = -ln(1+b)/dt and half-life = -dt*ln(2)/ln(1+b). One regression, two lines of algebra, one interpretable time scale.

The regression must include a constant explicitly. The statsmodels OLS documentation states that “no constant is added by the model unless you are using formulas,” so you call statsmodels.tools.add_constant yourself. Omitting the constant forces the fit through the origin, which distorts the slope estimate and therefore the half-life.

There is an algebraically identical alternative: regress the level on its lag, y_t = c + phi*y_{t-1} + e_t, where phi = 1 + b. The half-life in periods is then -ln(2)/ln(phi). Both forms give the same estimate; the difference form is convenient because the slope is directly the quantity you transform.

dy on y_{t-1} (b) y_t on y_{t-1} (phi)
Regression dy_t = a + b·y_{t-1} + e_t y_t = c + phi·y_{t-1} + e_t
Relation b = phi − 1 phi = 1 + b
Half-life -dt·ln(2)/ln(1+b) -ln(2)/ln(phi)
Equivalent? Yes — identical estimate Yes

As a diagnostic after fitting, you can inspect residual autocorrelation with statsmodels acf to check whether the AR(1) specification is adequate.

The Validity Condition: Why -1 < b < 0 Is Non-Negotiable

The half-life formula is defined only for -1 < b < 0. If b >= 0, the regression found no pull toward the mean, and any half-life you print is meaningless. If b <= -1, the log argument breaks and the fit is not a plausible OU model.

Treat this as a hard check, not a preference. The mapping b = e^{-theta dt} - 1 implies that a positive theta corresponds exactly to b in the open interval (-1, 0). Outside it, there is no theta to invert, so the correct behavior is to return “undefined” rather than a number. For a broader view of spreads that fail to be stationary, see fractional differentiation in Python.

In practice, a b estimate close to zero, such as -0.002, is formally valid but produces a half-life of about 346 bars, longer than most plausible holding periods. The formula still works; the interpretation does not. Validity is a floor, not a guarantee of usefulness.

Full Python Implementation: Half-Life With an ADF Diagnostic

The complete workflow: form the spread, run the Augmented Dickey-Fuller test as a diagnostic, run the OLS regression of dy on lagged y with an explicit constant, extract b, and convert to half-life. The adfuller signature is adfuller(x, maxlag=None, regression='c', autolag='AIC'), and its null hypothesis is a unit root. A p-value above your threshold means you cannot reject it, so the spread is not convincingly stationary and the half-life estimate is unreliable. The function returns the p-value; the threshold is your decision. Lagged levels are built with pandas Series.shift. The library is statsmodels.

import numpy as np
import pandas as pd
import statsmodels.api as sm
from statsmodels.tsa.stattools import adfuller

def ou_half_life(spread: pd.Series) -> dict:
    """Estimate OU half-life from a price spread.

    Regresses dy_t on y_{t-1}:  dy_t = a + b*y_{t-1} + e_t
    b = exp(-theta*dt) - 1  =>  theta = -log(1+b)/dt
    half-life = ln(2)/theta
    Returns dict with regression coefficient b, theta,
    half_life (in bars of the input series), and validity flag.
    """
    y = np.asarray(spread, dtype=float)
    if len(y) < 20:
        raise ValueError("Spread too short for a meaningful AR(1) estimate.")

    # Step 1: unit-root diagnostic on the level of the spread.
    # Null hypothesis = unit root; p above threshold => cannot reject.
    adf = adfuller(y, maxlag=None, regression="c", autolag="AIC", result_object=True)  # statsmodels 0.15+
    adf_pvalue = adf.pvalue

    # Step 2: dy_t = y_t - y_{t-1};  y_{t-1} = lagged level.
    y_lag = pd.Series(y).shift(1).dropna()   # y_{t-1}
    dy = np.diff(y)                            # dy_t

    # Step 3: OLS with an EXPLICIT constant.
    # statsmodels OLS adds no constant unless you use formulas,
    # so we must call sm.add_constant ourselves.
    X = sm.add_constant(y_lag.values)          # [1, y_{t-1}]
    model = sm.OLS(dy, X).fit()
    b = model.params[1]                         # coefficient on y_{t-1}

    # Step 4: validity check — only -1 < b < 0 implies mean reversion.
    if not (-1.0 < b < 0.0):
        return {
            "adf_pvalue": adf_pvalue,
            "b": b,
            "theta": None,
            "half_life": None,
            "valid": False,
            "note": "b outside (-1, 0): no estimated mean reversion; "
                    "half-life undefined.",
        }

    # Step 5: b -> theta -> half-life (dt = 1 bar).
    theta = -np.log(1.0 + b) / 1.0
    half_life = np.log(2.0) / theta

    return {
        "adf_pvalue": adf_pvalue,
        "b": b,
        "theta": theta,
        "half_life": half_life,   # in bars of the input frequency
        "valid": True,
    }

Each step maps to the derivation above. Step 2 builds dy_t and y_{t-1} for the estimating regression. Step 3 is the OLS fit whose slope is b = e^{-theta dt} - 1. Step 4 enforces the validity condition. Step 5 inverts: theta = -ln(1+b)/dt via numpy.log, then half-life = ln(2)/theta.

Note the dt = 1.0 in Step 5. Because the step size is one bar, the half-life comes out in the units of the input series: daily bars give days, hourly bars give hours. If your sampling is irregular, resample to a fixed grid before calling this, since the discretization assumes constant dt. For an estimator that solves the same OLS problem without the statsmodels API, numpy.linalg.lstsq works directly.

Worked Example: Two Regressions, Two Half-Lives

With b = -0.05 per daily bar: 1 + b = 0.95, so theta = -ln(0.95) = 0.05129 per day, and half-life = 0.6931 / 0.05129 = 13.51 days. With b = -0.01: 1 + b = 0.99, so theta = -ln(0.99) = 0.01005 per day, and half-life = 0.6931 / 0.01005 = 68.97 days. These are deterministic arithmetic examples, not market data.

Case b (per daily bar) 1 + b theta = −ln(1+b) Half-life = ln(2)/theta
1 −0.05 0.95 0.05129 / day 13.51 days
2 −0.01 0.99 0.01005 / day 68.97 days

The comparison carries the main lesson. Weakening b five-fold, from -0.05 to -0.01, stretches the half-life about five-fold. For small |b| the half-life is approximately ln(2)/|b|, so it scales inversely with the slope. As b approaches zero, the half-life diverges. That divergence is why the validity check matters: near-zero b estimates are fragile, and a small change in b matters: b = -0.010 gives 68.97 days, while b = -0.012 gives about 57.4 days.

Short histories make this worse. The Dickey-Fuller estimator of the AR(1) coefficient is downward biased in finite samples near a unit root, so short samples misstate the half-life in a known direction. To see how OU paths behave under known parameters before trusting an estimate, the Monte Carlo simulation methodology guide covers simulating mean-reverting paths.

Choosing Your Window: OU Half-Life vs. Fixed Z-Score Lookback

Set the lookback from the estimated half-life, using the one-to-two-half-life rule of thumb, rather than a fixed constant. The estimate itself carries risk the naive constant does not. The table compares the two approaches; spread formation is assumed handled upstream, as in the statsmodels coint test.

Dimension Fixed z-score lookback (naive) OU half-life-derived window
How the window is set Arbitrary constant (e.g. 20 or 50 bars) Estimated from the spread itself
Adaptation to reversion speed None — same window for all spreads Scales with measured reversion speed
Estimation risk None (no estimation) AR(1) coefficient biased in short samples near a unit root
Failure mode Window mismatched to true speed Regime change invalidates the estimate
Risk-adjusted result in arXiv 2412.12458 (pairs trading, preliminary) Naive rolling window: stronger risk-adjusted result OU model: underperformed on a risk-adjusted basis (preliminary findings)

The honest reading of the last row is that a better parameterization is not the same as better returns. The half-life is a principled way to pick a number; it is not evidence that the resulting strategy makes money.

The Honest Counterpoint: OU Underperformed Naive on a Risk-Adjusted Basis

A December 2024 arXiv preprint, a preliminary analysis of the Ornstein-Uhlenbeck process applied to pairs trading, reports findings suggesting that the OU model captures signals and trends effectively but underperforms the naive rolling-window model on a risk-adjusted basis. That is a direct empirical caution against treating an OU-derived parameter as an edge: it is a modeling tool, not a proven alpha source.

This qualification is worth stating plainly because the technique is easy to oversell. An Application of the Ornstein-Uhlenbeck Process to Pairs Trading reports, as preliminary findings, that the simpler approach held up better on a risk-adjusted basis in its setup, even though the OU framework tracked signals and trends well. Nothing in the mathematics above contradicts that: the math describes a time scale, and time scales are not returns.

The practical takeaway is narrow and useful: use the half-life to size windows and to check whether a candidate spread reverts on a horizon you can actually trade. Do not use it, on its own, to argue that a pair is worth trading.

Estimation Pitfalls: Bias, Drift, and What Half-Life Is Not

Three cautions carry most of the risk. First, finite-sample bias: the Dickey-Fuller estimator of the AR(1) coefficient is downward biased near a unit root, so short histories misstate the half-life. Second, drift: cointegration relationships move, and a half-life estimated on one window may not describe the next. Third, scope: a half-life is a descriptive time scale, not a trading signal. Costs, borrow, and relationship stability decide tradeability.

Re-estimation cadence is where drift becomes an operational question. Re-fitting on a rolling or expanding window, and validating the strategy as the walk-forward analysis methodology guide describes, keeps the estimate tied to the current regime. Evaluation hygiene matters too: parameter selection done inside a backtest without purged k-fold cross-validation leaks information and makes any window-sizing improvement look better than it is.

One further scope limit: the OU model assumes constant theta. If reversion speed itself is stochastic or state-dependent, a single half-life averages across regimes and may describe none of them accurately.

FAQ

What does it mean if b comes out positive or zero?

b >= 0 means the regression found no pull toward the mean. The spread behaves like a random walk or worse, and the half-life formula does not apply. Do not force a number out of it. Treat the pair as non-stationary and re-test the cointegration relationship before proceeding.

Should I run ADF before or after estimating the half-life?

Run it first, as a diagnostic. Its null hypothesis is a unit root; a p-value above your threshold means you cannot reject it, so the spread is not convincingly stationary and the half-life estimate is unreliable. Rejecting the unit root does not prove an OU model; failure to reject is a clear warning sign.

Can I use half-life to decide when to exit a trade?

Not by itself. A half-life is a descriptive time scale, the expected time for a deviation to halve, not a trading signal. Costs, borrow availability, cointegration drift, and regime change decide tradeability, and the arXiv preprint suggests, on preliminary findings, that OU-based modeling underperforms a naive rolling window on a risk-adjusted basis.

The Bottom Line

The OU half-life is worth computing because it replaces an arbitrary lookback with an estimated one, using one regression and two lines of algebra: b → theta → ln(2)/theta, valid only when -1 < b < 0. But it is a descriptive statistic, not an edge. It tells you the time scale of reversion, not whether trading that reversion is profitable after costs. The one empirical study of OU in pairs trading cited here, a preliminary preprint, suggests it underperforms a naive rolling window on a risk-adjusted basis. Use it to size windows, not to place trades. Nothing here is financial advice.

How This Guide Was Built

Research date: 2026-10-18. Sources fetched and verified: the statsmodels adfuller and OLS documentation pages. The abstract of arXiv 2412.12458 was read from a search snippet and is truncated before its full risk-adjusted wording. Avellaneda and Lee (2010) was located via Taylor & Francis and IDEAS/RePEc search results; its content beyond the title and abstract was not read. The Uhlenbeck-Ornstein 1930 Physical Review page was not fetchable (antibot-blocked), so the DOI is cited without a fetched confirmation. The Dickey-Fuller small-sample bias is a standard econometric result stated here without a primary link. The worked numbers are deterministic arithmetic, not market data.

This guide is based on official documentation, the cited papers, and a worked calculation — we did not run the method on live trading data.

← Back to all posts