Quant techniques · state-space models

A hedge ratio that moves: the Kalman filter in five lines

The hedge ratio between two related stocks drifts. Estimate it with a rolling regression and you have to pick a window: short windows are noisy, long ones lag. The Kalman filter replaces the window with a model. It treats the hedge ratio as a hidden quantity that wanders a little each day, and updates its estimate with each new price by exactly as much as the noise levels justify.

0βt=βt−1+wt,  wt∼N(0,Q)yt=xt βt+vt,  vt∼N(0,R)\beta_t = \beta_{t-1} + w_t,\ \ w_t \sim N(0, Q) \qquad y_t = x_t\,\beta_t + v_t,\ \ v_t \sim N(0, R) The model: β is a random walk you can’t see. You see y and x each day.
1P−=P+QP^- = P + Q Predict: your best guess of β doesn’t change, but you’re less sure of it, because β may have moved.
2K=P−xtxt2P−+RK = \dfrac{P^- x_t}{x_t^2 P^- + R} Kalman gain: how much to trust today’s observation compared with yesterday’s estimate.
3β^←β^+K (yt−xtβ^),P←(1−Kxt) P−\hat\beta \leftarrow \hat\beta + K\,(y_t - x_t\hat\beta), \qquad P \leftarrow (1 - K x_t)\,P^- Update: move towards whatever explains today’s surprise, then shrink the uncertainty.
The idea

Blend yesterday’s estimate with today’s evidence

At the start of each day you have an estimate β^\hat\beta with variance P. Two things happen.

The truth may have moved. In the model, β took a random step with variance Q overnight. Your estimate is still the best guess, but its variance grows to P+QP + Q.

You see a new observation. Today’s prices give yt=xtβt+vty_t = x_t\beta_t + v_t, which on its own says β ≈ yt/xty_t/x_t, with variance R/xt2R/x_t^2. You now have two independent, unbiased estimates of the same thing: the old one with variance P−P^-, and the new one with variance R/xt2R/x_t^2. The best way to combine two such estimates is to weight each by the inverse of its variance:

β^new=β^/P−+(yt/xt) xt2/R1/P−+xt2/R,1Pnew=1P−+xt2R\hat\beta_{\text{new}} = \frac{\hat\beta/P^- + (y_t/x_t)\,x_t^2/R}{1/P^- + x_t^2/R}, \qquad \frac{1}{P_{\text{new}}} = \frac{1}{P^-} + \frac{x_t^2}{R}

Rearranging this gives exactly steps 2 and 3. So the Kalman filter is precision-weighted averaging done once per observation, with the precision of the old estimate decaying by Q each step. For a linear model with Gaussian noise it’s the optimal estimator: no other method using the same data has lower mean squared error.

import numpy as np

def kalman_beta(x, y, Q, R, beta0=0.0, P0=1.0):
    """Track a time-varying slope in y_t = x_t * beta_t + noise. Returns estimates and their s.d."""
    beta, P = beta0, P0
    est, sd = [], []
    for xt, yt in zip(x, y):
        P += Q                                  # predict: beta may have drifted
        K = P * xt / (xt * xt * P + R)          # gain
        beta += K * (yt - xt * beta)            # update with today's surprise
        P *= 1 - K * xt
        est.append(beta)
        sd.append(np.sqrt(P))
    return np.array(est), np.array(sd)

With an intercept as well (a spread level that can move), the state becomes the vector (αt,βt)(\alpha_t, \beta_t), P becomes a 2×2 matrix and xtx_t becomes (1,xt)(1, x_t). The steps are the same with matrices in place of numbers.

See it work

Kalman vs a rolling window

The simulation has 500 days. The true β (black) drifts as a random walk and then jumps by 0.1 on day 300. The Kalman filter (blue) is told the true drift variance Q and the true noise R. Compare it with rolling OLS.

filter's assumed drift Qrolling OLS window
true hedge ratio βtKalman estimate, ±2 s.d. bandrolling OLS
–Kalman: RMS error of β
–rolling OLS: RMS error of β
–Kalman steady-state memory (≈ 1/gain, days)

What to look for:

  • With the right Q, the filter’s error is typically around half that of the best rolling window. A 10-day window is noisy; a 100-day window badly misses the jump.
  • Turn Q down (towards 10⁻³ × truth). The filter thinks β barely moves, so it averages over a very long memory, gets smooth, and takes weeks to catch up with the jump. Its band also gets too narrow: it’s overconfident.
  • Turn Q up. The filter trusts each day’s data too much and gets jittery, like a short rolling window.
  • The ±2 s.d. band widens right after the jump only if Q allows for it. The filter has no special handling for jumps.
Under the hood

It’s an EWMA whose memory you don’t pick by hand

When xtx_t is roughly constant, the gain settles to a steady value K∞xK_\infty x. The update β^←β^+K∞x (yt/x−β^)\hat\beta \leftarrow \hat\beta + K_\infty x\,(y_t/x - \hat\beta) is then an exponentially weighted moving average of the daily ratios yt/xty_t/x_t, with weight k=K∞xk = K_\infty x on the newest one. Writing λ=Q x2/R\lambda = Q\,x^2/R (signal-to-noise: how much β moves per day compared with how noisy one day’s reading is),

k=−λ+λ2+4λ2≈λ(λ small)k = \frac{-\lambda + \sqrt{\lambda^2 + 4\lambda}}{2} \approx \sqrt{\lambda} \quad (\lambda \text{ small})

The filter’s memory is about 1/k1/k days. In the figure, β moves 0.002 a day and one day’s reading has noise about 1/50 = 0.02, so λ = 0.01, k ≈ 0.095 and the memory is about 10.5 days. The filter has worked out the window for you from Q and R. Unlike an EWMA, it also gives an error band, adapts when xtx_t changes size, and generalises to many states.

Choosing Q and R in practice

  • R is the noise in the observation equation: the residual variance of a static regression is a good starting point.
  • Q controls how fast β is allowed to move. It matters more than R, because only the ratio Q/R affects the estimate.
  • Fit them by maximum likelihood. The filter produces one-step-ahead prediction errors et=yt−xtβ^−e_t = y_t - x_t\hat\beta^- with variance Ft=xt2P−+RF_t = x_t^2P^- + R. Maximise −12∑t(log⁡Ft+et2/Ft)-\tfrac12\sum_t \left(\log F_t + e_t^2/F_t\right) over Q and R.
  • Check the prediction errors. Standardised errors et/Fte_t/\sqrt{F_t} should look like white noise with variance 1. If their variance is above 1, the filter is overconfident.

Where people slip in interviews

  • Thinking the Kalman filter is a forecasting model. It’s an estimator of a hidden state. The forecast comes from the state model, which here is “β stays where it is”.
  • Setting Q = 0. Then β is constant, and the filter becomes recursive least squares over all history. It will never adapt.
  • Using future data. The filter is causal, which is why it’s safe in a backtest. The smoother (Rauch–Tung–Striebel), which also uses later data, is not.
  • Confusing the gain with a fixed learning rate. K depends on P and xtx_t, so it’s large early on, when the filter knows little, and settles later.
Practice

Try these before you open the answer

Warm-upYour estimate of β is 1.0 with variance 0.04. A new independent reading says 1.2 with variance 0.01. What is the combined estimate and its variance?
Show answer

Weights are inverse variances, 25 and 100:

β^=25(1.0)+100(1.2)125=1.16,P=1125=0.008\hat\beta = \frac{25(1.0) + 100(1.2)}{125} = 1.16, \qquad P = \frac{1}{125} = 0.008
LimitsWhat does the gain do if R → 0? If R → ∞?
Show answer

R → 0: the observation is perfect, K→1/xtK \to 1/x_t, and β^=yt/xt\hat\beta = y_t/x_t. R → ∞: the observation is useless, K → 0, and the estimate doesn’t move.

Q = 0With Q = 0, a flat prior (P₀ → ∞) and x_t = 1 for every t, what is the Kalman estimate after n observations?
Show answer

The running average of y1,…,yny_1, \dots, y_n. Each step the gain is 1/k1/k at observation k, which is exactly the update of a running mean.

Steady stateA local-level model has λ = Q/R = 0.04 (with x = 1). What is the steady-state gain, and roughly how many days of memory does the filter have?
Show answer
k=−0.04+0.0016+0.162=−0.04+0.4022≈0.181k = \frac{-0.04 + \sqrt{0.0016 + 0.16}}{2} = \frac{-0.04 + 0.402}{2} \approx 0.181

Memory ≈ 1/0.181 ≈ 5.5 days. The approximation √λ = 0.2 is close.

VarianceShow that in steady state with x = 1, the gain satisfies k²/(1 − k) = λ.
Show answer

Steady state means P is the same each step. With P−=P+QP^- = P + Q and k=P−/(P−+R)k = P^-/(P^- + R), the update gives P=(1−k)P−P = (1-k)P^-, so P−=(1−k)P−+QP^- = (1-k)P^- + Q, hence kP−=QkP^- = Q. Also P−=kR/(1−k)P^- = kR/(1-k) from the definition of k. Equating: k2R/(1−k)=Qk^2R/(1-k) = Q, so k2/(1−k)=Q/R=λk^2/(1-k) = Q/R = \lambda.

StretchThe spread y − βx is what you trade. Why might trading on the Kalman spread be safer in a backtest than trading on a spread from a full-sample regression?
Show answer

The full-sample β uses future prices, so the backtested spread is more stationary than anything you could have known at the time. The Kalman β at day t uses data up to t only, so its spread is the one you would actually have traded.

The error comparison comes from 200 simulated 1,000-day paths; the figure simulates its own 500-day path in your browser.