Module contents
Lesson 19 of 31Core 115 min

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

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.

InteractiveBuild a structural model

Real data: monthly AirPassengers logarithms, 1949 to 1960, thousands of passengers. Source: R Datasets. The fit uses the entire sample and is not an out-of-sample prediction.

Model: aₜ=T aₜ₋₁+Rηₜ, yₜ=Zₜaₜ+εₜ, with Var(η)=Q and Var(ε)=σ². Level and seasonality receive variances 0.0003 and 0.0001 per state; slope 0.00001; the step coefficient is constant. Initialization uses a₀=0, P₀=10 000 I: it is approximately diffuse. Variances are explicit choices, not estimates.

The dummy indicator is 0 through month 72 and 1 from month 73; it explores a hypothetical intervention without causal interpretation. Level and coefficient can share the signal in uncertain ways. Harmonics use rotations of 2πj/s; if s is even, the last harmonic j=s/2 has one alternating state.

View matrices and state order

States: level, slope, cos 1, sin 1, cos 2, sin 2, cos 3, sin 3. Z corresponds to month 72; R is identity. Q shows disturbance variances, with zero for a fixed coefficient. H=σ²=0.0025.

T =
    1.000     1.000         0         0         0         0         0         0
        0     1.000         0         0         0         0         0         0
        0         0     0.866     0.500         0         0         0         0
        0         0    −0.500     0.866         0         0         0         0
        0         0         0         0     0.500     0.866         0         0
        0         0         0         0    −0.866     0.500         0         0
        0         0         0         0         0         0         0     1.000
        0         0         0         0         0         0    −1.000         0

Zₜ =
    1.000         0     1.000         0     1.000         0     1.000         0

R =
    1.000         0         0         0         0         0         0         0
        0     1.000         0         0         0         0         0         0
        0         0     1.000         0         0         0         0         0
        0         0         0     1.000         0         0         0         0
        0         0         0         0     1.000         0         0         0
        0         0         0         0         0     1.000         0         0
        0         0         0         0         0         0     1.000         0
        0         0         0         0         0         0         0     1.000

Q =
 0.000300         0         0         0         0         0         0         0
        0  0.000010         0         0         0         0         0         0
        0         0  0.000100         0         0         0         0         0
        0         0         0  0.000100         0         0         0         0
        0         0         0         0  0.000100         0         0         0
        0         0         0         0         0  0.000100         0         0
        0         0         0         0         0         0  0.000100         0
        0         0         0         0         0         0         0  0.000100

The 95% bands are marginal for the latent signal or component, conditional on fixed parameters. The signal band includes covariances among components and excludes future observation noise.

  • Log of data
  • Smoothed signal

Smoothed level

Smoothed slope

Smoothed seasonality

3
0.05
72
State dimension8
Seasonal frequencies3
Approximate log likelihood115.88
Smoothed signal, month 1446.0566
Combine level, trend, harmonics and regressor; the smoother and its bands are calculated from the matrices shown.

Filter, smoother and innovations

A linear Gaussian system uses state ata_t, observation yty_t, known matrices and independent noises:

at=Ttat−1+Rtηt,ηt∼N(0,Qt),yt=Ztat+εt,εt∼N(0,Ht).a_t=T_ta_{t-1}+R_t\eta_t,\quad \eta_t\sim N(0,Q_t),\qquad y_t=Z_ta_t+\varepsilon_t,\quad\varepsilon_t\sim N(0,H_t).

The state disturbance covariance is RtQtRtTR_tQ_tR_t^\mathsf T; do not confuse RtR_t with observation variance HtH_t. The Kalman filter predicts the state mean and covariance, calculates innovation vt=yt−Ztat∣t−1v_t=y_t-Z_ta_{t|t-1} with covariance FtF_t, and updates using Kt=Pt∣t−1ZtTFt−1K_t=P_{t|t-1}Z_t^\mathsf TF_t^{-1}. 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 FtF_t, the product of Gaussian innovation densities gives the exact likelihood of the observed model; the sum of their logarithms gives the log-likelihood. If yty_t is missing, retain the prediction as the filtered state and do not add that observation to the sum. A filtered mean at tt uses information through tt; a one-step prediction uses information through t−1t-1. 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,

(μtbt)=(1101)(μt−1bt−1)+(ηtζt),yt=μt+εt.\begin{pmatrix}\mu_t\\b_t\end{pmatrix}= \begin{pmatrix}1&1\\0&1\end{pmatrix} \begin{pmatrix}\mu_{t-1}\\b_{t-1}\end{pmatrix} +\begin{pmatrix}\eta_t\\\zeta_t\end{pmatrix}, \qquad y_t=\mu_t+\varepsilon_t.

Level and slope variances control their flexibility. The local level model removes the slope; a damped cycle uses a rotation block multiplied by ρ\rho with 0≤ρ<10\le\rho<1. 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 ss, trigonometric seasonality includes, for each harmonic jj, the block

Tj=(cos⁡λjsin⁡λj−sin⁡λjcos⁡λj),λj=2πj/s.T_j=\begin{pmatrix}\cos\lambda_j&\sin\lambda_j\\ -\sin\lambda_j&\cos\lambda_j\end{pmatrix}, \qquad \lambda_j=2\pi j/s.

The observation sums the first coordinate of each pair. If ss is even, the Nyquist harmonic j=s/2j=s/2 has one state with transition −1-1, not two. With all harmonics and no disturbances, there are s−1s-1 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 QQ and observation variance H>0H>0, let q=Q/Hq=Q/H. The stationary prediction of normalized variance p=P−/Hp=P^-/H satisfies p=p/(p+1)+qp=p/(p+1)+q, and the positive root gives p=(q+q2+4q)/2p=(q+\sqrt{q^2+4q})/2. The limiting gain is

K∞=pp+1=q2+4q−q2.K_\infty=\frac{p}{p+1} =\frac{\sqrt{q^2+4q}-q}{2}.

The update μ^t∣t=(1−Kt)μ^t∣t−1+Ktyt\hat\mu_{t|t}=(1-K_t)\hat\mu_{t|t-1}+K_ty_t becomes, when KtK_t converges, simple exponential smoothing with α=K∞\alpha=K_\infty. This equivalence concerns the steady-state recursion; transient initialization can differ.

InteractiveHow much should the level change?

The same sample of 80 observations remains fixed as q changes. The true state is known only because this series is simulated.

  • Observations
  • Simulated state
  • Filter
  • Smoother

Log likelihood on the grid, with observation variance fixed at 1.

Generating model: initial state 0, independent normal increments with variance 0.05 and independent normal observation noise with variance 1. The filter uses initial mean 0 and initial variance 100; this is a broad proper prior, not exact diffuse initialization.

The filter at each date uses only data up to that date; the smoother also uses later observations. For very small q, the smoother approaches an almost constant level, conditioned on the prior; for large q, both follow observations more closely. The maximum is searched only on the displayed grid.

−1.3
Selected ratio q0.0501
Steady-state gain0.200
Selected log likelihood−114.66
Grid maximum: q0.0158
Change the signal-to-noise ratio and compare filter, smoother and log-likelihood on the same simulated sample.

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 P=TPTT+RQRTP=TPT^\mathsf T+RQR^\mathsf T; 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 κ\kappa; different values of κ\kappa 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.

InteractiveA gap is not an observation
  • Available observation
  • Filter and band
  • Smoother and band
  • Linear interpolation

Time index from 0 to 59. The model is x₀ ∼ N(0, 4), xₜ = xₜ₋₁ + ηₜ and yₜ = xₜ + εₜ, with ηₜ ∼ N(0, Q), εₜ ∼ N(0, R) and independent disturbances. Q and R controls change the scale of the same reproducible disturbances. The true state can only be shown because these data are simulated.

Without an observation, the filter predicts without correction: state variance grows by Q per step. The RTS smoother also uses future data and must not be used as a forecast in a backtest. Bands are means ±1.96 conditional standard deviations of the latent state under the model and known parameters; R must be added to variance for a future observation.

Linear interpolation connects observations bordering each gap and exists only if data are present on both sides. It provides no uncertainty band and does not extrapolate gaps at the ends.

Interval action
20
39
29
0.12
0.4
1
Missing observations20 / 60
Index 29Missing
Filter: mean / deviation0.902 / 1.169
Smoother: mean / deviation−0.096 / 0.844
Interpolation at index0.006
Remove observations and compare filter, smoother and linear interpolation. The bands shown correspond to the latent state.

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 βt=βt−1+ηt\beta_t=\beta_{t-1}+\eta_t and yt=xtβt+εty_t=x_t\beta_t+\varepsilon_t, with observed xtx_t 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 tt uses yty_t: to predict yty_t, use the beta predicted before observing it. The following experiment knows the true beta only because it generates the data.

InteractiveDynamic beta without looking ahead

Beta for each date is predicted before observing that date’s returns. The window line starts when enough previous observations are available.

Date t
  • True beta
  • Kalman prediction
  • Previous window

RMSE compares each estimate with the true simulated beta, only on the 200 dates where both are available. In real data latent beta is not observable and this RMSE cannot be calculated directly. One path does not determine which method always wins.

Reproducible model: β₀ = 0.8 and βₜ = βₜ₋₁ + ηₜ, with normal ηₜ of variance 0.0025. The first asset return xₜ is standard normal and the second is yₜ = βₜxₜ + εₜ, with normal εₜ of variance 0.16. Innovations and x returns are independent. There is no intercept and returns are synthetic, in percentage points.

Kalman assumes β₀ has mean 0 and variance 1, and observation variance 0.16. For t after 0 it adds q to filtered variance; after recording the prediction it updates using xₜ and yₜ. The window estimates Σxᵢyᵢ/Σxᵢ² using only dates from t−40 to t−1. The assumed initial filter value does not reveal the true beta.

The q control expresses how much beta can change according to the filter. The actual walk variance is 0.0025 in this simulation, but is unknown in a real application and must be estimated or selected without future information. A larger q usually makes the filter more sensitive to recent observations; it does not guarantee lower error in every sample.

40
0.00316
Kalman RMSE0.191
Window RMSE0.249
Dates compared200
Seed2619
Compare the Kalman-predicted beta with a regression estimated on the previous window; both use information available before the evaluated return.

State-space forecasting propagates mean and covariance through TT and RQRTRQR^\mathsf T and then applies ZZ and adds HH for the observation. If future regressor xtx_t 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.

[ ]Filter and smoother from scratchBrowser
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,P

Lab: 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.

[ ]Structural matricesBrowser
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.

[ ]Fitting with missing observationsBrowser
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.

[ ]Check filter and componentsBrowser
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.

[ ]Maximum likelihood with a broad priorBrowser
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.

[ ]A controlled outlierBrowser
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 HH; latent-state variance does not. The interval below treats estimated parameters as known.

[ ]Forecast and intervalBrowser
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 (Yt,εt)(Y_t,\varepsilon_t) stores the current observation and innovation. The same noise enters both parts: its covariance is σ2RRT\sigma^2RR^\mathsf T, 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.

[ ]ARMA and exact KalmanBrowser
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.

[ ]Dynamic beta with temporal calibrationBrowser
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 βt\beta_t changes, its variation also changes the spread: Δ(yt−βtxt)=Δyt−βtΔxt−(βt−βt−1)xt−1\Delta(y_t-\beta_tx_t)=\Delta y_t-\beta_t\Delta x_t-(\beta_t-\beta_{t-1})x_{t-1}. 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

ProofFrom Riccati to exponential smoothing
Prove: For a local level model with Q>0 and H>0, show that the stationary filter gain yields the same recursion as simple exponential smoothing.
0
Write p=P⁻/H and q=Q/H.

Step 1 of 3. Which equation does the normalized predicted variance satisfy at steady state?

NumericGain of a local level
If observation variance is 4 and level evolution variance is 1, what is the steady-state filter gain? Give three decimal places.
QuizInitializing a trend
Why is a local level with positive evolution noise not initialized with a stationary distribution, and what does diffuse initialization represent?
CodeGeneral ARMA in states
Implement arma_to_statespace(phi, theta, sigma2) for a causal zero-mean ARMA, with AR and MA coefficients in lag order and positive MA convention. Return T, Z, W and stationary P₀, where W is the state shock covariance. Retain the necessary lags of Y and ε and allow empty AR or MA. Reject nonpositive σ² and unstable AR roots. Tests compare Kalman likelihood against the exact joint covariance.
import numpy as np
from scipy.linalg import solve_discrete_lyapunov

def arma_to_statespace(phi, theta, sigma2):
  pass
Shift+Enter to run
CodeSeasons as rotations
Implement seasonal_transition(s,k). Return T, Z and a matrix M whose rows are Z·Tᵗ for t=0,…,s−1, with k harmonics of period s≥2 and 1≤k≤⌊s/2⌋. Each ordinary harmonic occupies a state pair with a rotation matrix and Z selects its first coordinate. If s is even and j=s/2, use a single state with transition −1. Use M to check that with all harmonics and no disturbances, the signals generated over one period span the space of zero-sum seasonal vectors.
import numpy as np
from scipy.linalg import block_diag

def seasonal_transition(s,k):
  pass
Shift+Enter to run
Key idea

State 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.