Concepts and theory

Background reading

Concepts and theory

Approach 1

Open lab →

Market factor model

Each asset's sensitivities to observable market factors are time-varying states tracked by a Kalman filter; the state-space form then gives exact multi-step forecasts with volatility-scaled bands.

How does the model work?

Asset returns y_t load on a vector x_tthat stacks the current and p lagged values of the observable factors u_t. The loadings are not fixed: each asset's β_t follows a random walk and is estimated by its own Kalman filter.

y_(i,t) = x_tᵀ β_(i,t) + ε_(i,t),   ε ~ N(0, σ²_i)
β_(i,t) = β_(i,t-1) + η_(i,t),   η ~ N(0, q_i I)
x_t = A · x_(t-1) + B · ξ_t,   ξ ~ N(0, Q)

The drift q_i is chosen per asset by one-step prediction error; zero drift recovers a constant beta (recursive least squares). A is the companion form of a per-factor AR(1) and Q the full covariance of the factor innovations.

Why time-varying betas?

On the bundled data half-sample market betas move by several standard errors within nine months, so a full-sample constant-beta regression is misspecified. Filtering the loadings is the one place a Kalman filter genuinely earns its keep with observed factors; an earlier version filtered the factor state itself, which is fully observed and has nothing to estimate.

How are the forecasts and bands built?

Multi-step means propagate the last factor state through A and the latest betas. Variances combine shared factor uncertainty, each asset's beta uncertainty (which grows with the horizon through the drift) and idiosyncratic noise. Both noise levels are scaled by the ratio of recent realised volatility to its sample average, so the fan reflects the current regime; the unscaled bands were about 20% too narrow out of sample. For a single asset the bands are drawn at the empirical quantiles of the model's own standardised forecast errors rather than at ±1 and ±2 standard deviations: daily returns have a narrower middle and fatter tails than a bell curve. That correction held up on 2025–2026 data and did not on a 31-day holdout, so read the inner band as approximate.

Forecast vs nowcast

The page can compare actual returns against two series. The forecast lags both the factor state and the betas by one day (the drift, noise level and means are still fitted on the whole window, so treat it as an in-sample conditional forecast; the out-of-sample picture comes from the forecast backtest script). The nowcast conditions on the factor's realised same-day return with yesterday's beta and shows how much of each day's move the factors explain — explanatory power, not skill.

What outputs does this approach show?

Cumulative actual vs predicted returns, a forecast fan chart with ±1σ and ±2σ bands, day-by-day prediction errors, a heatmap of the latest sensitivities, and each asset's beta to each factor over time.

Approach 2

Open lab →

Hidden factor model

A two-step dynamic factor model: EM-PCA extracts latent factors, a fitted vector autoregression supplies their dynamics, and a Kalman filter turns both into one-step-ahead predictions and multi-step forecasts.

What is the hidden factor model?

The latent state is a low-dimensional summary of common variation across your assets. Given an n × T return matrix Y and k factors, the method recovers a loading matrix C (assets × factors) and a factor trajectory X (factors × time). The Kalman state stacks the current factor and p lags, so its dimension is m = k × (p + 1), while k must stay below the number of assets (with k = n there is nothing left to call noise).

How does EM-PCA infer the latent factors?

The factors are the leading principal components of the return panel. They are now computed exactly, by a singular value decomposition. Earlier versions reached the same subspace with the EM iterations below (the zero-noise EM for PCA, Listing 9.10 of the reference text), stopping slightly short of it; the name EM-PCA has stuck:

  • E-step: project data onto the current loading estimate, X = (CᵀC)⁻¹ Cᵀ Y.
  • M-step: update loadings, C = Y Xᵀ (X Xᵀ)⁻¹.
  • Iterate until the mean-squared reconstruction error converges.

Factors are identified only up to an invertible transform, so they are reported on their principal axes: orthonormal loadings, uncorrelated scores ordered by variance. The decomposition is deterministic, so nothing depends on a random initialisation.

Where do the factor dynamics come from?

A ridge-shrunk vector autoregression of order p + 1 is fitted to the factor scores and written in companion form:

x_t = [f_t; f_(t-1); …; f_(t-p)]
x_t = A · x_(t-1) + B · η_t,   η_t ~ N(0, Q)
y_t = [C, 0, …, 0] · x_t + ε_t,   ε_t ~ N(0, E)

A carries the fitted persistence of the factors and Q their innovation covariance, both in the factors' own units. Daily factor returns are close to white noise, so the ridge penalty pulls the coefficients toward zero — the “predict the mean” prior — and the companion matrix is kept stationary. An earlier version assumed a shift-register transition instead, which is false for PCA scores and made the predictions worse than a constant.

How does Kalman filtering apply to the latent state?

A standard Kalman filter runs on the latent state with measurement noise E estimated from the EM residuals Y − C·X. Every in-sample prediction is the prior C·x_(t|t-1) + μ: the state lags by one day, while the loadings, dynamics and noise are fitted on the whole window, so it is an in-sample conditional forecast. Multi-step forecasts propagate the final posterior analytically — no Monte Carlo required.

What metrics indicate a good fit?

The lab reports a fit-error (MSE) metric that quantifies how well the latent factors explain the historical returns, plus cumulative-return, prediction-accuracy and forecast-fan charts. Expect the one-step predictions to stay close to the mean: that is what honest daily forecasts look like.

Approach 3

Open lab →

Adaptive Kalman + Mean-Variance Optimiser

A five-step pipeline: latent dynamic factor model → adaptive Kalman filter → covariance conditioning → turnover-penalised, cost-aware MVO → optional PID control.

How does the adaptive measurement-noise update work?

The same latent factor model as Approach 2 feeds a linear Kalman filter whose noise covariances are both refreshed at every step: the idiosyncratic E from the post-fit residual (the Myers–Tapley form) and the factor innovation covariance Q from the filtered factor innovations:

E_t = (1 − α) · E_(t-1) + α · diag( r_t r_tᵀ + C · P_(t|t) · Cᵀ )
Q_t = (1 − α) · Q_(t-1) + α · ( η̂_t η̂_tᵀ + P_(t|t)[factors] ),   α = 0.1

In equities most variance is systematic, so adapting E alone cannot follow a volatility regime; adapting Q is what makes the risk model track it (correlation with true conditional variance 0.82 versus 0.13 on a GARCH panel). In walk-forward mode the model is fitted on a burn-in window only and refit periodically on past data, with the Kalman state rotated to the new loading basis.

By default the optimiser does not trade on this covariance. On real data its speed (a memory of about a week) cost more in noise than it gained: a slower estimate with 63-day volatilities and 125-day correlations (an iterated EWMA) scored better out of sample, gave lower realised volatility and traded about a quarter as much. The Kalman model still supplies the factor attribution, the stress test and the forecast fan, and the advanced settings can hand its covariance back to the optimiser.

What does the covariance conditioning step do?

The risk-model covariance S_t (the iterated EWMA by default, or C P_t Cᵀ + E_t) is blended toward a scaled identity using the closed-form coefficient of Chen, Wiesel, Eldar & Hero (2010):

S_t* = (1 − ρ) · S_t + ρ · (tr(S_t) / n) · I_n

Their optimality result is for a sample covariance built from i.i.d. observations. S_t here is not one, so treat ρ as a principled conditioning heuristic rather than an oracle-optimal shrinkage; in practice it is small.

How is the turnover-penalised portfolio optimised?

At each rebalancing date the model solves:

max_w   h · ( wᵀ μ̂_t − (λ / 2) · wᵀ S_t* w ) − κ · ‖w − w_prev‖₁ − (γ / 2) · ‖w − 1/n‖²
s.t.   wᵀ1 = 1,   0 ≤ w ≤ w_max

μ̂_t is the Kalman-predicted return vector, shrunk toward the cross-sectional average of the assets' trailing means and capped at a per-asset Sharpe ratio. By default the shrinkage is complete, so μ̂_t is flat and the optimiser runs as a pure risk model; the return signal has shown no out-of-sample value on daily data and the slider lets you dial it back in. h is the expected holding period (default 63 days), which puts the expected return and risk of the position on the same horizon as the one-off trading cost; S_t* is the conditioned covariance; λ is the risk-aversion coefficient; κ is the one-way transaction-cost rate; and γ is an optional equal-weight anchor that is off by default. The L1 turnover term makes this an SOCP, solved by CLARABEL with SCS as fallback.

The backtest charges κ per unit of turnover against realised returns, reports its KPIs on the post-burn-in window only, and shows the Sharpe difference from equal weight with a block-bootstrap interval. Expect performance close to the equal-weight benchmark at somewhat lower volatility: the optimiser's value is in the risk model and cost-aware trading.

What does the PID-controlled turnover penalty do?

When PID control is enabled, a proportional-integral controller modulates κ at each rebalance to keep realised L1 turnover near a user-specified target band:

  • Realised > target → over-trading → raise κ to suppress further turnover.
  • Realised < target → under-trading → relax κ to permit more movement.

A single pid_aggressiveness ∈ [0, 1] knob maps to internal proportional and integral gains. Derivative action is omitted because typical rebalance cadences are too noisy for it to be useful.

What outputs does this approach show?

Time-varying portfolio weights (stacked area), cumulative return against an equal-weight benchmark, drawdown comparison, rolling 30-day Sharpe ratio, an efficient frontier at the final risk-model covariance, per-factor risk attribution, plus headline KPIs (net total return, Sharpe, max drawdown, average turnover, total cost).