Objective
Given a state-space model and data up to time , compute the distribution of the hidden state: . 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:
- Predict. Time passes; the state evolves and picks up noise. Your belief moves according to the state equation and becomes less certain.
- Update. A noisy observation arrives. You move your belief towards it by a fraction 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: , , and , . Suppose .
Predict. Adding independent noise :
Joint distribution with the new observation. Given , is bivariate normal with
Update by normal conditioning (, and ). Define the innovation and the gain :
Equivalently, precisions add: , and is the precision-weighted average of the prediction and the observation.
The gain
is the share of the surprise you believe is signal.
- Noisy measurements ( large): , ignore the data, keep the prediction.
- Fast-moving state ( large, so large): , trust the latest observation.
- The gain is not a function of the data. and follow a deterministic recursion, so they can be computed in advance.
The general filter
For , , the same argument with matrices gives:
The likelihood comes free. Innovations are independent under the model (the prediction-error decomposition), so
Maximise it over the unknowns (, , entries of ) to estimate the model. The same property gives the main diagnostic: standardised innovations should be serially uncorrelated with unit variance. Autocorrelated innovations mean the dynamics are wrong; variance above 1 means or 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 (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 , . After a diffuse start and a first observation of , the filtered estimate is with (a diffuse prior updated with one observation has ). The next three observations are . Run the filter.
Show solutionHide solution
Each step: , , , , .
| 1 | 12 | 10.000 | 5.000 | 2.000 | 5/9 = 0.556 | 11.111 | 2.222 |
| 2 | 9 | 11.111 | 3.222 | −2.111 | 0.446 | 10.169 | 1.785 |
| 3 | 13 | 10.169 | 2.785 | 2.831 | 0.410 | 11.331 | 1.642 |
Step 1 in detail: , , .
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 back. That balance is the steady state.
Worked example
the steady-state gain is exponential smoothing
For the same model (, ), 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 solutionHide solution
In steady state is constant. Combine the two recursions: , i.e. , so
Then and . In terms of the signal-to-noise ratio , ; here .
The update becomes : an exponentially weighted moving average with weight on the newest point, decay and half-life observations. These match the previous lesson's ARIMA(0,1,1) result exactly: with , and equals the ARIMA innovation variance .
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 , which can be estimated. The filtered variance in steady state is , a standard error of against for a raw observation.
A runnable filter
The filter below tracks a simulated random-walk level observed with noise, using the true and , then checks itself against statsmodels and estimates and 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 , exactly the hand calculation, converging to the steady-state .
- The filter's error () is well below the raw noise ( in this sample, in theory) and close to the steady-state standard error of .
- Our hand-written filter matches statsmodels to (the residual difference is the approximate versus exact diffuse start).
- Maximum likelihood recovers and 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 . The smoother uses the full sample, running backwards after a forward pass (Rauch–Tung–Striebel):
with . Smoothed estimates are more accurate ( against 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 , the observation noise is , the prediction is , and the observation is . What are and ?
Knowledge check
A local level model has equal state and observation noise, . 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: , . Update: , , , , .
- 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 , .
- 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).