Loading results...
A synthetic pair with a known hedge ratio, filtered live in your browser. Change the process noise (how fast the filter lets the hedge ratio move) and the measurement noise (how much of each surprise it attributes to noise) and watch every intermediate quantity: gain, prediction and update variances, innovations and their bands, the likelihood surface, and what a trader would have earned.
Formation = first 500 days; trading = last 500. Measurement noise = multiplier × ĥ, the static-OLS residual variance of the formation window. Trades fill one day after the signal; the hedge is frozen at entry. The Kalman z is the innovation divided by √Ft: if the measurement noise is set too high, z is compressed and the filter never reaches the entry level (try ×1). Colours: Kalman blue, static OLS orange, rolling OLS aqua, truth dashed.
Formation-window log-likelihood over the process/measurement noise grid. The cross marks your setting, the ring the maximum. A maximum at large δ means the model prefers to track the spread rather than trade it.
How much of today's surprise moves β. It starts large (diffuse prior) and settles where process and measurement noise balance.
Named pairs on daily data to November 2026: semiconductors, technology, industrials and controls. They are hand-picked companies that exist today, so they illustrate the methods; they are not evidence (the CRSP study is). Only derived analytics are shown, never the instruments' own prices.
EG p = Engle-Granger p-value on the last two years. Verdict = the Kalman-hedge model's "is this residual tradable?" check at the last date (expected return net of costs and borrow, convergence probability, break alarms). Sharpe columns = walk-forward backtests with the configurations frozen on CRSP validation (net of costs).
Loading study...
$$y_t = d_t + Z_t\alpha_t + \varepsilon_t,\quad \varepsilon_t\sim N(0,H_t)\qquad\qquad \alpha_{t+1} = c_t + T_t\alpha_t + R_t\eta_t,\quad \eta_t\sim N(0,Q_t)$$
\(\alpha_t\) is the hidden state, \(Z_t\) maps it to what we observe, \(H_t\) is measurement noise, \(T_t\) moves the state forward, \(Q_t\) is how far it may move per day (process noise), \(R_t\) selects which states the shocks hit. For a pair of log prices \(y_t\) (leg A) and \(x_t\) (leg B): $$y_t = \alpha_t + \beta_t (x_t - c) + \varepsilon_t,\qquad \begin{pmatrix}\alpha_{t+1}\\ \beta_{t+1}\end{pmatrix} = \begin{pmatrix}\alpha_t\\ \beta_t\end{pmatrix} + \eta_t$$ so \(Z_t = [1,\; x_t - c]\) is time-varying and \(T = I\). Centring at \(c = x_1\) changes no fitted value but makes \([1, x_t]\) well conditioned (log prices near 4 are almost collinear with the constant).
src/kpt/ssm/model.py, models.py
If \(a\) and \(y\) are jointly normal, \(E[a\mid y] = \mu_a + \Sigma_{ay}\Sigma_{yy}^{-1}(y-\mu_y)\) and \(\operatorname{Var}[a\mid y] = \Sigma_{aa} - \Sigma_{ay}\Sigma_{yy}^{-1}\Sigma_{ya}\). Given data to \(t-1\), \(\alpha_t\sim N(a_{t|t-1}, P_{t|t-1})\) and \(y_t = d_t + Z_t\alpha_t + \varepsilon_t\), so \(\Sigma_{ay} = P_{t|t-1}Z_t'\) and \(\Sigma_{yy} = Z_tP_{t|t-1}Z_t' + H_t\). That is the whole filter:
$$v_t = y_t - d_t - Z_t a_{t|t-1},\quad F_t = Z_tP_{t|t-1}Z_t' + H_t,\quad K_t = P_{t|t-1}Z_t'F_t^{-1}$$ $$a_{t|t} = a_{t|t-1} + K_t v_t,\qquad P_{t|t} = (I-K_tZ_t)P_{t|t-1}(I-K_tZ_t)' + K_tH_tK_t'$$ $$a_{t+1|t} = c_t + T_t a_{t|t},\qquad P_{t+1|t} = T_tP_{t|t}T_t' + R_tQ_tR_t'$$
The gain \(K_t\) is a regression coefficient of the state on the surprise. The Joseph form for \(P_{t|t}\) stays symmetric and positive semi-definite under rounding error; \(F_t\) is inverted through its Cholesky factor.
src/kpt/ssm/filter.py (generic), fast.py (unrolled 2- and 3-state versions, checked to 1e-13)
The innovations are independent \(N(0, F_t)\) given the past (prediction-error decomposition), so $$\log L(\theta) = -\tfrac12\sum_t\left[p\log 2\pi + \log|F_t| + v_t'F_t^{-1}v_t\right].$$ Variances are optimised as \(\exp(u)\), AR coefficients as \(\tanh(u)\); standard errors come from the inverse Hessian with the delta method. If every variance is proportional to \(\sigma^2\), it concentrates out: \(\hat\sigma^2 = \tfrac1N\sum v_t^2/F_t^*\).
Finding: on real pairs the likelihood is maximised by LARGE process noise (median \(q_\beta/h \approx 56\)): the random-walk intercept absorbs the mean-reverting spread, the innovations become white noise, and the trading signal disappears. The parameter that fits best trades worst.
src/kpt/ssm/mle.py, fast.py (fit_dynreg, fit_pci)
Backward pass (Rauch-Tung-Striebel): \(J_t = P_{t|t}T_t'P_{t+1|t}^{-1}\), \(a_{t|n} = a_{t|t} + J_t(a_{t+1|n} - a_{t+1|t})\), \(P_{t|n} = P_{t|t} + J_t(P_{t+1|n} - P_{t+1|t})J_t'\), and \(\operatorname{Cov}(\alpha_{t+1},\alpha_t\mid Y_n) = P_{t+1|n}J_t'\). The smoothed path uses future data: it is a diagnostic, never a signal.
EM (Shumway-Stoffer) replaces unobserved states by smoothed moments: \(Q \leftarrow \tfrac1{n-1}\sum E[(\alpha_t - T\alpha_{t-1})(\alpha_t - T\alpha_{t-1})']\), \(H \leftarrow \tfrac1n\sum[(y_t - Z_ta_{t|n})(\cdot)' + Z_tP_{t|n}Z_t']\). Each step cannot lower the likelihood (checked in the tests; full-matrix EM reproduces pykalman exactly).
src/kpt/ssm/smoother.py, em.py
For a time-invariant model \(P\) converges to the Riccati fixed point. In the local-level model with signal-to-noise \(q\): \(\bar P = h\,(q + \sqrt{q^2+4q})/2\) and \(\bar K = \bar P/(\bar P + h)\) — exponential smoothing with weight \(\bar K\), equivalent in mean lag to a rolling window of \((2-\bar K)/\bar K\) days. With \(Q = 0\) the filter is recursive least squares (an expanding-window OLS), and its standardised one-step errors are the recursive residuals of the CUSUM test.
src/kpt/ssm/steady_state.py, src/kpt/stats/ols.py (recursive_ls)
$$y_t = \beta_t (x_t - c) + l_t + m_t + \varepsilon_t,\quad \beta_{t+1} = \beta_t + \eta^\beta_t,\quad l_{t+1} = l_t + \eta^l_t,\quad m_{t+1} = \phi m_t + \eta^m_t$$ Only \(m_t\) (AR(1), half-life \(-\ln 2/\ln\phi\)) is a deviation a trader can expect back; \(l_t\) is permanent drift. The share of spread-change variance that is mean-reverting is \(R^2_{MR} = \frac{2q_m/(1+\phi)}{2q_m/(1+\phi) + q_l}\) (Clegg & Krauss 2018). The signal is \(m_{t|t}/\mathrm{sd}(m)\).
src/kpt/ssm/fast.py (pci_filter, fit_pci), signals/hedges.py (KalmanSpread)
\(dS = \kappa(\mu - S)dt + \sigma dW\) sampled daily is AR(1) with \(\phi = e^{-\kappa}\); half-life \(\ln 2/\kappa\). In units \(z = (S-\mu)/\sigma_s\) the generator is \(\mathcal L f = \kappa(f'' - zf')\), whose scale density is \(e^{z^2/2}\). A short-spread trade at \(z_0\) closing at \(z_e < z_0\) or stopping at \(z_s > z_0\) converges first with probability $$P = \frac{\operatorname{erfi}(z_s/\sqrt2) - \operatorname{erfi}(z_0/\sqrt2)}{\operatorname{erfi}(z_s/\sqrt2) - \operatorname{erfi}(z_e/\sqrt2)},$$ independent of \(\kappa\): speed changes when, not which. With daily monitoring and a time stop the same quantities, the expected holding time and the expected exit level come from a grid recursion on the exact AR(1) transition (checked against Monte Carlo).
src/kpt/stats/ou.py, signals/opportunity.py
ADF regression \(\Delta y_t = a + \rho y_{t-1} + \sum\gamma_i\Delta y_{t-i} + e_t\): the t-ratio of \(\rho\) has a Dickey-Fuller distribution (MacKinnon p-values). Engle-Granger tests the OLS residual, whose critical values are more negative because \(\hat\beta\) was chosen to make it look stationary. CUSUM: \(W_r = \sum_{t\le r} w_t/\hat\sigma\) of recursive residuals with bounds \(\pm a[\sqrt{n-k} + 2(r-k)/\sqrt{n-k}]\). Page: \(S^+_t = \max(0, S^+_{t-1} + e_t - k)\), alarm at \(h\). Andrews' sup-F: the largest Chow statistic over trimmed break dates (critical values simulated from Brownian bridges). PELT: exact penalised segmentation with pruning.
Finding: textbook CUSUM and PELT assume independent errors. A pairs spread is persistent, so on stable synthetic pairs the 5% CUSUM rejects 96% of the time and PELT always finds a change point. Monitor the spread's own innovations instead, with thresholds calibrated to a target false-alarm rate.
src/kpt/stats/unitroot.py, breaks.py
Full step-by-step derivations: docs/math in the repository.
Loading...