Kalman
polars_ts.bayesian.kalman
Kalman Filter and Rauch-Tung-Striebel (RTS) smoother.
Linear Gaussian state-space model:
x_t = F @ x_{t-1} + w_t, w_t ~ N(0, Q) (state transition)
y_t = H @ x_t + v_t, v_t ~ N(0, R) (observation)
The Kalman filter computes filtered state estimates (forward pass), and the RTS smoother refines them (backward pass).
KalmanResult
dataclass
Container for Kalman filter / smoother output.
Attributes
filtered_states
Array of shape (T, n) — filtered state means.
filtered_covs
Array of shape (T, n, n) — filtered state covariances.
predicted_states
Array of shape (T, n) — one-step-ahead predicted state means.
predicted_covs
Array of shape (T, n, n) — one-step-ahead predicted covariances.
smoothed_states
Array of shape (T, n) — smoothed state means (after RTS pass).
None if smoothing was not requested.
smoothed_covs
Array of shape (T, n, n) — smoothed state covariances.
None if smoothing was not requested.
log_likelihood
Total log-likelihood of the observations.
KalmanFilter
Kalman Filter with optional RTS smoother.
Parameters
F
State transition matrix of shape (n, n).
H
Observation matrix of shape (m, n) where m is the
observation dimension and n is the state dimension.
Q
Process noise covariance of shape (n, n).
R
Observation noise covariance of shape (m, m).
x0
Initial state mean of shape (n,). Defaults to zeros.
P0
Initial state covariance of shape (n, n).
Defaults to 1e6 * I (diffuse prior).
filter(y)
Run the Kalman filter forward pass.
Parameters
y
Observations of shape (T,) or (T, m).
Use np.nan for missing observations.
Returns
KalmanResult Filtered states, covariances, and log-likelihood.
smooth(y)
Run the Kalman filter + RTS smoother.
Parameters
y
Observations of shape (T,) or (T, m).
Returns
KalmanResult Filtered and smoothed states, covariances, and log-likelihood.
kalman_filter(df, F, H, Q, R, x0=None, P0=None, smooth=True, id_col='unique_id', target_col='y')
Apply Kalman filter (and optional RTS smoother) to each time series.
Convenience function that wraps :class:KalmanFilter for panel data.
Parameters
df
DataFrame with columns id_col and target_col.
F
State transition matrix (n, n).
H
Observation matrix (m, n).
Q
Process noise covariance (n, n).
R
Observation noise covariance (m, m).
x0
Initial state mean (n,). Defaults to zeros.
P0
Initial state covariance (n, n). Defaults to diffuse prior.
smooth
Whether to run the RTS smoother after filtering.
id_col
Column identifying each time series.
target_col
Column with the observed values.
Returns
dict[str, KalmanResult] Mapping from series ID to the filter/smoother result.