Skip to content
LeetQuant
E07 Advanced Time Series

E07 · Advanced Time Series · Lesson 2 of 4

The Kalman Filter

The predict and update equations derived from normal conditioning for the local level model, the Kalman gain as a signal-to-noise weight, the steady-state gain and its link to exponential smoothing, the likelihood, a runnable filter checked against statsmodels, and smoothing in brief.

18 min

Objective

Given a state-space model and data up to time tt, compute the distribution of the hidden state: αt∣y1,…,yt∼N(at∣t,Pt∣t)\alpha_t \mid y_1, \dots, y_t \sim N(a_{t|t}, P_{t|t}). In a linear Gaussian model this distribution is exactly normal, and the Kalman filter updates its mean and variance one observation at a time. You should be able to derive the scalar version from scratch, explain the gain, and know what the filter gives you beyond the state estimate.

Intuition

Each period you hold a belief about the state. Two things happen:

  1. Predict. Time passes; the state evolves and picks up noise. Your belief moves according to the state equation and becomes less certain.
  2. Update. A noisy observation arrives. You move your belief towards it by a fraction KK that depends on how uncertain you are relative to how noisy the measurement is, and your belief becomes more certain.

It is the "best guess from a noisy signal" calculation, repeated, with yesterday's posterior as today's prior.

Derivation for the local level model

Model: yt=μt+εty_t = \mu_t + \varepsilon_t, εt∼N(0,r)\varepsilon_t \sim N(0, r), and μt=μt−1+ηt\mu_t = \mu_{t-1} + \eta_t, ηt∼N(0,q)\eta_t \sim N(0, q). Suppose μt−1∣Ft−1∼N(at−1∣t−1,Pt−1∣t−1)\mu_{t-1} \mid \mathcal F_{t-1} \sim N(a_{t-1|t-1}, P_{t-1|t-1}).

Predict. Adding independent noise ηt\eta_t:

at∣t−1=at−1∣t−1,Pt∣t−1=Pt−1∣t−1+q.a_{t|t-1} = a_{t-1|t-1}, \qquad P_{t|t-1} = P_{t-1|t-1} + q .

Joint distribution with the new observation. Given Ft−1\mathcal F_{t-1}, (μt,yt)(\mu_t, y_t) is bivariate normal with

E[yt]=at∣t−1,Var⁡(yt)=Ft=Pt∣t−1+r,Cov⁡(μt,yt)=Pt∣t−1.\mathbb E[y_t] = a_{t|t-1}, \quad \operatorname{Var}(y_t) = F_t = P_{t|t-1} + r, \quad \operatorname{Cov}(\mu_t, y_t) = P_{t|t-1} .

Update by normal conditioning (E[X∣Y]=EX+Cov⁡(X,Y)Var⁡Y(Y−EY)\mathbb E[X \mid Y] = \mathbb E X + \frac{\operatorname{Cov}(X,Y)}{\operatorname{Var} Y}(Y - \mathbb E Y), and Var⁡(X∣Y)=Var⁡X−Cov⁡2/Var⁡Y\operatorname{Var}(X \mid Y) = \operatorname{Var} X - \operatorname{Cov}^2/\operatorname{Var} Y). Define the innovation vt=yt−at∣t−1v_t = y_t - a_{t|t-1} and the gain Kt=Pt∣t−1/FtK_t = P_{t|t-1}/F_t:

at∣t=at∣t−1+Ktvt,Pt∣t=(1−Kt) Pt∣t−1=Pt∣t−1 rPt∣t−1+r.a_{t|t} = a_{t|t-1} + K_t v_t, \qquad P_{t|t} = (1 - K_t)\,P_{t|t-1} = \frac{P_{t|t-1}\,r}{P_{t|t-1} + r} .

Equivalently, precisions add: 1/Pt∣t=1/Pt∣t−1+1/r1/P_{t|t} = 1/P_{t|t-1} + 1/r, and at∣ta_{t|t} is the precision-weighted average of the prediction and the observation.

The gain

Kt=Pt∣t−1/(Pt∣t−1+r)∈[0,1]K_t = P_{t|t-1}/(P_{t|t-1} + r) \in [0, 1] is the share of the surprise you believe is signal.

  • Noisy measurements (rr large): K→0K \to 0, ignore the data, keep the prediction.
  • Fast-moving state (qq large, so Pt∣t−1P_{t|t-1} large): K→1K \to 1, trust the latest observation.
  • The gain is not a function of the data. PtP_t and KtK_t follow a deterministic recursion, so they can be computed in advance.

The general filter

For αt=c+Tαt−1+Rηt\alpha_t = c + T\alpha_{t-1} + R\eta_t, yt=d+Ztαt+εty_t = d + Z_t\alpha_t + \varepsilon_t, the same argument with matrices gives:

predict:at∣t−1=c+Tat−1∣t−1,Pt∣t−1=TPt−1∣t−1T′+RQR′,innovation:vt=yt−d−Ztat∣t−1,Ft=ZtPt∣t−1Zt′+H,update:Kt=Pt∣t−1Zt′Ft−1,at∣t=at∣t−1+Ktvt,Pt∣t=(I−KtZt)Pt∣t−1.\begin{aligned} \text{predict:}\quad & a_{t|t-1} = c + T a_{t-1|t-1}, \qquad P_{t|t-1} = T P_{t-1|t-1} T' + RQR', \\ \text{innovation:}\quad & v_t = y_t - d - Z_t a_{t|t-1}, \qquad F_t = Z_t P_{t|t-1} Z_t' + H, \\ \text{update:}\quad & K_t = P_{t|t-1} Z_t' F_t^{-1}, \quad a_{t|t} = a_{t|t-1} + K_t v_t, \quad P_{t|t} = (I - K_t Z_t) P_{t|t-1} . \end{aligned}

The likelihood comes free. Innovations are independent N(0,Ft)N(0, F_t) under the model (the prediction-error decomposition), so

log⁡L=−12∑t(plog⁡2π+log⁡∣Ft∣+vt′Ft−1vt).\log L = -\tfrac12 \sum_t \Big( p\log 2\pi + \log|F_t| + v_t' F_t^{-1} v_t \Big) .

Maximise it over the unknowns (qq, rr, entries of TT) to estimate the model. The same property gives the main diagnostic: standardised innovations vt/Ftv_t/\sqrt{F_t} should be serially uncorrelated with unit variance. Autocorrelated innovations mean the dynamics are wrong; variance above 1 means qq or rr is too small.

Initialisation. Stationary states start at their unconditional mean and Lyapunov covariance. Non-stationary states (random walks) need a diffuse prior: a huge P0P_{0} (approximate) or the exact diffuse treatment in statsmodels. Either way, leave the first observation(s) out of the likelihood; their innovation variance is essentially infinite.

Worked example

three steps by hand

Local level with q=1q = 1, r=4r = 4. After a diffuse start and a first observation of 1010, the filtered estimate is a=10a = 10 with P=4P = 4 (a diffuse prior updated with one observation has P=rP = r). The next three observations are 12,9,1312, 9, 13. Run the filter.

Show solution

Each step: Ppred=P+1P_{\text{pred}} = P + 1, F=Ppred+4F = P_{\text{pred}} + 4, K=Ppred/FK = P_{\text{pred}}/F, a←a+K(y−a)a \leftarrow a + K(y - a), P←(1−K)PpredP \leftarrow (1 - K)P_{\text{pred}}.

ttyty_tat∣t−1a_{t\mid t-1}Pt∣t−1P_{t\mid t-1}vtv_tKtK_tat∣ta_{t\mid t}Pt∣tP_{t\mid t}
11210.0005.0002.0005/9 = 0.55611.1112.222
2911.1113.222−2.1110.44610.1691.785
31310.1692.7852.8310.41011.3311.642

Step 1 in detail: K=5/9K = 5/9, a=10+(5/9)(2)=11.111a = 10 + (5/9)(2) = 11.111, P=(4/9)(5)=20/9P = (4/9)(5) = 20/9.

Two things to notice. The gain falls (0.556, 0.446, 0.410) because uncertainty about the level shrinks as data accumulate. It does not fall to zero, because the level keeps moving: each prediction step adds q=1q = 1 back. That balance is the steady state.

Worked example

the steady-state gain is exponential smoothing

For the same model (q=1q = 1, r=4r = 4), find the steady-state predicted variance, gain and innovation variance. What smoothing rule does the filter converge to, and what is its half-life?

Show solution

In steady state Pt∣t−1=PP_{t|t-1} = P is constant. Combine the two recursions: P=PrP+r+qP = \dfrac{Pr}{P + r} + q, i.e. P2/(P+r)=qP^2/(P + r) = q, so

P2−qP−qr=0⇒P=q+q2+4qr2=1+172≈2.562.P^2 - qP - qr = 0 \quad\Rightarrow\quad P = \frac{q + \sqrt{q^2 + 4qr}}{2} = \frac{1 + \sqrt{17}}{2} \approx 2.562 .

Then K=P/(P+r)=2.562/6.562≈0.390K = P/(P + r) = 2.562/6.562 \approx 0.390 and F=6.562F = 6.562. In terms of the signal-to-noise ratio s=q/rs = q/r, K=( ⁣−s+s2+4s)/2K = \big(\!-s + \sqrt{s^2 + 4s}\big)/2; here s=0.25s = 0.25.

The update becomes at=(1−K)at−1+Kyta_t = (1 - K)a_{t-1} + K y_t: an exponentially weighted moving average with weight 0.3900.390 on the newest point, decay 0.6100.610 and half-life ln⁡0.5/ln⁡0.610≈1.4\ln 0.5/\ln 0.610 \approx 1.4 observations. These match the previous lesson's ARIMA(0,1,1) result exactly: K=1+θK = 1 + \theta with θ=−0.610\theta = -0.610, and FF equals the ARIMA innovation variance 6.566.56.

This is the key interview insight: exponential smoothing is the optimal filter for a random walk observed with noise, and the smoothing weight is not a free tuning knob; it is pinned down by q/rq/r, which can be estimated. The filtered variance in steady state is P−q=1.562P - q = 1.562, a standard error of 1.251.25 against 22 for a raw observation.

A runnable filter

The filter below tracks a simulated random-walk level observed with noise, using the true qq and rr, then checks itself against statsmodels and estimates qq and rr by maximum likelihood.

import numpy as np

def local_level_filter(y, q, r, a0=0.0, p0=1e7):
    """Kalman filter for y_t = mu_t + eps_t, mu_t = mu_{t-1} + eta_t."""
    a, p = a0, p0                      # filtered mean and variance at t = 0
    filt, gains, loglik = [], [], 0.0
    for t, yt in enumerate(y):
        a_pred, p_pred = a, p + q      # predict
        v, f = yt - a_pred, p_pred + r # innovation and its variance
        k = p_pred / f                 # Kalman gain
        a, p = a_pred + k * v, (1 - k) * p_pred   # update
        if t > 0:                      # skip the diffuse first step
            loglik += -0.5 * (np.log(2 * np.pi * f) + v**2 / f)
        filt.append(a)
        gains.append(k)
    return np.array(filt), np.array(gains), loglik

rng = np.random.default_rng(0)
n, q, r = 500, 1.0, 4.0
mu = np.cumsum(rng.normal(0, np.sqrt(q), n))   # true level (random walk)
y = mu + rng.normal(0, np.sqrt(r), n)          # noisy observations

filt, gains, ll = local_level_filter(y, q, r)
print("gains:", np.round(gains[:5], 3), "->", round(gains[-1], 4))
print("RMSE raw obs:", round(np.sqrt(np.mean((y - mu) ** 2)), 3))
print("RMSE filter: ", round(np.sqrt(np.mean((filt - mu) ** 2)), 3))
print("log-lik:", round(ll, 2))

import statsmodels.api as sm
mod = sm.tsa.UnobservedComponents(y, level="llevel")
same = mod.filter([r, q])          # params: [obs variance r, level variance q]
print("max diff vs statsmodels:", f"{np.max(np.abs(same.filtered_state[0] - filt)):.1e}")
fit = mod.fit(disp=False)          # estimate r and q by maximum likelihood
print("MLE r, q:", np.round(fit.params, 2))
smooth = mod.smooth([r, q]).smoothed_state[0]
print("RMSE smoother:", round(np.sqrt(np.mean((smooth - mu) ** 2)), 3))

Output:

gains: [1.    0.556 0.446 0.41  0.398] -> 0.3904
RMSE raw obs: 1.881
RMSE filter:  1.173
log-lik: -1152.17
max diff vs statsmodels: 9.8e-06
MLE r, q: [3.36 1.08]
RMSE smoother: 0.975

Reading it:

  • The first gain is 1 (the diffuse prior means the first observation is taken at face value), then 0.556,0.446,0.4100.556, 0.446, 0.410, exactly the hand calculation, converging to the steady-state 0.39040.3904.
  • The filter's error (1.171.17) is well below the raw noise (1.881.88 in this sample, 22 in theory) and close to the steady-state standard error of 1.251.25.
  • Our hand-written filter matches statsmodels to 10−510^{-5} (the residual difference is the approximate versus exact diffuse start).
  • Maximum likelihood recovers r≈3.36r \approx 3.36 and q≈1.08q \approx 1.08 from 500 points, against true values 4 and 1. Variance ratios are estimated imprecisely; expect this.

Smoothing in brief

The filter uses data up to tt. The smoother uses the full sample, running backwards after a forward pass (Rauch–Tung–Striebel):

at∣n=at∣t+Jt(at+1∣n−at+1∣t),Jt=Pt∣tT′Pt+1∣t−1,a_{t|n} = a_{t|t} + J_t\big(a_{t+1|n} - a_{t+1|t}\big), \qquad J_t = P_{t|t}T'P_{t+1|t}^{-1},

with Pt∣n=Pt∣t+Jt(Pt+1∣n−Pt+1∣t)Jt′P_{t|n} = P_{t|t} + J_t(P_{t+1|n} - P_{t+1|t})J_t'. Smoothed estimates are more accurate (0.9750.975 against 1.1731.173 above) because they also see what happened next. They are right for estimating the history of a latent quantity (what was the fair value last March?) and wrong for any backtest signal, because they use the future.

Knowledge check

In a local level model the predicted variance is Pt∣t−1=3P_{t|t-1} = 3, the observation noise is r=1r = 1, the prediction is at∣t−1=5a_{t|t-1} = 5, and the observation is yt=9y_t = 9. What are at∣ta_{t|t} and Pt∣tP_{t|t}?

Knowledge check

A local level model has equal state and observation noise, q=rq = r. What is the steady-state Kalman gain?

Knowledge check

You fit a Kalman filter by maximum likelihood. How should you check whether the model is adequate?

Key takeaways

  • Predict: at∣t−1=c+Taa_{t|t-1} = c + Ta, Pt∣t−1=TPT′+RQR′P_{t|t-1} = TPT' + RQR'. Update: v=y−d−Zav = y - d - Za, F=ZPZ′+HF = ZPZ' + H, K=PZ′F−1K = PZ'F^{-1}, a←a+Kva \leftarrow a + Kv, P←(I−KZ)PP \leftarrow (I - KZ)P.
  • The scalar version is just normal conditioning; precisions add and the gain is the share of the surprise that is signal.
  • The gain sequence is deterministic and converges; for the local level model the steady-state filter is an EWMA with weight K=(−s+s2+4s)/2K = (-s + \sqrt{s^2+4s})/2, s=q/rs = q/r.
  • The innovations give the exact likelihood and the main diagnostic.
  • Filtered estimates are real-time; smoothed estimates use the future and belong in historical analysis, not in backtest signals.

Practice problems

Finished reading?

Answer the 3 knowledge checks to complete this lesson (0 done).