# State-Space Models and Kalman Filtering
::: {.hero}
**Part III. Nonstationary and Seasonal Models**
**Chapter goal:** learn how to represent time series through hidden dynamic states and update uncertainty sequentially. We develop linear Gaussian state-space models, Kalman prediction and update equations, local-level and local-linear trend models, missing-data handling, forecasting, smoothing, likelihood evaluation, and connections to modern sequence learning and AI-assisted modeling.
:::
## Learning objectives
After studying this chapter, you should be able to:
1. explain why a hidden-state representation is useful for time series forecasting, filtering, and smoothing;
2. write a linear Gaussian state-space model using observation and state equations;
3. derive the Kalman filter from conditional Gaussian projection formulas;
4. implement the prediction, innovation, Kalman gain, and update steps;
5. interpret the local-level and local-linear trend models;
6. compute forecast distributions and prediction intervals from the filtering recursions;
7. handle missing observations naturally inside a state-space model;
8. distinguish filtering, forecasting, and smoothing;
9. connect ARIMA-type models, dynamic regression, HMMs, RNNs, and attention models through the hidden-state viewpoint;
10. use AI tools to debug recursive algorithms while verifying dimensions, assumptions, and numerical stability manually.
## 10.1 From observed series to hidden dynamic states
Classical ARIMA and SARIMA models describe $X_t$ directly in terms of past observations and past shocks. State-space models introduce an additional layer: an unobserved state vector $\boldsymbol{\alpha}_t$ that evolves over time and generates the observed series.
The basic idea is:
$$
\text{hidden state at time } t \longrightarrow \text{observation at time } t.
$$
For example, suppose the observed series is noisy sales demand. The hidden state might contain:
$$
\boldsymbol{\alpha}_t=
\begin{bmatrix}
\text{current level}\\
\text{current trend}\\
\text{seasonal component}
\end{bmatrix}.
$$
The observed value $y_t$ is noisy, but the hidden state evolves smoothly. The goal is to update our belief about the state as observations arrive.
::: {.callout-note}
## Three related tasks
At time $t$, we distinguish three tasks:
- **Filtering:** estimate $\boldsymbol{\alpha}_t$ using data through time $t$.
- **Forecasting:** estimate future states or observations using data through time $t$.
- **Smoothing:** estimate past states using data from the full sample.
:::
This chapter focuses on linear Gaussian state-space models, where all conditional distributions are Gaussian and the Kalman filter gives exact recursive formulas.
## 10.2 The linear Gaussian state-space model
A standard time-invariant linear Gaussian state-space model is
$$
y_t=\mathbf{F}^\top \boldsymbol{\alpha}_t+v_t,
\qquad v_t\sim N(0,V),
$$
and
$$
\boldsymbol{\alpha}_t=\mathbf{G}\boldsymbol{\alpha}_{t-1}+\mathbf{w}_t,
\qquad \mathbf{w}_t\sim N(\mathbf{0},\mathbf{W}).
$$
Here:
- $y_t\in \mathbb{R}$ is the observed value;
- $\boldsymbol{\alpha}_t\in\mathbb{R}^d$ is the hidden state vector;
- $\mathbf{F}\in\mathbb{R}^d$ maps the state to the observation;
- $\mathbf{G}\in\mathbb{R}^{d\times d}$ evolves the hidden state;
- $V>0$ is the observation-noise variance;
- $\mathbf{W}$ is the state-noise covariance matrix.
More generally, these quantities may vary with time:
$$
y_t=\mathbf{F}_t^\top \boldsymbol{\alpha}_t+v_t,
\qquad v_t\sim N(0,V_t),
$$
$$
\boldsymbol{\alpha}_t=\mathbf{G}_t\boldsymbol{\alpha}_{t-1}+\mathbf{w}_t,
\qquad \mathbf{w}_t\sim N(\mathbf{0},\mathbf{W}_t).
$$
We also need an initial belief:
$$
\boldsymbol{\alpha}_0\mid \mathcal{D}_0\sim N(\mathbf{m}_0,\mathbf{C}_0),
$$
where $\mathcal{D}_t=\{y_1,\ldots,y_t\}$ denotes the observed data through time $t$.
::: {.callout-tip}
## Interpretation
The Kalman filter is a recursive Bayesian update for this model. Before observing $y_t$, we have a predicted distribution for $\boldsymbol{\alpha}_t$. After observing $y_t$, we update the distribution using the prediction error.
:::
## 10.3 Conditional Gaussian updating
The Kalman filter is easiest to understand through a basic fact about jointly Gaussian random variables.
Suppose
$$
\begin{bmatrix}
\mathbf{x}\\
y
\end{bmatrix}
\sim N\left(
\begin{bmatrix}
\mathbf{a}\\
f
\end{bmatrix},
\begin{bmatrix}
\mathbf{R} & \mathbf{r}\\
\mathbf{r}^\top & Q
\end{bmatrix}
\right).
$$
Then the conditional distribution of $\mathbf{x}$ given $y$ is Gaussian:
$$
\mathbf{x}\mid y\sim N\left(\mathbf{a}+\mathbf{r}Q^{-1}(y-f),\;\mathbf{R}-\mathbf{r}Q^{-1}\mathbf{r}^\top\right).
$$
In the state-space setting:
- $\mathbf{x}$ is the hidden state $\boldsymbol{\alpha}_t$;
- $y$ is the observation $y_t$;
- $f$ is the one-step forecast of $y_t$;
- $y_t-f_t$ is the innovation, or prediction error;
- $\mathbf{r}Q^{-1}$ becomes the Kalman gain.
So the update has a simple geometric interpretation:
$$
\text{updated state}= ext{predicted state}+\text{gain}\times\text{prediction error}.
$$
## 10.4 Kalman filter notation
We use the following notation.
The **filtered distribution** at time $t-1$ is
$$
\boldsymbol{\alpha}_{t-1}\mid \mathcal{D}_{t-1}
\sim N(\mathbf{m}_{t-1},\mathbf{C}_{t-1}).
$$
The **one-step predicted state distribution** is
$$
\boldsymbol{\alpha}_{t}\mid \mathcal{D}_{t-1}
\sim N(\mathbf{a}_{t},\mathbf{R}_{t}).
$$
The **one-step forecast distribution** for the observation is
$$
y_t\mid \mathcal{D}_{t-1}
\sim N(f_t,Q_t).
$$
The **filtered distribution** after observing $y_t$ is
$$
\boldsymbol{\alpha}_{t}\mid \mathcal{D}_{t}
\sim N(\mathbf{m}_{t},\mathbf{C}_{t}).
$$
The Kalman filter recursively maps
$$
(\mathbf{m}_{t-1},\mathbf{C}_{t-1})
\longrightarrow
(\mathbf{a}_{t},\mathbf{R}_{t})
\longrightarrow
(f_t,Q_t)
\longrightarrow
(\mathbf{m}_{t},\mathbf{C}_{t}).
$$
## 10.5 Prediction step
Start with
$$
\boldsymbol{\alpha}_{t-1}\mid \mathcal{D}_{t-1}
\sim N(\mathbf{m}_{t-1},\mathbf{C}_{t-1}).
$$
Using the state equation
$$
\boldsymbol{\alpha}_t=\mathbf{G}\boldsymbol{\alpha}_{t-1}+\mathbf{w}_t,
$$
we obtain
$$
\mathbf{a}_t=\mathbf{G}\mathbf{m}_{t-1},
$$
and
$$
\mathbf{R}_t=\mathbf{G}\mathbf{C}_{t-1}\mathbf{G}^\top+\mathbf{W}.
$$
So
$$
\boldsymbol{\alpha}_{t}\mid \mathcal{D}_{t-1}
\sim N(\mathbf{a}_{t},\mathbf{R}_{t}).
$$
The extra term $\mathbf{W}$ increases uncertainty because the state evolves with random noise.
## 10.6 Forecast step
Using the observation equation
$$
y_t=\mathbf{F}^\top\boldsymbol{\alpha}_t+v_t,
$$
and the predicted state distribution, we get
$$
f_t=\mathbf{F}^\top\mathbf{a}_t,
$$
and
$$
Q_t=\mathbf{F}^\top\mathbf{R}_t\mathbf{F}+V.
$$
The innovation is
$$
e_t=y_t-f_t.
$$
Thus
$$
y_t\mid\mathcal{D}_{t-1}\sim N(f_t,Q_t).
$$
A $95\%$ one-step prediction interval is approximately
$$
f_t\pm 1.96\sqrt{Q_t}.
$$
## 10.7 Update step
The Kalman gain is
$$
\mathbf{A}_t=\mathbf{R}_t\mathbf{F}Q_t^{-1}.
$$
Then the updated state mean is
$$
\mathbf{m}_t=\mathbf{a}_t+\mathbf{A}_t e_t.
$$
The updated state covariance is
$$
\mathbf{C}_t=\mathbf{R}_t-\mathbf{A}_tQ_t\mathbf{A}_t^\top.
$$
Equivalently,
$$
\mathbf{C}_t=\mathbf{R}_t-\mathbf{R}_t\mathbf{F}Q_t^{-1}\mathbf{F}^\top\mathbf{R}_t.
$$
::: {.callout-note}
## Why the gain matters
If observation noise $V$ is large, then $Q_t$ is large and the gain is small. The filter trusts the model more than the new observation.
If state uncertainty $\mathbf{R}_t$ is large, then the gain is larger. The filter learns more from the new observation.
:::
## 10.8 Algorithm summary
For $t=1,2,\ldots,n$:
1. **Predict state**
$$
\mathbf{a}_t=\mathbf{G}\mathbf{m}_{t-1},
\qquad
\mathbf{R}_t=\mathbf{G}\mathbf{C}_{t-1}\mathbf{G}^\top+\mathbf{W}.
$$
2. **Forecast observation**
$$
f_t=\mathbf{F}^\top\mathbf{a}_t,
\qquad
Q_t=\mathbf{F}^\top\mathbf{R}_t\mathbf{F}+V.
$$
3. **Compute innovation**
$$
e_t=y_t-f_t.
$$
4. **Compute gain**
$$
\mathbf{A}_t=\mathbf{R}_t\mathbf{F}Q_t^{-1}.
$$
5. **Update state**
$$
\mathbf{m}_t=\mathbf{a}_t+\mathbf{A}_t e_t,
\qquad
\mathbf{C}_t=\mathbf{R}_t-\mathbf{A}_tQ_t\mathbf{A}_t^\top.
$$
::: {.callout-warning}
## Dimension check
If $\boldsymbol{\alpha}_t\in\mathbb{R}^d$, then
$$
\mathbf{F}\in\mathbb{R}^d,
\quad
\mathbf{G}\in\mathbb{R}^{d\times d},
\quad
\mathbf{W}\in\mathbb{R}^{d\times d},
\quad
\mathbf{A}_t\in\mathbb{R}^d.
$$
Dimension errors are the most common implementation mistakes.
:::
## 10.9 Local-level model
The simplest useful state-space model is the local-level model:
$$
y_t=\mu_t+v_t,
\qquad v_t\sim N(0,V),
$$
$$
\mu_t=\mu_{t-1}+w_t,
\qquad w_t\sim N(0,W).
$$
Here the hidden state is one-dimensional:
$$
\boldsymbol{\alpha}_t=\mu_t.
$$
Thus
$$
\mathbf{F}=1,
\qquad
\mathbf{G}=1.
$$
The Kalman equations reduce to scalar recursions:
$$
a_t=m_{t-1},
\qquad
R_t=C_{t-1}+W,
$$
$$
f_t=a_t,
\qquad
Q_t=R_t+V,
$$
$$
A_t=\frac{R_t}{Q_t},
$$
$$
m_t=a_t+A_t(y_t-a_t),
$$
$$
C_t=R_t-A_t^2Q_t=R_t\left(1-\frac{R_t}{Q_t}\right).
$$
Since $Q_t=R_t+V$, the scalar gain is
$$
A_t=\frac{R_t}{R_t+V}.
$$
If $V$ is large, then $A_t$ is small. If $R_t$ is large, then $A_t$ is large.
::: {.callout-tip}
## Local-level intuition
The local-level model is a smoothed random walk observed with noise. It is useful when the true level evolves slowly but observations are noisy.
:::
## 10.10 Local-linear trend model
The local-level model allows the level to change but does not explicitly model slope. A local-linear trend model has two hidden components:
$$
\boldsymbol{\alpha}_t=
\begin{bmatrix}
\mu_t\\
\beta_t
\end{bmatrix},
$$
where $\mu_t$ is the level and $\beta_t$ is the slope.
A common specification is
$$
y_t=\mu_t+v_t,
$$
$$
\mu_t=\mu_{t-1}+\beta_{t-1}+w_{1,t},
$$
$$
\beta_t=\beta_{t-1}+w_{2,t}.
$$
In matrix form:
$$
y_t=
\begin{bmatrix}1 & 0\end{bmatrix}
\begin{bmatrix}
\mu_t\\
\beta_t
\end{bmatrix}+v_t,
$$
and
$$
\begin{bmatrix}
\mu_t\\
\beta_t
\end{bmatrix}
=
\begin{bmatrix}
1 & 1\\
0 & 1
\end{bmatrix}
\begin{bmatrix}
\mu_{t-1}\\
\beta_{t-1}
\end{bmatrix}
+
\begin{bmatrix}
w_{1,t}\\
w_{2,t}
\end{bmatrix}.
$$
So
$$
\mathbf{F}=\begin{bmatrix}1\\0\end{bmatrix},
\qquad
\mathbf{G}=\begin{bmatrix}1&1\\0&1\end{bmatrix}.
$$
This is a dynamic version of a line. The intercept and slope evolve over time.
## 10.11 AR(1) as a state-space model
An AR(1) model is
$$
y_t=\phi y_{t-1}+w_t.
$$
It can be written as a state-space model with the hidden state $\alpha_t=y_t$:
$$
\alpha_t=\phi\alpha_{t-1}+w_t,
$$
$$
y_t=\alpha_t+v_t.
$$
If $v_t=0$, then the observation is exact. If $v_t$ is nonzero, this becomes a noisy AR(1) state process.
This perspective shows that AR models are special cases of state-space models. State-space models are more flexible because they can include trends, seasonality, regression effects, missing observations, and measurement noise in one unified framework.
## 10.12 Forecasting with a state-space model
Given the filtered state distribution at time $t$,
$$
\boldsymbol{\alpha}_t\mid\mathcal{D}_t\sim N(\mathbf{m}_t,\mathbf{C}_t),
$$
we can forecast $h$ steps ahead by repeatedly applying the state equation.
For time-invariant $\mathbf{G}$,
$$
\mathbf{a}_{t+h|t}=\mathbf{G}^h\mathbf{m}_t.
$$
The $h$-step state covariance is
$$
\mathbf{R}_{t+h|t}
=\mathbf{G}^h\mathbf{C}_t(\mathbf{G}^h)^\top
+\sum_{j=0}^{h-1}\mathbf{G}^j\mathbf{W}(\mathbf{G}^j)^\top.
$$
Then the $h$-step forecast distribution for the observation is
$$
y_{t+h}\mid\mathcal{D}_t
\sim N(f_{t+h|t},Q_{t+h|t}),
$$
where
$$
f_{t+h|t}=\mathbf{F}^\top\mathbf{a}_{t+h|t},
$$
and
$$
Q_{t+h|t}=\mathbf{F}^\top\mathbf{R}_{t+h|t}\mathbf{F}+V.
$$
## 10.13 Missing observations
A major advantage of the Kalman filter is that it handles missing observations naturally.
Suppose $y_t$ is missing. We still perform the state prediction:
$$
\mathbf{a}_t=\mathbf{G}\mathbf{m}_{t-1},
\qquad
\mathbf{R}_t=\mathbf{G}\mathbf{C}_{t-1}\mathbf{G}^\top+\mathbf{W}.
$$
But we skip the observation update:
$$
\mathbf{m}_t=\mathbf{a}_t,
\qquad
\mathbf{C}_t=\mathbf{R}_t.
$$
The uncertainty grows because no new information is available at that time.
::: {.callout-note}
## Practical consequence
Unlike many ARIMA workflows, a state-space implementation does not require manually interpolating missing observations before model fitting.
:::
## 10.14 Smoothing
Filtering estimates $\boldsymbol{\alpha}_t$ using $\mathcal{D}_t$. Smoothing estimates $\boldsymbol{\alpha}_t$ using the full data $\mathcal{D}_n$.
The smoothed distribution is
$$
\boldsymbol{\alpha}_t\mid\mathcal{D}_n
\sim N(\mathbf{s}_t,\mathbf{S}_t).
$$
For the linear Gaussian model, the Rauch--Tung--Striebel backward smoother uses
$$
\mathbf{J}_t=\mathbf{C}_t\mathbf{G}^\top\mathbf{R}_{t+1}^{-1},
$$
then recursively computes
$$
\mathbf{s}_t=\mathbf{m}_t+\mathbf{J}_t(\mathbf{s}_{t+1}-\mathbf{a}_{t+1}),
$$
and
$$
\mathbf{S}_t=\mathbf{C}_t+\mathbf{J}_t(\mathbf{S}_{t+1}-\mathbf{R}_{t+1})\mathbf{J}_t^\top.
$$
Smoothing is especially useful for:
- estimating historical trend components;
- decomposing a series into level, trend, and seasonality;
- denoising signals;
- reconstructing missing sections of a sequence.
## 10.15 Likelihood evaluation
The Kalman filter also gives the Gaussian likelihood. Since
$$
y_t\mid\mathcal{D}_{t-1}\sim N(f_t,Q_t),
$$
the log likelihood contribution is
$$
\ell_t=-\frac{1}{2}\left[\log(2\pi)+\log Q_t+\frac{e_t^2}{Q_t}\right].
$$
The full log likelihood is
$$
\ell=\sum_{t=1}^n \ell_t.
$$
We can estimate unknown parameters, such as $V$, $W$, or entries of $\mathbf{G}$, by maximizing this likelihood.
::: {.callout-warning}
## Parameter constraints
Variance and covariance parameters must satisfy positivity constraints. In numerical optimization, it is common to optimize over log-variances or Cholesky factors rather than raw covariance entries.
:::
## 10.16 Interactive HTML: Kalman filter playground
The following interactive module simulates a local-level model and filters the hidden state. Move the sliders to see how process noise and observation noise change the Kalman gain and the smoothness of the filtered estimate.
::: {.callout-important}
## Reading the display
- Larger process noise means the hidden level is allowed to move more.
- Larger observation noise means the filter trusts observations less.
- The shaded interval is an approximate filtering uncertainty band for the hidden level.
:::
::: {.panel-tabset}
## Interactive simulator
```{=html}
<div class="interactive-card">
<h3>Local-Level Kalman Filter Simulator</h3>
<p>
Model: <span class="math">y_t = \mu_t + v_t</span>,
<span class="math">\mu_t = \mu_{t-1}+w_t</span>.
</p>
<div class="control-grid">
<label>Process noise W: <span id="ch10-w-label">0.20</span>
<input id="ch10-w" type="range" min="0.01" max="1.50" step="0.01" value="0.20">
</label>
<label>Observation noise V: <span id="ch10-v-label">0.80</span>
<input id="ch10-v" type="range" min="0.05" max="3.00" step="0.05" value="0.80">
</label>
<label>Seed: <span id="ch10-seed-label">7</span>
<input id="ch10-seed" type="range" min="1" max="50" step="1" value="7">
</label>
</div>
<div id="ch10-kalman-plot" style="width:100%;height:520px;"></div>
<div id="ch10-kalman-summary" class="small-note"></div>
</div>
<script>
(function(){
function lcg(seed){
let s = seed % 2147483647;
if (s <= 0) s += 2147483646;
return function(){
s = s * 16807 % 2147483647;
return (s - 1) / 2147483646;
};
}
function randn(rng){
const u1 = Math.max(rng(), 1e-12);
const u2 = Math.max(rng(), 1e-12);
return Math.sqrt(-2*Math.log(u1))*Math.cos(2*Math.PI*u2);
}
function simulateAndFilter(W, V, seed){
const n = 120;
const rng = lcg(seed);
const t = [], mu = [], y = [], m = [], lo = [], hi = [], gains = [];
let level = 0.0;
let mPrev = 0.0;
let CPrev = 5.0;
for(let i=0;i<n;i++){
t.push(i+1);
level = level + Math.sqrt(W)*randn(rng);
const obs = level + Math.sqrt(V)*randn(rng);
mu.push(level);
y.push(obs);
const a = mPrev;
const R = CPrev + W;
const f = a;
const Q = R + V;
const e = obs - f;
const A = R / Q;
const mNow = a + A*e;
const CNow = R - A*A*Q;
m.push(mNow);
lo.push(mNow - 1.96*Math.sqrt(Math.max(CNow,0)));
hi.push(mNow + 1.96*Math.sqrt(Math.max(CNow,0)));
gains.push(A);
mPrev = mNow;
CPrev = CNow;
}
return {t, mu, y, m, lo, hi, gains};
}
function draw(){
const W = parseFloat(document.getElementById('ch10-w').value);
const V = parseFloat(document.getElementById('ch10-v').value);
const seed = parseInt(document.getElementById('ch10-seed').value);
document.getElementById('ch10-w-label').textContent = W.toFixed(2);
document.getElementById('ch10-v-label').textContent = V.toFixed(2);
document.getElementById('ch10-seed-label').textContent = seed.toString();
const z = simulateAndFilter(W,V,seed);
const bandX = z.t.concat([...z.t].reverse());
const bandY = z.hi.concat([...z.lo].reverse());
const traces = [
{x: bandX, y: bandY, type:'scatter', mode:'lines', fill:'toself', name:'95% filtered state band', line:{width:0}, opacity:0.25},
{x: z.t, y: z.y, type:'scatter', mode:'markers', name:'observations y_t', marker:{size:5}},
{x: z.t, y: z.mu, type:'scatter', mode:'lines', name:'true hidden level μ_t', line:{width:2}},
{x: z.t, y: z.m, type:'scatter', mode:'lines', name:'filtered estimate m_t', line:{width:3}}
];
const avgGain = z.gains.reduce((a,b)=>a+b,0)/z.gains.length;
const layout = {
margin:{l:50,r:20,t:30,b:45},
xaxis:{title:'time'},
yaxis:{title:'value'},
legend:{orientation:'h'},
hovermode:'x unified'
};
Plotly.newPlot('ch10-kalman-plot', traces, layout, {responsive:true});
document.getElementById('ch10-kalman-summary').innerHTML =
'<b>Average Kalman gain:</b> ' + avgGain.toFixed(3) +
'. A larger gain means the filter moves more strongly toward each new observation.';
}
['ch10-w','ch10-v','ch10-seed'].forEach(id => document.getElementById(id).addEventListener('input', draw));
draw();
})();
</script>
```
## What to notice
When $V$ is large relative to $W$, the filtered curve is smooth and reacts slowly. When $W$ is large relative to $V$, the filtered curve follows the observations more closely.
:::
## 10.17 Python example: local-level model from scratch
The following code implements the local-level Kalman filter without using a time-series package.
```{python}
#| label: py-ch10-local-level-from-scratch
#| fig-cap: "Local-level Kalman filter implemented from scratch."
#| warning: false
#| message: false
import numpy as np
import matplotlib.pyplot as plt
rng = np.random.default_rng(7)
n = 120
W = 0.20 # state innovation variance
V = 0.80 # observation noise variance
mu = np.zeros(n)
y = np.zeros(n)
for t in range(1, n):
mu[t] = mu[t-1] + rng.normal(0, np.sqrt(W))
y = mu + rng.normal(0, np.sqrt(V), size=n)
# Kalman filter initialization
m = np.zeros(n)
C = np.zeros(n)
f = np.zeros(n)
Q = np.zeros(n)
gain = np.zeros(n)
m_prev = 0.0
C_prev = 5.0
for t in range(n):
# prediction
a = m_prev
R = C_prev + W
# forecast
f[t] = a
Q[t] = R + V
e = y[t] - f[t]
# update
gain[t] = R / Q[t]
m[t] = a + gain[t] * e
C[t] = R - gain[t] ** 2 * Q[t]
m_prev, C_prev = m[t], C[t]
plt.figure(figsize=(10, 4))
plt.plot(mu, label="true hidden level")
plt.scatter(np.arange(n), y, s=12, alpha=0.6, label="observations")
plt.plot(m, linewidth=2, label="filtered estimate")
plt.fill_between(
np.arange(n),
m - 1.96 * np.sqrt(C),
m + 1.96 * np.sqrt(C),
alpha=0.2,
label="95% filtered interval"
)
plt.title("Local-level Kalman filter")
plt.xlabel("time")
plt.legend()
plt.show()
```
The plot shows three different objects:
- the hidden level $\mu_t$, which is not observed in real applications;
- the noisy observations $y_t$;
- the filtered estimate $m_t=E(\mu_t\mid\mathcal{D}_t)$.
## 10.18 Python example: vector Kalman filter
The next implementation handles a general linear Gaussian state-space model.
```{python}
#| label: py-ch10-general-kalman-function
#| warning: false
#| message: false
import numpy as np
def kalman_filter(y, F, G, V, W, m0, C0):
"""Kalman filter for a scalar-observation linear Gaussian state-space model.
Parameters
----------
y : array, shape (n,)
Observations. Missing values may be represented by np.nan.
F : array, shape (d,)
Observation vector; y_t = F.T @ alpha_t + v_t.
G : array, shape (d, d)
State transition matrix.
V : float
Observation variance.
W : array, shape (d, d)
State innovation covariance.
m0 : array, shape (d,)
Initial state mean.
C0 : array, shape (d, d)
Initial state covariance.
Returns
-------
dict containing filtered means, covariances, forecasts, forecast variances,
innovations, and Kalman gains.
"""
y = np.asarray(y, dtype=float)
F = np.asarray(F, dtype=float)
G = np.asarray(G, dtype=float)
W = np.asarray(W, dtype=float)
n = len(y)
d = len(F)
m = np.zeros((n, d))
C = np.zeros((n, d, d))
a = np.zeros((n, d))
R = np.zeros((n, d, d))
forecast = np.zeros(n)
Q = np.zeros(n)
innovation = np.full(n, np.nan)
gain = np.zeros((n, d))
m_prev = np.asarray(m0, dtype=float)
C_prev = np.asarray(C0, dtype=float)
for t in range(n):
# State prediction
a[t] = G @ m_prev
R[t] = G @ C_prev @ G.T + W
# Observation forecast
forecast[t] = F @ a[t]
Q[t] = F @ R[t] @ F + V
if np.isnan(y[t]):
# Missing observation: prediction becomes filtering distribution
m[t] = a[t]
C[t] = R[t]
else:
innovation[t] = y[t] - forecast[t]
gain[t] = R[t] @ F / Q[t]
m[t] = a[t] + gain[t] * innovation[t]
C[t] = R[t] - np.outer(gain[t], gain[t]) * Q[t]
m_prev, C_prev = m[t], C[t]
return {
"m": m, "C": C, "a": a, "R": R,
"forecast": forecast, "Q": Q,
"innovation": innovation, "gain": gain
}
```
## 10.19 Python example: local-linear trend model
Now we apply the vector filter to the local-linear trend model.
```{python}
#| label: py-ch10-local-linear-trend
#| fig-cap: "Kalman filtering for a local-linear trend model."
#| warning: false
#| message: false
rng = np.random.default_rng(10)
n = 160
true_level = np.zeros(n)
true_slope = np.zeros(n)
y = np.zeros(n)
level_noise_var = 0.05
slope_noise_var = 0.005
obs_noise_var = 0.50
true_level[0] = 2.0
true_slope[0] = 0.04
for t in range(1, n):
true_level[t] = true_level[t-1] + true_slope[t-1] + rng.normal(0, np.sqrt(level_noise_var))
true_slope[t] = true_slope[t-1] + rng.normal(0, np.sqrt(slope_noise_var))
y = true_level + rng.normal(0, np.sqrt(obs_noise_var), size=n)
F = np.array([1.0, 0.0])
G = np.array([[1.0, 1.0],
[0.0, 1.0]])
W = np.diag([level_noise_var, slope_noise_var])
V = obs_noise_var
m0 = np.array([0.0, 0.0])
C0 = np.diag([10.0, 1.0])
out = kalman_filter(y, F, G, V, W, m0, C0)
filtered_level = out["m"][:, 0]
filtered_slope = out["m"][:, 1]
plt.figure(figsize=(10, 4))
plt.scatter(np.arange(n), y, s=12, alpha=0.5, label="observed data")
plt.plot(true_level, label="true level")
plt.plot(filtered_level, linewidth=2, label="filtered level")
plt.title("Local-linear trend model")
plt.xlabel("time")
plt.legend()
plt.show()
plt.figure(figsize=(10, 3))
plt.plot(true_slope, label="true slope")
plt.plot(filtered_slope, linewidth=2, label="filtered slope")
plt.title("Estimated dynamic slope")
plt.xlabel("time")
plt.legend()
plt.show()
```
This example shows why state-space models are useful for nonstationary data. Rather than differencing the series and modeling the transformed data, we explicitly model the evolving level and slope.
## 10.20 Python example: missing observations
The same filtering function can handle missing values represented by `np.nan`.
```{python}
#| label: py-ch10-missing-values
#| fig-cap: "Kalman filtering with missing observations."
#| warning: false
#| message: false
rng = np.random.default_rng(12)
y_missing = y.copy()
missing_index = np.r_[40:58, 100:112]
y_missing[missing_index] = np.nan
out_missing = kalman_filter(y_missing, F, G, V, W, m0, C0)
filtered_missing = out_missing["m"][:, 0]
C_level = out_missing["C"][:, 0, 0]
plt.figure(figsize=(10, 4))
plt.scatter(np.arange(n), y_missing, s=14, alpha=0.6, label="observed data with gaps")
plt.plot(true_level, label="true level")
plt.plot(filtered_missing, linewidth=2, label="filtered level")
plt.fill_between(
np.arange(n),
filtered_missing - 1.96 * np.sqrt(C_level),
filtered_missing + 1.96 * np.sqrt(C_level),
alpha=0.2,
label="95% state interval"
)
plt.axvspan(40, 57, alpha=0.1)
plt.axvspan(100, 111, alpha=0.1)
plt.title("State-space filtering naturally handles missing observations")
plt.xlabel("time")
plt.legend()
plt.show()
```
During gaps, the filter still evolves the state forward, but uncertainty increases because no observations are available for correction.
## 10.21 Python example: log likelihood
We can estimate model parameters by maximizing the Kalman filter log likelihood. The function below evaluates the log likelihood for fixed parameters.
```{python}
#| label: py-ch10-loglikelihood
#| warning: false
#| message: false
def kalman_loglik(y, F, G, V, W, m0, C0):
out = kalman_filter(y, F, G, V, W, m0, C0)
e = out["innovation"]
Q = out["Q"]
observed = ~np.isnan(y)
ll = -0.5 * np.sum(
np.log(2 * np.pi) + np.log(Q[observed]) + e[observed] ** 2 / Q[observed]
)
return ll
candidate_values = np.linspace(0.05, 2.0, 60)
loglik_values = []
for V_candidate in candidate_values:
ll = kalman_loglik(y, F, G, V_candidate, W, m0, C0)
loglik_values.append(ll)
best_V = candidate_values[np.argmax(loglik_values)]
print(f"Best observation variance on grid: {best_V:.3f}")
plt.figure(figsize=(8, 4))
plt.plot(candidate_values, loglik_values)
plt.axvline(best_V, linestyle="--")
plt.xlabel("candidate observation variance V")
plt.ylabel("Kalman log likelihood")
plt.title("Grid likelihood for observation noise variance")
plt.show()
```
This is not a full maximum-likelihood routine, but it illustrates the principle. In practice, we often optimize over multiple transformed parameters using numerical optimization.
## 10.22 Forecasting with the local-linear model
The following code produces multi-step forecasts from the filtered distribution at the end of the sample.
```{python}
#| label: py-ch10-state-space-forecast
#| fig-cap: "Multi-step forecasts from a local-linear state-space model."
#| warning: false
#| message: false
h = 30
last_m = out["m"][-1]
last_C = out["C"][-1]
forecast_mean = np.zeros(h)
forecast_var = np.zeros(h)
m_h = last_m.copy()
C_h = last_C.copy()
for j in range(h):
m_h = G @ m_h
C_h = G @ C_h @ G.T + W
forecast_mean[j] = F @ m_h
forecast_var[j] = F @ C_h @ F + V
future_time = np.arange(n, n + h)
plt.figure(figsize=(10, 4))
plt.plot(np.arange(n), y, label="observed")
plt.plot(future_time, forecast_mean, label="forecast mean")
plt.fill_between(
future_time,
forecast_mean - 1.96 * np.sqrt(forecast_var),
forecast_mean + 1.96 * np.sqrt(forecast_var),
alpha=0.2,
label="95% forecast interval"
)
plt.axvline(n - 1, linestyle="--")
plt.title("State-space forecast")
plt.xlabel("time")
plt.legend()
plt.show()
```
The forecast interval widens with horizon because state uncertainty accumulates over time.
## 10.23 State-space models and ARIMA
Many ARIMA models have state-space representations. This matters for at least three reasons.
First, it allows ARIMA models to be fitted by Kalman filtering. Second, it gives a natural way to compute likelihoods and handle missing values. Third, it shows how ARIMA belongs to a larger family of dynamic hidden-state models.
For example, the random walk plus noise model is
$$
\mu_t=\mu_{t-1}+w_t,
\qquad
y_t=\mu_t+v_t.
$$
This is close in spirit to an integrated model, but it separates **state noise** $w_t$ from **observation noise** $v_t$. In many scientific and engineering settings, this distinction is essential.
The state-space view is especially useful when we want to combine:
$$
\text{trend} + \text{seasonality} + \text{regression} + \text{ARMA errors} + \text{missing data}.
$$
## 10.24 Dynamic regression
A static regression model is
$$
y_t=\mathbf{x}_t^\top\boldsymbol{\beta}+\epsilon_t.
$$
A dynamic regression model allows coefficients to change over time:
$$
y_t=\mathbf{x}_t^\top\boldsymbol{\beta}_t+v_t,
$$
$$
\boldsymbol{\beta}_t=\boldsymbol{\beta}_{t-1}+\mathbf{w}_t.
$$
This is a state-space model with state $\boldsymbol{\alpha}_t=\boldsymbol{\beta}_t$ and observation vector $\mathbf{F}_t=\mathbf{x}_t$.
Dynamic regression is useful when the effect of a predictor is not constant. Examples include:
- changing price sensitivity in retail demand;
- time-varying market beta in finance;
- changing intervention effects in public-health data;
- evolving relationship between weather and energy demand.
## 10.25 State-space models and modern sequence learning
State-space models provide a bridge from classical time-series theory to modern AI.
### Connection to RNNs
A recurrent neural network has a hidden state update
$$
\mathbf{h}_t=\sigma(\mathbf{A}\mathbf{h}_{t-1}+\mathbf{B}\mathbf{x}_t+\mathbf{b}).
$$
A linear Gaussian state-space model has a hidden state update
$$
\boldsymbol{\alpha}_t=\mathbf{G}\boldsymbol{\alpha}_{t-1}+\mathbf{w}_t.
$$
Both models maintain a hidden summary of the past. The state-space model is probabilistic and interpretable. The RNN is nonlinear and highly expressive.
### Connection to HMMs
A hidden Markov model also has hidden states, but the states are usually discrete:
$$
S_t\in\{1,2,\ldots,K\}.
$$
The Kalman filter is the Gaussian continuous-state analogue of recursive filtering for hidden Markov models.
### Connection to attention models
Attention models do not compress the past into a single low-dimensional state in the same way. Instead, they learn to attend to many past positions. However, state-space ideas remain important in modern long-sequence modeling because they offer efficient recurrent updates.
::: {.callout-important}
## AI perspective
A state-space model is an interpretable probabilistic memory system. RNNs, gated models, and transformers are more flexible sequence models, but they inherit the same core question: how should past information be stored and used for prediction?
:::
## 10.26 AI-assisted modeling component
AI tools can help with state-space modeling, but recursion and matrix notation are easy places for AI-generated code to make subtle mistakes. Use AI as a critic and debugging assistant, not as an authority.
### Prompt 1: Dimension audit
> I am implementing a Kalman filter with state dimension $d=2$. My observation vector is $F=[1,0]^T$, transition matrix is $G=\begin{bmatrix}1&1\\0&1\end{bmatrix}$, and state covariance is $C_t$. Check the dimensions of every term in the prediction, forecast, gain, and update equations. Do not change the model; only check dimensions.
### Prompt 2: Model interpretation
> Explain the difference between a local-level model and a local-linear trend model. Give one example where the local-level model is sufficient and one example where the local-linear trend model is more appropriate.
### Prompt 3: Debugging recursive code
> Here is my Kalman filter function. Identify possible indexing, covariance-update, missing-data, and numerical-stability issues. Do not rewrite the entire function unless necessary. Explain each issue mathematically.
### Prompt 4: Forecast uncertainty
> Why does the state-space forecast interval widen as the horizon increases? Explain using the formula for $R_{t+h|t}$.
### Verification checklist for AI answers
1. Are the dimensions correct?
2. Are covariance matrices symmetric and positive semidefinite?
3. Is $Q_t$ positive?
4. Are missing observations skipped rather than imputed without justification?
5. Are filtering and smoothing clearly distinguished?
6. Are forecast intervals based on observation uncertainty, not only state uncertainty?
## 10.27 Common mistakes
### Mistake 1: Confusing state noise with observation noise
In
$$
y_t=\mu_t+v_t,
\qquad
\mu_t=\mu_{t-1}+w_t,
$$
$v_t$ is measurement noise and $w_t$ is state evolution noise. Increasing $V$ makes observations less reliable. Increasing $W$ makes the hidden state more flexible.
### Mistake 2: Updating when $y_t$ is missing
If $y_t$ is missing, do not compute an innovation using an imputed value unless the imputation is explicitly part of the model. The standard filter simply skips the update.
### Mistake 3: Using only state variance for forecast intervals
Forecast intervals for future observations must include observation variance $V$:
$$
Q_{t+h|t}=\mathbf{F}^\top\mathbf{R}_{t+h|t}\mathbf{F}+V.
$$
### Mistake 4: Forgetting covariance propagation
The forecast mean evolves through $\mathbf{G}$, but so does uncertainty:
$$
\mathbf{R}_t=\mathbf{G}\mathbf{C}_{t-1}\mathbf{G}^\top+\mathbf{W}.
$$
### Mistake 5: Confusing filtering with smoothing
Filtering uses only present and past data. Smoothing uses future data as well. A smoothed estimate usually looks better, but it is not available in real-time forecasting.
## 10.28 Exercises
### Exercise 1: Scalar Kalman gain
For the local-level model, show that the Kalman gain is
$$
A_t=\frac{R_t}{R_t+V}.
$$
Explain what happens to $A_t$ as $V\to\infty$ and as $V\to 0$.
### Exercise 2: Local-level recursions
Starting from
$$
\mu_t=\mu_{t-1}+w_t,
\qquad
y_t=\mu_t+v_t,
$$
derive all scalar Kalman filter equations.
### Exercise 3: Matrix dimensions
Let
$$
\mathbf{F}=\begin{bmatrix}1\\0\end{bmatrix},
\qquad
\mathbf{G}=\begin{bmatrix}1&1\\0&1\end{bmatrix}.
$$
List the dimensions of $\mathbf{a}_t$, $\mathbf{R}_t$, $f_t$, $Q_t$, $e_t$, $\mathbf{A}_t$, $\mathbf{m}_t$, and $\mathbf{C}_t$.
### Exercise 4: Missing observation
Suppose $y_t$ is missing. Write the filtering equations for time $t$. Explain why the covariance usually increases relative to time $t-1$.
### Exercise 5: Forecast variance
For a local-level model with $G=1$, show that
$$
R_{t+h|t}=C_t+hW.
$$
Then write the $h$-step observation forecast variance.
### Exercise 6: Local-linear trend simulation
Simulate a local-linear trend model and fit it using the Kalman filter. Compare the filtered slope estimate with the true slope.
### Exercise 7: State-space versus ARIMA
Write a short explanation comparing an ARIMA model and a local-linear trend state-space model for a trending nonstationary series.
### Exercise 8: AI critique
Ask an AI tool to generate a Kalman filter for the local-level model. Then audit the code for dimension consistency, missing-data handling, and the correct covariance update.
## 10.29 Mini project: noisy sensor tracking
Choose or simulate a time series representing a noisy sensor measurement. Examples include position tracking, temperature monitoring, demand level, or a latent biological signal.
Your project should include:
1. a clear state-space model specification;
2. simulation or data description;
3. implementation of the Kalman filter;
4. plots of observations, filtered state estimates, and uncertainty bands;
5. a missing-data experiment;
6. multi-step forecasts with prediction intervals;
7. an AI-assisted debugging appendix describing how you checked the recursive equations.
## 10.30 Chapter checklist
You should now be able to:
- [ ] define a linear Gaussian state-space model;
- [ ] identify the hidden state, observation equation, and state equation;
- [ ] derive the Kalman prediction step;
- [ ] derive the Kalman forecast step;
- [ ] derive the Kalman update step;
- [ ] explain the Kalman gain;
- [ ] implement the local-level Kalman filter from scratch;
- [ ] implement a vector Kalman filter;
- [ ] handle missing observations;
- [ ] compute multi-step forecast intervals;
- [ ] distinguish filtering, smoothing, and forecasting;
- [ ] explain how state-space models connect to ARIMA, HMMs, and RNNs.
## 10.31 Key takeaways
A state-space model separates a time series into hidden dynamic structure and noisy observations. The Kalman filter provides an exact recursive solution for linear Gaussian models. It updates a predicted state using the new observation's innovation, weighted by the Kalman gain. This gives a mathematically transparent framework for filtering, forecasting, smoothing, likelihood evaluation, missing-data handling, dynamic regression, and modern sequence-learning connections.