State space models for time series: Kalman in action
Building on the Kalman filter from m14, this lesson assembles structural time-series models, represents ARMA in state space, handles diffuse initialization and missing data, interpolates gaps with smoothing, estimates time-varying regression coefficients and forecasts with uncertainty.
After this lesson you can
- Assemble a structural model with trend, trigonometric seasonality and regressors by writing its system matrices.
- Represent an ARMA(p, q) in state space and verify that Kalman reproduces the exact likelihood.
- Estimate structural-model variances by maximum likelihood with diffuse initialization.
- Interpolate gaps and detect outliers and breaks using auxiliary smoother residuals.
- Estimate a dynamic beta between two assets and compare it with rolling-window regression.
Before you start
- 26ARMA modelInnovations algorithmExact Gaussian likelihood of ARMAETS innovations state space modelsHolt and Holt-Winters methodsAdditive and multiplicative decomposition
- 14Linear Gaussian state-space modelKalman filterRauch-Tung-Striebel smootherMaximum likelihood for state-space modelsInnovations and prediction error decompositionNumerical stability of the Kalman filter
A series with hidden components
A measurement can combine a changing level, trend, seasonal components and noise; some dates can also be missing. Rather than filling gaps first and then fitting them as if they were data, a state-space model describes components and their uncertainties jointly.
Assembling components does not guarantee that they are well identified. Add or remove components and compare their bands: uncertainty is conditional on the model and chosen variances. The passenger series is observed; the components you separate are model estimates, not independent measurements of each component.
Filter, smoother and innovations
A linear Gaussian system uses state , observation , known matrices and independent noises:
The state disturbance covariance is ; do not confuse with observation variance . The Kalman filter predicts the state mean and covariance, calculates innovation with covariance , and updates using . The RTS smoother moves backwards and conditions each state on all observations. In implementation, solve linear systems and use a numerically stable covariance update; avoid an explicit inverse where possible.
With proper initialization and nonsingular , the product of Gaussian innovation densities gives the exact likelihood of the observed model; the sum of their logarithms gives the log-likelihood. If is missing, retain the prediction as the filtered state and do not add that observation to the sum. A filtered mean at uses information through ; a one-step prediction uses information through . Confusing them introduces look-ahead in a backtest.
Level, trend and seasonal components
A structural model represents interpretable components. For a local level and slope,
Level and slope variances control their flexibility. The local level model removes the slope; a damped cycle uses a rotation block multiplied by with . If an estimated variance reaches zero, the corresponding component becomes deterministic in that direction: this is not automatically a failure, but tests at the boundary require care.
For a period , trigonometric seasonality includes, for each harmonic , the block
The observation sums the first coordinate of each pair. If is even, the Nyquist harmonic has one state with transition , not two. With all harmonics and no disturbances, there are seasonal states and the same space of zero-sum periodic patterns as with seasonal dummy variables is obtained. For stochastic seasonality, equivalent spaces do not imply equivalent laws: disturbance and initialization covariances must also be transformed. Multiple seasonalities are stacked in blocks, avoiding duplicate common frequencies without identification constraints.
The gain as exponential smoothing
For a local level with state variance and observation variance , let . The stationary prediction of normalized variance satisfies , and the positive root gives . The limiting gain is
The update becomes, when converges, simple exponential smoothing with . This equivalence concerns the steady-state recursion; transient initialization can differ.
ARMA and the initial distribution
An ARMA in state-space form retains the necessary lags of the series and its innovations. If the AR is stable, the stationary initial distribution is obtained by solving ; with it, Kalman reproduces the exact joint likelihood, not merely a likelihood that discards initial terms. The lab checks an explicit representation against the covariance matrix and SARIMAX.
A random level or trend has no stationary state distribution that can be used for initialization. Diffuse initialization expresses a lack of information about those directions. The approximation fixes a large proper variance ; different values of can affect the first innovations and the likelihood. Exact diffuse initialization separates finite and diffuse parts and treats the first updates specially; it does not literally take infinity in the usual recursion. Treatment of initial terms and likelihood constants must match before comparing values. statsmodels documents both initializations.
Gaps, anomalies and the future
In gap interpolation, the filter advances without an update on missing dates; its uncertainty usually increases during a sequence without data. The smoother incorporates later observations and can reduce uncertainty in an interior gap. The latent-state band is not an observation band: for a future observation, measurement variance must be added. Linear interpolation alone does not provide model uncertainty and does not automatically extrapolate endpoints.
To detect an outlying observation, examine standardized innovations and their context; a persistent change may indicate a state break rather than an isolated measurement error. Smoothed expectations of measurement and state disturbances help locate the type of anomaly. Turning them into tests requires their appropriate variances and covariances and consideration of multiple comparisons. The smoother uses the future: it serves retrospective analysis, not simulation of a real-time decision.
Time-varying betas and forecasting
A time-varying coefficient regression can use and , with observed and specified variances. A small evolution variance favors an almost constant beta; a large one allows rapid response at the cost of more noise. The filtered beta at uses : to predict , use the beta predicted before observing it. The following experiment knows the true beta only because it generates the data.
State-space forecasting propagates mean and covariance through and and then applies and adds for the observation. If future regressor is unknown, its uncertainty requires a model or scenarios; treating it as known does not incorporate that uncertainty. Conditional bands also depend on estimated parameters, whose uncertainty is not automatically included in the filter.
Lab: our own filter and smoother
The reference lesson on linear Gaussian state space explains the general framework. Here we implement a self-contained version with scalar observations so you can check each matrix. The first prediction is the given prior; the transition is applied from the second date onward. The algorithm accepts missing dates and uses Joseph form for filtered covariance. The cell’s RTS version requires invertible predicted covariances; degenerate states require a formulation appropriate to the admissible subspace.
import numpy as np
from scipy.linalg import block_diag, solve_discrete_lyapunov, toeplitz
from scipy.optimize import minimize, minimize_scalar
from scipy.stats import multivariate_normal
from statsmodels.tsa.statespace.kalman_smoother import KalmanSmoother
from statsmodels.tsa.statespace.structural import UnobservedComponents
from statsmodels.tsa.statespace.sarimax import SARIMAX
from statsmodels.tsa.arima_process import arma_acovf
def filtrar(y, T, Z, W, H, a0, P0):
y = np.asarray(y,dtype=float)
T, W = np.asarray(T), np.asarray(W)
n, d = len(y), len(a0)
Z = np.asarray(Z,dtype=float)
if Z.ndim == 1:
Z = np.broadcast_to(Z,(n,d))
ap, Pp, af, Pf = [], [], [], []
a, P = np.asarray(a0,dtype=float).copy(), np.asarray(P0,dtype=float).copy()
ll = 0.
I = np.eye(d)
for t in range(n):
if t:
a, P = T@a, T@[email protected]+W
ap.append(a.copy()); Pp.append(P.copy())
if np.isfinite(y[t]):
z = Z[t]
v = y[t]-z@a
F = z@P@z+H
if F <= 0:
raise ValueError("varianza de innovación no positiva")
K = P@z/F
a = a+K*v
A = I-np.outer(K,z)
P = A@[email protected]+H*np.outer(K,K)
ll -= .5*(np.log(2*np.pi*F)+v*v/F)
af.append(a.copy()); Pf.append(P.copy())
return np.array(ap),np.array(Pp),np.array(af),np.array(Pf),ll
def suavizar(T, filtrado):
ap,Pp,af,Pf,ll = filtrado
a, P = af.copy(), Pf.copy()
for t in range(len(a)-2,-1,-1):
J = np.linalg.solve(Pp[t+1],T@Pf[t]).T
a[t] = af[t]+J@(a[t+1]-ap[t+1])
P[t] = Pf[t]+J@(P[t+1]-Pp[t+1])@J.T
return a,PLab: assembling and fitting components
The next cell constructs a level, slope and harmonic pairs; if the period is even, the last harmonic occupies one coordinate. The observation adds the first coordinate of each harmonic. The optional regressor uses a constant state coefficient and a demonstration step: it is not an observed causal intervention.
def ensamblar(periodo, armonicos, pendiente=True, regresor=None):
if periodo < 2 or not 0 <= armonicos <= periodo//2:
raise ValueError("periodo o armónicos inválidos")
bloques = [np.array([[1.,1.],[0.,1.]]) if pendiente else np.ones((1,1))]
q = [1e-3,1e-5] if pendiente else [1e-3]
obs = [1.,0.] if pendiente else [1.]
for j in range(1,armonicos+1):
if periodo%2 == 0 and j == periodo//2:
bloques.append(np.array([[-1.]])); q.append(1e-4); obs.append(1.)
else:
angulo = 2*np.pi*j/periodo
c,s = np.cos(angulo),np.sin(angulo)
bloques.append(np.array([[c,s],[-s,c]]))
q.extend([1e-4,1e-4]); obs.extend([1.,0.])
if regresor is not None:
bloques.append(np.ones((1,1))); q.append(0.); obs.append(0.)
T = block_diag(*bloques)
Z = np.asarray(obs)
if regresor is not None:
Z = np.broadcast_to(Z,(len(regresor),len(Z))).copy()
Z[:,-1] = regresor
return T,Z,np.diag(q)
for s in (5,6,12):
T0,Z0,W0 = ensamblar(s,s//2,False)
print("periodo, estados estacionales, error periodicidad:",
s,len(Z0)-1,np.max(abs(np.linalg.matrix_power(T0[1:,1:],s)-np.eye(len(Z0)-1))))We use the 144 values of AirPassengers, also present in the decomposition lesson. We work in logarithms and hide a segment to check interpolation; retaining a complete evaluation window would be necessary to compare actual forecasts.
y = np.array([112,118,132,129,121,135,148,148,136,119,104,118,115,126,141,135,125,149,170,170,158,133,114,140,145,150,178,163,172,178,199,199,184,162,146,166,171,180,193,181,183,218,230,242,209,191,172,194,196,196,236,235,229,243,264,272,237,211,180,201,204,188,235,227,234,264,302,293,259,229,203,229,242,233,267,269,270,315,364,347,312,274,237,278,284,277,317,313,318,374,413,405,355,306,271,306,315,301,356,348,355,422,465,467,404,347,305,336,340,318,362,348,363,435,491,505,404,359,310,337,360,342,406,396,420,472,548,559,463,407,362,405,417,391,419,461,472,535,622,606,508,461,390,432], dtype=float)
logpasajeros = np.log(y)
observado = logpasajeros.copy()
observado[50:60] = np.nan
T,Z,W = ensamblar(12,2)
H = .01
a0 = np.zeros(len(Z))
P0 = np.eye(len(Z))*1e4
filtro = filtrar(observado,T,Z,W,H,a0,P0)
estados, covariancias = suavizar(T,filtro)
señal = estados@Z
print("meses y ausentes:", len(y),np.sum(~np.isfinite(observado)))
print("log-verosimilitud con prior amplio propio:", filtro[-1])
print("señal suavizada en límites y centro del hueco:", señal[[50,55,59]])
print("incertidumbre del estado nivel en el hueco:",
np.sqrt(covariancias[[50,55,59],0,0]))We check the complete model, with the same matrices and finite prior, against the statsmodels smoother and an equivalent structural model. For the likelihood comparison we also set the number of discarded initial terms to zero.
mod = KalmanSmoother(k_endog=1,k_states=len(Z),initialization="known",
initial_state=a0,initial_state_cov=P0)
mod.bind(observado)
mod["design"] = Z[None,:]
mod["transition"] = T
mod["selection"] = np.eye(len(Z))
mod["state_cov"] = W
mod["obs_cov"] = np.array([[H]])
ref = mod.smooth()
print("error máximo en estados suavizados:",
np.max(abs(estados-ref.smoothed_state.T)))
print("diferencia de log-verosimilitud:", filtro[-1]-ref.llf)
uc = UnobservedComponents(observado,level="local linear trend",
freq_seasonal=[{"period":12,"harmonics":2}],
stochastic_freq_seasonal=[True])
uc.ssm.initialize_known(a0,P0)
uc.ssm.loglikelihood_burn = 0
uc_ref = uc.smooth([H,W[0,0],W[1,1],W[2,2]])
print("diferencia con UnobservedComponents:", filtro[-1]-uc_ref.llf)Lab: variances, outliers and forecasting
We optimize four positive variances with a fixed approximate prior. Initialization is part of the experiment: comparison with an exact diffuse filter need not return the same numerical likelihood. The minimum is sought in a bounded domain to make the boundary explicit and does not prove a global optimum.
def objetivo(logvar):
var = np.exp(logvar)
W = np.diag([var[1],var[2],var[3],var[3],var[3],var[3]])
return -filtrar(observado,T,Z,W,var[0],a0,P0)[-1]
inicio = np.log([.01,.001,.00001,.0001])
fit = minimize(objetivo,inicio,method="L-BFGS-B",
bounds=[(-14,1)]*4,options={"maxiter":150})
if not fit.success:
raise RuntimeError(fit.message)
estimadas = np.exp(fit.x)
print("varianzas estimadas H, nivel, pendiente y estación:",estimadas)
print("log-verosimilitud propia con prior amplio:", -fit.fun)
difuso = UnobservedComponents(observado,level="local linear trend",
freq_seasonal=[{"period":12,"harmonics":2}],
stochastic_freq_seasonal=[True],use_exact_diffuse=True)
print("log-verosimilitud difusa exacta con los mismos parámetros:",difuso.smooth(estimadas).llf)We separately introduce a known isolated anomaly and a permanent step and compare the smoothed observation disturbance with the smoothed level change. Here we retain the variances fixed in the first model, not the newly optimized ones. These are retrospective indicators, not p-values or automatic identification of a break.
contaminado = observado.copy()
contaminado[95] += .5
fc = filtrar(contaminado,T,Z,W,H,a0,P0)
ac,Pc = suavizar(T,fc)
error_obs = float(np.asarray(contaminado[95]-Z@ac[95]).item())
cambio_nivel = (ac[95]-T@ac[94])[0]
print("perturbación de observación y de nivel suavizadas:",error_obs,cambio_nivel)
print("índice de la perturbación artificial:",95)
escalon = observado.copy()
escalon[95:] += .5
fe = filtrar(escalon,T,Z,W,H,a0,P0)
ae,Pe = suavizar(T,fe)
error_escalon = float(np.asarray(escalon[95]-Z@ae[95]).item())
cambio_escalon = (ae[95]-T@ae[94])[0]
print("observación y nivel suavizados en el inicio del escalón:",
error_escalon,cambio_escalon)To forecast, we filter again with the estimated variances, start from the last filtered state and propagate the dynamics. Observation variance includes ; latent-state variance does not. The interval below treats estimated parameters as known.
W_ajustada = np.diag([estimadas[1],estimadas[2]]+[estimadas[3]]*4)
H_ajustada = estimadas[0]
ap,Pp,af,Pf,ll = filtrar(observado,T,Z,W_ajustada,H_ajustada,a0,P0)
a, P = af[-1].copy(),Pf[-1].copy()
for h in range(1,13):
a, P = T@a,T@[email protected]+W_ajustada
if h in (1,6,12):
media = Z@a
sd = np.sqrt(Z@P@Z+H_ajustada)
print("h, media logarítmica, intervalo 95 %:",h,media,media-1.96*sd,media+1.96*sd)Lab: ARMA in states and exact likelihood
For ARMA(1,1), state stores the current observation and innovation. The same noise enters both parts: its covariance is , which is singular. Singularity of that state covariance does not invalidate the scalar filter if each observed innovation variance is positive. Generalization to more lags is left as an exercise.
rng = np.random.default_rng(2619)
phi, theta, sigma2 = np.array([.6]),np.array([.3]),.5
innov = rng.normal(scale=np.sqrt(sigma2),size=280)
serie = np.zeros(len(innov))
for t in range(1,len(serie)):
serie[t] = phi[0]*serie[t-1]+innov[t]+theta[0]*innov[t-1]
serie = serie[200:]
Ta = np.array([[phi[0],theta[0]],[0.,0.]])
Za = np.array([1.,0.])
Ra = np.array([1.,1.])
Wa = sigma2*np.outer(Ra,Ra)
Pa = solve_discrete_lyapunov(Ta,Wa)
ll_kalman = filtrar(serie,Ta,Za,Wa,0.,np.zeros(len(Za)),Pa)[-1]
gamma = arma_acovf(np.r_[1.,-phi],np.r_[1.,theta],nobs=len(serie),sigma2=sigma2)
cov_arma = toeplitz(gamma)
ll_conjunta = multivariate_normal.logpdf(serie,mean=np.zeros(len(serie)),cov=cov_arma)
L = np.linalg.cholesky(cov_arma)
innov_estandar = np.linalg.solve(L,serie)
innov_var = np.diag(L)**2
innovaciones = np.diag(L)*innov_estandar
ll_innov = -.5*np.sum(np.log(2*np.pi*innov_var)+innovaciones**2/innov_var)
sar = SARIMAX(serie,order=(1,0,1),trend="n",initialization="stationary")
ll_sar = sar.filter([phi[0],theta[0],sigma2]).llf
print("log-verosimilitudes Kalman, conjunta, innovaciones y SARIMAX:",
ll_kalman,ll_conjunta,ll_innov,ll_sar)
print("diferencia máxima:",max(abs(ll_kalman-ll_conjunta),
abs(ll_kalman-ll_innov),abs(ll_kalman-ll_sar)))Lab: changing beta and hedging
We generate two synthetic log prices by accumulating returns. The true beta follows a random walk; the return of the second series depends on the first and independent noise. We estimate beta variance by likelihood using only the first part, hold that parameter fixed and compare beta predictions before each test return. The hedge calculated with those betas is a return residual, not a funded portfolio with costs.
rng = np.random.default_rng(2620)
n, corte = 260, 180
x = .01*rng.normal(size=n)
beta_real = np.empty(n); beta_real[0] = 1.
for t in range(1,n):
beta_real[t] = beta_real[t-1]+.05*rng.normal()
ret_y = beta_real*x+.004*rng.normal(size=n)
precios_x = 100*np.exp(np.r_[0.,np.cumsum(x)])
precios_y = 100*np.exp(np.r_[0.,np.cumsum(ret_y)])
rx = np.diff(np.log(precios_x)); ry = np.diff(np.log(precios_y))
def filtrar_beta(y,x,q):
return filtrar(y,np.ones((1,1)),x[:,None],np.array([[q]]),.004**2,
np.array([0.]),np.array([[1.]]))
opt = minimize_scalar(lambda logq: -filtrar_beta(ry[:corte],rx[:corte],np.exp(logq))[-1],
bounds=(-12,-1),method="bounded")
q_est = np.exp(opt.x)
beta_kalman = filtrar_beta(ry,rx,q_est)[0][:,0]
beta_estatica = rx[:corte]@ry[:corte]/(rx[:corte]@rx[:corte])
ventana = 40
beta_ventana = np.array([rx[t-ventana:t]@ry[t-ventana:t]/
(rx[t-ventana:t]@rx[t-ventana:t]) for t in range(corte,n)])
errores = {
"Kalman": ry[corte:]-beta_kalman[corte:]*rx[corte:],
"estática": ry[corte:]-beta_estatica*rx[corte:],
"ventana": ry[corte:]-beta_ventana*rx[corte:],
}
print("varianza verdadera y estimada de la beta:",.05**2,q_est)
print("desviación del residual de cobertura fuera de muestra:",
{nombre:np.std(v,ddof=1) for nombre,v in errores.items()})
logx = np.log(precios_x[1:]/precios_x[0])
logy = np.log(precios_y[1:]/precios_y[0])
betas = {"Kalman":beta_kalman[corte:],
"estática":np.full(n-corte,beta_estatica),"ventana":beta_ventana}
spreads = {nombre:logy[corte:]-b*logx[corte:] for nombre,b in betas.items()}
print("desviación del spread de logprecios fuera de muestra:",
{nombre:np.std(v,ddof=1) for nombre,v in spreads.items()})
print("ganancias estacionarias en una rejilla de razones señal-ruido:",
[(np.sqrt(q*q+4*q)-q)/2 for q in np.linspace(.05,1.,39)])The spread uses log prices normalized to the same origin and the beta available before the corresponding return. When changes, its variation also changes the spread: . Therefore the deviation of the level spread and that of the return residual are not the same measure. Neither demonstrates cointegration or profitability of a real hedge.
Exercises
Step 1 of 3. Which equation does the normalized predicted variance satisfy at steady state?
import numpy as np
from scipy.linalg import solve_discrete_lyapunov
def arma_to_statespace(phi, theta, sigma2):
passimport numpy as np
from scipy.linalg import block_diag
def seasonal_transition(s,k):
passState space combines dynamics, seasonal components and missing observations in one recursion. Initialization and variances are part of the model; filtering, smoothing and forecasting answer questions conditioned on different information.