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.
Blend yesterday’s estimate with today’s evidence
At the start of each day you have an estimate 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 .
You see a new observation. Today’s prices give , which on its own says β ≈ , with variance . You now have two independent, unbiased estimates of the same thing: the old one with variance , and the new one with variance . The best way to combine two such estimates is to weight each by the inverse of its variance:
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 , P becomes a 2×2 matrix and becomes . The steps are the same with matrices in place of numbers.
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.
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.
It’s an EWMA whose memory you don’t pick by hand
When is roughly constant, the gain settles to a steady value . The update is then an exponentially weighted moving average of the daily ratios , with weight on the newest one. Writing (signal-to-noise: how much β moves per day compared with how noisy one day’s reading is),
The filter’s memory is about 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 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 with variance . Maximise over Q and R.
- Check the prediction errors. Standardised errors 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 , so it’s large early on, when the filter knows little, and settles later.
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:
LimitsWhat does the gain do if R → 0? If R → ∞?Show answer
R → 0: the observation is perfect, , and . 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 . Each step the gain is 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
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 and , the update gives , so , hence . Also from the definition of k. Equating: , so .
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.