squeeze-kernel 1.0.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,30 @@
1
+ """
2
+ Squeeze Kernel Covariance Estimator
3
+ ====================================
4
+
5
+ Streaming, PSD-by-construction covariance estimator whose public surface
6
+ is one number: everything else derives from that decay, is a structural
7
+ constant of the method, or is state computed online -- including per-asset
8
+ market clocks read from the correlation structure itself.
9
+
10
+ Quick start::
11
+
12
+ import numpy as np
13
+ from squeeze_kernel import SqueezeKernel
14
+
15
+ returns = np.random.default_rng(42).normal(0.0, 0.01, size=(250, 30))
16
+
17
+ sk = SqueezeKernel(lam=0.996) # the entire public surface
18
+ for r_t in returns:
19
+ sk.update(r_t) # NaN marks missing assets
20
+
21
+ cov = sk.covariance()
22
+ corr = sk.correlation()
23
+ """
24
+
25
+ from squeeze_kernel.core import SqueezeKernel
26
+ from squeeze_kernel.batch import estimate_squeeze_cov
27
+
28
+ __all__ = ["SqueezeKernel", "estimate_squeeze_cov"]
29
+
30
+ __version__ = "1.0.0"
@@ -0,0 +1,52 @@
1
+ """Batch estimation over an entire returns panel."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+ from numpy.typing import ArrayLike
7
+
8
+ from squeeze_kernel.core import SqueezeKernel
9
+
10
+
11
+ def estimate_squeeze_cov(
12
+ returns: ArrayLike,
13
+ *,
14
+ lam: float = 0.996,
15
+ with_corr: bool = True,
16
+ with_weights: bool = False,
17
+ ) -> tuple[np.ndarray, np.ndarray | None, np.ndarray | None]:
18
+ """Run :class:`SqueezeKernel` over a panel and collect the estimate path.
19
+
20
+ Parameters
21
+ ----------
22
+ returns : array-like, shape (T, n)
23
+ Daily returns; NaN marks missing observations.
24
+ lam : float
25
+ The estimator's single parameter (default 0.996).
26
+ with_corr : bool
27
+ Also return the correlation path.
28
+ with_weights : bool
29
+ Also return the per-day kernel weight.
30
+
31
+ Returns
32
+ -------
33
+ cov : ndarray, shape (T, n, n)
34
+ corr : ndarray or None, shape (T, n, n)
35
+ weights : ndarray or None, shape (T,)
36
+ """
37
+ values = np.asarray(returns, dtype=np.float64)
38
+ if values.ndim != 2:
39
+ raise ValueError(f"Expected 2D returns, got shape {values.shape}.")
40
+ t_total, n_assets = values.shape
41
+ sk = SqueezeKernel(lam=lam)
42
+ cov = np.empty((t_total, n_assets, n_assets), dtype=np.float64)
43
+ corr = np.empty_like(cov) if with_corr else None
44
+ weights = np.empty(t_total, dtype=np.float64) if with_weights else None
45
+ for t in range(t_total):
46
+ w_t = sk.update(values[t])
47
+ cov[t] = sk.covariance()
48
+ if corr is not None:
49
+ corr[t] = sk.correlation()
50
+ if weights is not None:
51
+ weights[t] = w_t
52
+ return cov, corr, weights
squeeze_kernel/core.py ADDED
@@ -0,0 +1,598 @@
1
+ """The Squeeze Kernel covariance estimator.
2
+
3
+ One public number, ``lam``; everything else derives from it, is a
4
+ structural constant of the method, or is state computed online:
5
+
6
+ - a ladder of three correlation timescales with decays
7
+ ``(lam**4, lam, lam**(1/4))`` and prior weights proportional to the
8
+ square root of the half-life;
9
+ - per-asset variance on a ladder of half-lives ``(h/16, h/4, h)``,
10
+ pooled panel-wide by weights that move on tanh-saturated evidence;
11
+ - per-asset market clocks read from the correlation neighbourhood (the
12
+ Schur-square-weighted mean of squared surprises) through the saturating
13
+ kernel ``w = a / (a + kappa)``, with the kernel scale
14
+ ``kappa = EWMA(activity) / 3`` as state;
15
+ - a diagonal-congruence update of each timescale's correlation state on
16
+ those clocks, the day's innovation scaled by ``omega = n/m`` with ``m``
17
+ its Mahalanobis distance under the previous forecast;
18
+ - per timescale, a learned pool of the raw correlation, its
19
+ equicorrelation level and its Hadamard square, with the self-tuning
20
+ intensity rule's split ``(1-a, a(1-a), a**2)`` as the prior;
21
+ - timescale weights and pool splits moved by exponentiated gradient on
22
+ the blend's own log score at the null-calibrated temperature.
23
+
24
+ Positive semi-definite by construction, missing values (NaN) native,
25
+ ``O(K n^2)`` state work plus one Cholesky factorisation of the blend and
26
+ ``K`` positive-definiteness checks a day.
27
+ """
28
+ from __future__ import annotations
29
+
30
+ import numpy as np
31
+ from numpy.typing import ArrayLike
32
+
33
+ try:
34
+ # SciPy's LAPACK bindings factorise an SPD matrix several times faster
35
+ # than the NumPy route and compute the identical quantities.
36
+ from scipy.linalg import cho_factor as _cho_factor, cho_solve as _cho_solve
37
+ except ImportError: # pragma: no cover
38
+ _cho_factor = _cho_solve = None
39
+
40
+ __all__ = ["SqueezeKernel"]
41
+
42
+ # Structural constants of the method (each bracketed by ablation in the paper).
43
+ _B = 4.0 # ladder spacing: timescales (h/b, h, h*b)
44
+ _THETA = 0.5 # timescale prior weights ~ h**theta
45
+ _KAPPA_C = 1.0 / 3.0 # kernel scale: kappa = kappa_c * EWMA(activity)
46
+ _EPS = 1e-8 # numerical floor, squared-return units
47
+
48
+
49
+ class _BlendGradient:
50
+ """Exponentiated gradient on the BLEND's log score, at the
51
+ null-calibrated temperature.
52
+
53
+ The emitted covariance is the pool of the timescales' correlations,
54
+ each itself a pool of three experts, times the volatilities. The
55
+ Gaussian log score of the blend has gradient
56
+
57
+ d ell / d w_k = -1/2 tr(Sigma^-1 Sigma_k) + 1/2 u' Sigma_k u,
58
+ u = Sigma^-1 r,
59
+
60
+ so the update moves the blend rather than selecting a timescale. The
61
+ gradient is studentised across timescales (and across experts within
62
+ one) by its running rms and scaled by sqrt(2 eps), eps the fixed-share
63
+ rate: the accumulated log-odds then have unit variance under
64
+ uninformative evidence. Evidence memory: the fastest timescale.
65
+ Causal: ``score`` reads the previous step's forecast, ``advance``
66
+ updates the weights used for the next blend.
67
+ """
68
+
69
+ _JITTER = 1e-12
70
+ _FLOOR = 1e-8 # spectral floor of the scored blend
71
+ _CERT = 10.0 # certify lambda_min >= _CERT * _FLOOR before skipping the floor
72
+
73
+ @staticmethod
74
+ def _solve(sig: np.ndarray, r: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
75
+ """(sig^-1 r, sig^-1) from one Cholesky factorisation."""
76
+ if _cho_factor is not None:
77
+ cf = _cho_factor(sig, lower=True, check_finite=False)
78
+ return (_cho_solve(cf, r, check_finite=False),
79
+ _cho_solve(cf, np.eye(sig.shape[0]), check_finite=False))
80
+ sinv = np.linalg.inv(sig)
81
+ return sinv @ r, sinv
82
+
83
+ def __init__(self, half_lives: np.ndarray, prior: np.ndarray,
84
+ n_experts: int = 3) -> None:
85
+ hl = np.asarray(half_lives, dtype=np.float64)
86
+ self.prior = np.asarray(prior, dtype=np.float64)
87
+ self.w = self.prior.copy()
88
+ self.eps = float(1.0 - 2.0 ** (-1.0 / float(hl.min())))
89
+ self._gamma_scale = 2.0 ** (-1.0 / float(np.median(hl)))
90
+ self.scale = 1.0
91
+ self.prev_sig: list[np.ndarray] | None = None
92
+ self.prev_w: np.ndarray | None = None
93
+ # Each timescale's correlation is a convex combination of three PSD
94
+ # unit-diagonal experts -- raw, equicorrelation at its mean level,
95
+ # Schur square -- whose prior is the intensity rule's split
96
+ # (1-a, a(1-a), a^2) and whose weights are moved by the same
97
+ # gradient step, studentised within the timescale. Starts uniform
98
+ # and forgets toward the prior at the fixed-share rate.
99
+ self.n_experts = int(n_experts)
100
+ self.v = np.full((hl.size, self.n_experts), 1.0 / self.n_experts)
101
+ self.scale_v = np.ones(hl.size)
102
+ self.prev_comps: list[tuple[np.ndarray, ...]] | None = None
103
+ self.prev_prior: np.ndarray | None = None
104
+ self.prev_cov: np.ndarray | None = None
105
+ self.prev_vol: np.ndarray | None = None
106
+ self.prev_v: np.ndarray | None = None
107
+ self._gc: np.ndarray | None = None
108
+ # The day's Mahalanobis distance under the forecast, m = r' Sigma^-1 r
109
+ # on the observed subvector, and that subvector's size: read by the
110
+ # observation weight; NaN on a day the gradient abstains.
111
+ self.m_last = float("nan")
112
+ self.n_last = 0
113
+
114
+ def score(self, r_t: np.ndarray, finite: np.ndarray) -> np.ndarray | None:
115
+ """Gradient of the previous blend's log score at ``r_t`` (observed
116
+ subvector), one entry per timescale; ``None`` on a degenerate day."""
117
+ self.m_last = float("nan")
118
+ self.n_last = 0
119
+ if self.prev_sig is None or self.prev_w is None:
120
+ return None
121
+ idx = np.flatnonzero(finite)
122
+ if idx.size < 2:
123
+ return None
124
+ K = len(self.prev_sig)
125
+ full = idx.size == self.prev_sig[0].shape[0]
126
+ # The day counts only if every timescale's observed sub-block is
127
+ # positive definite (a newly listed asset enters with a zero row and
128
+ # fails this); otherwise the mixture keeps its weights for the day.
129
+ # The matrices held here are correlations (vol > 0 on observed
130
+ # assets, so PD of the correlation block <=> PD of the covariance).
131
+ for k in range(K):
132
+ sub = self.prev_sig[k] if full else self.prev_sig[k][np.ix_(idx, idx)]
133
+ try:
134
+ if _cho_factor is not None:
135
+ _cho_factor(sub, lower=True, check_finite=False)
136
+ else:
137
+ np.linalg.cholesky(sub)
138
+ except (np.linalg.LinAlgError, ValueError):
139
+ return None
140
+ prev_vol, prev_cov = self.prev_vol, self.prev_cov
141
+ assert prev_vol is not None and prev_cov is not None
142
+ # an asset observed today but without a variance state at the
143
+ # forecast has a zero covariance row: abstain, as the covariance
144
+ # factorisation would
145
+ if not full and np.any(prev_vol[idx] <= 0.0):
146
+ return None
147
+ sig = prev_cov if full else prev_cov[np.ix_(idx, idx)]
148
+ sig = 0.5 * (sig + sig.T)
149
+ # The spectrum is floored at _FLOOR before factorising: a
150
+ # near-singular early blend would otherwise hand the running scale
151
+ # one enormous gradient and silence the mixer for years. The floor
152
+ # acts only when lambda_min < _FLOOR, so factorise first and
153
+ # certify: the inverse gives lambda_min >= 1/||sig^-1||_F, and a
154
+ # certified day is bit-identical to the floored path (no floor, same
155
+ # factor). Uncertified or failed days take the eigenvalue floor.
156
+ sol: tuple[np.ndarray, np.ndarray] | None = None
157
+ try:
158
+ sol = self._solve(sig, r_t[idx])
159
+ fro = float(np.linalg.norm(sol[1]))
160
+ if not (np.isfinite(fro) and fro * self._CERT * self._FLOOR <= 1.0):
161
+ sol = None
162
+ except (np.linalg.LinAlgError, ValueError):
163
+ sol = None
164
+ if sol is None:
165
+ min_eig = float(np.linalg.eigvalsh(sig).min())
166
+ if min_eig < self._FLOOR:
167
+ sig = sig + np.eye(idx.size) * (self._FLOOR - min_eig)
168
+ try:
169
+ sol = self._solve(sig, r_t[idx])
170
+ except (np.linalg.LinAlgError, ValueError):
171
+ return None
172
+ u, sinv = sol
173
+ self.m_last = float(r_t[idx] @ u)
174
+ self.n_last = int(idx.size)
175
+ g = np.empty(K)
176
+ self._gc = None
177
+ prev_comps, prev_v = self.prev_comps, self.prev_v
178
+ assert prev_comps is not None and prev_v is not None
179
+ # Gradients on the expert CORRELATIONS:
180
+ # tr(Sinv (T o vv)) = sum((Sinv o vv) * T),
181
+ # u'(T o vv) u = (u o s)' T (u o s);
182
+ # the timescale gradient follows by linearity of the pool.
183
+ vo = prev_vol if full else prev_vol[idx]
184
+ mw = sinv * np.multiply.outer(vo, vo)
185
+ ut = u * vo
186
+ J = self.n_experts
187
+ gc = np.empty((K, J))
188
+ for k in range(K):
189
+ for j in range(J):
190
+ t_ = prev_comps[k][j]
191
+ ts = t_ if full else t_[np.ix_(idx, idx)]
192
+ gc[k, j] = -0.5 * float((mw * ts).sum()) + 0.5 * float(ut @ ts @ ut)
193
+ g[k] = float(prev_v[k] @ gc[k])
194
+ if not np.all(np.isfinite(g)):
195
+ return None
196
+ self._gc = gc
197
+ return g
198
+
199
+ def advance(self, g: np.ndarray | None) -> None:
200
+ if g is not None:
201
+ dd = g - g.mean()
202
+ rms = float(np.sqrt((dd @ dd) / dd.size))
203
+ self.scale = (self._gamma_scale * self.scale
204
+ + (1.0 - self._gamma_scale) * rms)
205
+ ell = (dd / (self.scale + self._JITTER)) * np.sqrt(2.0 * self.eps)
206
+ lw = np.log(np.maximum(self.w, 1e-300)) + ell
207
+ lw -= lw.max()
208
+ w = np.exp(lw)
209
+ self.w = w / w.sum()
210
+ if self._gc is not None and self.prev_prior is not None:
211
+ for k in range(self.v.shape[0]):
212
+ gc = self._gc[k]
213
+ if not np.all(np.isfinite(gc)):
214
+ continue
215
+ ddv = gc - gc.mean()
216
+ rmsv = float(np.sqrt((ddv @ ddv) / float(self.n_experts)))
217
+ self.scale_v[k] = (self._gamma_scale * self.scale_v[k]
218
+ + (1.0 - self._gamma_scale) * rmsv)
219
+ lv = (np.log(np.maximum(self.v[k], 1e-300))
220
+ + (ddv / (self.scale_v[k] + self._JITTER)) * np.sqrt(2.0 * self.eps))
221
+ lv -= lv.max()
222
+ vk = np.exp(lv)
223
+ vk /= vk.sum()
224
+ self.v[k] = (1.0 - self.eps) * vk + self.eps * self.prev_prior[k]
225
+ self.w = (1.0 - self.eps) * self.w + self.eps * self.prior
226
+
227
+ def record(self, rung_corrs: list[np.ndarray],
228
+ comps: list[tuple[np.ndarray, ...]],
229
+ prior: np.ndarray, cov: np.ndarray, vol: np.ndarray) -> None:
230
+ """Cache this step's forecast for next step's ``score``: the
231
+ timescale correlations (pooled), the expert correlations, the
232
+ rule's prior split, the emitted covariance and the volatilities."""
233
+ self.prev_sig = rung_corrs
234
+ self.prev_w = self.w.copy()
235
+ self.prev_comps = comps
236
+ self.prev_prior = prior.copy()
237
+ self.prev_cov = cov
238
+ self.prev_vol = vol
239
+ self.prev_v = self.v.copy()
240
+
241
+ @property
242
+ def tilt(self) -> float:
243
+ """Signed departure of the blend from its prior toward the fast (+)
244
+ or slow (-) timescale."""
245
+ return float(self.w[0] - self.prior[0] - (self.w[-1] - self.prior[-1]))
246
+
247
+
248
+ class _Engine:
249
+ """State and daily update for a panel of ``n_assets``."""
250
+
251
+ def __init__(self, n_assets: int, lam: float) -> None:
252
+ n = n_assets
253
+ eps = _EPS
254
+ self.n_assets = n
255
+ self.epsilon = eps
256
+ h = float(-1.0 / np.log2(lam))
257
+ hl = np.asarray((h / _B, h, h * _B), dtype=np.float64)
258
+ self._corr_lam = 2.0 ** (-1.0 / hl)
259
+ w = hl ** _THETA
260
+ self._corr_w = w / w.sum()
261
+ K = hl.size
262
+ self._Q_list = [np.eye(n, dtype=np.float64) for _ in hl]
263
+ self._S_list = [float(eps) for _ in hl]
264
+ self._J_list = [float(eps) for _ in hl]
265
+ self._kap_lam = 2.0 ** (-1.0 / float(np.median(hl)))
266
+ self._kap_state = 1.0 # chi-squared null mean of d^2
267
+ self._last_kappa = _KAPPA_C * self._kap_state
268
+ # per-asset market clocks: each asset's trading time advances with
269
+ # the squared surprise of its correlation neighbourhood
270
+ self._S_asset = np.full((K, n), float(eps))
271
+ # diagnostic only: information masses of each asset's observed days
272
+ self._S_obs = np.full((K, n), float(eps))
273
+ self._J_obs = np.full((K, n), float(eps))
274
+ self._w_asset = np.zeros(n) # the day's per-asset clock increments
275
+ self._kap_asset = np.ones(n)
276
+ self._C_prev = np.eye(n)
277
+ self._detector = _BlendGradient(hl, self._corr_w)
278
+ self._last_omega = 1.0
279
+ # variance ladder two octaves below the correlation ladder
280
+ hv = float(np.median(hl))
281
+ self._lv_l = 2.0 ** (-1.0 / np.array([hv / 16.0, hv / 4.0, hv]))
282
+ self._eps_v = float(1.0 - self._lv_l[0])
283
+ self._pi_v = np.full(3, 1.0 / 3.0)
284
+ self._gamma_v = 2.0 ** (-1.0 / hv)
285
+ self._w_p = self._pi_v.copy()
286
+ self._scale_p = 1.0
287
+ self._var_t = np.zeros(n, dtype=np.float64)
288
+ self._var_init = np.zeros(n, dtype=bool)
289
+ self._var_l: np.ndarray | None = None
290
+ self._vol_t: np.ndarray | None = None
291
+ self._cov: np.ndarray | None = None
292
+ self._corr: np.ndarray | None = None
293
+ self._last_weight = 0.0
294
+ self._offmask = ~np.eye(n, dtype=bool)
295
+ self._scratch_had = np.empty((n, n), dtype=np.float64)
296
+ self._n_off = float(n * (n - 1)) if n > 1 else 1.0
297
+
298
+ def update(self, r_t: np.ndarray) -> float:
299
+ n = self.n_assets
300
+ eps = self.epsilon
301
+ finite = np.isfinite(r_t)
302
+
303
+ # ── score r_t under yesterday's forecast, move the blend weights ──
304
+ detector = self._detector
305
+ detector.advance(detector.score(r_t, finite))
306
+
307
+ # ── volatility ladder ──
308
+ var_t, var_init = self._var_t, self._var_init
309
+ first = finite & ~var_init
310
+ repeat = finite & var_init
311
+ if np.any(first):
312
+ var_t[first] = r_t[first] ** 2 + eps
313
+ var_init[first] = True
314
+ if self._var_l is None:
315
+ self._var_l = np.full((3, n), eps)
316
+ self._var_l[:, first] = r_t[first] ** 2 + eps
317
+ if np.any(repeat):
318
+ assert self._var_l is not None
319
+ r2 = r_t[repeat] ** 2
320
+ vr = self._var_l[:, repeat]
321
+ vr_safe = np.maximum(vr, eps)
322
+ ell_v = -0.5 * (np.log(vr_safe) + r2 / vr_safe)
323
+ ep = ell_v.sum(axis=1)
324
+ dp = ep - ep.mean()
325
+ rp = float(np.sqrt((dp @ dp) / 3.0))
326
+ self._scale_p = (self._gamma_v * self._scale_p
327
+ + (1.0 - self._gamma_v) * rp)
328
+ zp = np.tanh(dp / (self._scale_p + 1e-12))
329
+ lw = np.log(np.maximum(self._w_p, 1e-300)) + zp * np.sqrt(2.0 * self._eps_v)
330
+ lw -= lw.max()
331
+ w_p = np.exp(lw)
332
+ w_p /= w_p.sum()
333
+ self._w_p = (1.0 - self._eps_v) * w_p + self._eps_v * self._pi_v
334
+ lv = self._lv_l[:, None]
335
+ self._var_l[:, repeat] = lv * vr + (1.0 - lv) * r2
336
+ var_t[repeat] = (self._w_p[:, None] * self._var_l[:, repeat]).sum(axis=0)
337
+
338
+ vol_t = np.zeros(n, dtype=np.float64)
339
+ vol_t[var_init] = np.sqrt(var_t[var_init])
340
+
341
+ # ── standardised surprise and the panel kernel weight ──
342
+ z_t = np.zeros(n, dtype=np.float64)
343
+ n_obs = int(finite.sum())
344
+ if n_obs > 0:
345
+ z_t[finite] = r_t[finite] / (vol_t[finite] + eps)
346
+ d2 = float(z_t[finite] @ z_t[finite]) / n_obs
347
+ # kappa_t = c * EWMA(d^2): state, not parameter; today's weight
348
+ # uses the state BEFORE absorbing today's d^2.
349
+ kappa_t = _KAPPA_C * self._kap_state
350
+ self._kap_state = (self._kap_lam * self._kap_state
351
+ + (1.0 - self._kap_lam) * d2)
352
+ w_t = d2 / (d2 + kappa_t)
353
+ self._last_kappa = kappa_t
354
+ else:
355
+ w_t = 0.0
356
+
357
+ # ── per-asset clocks and the diagonal-congruence update ──
358
+ corr_lam = self._corr_lam
359
+ Q_list, S_list, J_list = self._Q_list, self._S_list, self._J_list
360
+ w_vec = None
361
+ if n_obs > 0:
362
+ kap_a = self._kap_asset
363
+ H = self._C_prev * self._C_prev
364
+ denom = H @ finite.astype(np.float64)
365
+ a_act = (H @ (z_t * z_t)) / np.maximum(denom, eps)
366
+ w_vec = np.where(finite,
367
+ a_act / (a_act + _KAPPA_C * kap_a),
368
+ w_t)
369
+ self._kap_asset = np.where(
370
+ finite,
371
+ self._kap_lam * kap_a + (1.0 - self._kap_lam) * a_act,
372
+ kap_a)
373
+ self._w_asset = np.zeros(n) if w_vec is None else w_vec
374
+ # observation weight: sqrt(omega) on the innovation, omega = n/m
375
+ # from the gradient's own solve of the forecast at r_t; one on a
376
+ # day the gradient abstained.
377
+ sq_omega = 1.0
378
+ if w_vec is not None:
379
+ m_day = detector.m_last
380
+ if np.isfinite(m_day) and m_day > 1e-12:
381
+ sq_omega = float(np.sqrt(detector.n_last / m_day))
382
+ self._last_omega = sq_omega * sq_omega
383
+ # a missing asset's clock runs on the panel clock but adds nothing to its correlations
384
+ w_obs = np.where(finite, self._w_asset, 0.0)
385
+ for k in range(corr_lam.size):
386
+ self._S_obs[k] = corr_lam[k] * self._S_obs[k] + w_obs
387
+ self._J_obs[k] = corr_lam[k] * corr_lam[k] * self._J_obs[k] + w_obs
388
+ S_list[k] = corr_lam[k] * S_list[k] + w_t
389
+ J_list[k] = corr_lam[k] * corr_lam[k] * J_list[k] + w_t
390
+ if w_vec is not None:
391
+ S_a = self._S_asset
392
+ S_a[k] = corr_lam[k] * S_a[k] + w_vec
393
+ eta_v = w_vec / S_a[k]
394
+ o = np.sqrt(1.0 - eta_v)
395
+ u = np.sqrt(eta_v) * z_t
396
+ if sq_omega != 1.0:
397
+ u = u * sq_omega
398
+ np.multiply.outer(o, o, out=self._scratch_had)
399
+ Q_list[k] *= self._scratch_had
400
+ np.multiply.outer(u, u, out=self._scratch_had)
401
+ Q_list[k] += self._scratch_had
402
+ self._vol_t = vol_t
403
+ self._materialize()
404
+ self._last_weight = w_t
405
+ return w_t
406
+
407
+ def _intensity(self, corr: np.ndarray, S_t: float, J_t: float) -> float:
408
+ """Self-tuning shrinkage intensity of one timescale from its raw
409
+ correlation and information masses: alpha from the online
410
+ concentration c = n/nu (nu = S^2/J) and the de-noised
411
+ equicorrelation-explained fraction g = rho^2 / (mo - vhat),
412
+ alpha = min(1,c) g^2 / (g^2 + (1-g)^2 max(0, 1/c - 1))."""
413
+ eps = self.epsilon
414
+ n = self.n_assets
415
+ S_t = max(S_t, eps)
416
+ off = corr[self._offmask]
417
+ nu = S_t * S_t / max(J_t, eps)
418
+ c_k = n / max(nu, eps)
419
+ vhat = float(((1.0 - off * off) ** 2).mean()) / max(nu, eps)
420
+ mo_r = float((off * off).mean())
421
+ rho_r = float(off.mean())
422
+ gt = min(1.0, rho_r * rho_r / max(mo_r - vhat, 1e-6))
423
+ r_ = (1.0 - gt) / max(gt, 1e-6)
424
+ s_ = max(0.0, 1.0 / max(c_k, eps) - 1.0)
425
+ return min(1.0, c_k) / (1.0 + r_ * r_ * s_)
426
+
427
+ def _raw_corr(self, Q: np.ndarray) -> np.ndarray:
428
+ """One timescale's state normalised to a correlation (unshrunk);
429
+ an asset never observed has a zero row and a zero diagonal."""
430
+ eps = self.epsilon
431
+ diag_z = np.diagonal(Q).copy()
432
+ inv_diag = 1.0 / np.sqrt(np.maximum(diag_z, eps))
433
+ corr = np.multiply.outer(inv_diag, inv_diag)
434
+ corr *= Q
435
+ np.fill_diagonal(corr, np.where(diag_z > eps, 1.0, 0.0))
436
+ return np.asarray(corr)
437
+
438
+ def _rung_experts(self, Q: np.ndarray, S_t: float, J_t: float
439
+ ) -> tuple[tuple[np.ndarray, ...], np.ndarray]:
440
+ """The three PSD unit-diagonal experts of one timescale -- raw
441
+ correlation, equicorrelation at its mean level, Schur square --
442
+ and the rule's prior split (1-a, a(1-a), a^2)."""
443
+ n = self.n_assets
444
+ corr = self._raw_corr(Q)
445
+ a = self._intensity(corr, S_t, J_t)
446
+ rho = (corr.sum() - n) / self._n_off
447
+ rho = float(min(max(rho, -0.99 / max(n - 1, 1)), 0.999))
448
+ E = np.full((n, n), rho)
449
+ np.fill_diagonal(E, 1.0)
450
+ return (corr, E, corr * corr), np.array([1.0 - a, a * (1.0 - a), a * a])
451
+
452
+ def _materialize(self) -> None:
453
+ """Pool each timescale's experts, blend the timescales, apply the
454
+ volatilities; cache the forecast for the next day's gradient."""
455
+ detector = self._detector
456
+ vol_t = self._vol_t
457
+ assert vol_t is not None
458
+ eps = self.epsilon
459
+ vv = np.multiply.outer(vol_t, vol_t)
460
+ K = self._corr_lam.size
461
+ v = detector.v
462
+ comps: list[tuple[np.ndarray, ...]] = []
463
+ prior = np.empty(v.shape)
464
+ sig_k = []
465
+ for k in range(K):
466
+ experts, prior[k] = self._rung_experts(self._Q_list[k], self._S_list[k], self._J_list[k])
467
+ corr_k = v[k, 0] * experts[0]
468
+ for j in range(1, len(experts)):
469
+ corr_k = corr_k + v[k, j] * experts[j]
470
+ comps.append(experts)
471
+ sig_k.append(corr_k) # pooled correlation; vv applied once below
472
+ w = np.asarray(detector.w)
473
+ cb = w[0] * sig_k[0]
474
+ for k in range(1, K):
475
+ cb = cb + w[k] * sig_k[k]
476
+ self._C_prev = cb # next day's neighbourhood weighting
477
+ cov = cb * vv
478
+ cov = (cov + cov.T) * 0.5
479
+ detector.record(sig_k, comps, prior, cov, vol_t)
480
+ self._cov = cov
481
+ d = np.sqrt(np.maximum(np.diagonal(cov), eps))
482
+ self._corr = cov / np.outer(d, d)
483
+ np.fill_diagonal(self._corr, 1.0)
484
+
485
+
486
+ class SqueezeKernel:
487
+ """Streaming covariance estimator whose public surface is one number.
488
+
489
+ Parameters
490
+ ----------
491
+ lam : float
492
+ The exponential decay of the anchor correlation timescale per
493
+ trading day, in the classical EWMA convention (default 0.996, a
494
+ half-life of about 173 days). The timescale ladder, the variance
495
+ ladder, the kernel-scale clock and the timescale prior all derive
496
+ from it.
497
+
498
+ The number of assets is inferred from the first ``update`` call.
499
+ Returns are expected in decimal units (``0.01`` = 1%).
500
+
501
+ Examples
502
+ --------
503
+ >>> import numpy as np
504
+ >>> returns = np.random.default_rng(42).normal(0.0, 0.01, size=(250, 3))
505
+ >>> sk = SqueezeKernel()
506
+ >>> for r_t in returns:
507
+ ... _ = sk.update(r_t)
508
+ >>> sk.covariance().shape
509
+ (3, 3)
510
+ """
511
+
512
+ def __init__(self, lam: float = 0.996) -> None:
513
+ if not (0.0 < lam < 1.0):
514
+ raise ValueError("lam must be in (0, 1).")
515
+ self.lam = float(lam)
516
+ self._est: _Engine | None = None
517
+ self._t = 0
518
+
519
+ @property
520
+ def half_life(self) -> float:
521
+ """Anchor half-life in trading days implied by ``lam``."""
522
+ return float(-1.0 / np.log2(self.lam))
523
+
524
+ def update(self, r_t: ArrayLike, mask: ArrayLike | None = None) -> float:
525
+ """Process one return vector; returns the day's kernel weight.
526
+
527
+ ``r_t`` may contain NaN for missing assets; ``mask`` (optional
528
+ boolean, True = observed) is an alternative way to mark them.
529
+ """
530
+ r = np.asarray(r_t, dtype=np.float64)
531
+ if r.ndim != 1:
532
+ raise ValueError("r_t must be one-dimensional.")
533
+ if mask is not None:
534
+ m = np.asarray(mask, dtype=bool)
535
+ if m.shape != r.shape:
536
+ raise ValueError("mask must match r_t's shape.")
537
+ r = np.where(m, r, np.nan)
538
+ if self._est is None:
539
+ self._est = _Engine(r.size, self.lam)
540
+ elif r.size != self._est.n_assets:
541
+ raise ValueError(f"Expected {self._est.n_assets} assets, got {r.size}.")
542
+ self._t += 1
543
+ return self._est.update(r)
544
+
545
+ def covariance(self) -> np.ndarray:
546
+ """Current covariance forecast (n x n)."""
547
+ if self._est is None or self._est._cov is None:
548
+ raise RuntimeError("Call update() at least once first.")
549
+ return self._est._cov.copy()
550
+
551
+ def correlation(self) -> np.ndarray:
552
+ """Current correlation forecast (n x n)."""
553
+ if self._est is None or self._est._corr is None:
554
+ raise RuntimeError("Call update() at least once first.")
555
+ return self._est._corr.copy()
556
+
557
+ def rung_correlations(self) -> np.ndarray:
558
+ """Raw (unshrunk) correlation state of each timescale, fastest
559
+ first, shape (3, n, n). Diagnostics, not forecasts: the emitted
560
+ forecast pools each of these with its shrinkage targets, and a
561
+ timescale whose effective size (``state()["rung_nu"]``) is below n
562
+ is close to singular."""
563
+ if self._est is None:
564
+ raise RuntimeError("Call update() at least once first.")
565
+ return np.array([self._est._raw_corr(Q) for Q in self._est._Q_list])
566
+
567
+ def state(self) -> dict[str, object]:
568
+ """Diagnostics: update count, last kernel weight, kernel scale,
569
+ per-timescale information masses and effective sizes (panel clock),
570
+ blend tilt, pool splits, the last observation weight, the day's
571
+ Mahalanobis distance ``m_t`` under the previous forecast on its
572
+ ``n_t`` observed assets (NaN on a day the mixture abstained), the
573
+ day's per-asset clock increments ``clock_t`` (the panel clock for a
574
+ missing asset) and the per-asset effective sizes ``asset_nu``
575
+ (shape (3, n)): S^2/J of each asset's clock increments on the days
576
+ it was observed, on each timescale's decay."""
577
+ if self._est is None:
578
+ return {"n_assets": None, "t": 0}
579
+ est = self._est
580
+ det = est._detector
581
+ S = list(est._S_list)
582
+ J = list(est._J_list)
583
+ nu = [s * s / max(j, est.epsilon) for s, j in zip(S, J)]
584
+ return {
585
+ "n_assets": est.n_assets,
586
+ "t": self._t,
587
+ "last_weight": est._last_weight,
588
+ "kappa_t": est._last_kappa,
589
+ "rung_S": S,
590
+ "rung_nu": nu,
591
+ "detector_tilt": det.tilt,
592
+ "split": det.v.copy(),
593
+ "omega_t": est._last_omega,
594
+ "m_t": det.m_last,
595
+ "n_t": det.n_last,
596
+ "clock_t": est._w_asset.copy(),
597
+ "asset_nu": est._S_obs ** 2 / np.maximum(est._J_obs, est.epsilon),
598
+ }
@@ -0,0 +1,265 @@
1
+ Metadata-Version: 2.4
2
+ Name: squeeze-kernel
3
+ Version: 1.0.0
4
+ Summary: Streaming, PSD-by-construction covariance estimator with Fisher-kernel weighting and adaptive shrinkage
5
+ Keywords: covariance,correlation,ewma,kernel,risk,streaming
6
+ Author: Robert Kende
7
+ License-Expression: MIT
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Science/Research
10
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
11
+ Classifier: License :: OSI Approved :: MIT License
12
+ Classifier: Programming Language :: Python :: 3
13
+ Classifier: Programming Language :: Python :: 3.10
14
+ Classifier: Programming Language :: Python :: 3.11
15
+ Classifier: Programming Language :: Python :: 3.12
16
+ Classifier: Programming Language :: Python :: 3.13
17
+ Classifier: Operating System :: OS Independent
18
+ Requires-Dist: numpy>=1.24
19
+ Requires-Dist: pytest>=7.0 ; extra == 'dev'
20
+ Requires-Dist: ruff>=0.7 ; extra == 'dev'
21
+ Requires-Dist: scipy>=1.11 ; extra == 'dev'
22
+ Requires-Dist: mypy>=1.10 ; extra == 'dev'
23
+ Requires-Dist: scipy>=1.11 ; extra == 'full'
24
+ Requires-Python: >=3.10
25
+ Project-URL: Homepage, https://github.com/r0k3/squeeze-kernel
26
+ Project-URL: Repository, https://github.com/r0k3/squeeze-kernel
27
+ Project-URL: Issues, https://github.com/r0k3/squeeze-kernel/issues
28
+ Provides-Extra: dev
29
+ Provides-Extra: full
30
+ Description-Content-Type: text/markdown
31
+
32
+ # Squeeze Kernel Covariance Estimator
33
+
34
+ [![CI](https://github.com/r0k3/squeeze-kernel/actions/workflows/ci.yml/badge.svg)](https://github.com/r0k3/squeeze-kernel/actions/workflows/ci.yml)
35
+ [![PyPI](https://img.shields.io/pypi/v/squeeze-kernel.svg)](https://pypi.org/project/squeeze-kernel/)
36
+ [![Python](https://img.shields.io/pypi/pyversions/squeeze-kernel.svg)](https://pypi.org/project/squeeze-kernel/)
37
+ [![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)
38
+ [![DOI](https://zenodo.org/badge/1188987927.svg)](https://doi.org/10.5281/zenodo.19170801)
39
+ [![Paper](https://img.shields.io/badge/paper-SSRN%206455918-b31b1b.svg)](https://ssrn.com/abstract=6455918)
40
+
41
+ **A streaming covariance estimator for panels of financial returns that beats every fitted baseline out of sample, costs half a millisecond to ten milliseconds a day, and has one parameter.**
42
+
43
+ ```python
44
+ from squeeze_kernel import SqueezeKernel
45
+
46
+ sk = SqueezeKernel(lam=0.996) # the entire public surface
47
+ for r_t in returns: # NaN marks missing assets
48
+ sk.update(r_t)
49
+ cov = sk.covariance() # positive semi-definite by construction, every day
50
+ ```
51
+
52
+ - **State of the art, measured.** On thirty years of S&P 500 constituents it leads ten baselines fitted to the data (CM-IEWMA, DCC, DCC-NL, nonlinear shrinkage, Ledoit–Wolf, OAS, RMT denoising, Gerber, IEWMA, EWMA) at every universe size from 50 to 300, every Diebold–Mariano *p* below 10⁻⁷, and it is the **sole member of the 90% model confidence set at every size**. With its configuration frozen on data to 2021 it stays first on 2022–2026, on **twenty-four sealed small- and mid-cap universes it had never seen**, and on the public Fama–French 49 panel on the competing authors' own metric.
53
+ - **Fast, with nothing that can fail.** One `O(Kn²)` state update, one Cholesky factorisation of the blend and `K` positive-definiteness checks a day. No rolling window, no likelihood refit, no daily solver. **0.54 ms a day at n = 50, 10.1 ms at n = 300.** The closest competitor on accuracy, CM-IEWMA as released by its authors, takes 18 to 51 times as long and spends most of it in a convex programme that is infeasible on about one scored day in five at n = 300.
54
+ - **One number, no tuning.** Everything else is derived from `lam`, fixed by a structural argument, or computed online from the estimator's own state. Listings, delistings and halts enter as `NaN`. Only dependency: NumPy.
55
+
56
+ Paper: Kende (2026), *The Squeeze Kernel Covariance Estimator*, [SSRN 6455918](https://ssrn.com/abstract=6455918). Every number on this page is taken from the tables of the paper's September 2026 revision, *A Diagonal-Congruence Flow in Per-Asset Trading Time*, which describes this estimator and carries the protocol, the proofs and the full ablation ledger.
57
+
58
+ [Benchmarks](#benchmarks) · [See the difference](#see-the-difference) · [Installation](#installation) · [Quickstart](#quickstart) · [How it works](#how-it-works) · [Citation](#citation)
59
+
60
+ ## Why
61
+
62
+ Markets do not keep calendar time. Following Mandelbrot, the estimator treats a panel as a collection of partially coupled markets, **each advancing on its own activity-driven clock**, and reads those clocks from the panel's own correlation structure: a hot cluster (say precious metals and FX) advances its correlation state while an idle one (agriculture) does not, and nobody has to identify the cluster. On those clocks it runs a single recursion that **learns in market time and forgets in calendar time**, shrinks itself from two online statistics, and re-weights its three timescales by the gradient of its own log score. Nothing is fitted but `lam`.
63
+
64
+ Against the field it is scored on:
65
+
66
+ | | Squeeze Kernel | CM-IEWMA (as released) | DCC, DCC-NL | Window shrinkage (LW, OAS, NLS, RMT) |
67
+ |---|---|---|---|---|
68
+ | Clock | per-asset market clocks | calendar | calendar | calendar window |
69
+ | Daily work | `O(Kn²)` update, one Cholesky, no solver | daily convex programme | GARCH recursion | re-estimate on the window |
70
+ | Tuned in the paper | nothing: `lam = 0.996`, fixed on data to 2021 | fitted on a tuning block, re-fitted to each sealed universe | fitted on a tuning block, re-fitted to each sealed universe | fitted on a tuning block, re-fitted to each sealed universe |
71
+ | Milliseconds a day, n = 50 → 300 | **0.54 → 10.1** | 18.8 → 182.2 | 0.05 → 0.83, 0.09 → 1.83 | not timed |
72
+ | Days the solver fails, n = 300 | no solver | 1,196 of 6,439 scored | — | — |
73
+
74
+ ## Benchmarks
75
+
76
+ The score is the one-step-ahead Gaussian negative log-likelihood (NLL) of the next day's returns under each estimator's forecast, averaged per day; lower is better. Every baseline is fitted on a tuning block before it is scored. The ranking holds under the Student-t and density-power scores as well.
77
+
78
+ ### Thirty years of S&P 500 constituents, 1995–2026
79
+
80
+ Each baseline's row is its **excess NLL per day over the Squeeze Kernel**. Every Diebold–Mariano *p* is below 10⁻⁷. The Squeeze Kernel is the sole member of the 90% model confidence set at every size.
81
+
82
+ | | n = 50 | n = 100 | n = 200 | n = 300 |
83
+ |---|---:|---:|---:|---:|
84
+ | **Squeeze Kernel, average NLL** | **−371.28** | **−753.21** | **−1539.32** | **−2334.88** |
85
+ | CM-IEWMA | +1.63 | +4.58 | +12.45 | +20.70 |
86
+ | DCC | +2.04 | +5.31 | +13.49 | +25.38 |
87
+ | DCC-NL | +2.21 | +5.53 | +13.90 | +24.67 |
88
+ | RMT denoising | +6.60 | +14.72 | +32.39 | +58.94 |
89
+ | Gerber (PSD) | +7.00 | +15.61 | +38.82 | +62.98 |
90
+ | Nonlinear shrinkage | +6.29 | +16.10 | +42.84 | +73.22 |
91
+ | IEWMA | +3.98 | +16.56 | +79.79 | +224.73 |
92
+ | EWMA | +7.10 | +19.92 | +58.71 | +80.81 |
93
+ | Ledoit–Wolf | +6.75 | +20.44 | +60.42 | +98.94 |
94
+ | OAS | +8.44 | +23.96 | +66.04 | +106.56 |
95
+
96
+ ### Out of sample, configuration frozen on data to 2021
97
+
98
+ | | n = 50 | n = 100 | n = 200 | n = 300 |
99
+ |---|---:|---:|---:|---:|
100
+ | **S&P constituents, 2022–2026**: lead over the best baseline (CM-IEWMA at every size), NLL per day | 1.72 | 3.72 | 11.12 | 19.16 |
101
+ | **Twenty-four sealed small- and mid-cap universes**, six per size, 2022–2026, field fitted to each universe: universes on which it is first | 6 of 6 | 6 of 6 | 6 of 6 | 6 of 6 |
102
+ | lead over the best baseline, range | 0.1–1.2 | 2.7–4.0 | 8.6–10.9 | 13.2–17.5 |
103
+ | sole member of the 90% model confidence set | 1 of 6 | 6 of 6 | 6 of 6 | 6 of 6 |
104
+
105
+ Carried **zero-shot** to another panel, same `lam`:
106
+
107
+ | Panel | Result |
108
+ |---|---|
109
+ | **Fama–French 49 industries**, scored with the CM-IEWMA authors' own regret metric (lower is better) | **16.35**, against CM-IEWMA 16.96, IEWMA 18.20, EWMA 19.39 |
110
+
111
+ ### Cost
112
+
113
+ Milliseconds per forecast day, single-threaded, over the full thirty-year pass:
114
+
115
+ | | n = 50 | n = 100 | n = 200 | n = 300 |
116
+ |---|---:|---:|---:|---:|
117
+ | **Squeeze Kernel** | **0.54** | **0.91** | **2.80** | **10.1** |
118
+ | CM-IEWMA as released | 18.8 | 46.4 | 106.8 | 182.2 |
119
+ | of which the daily convex programme | 16.1 | 39.9 | 85.4 | 142.1 |
120
+ | days on which the programme fails | 0 | 50 | 294 | 1,196 |
121
+ | peak memory, GB | 2.0 | 6.4 | 22.4 | 45.3 |
122
+ | DCC | 0.05 | 0.11 | 0.28 | 0.83 |
123
+ | DCC-NL | 0.09 | 0.25 | 0.92 | 1.83 |
124
+
125
+ Two honest footnotes. The released CM-IEWMA code overstates what the method has to cost: its linear algebra alone, with the programme treated as free, would run in 60% to 121% of the Squeeze Kernel's time. The cost is the solver, and so is the fragility. And DCC and DCC-NL are cheaper than both; they are also 13 to 25 NLL per day behind at n = 200 and 300.
126
+
127
+ ## See the difference
128
+
129
+ A passive strategy any allocator would recognise: long-only minimum-variance over 300 liquid US stocks, scaled to a 15% volatility target, rebalanced monthly, 5 bps costs. Two runs on identical data; the only difference is the covariance matrix. The Squeeze Kernel arm runs `SqueezeKernel(lam=0.996)`, **nothing tuned on this panel**.
130
+
131
+ <picture>
132
+ <source media="(prefers-color-scheme: dark)" srcset="https://raw.githubusercontent.com/r0k3/squeeze-kernel/main/examples/figures/vol_targeted_portfolio_dark.png">
133
+ <img alt="Vol-targeted long-only minimum-variance portfolio on 300 US equities: Squeeze Kernel vs Ledoit-Wolf equity curves, drawdown, realized volatility, and risk/return profile" src="https://raw.githubusercontent.com/r0k3/squeeze-kernel/main/examples/figures/vol_targeted_portfolio.png">
134
+ </picture>
135
+
136
+ | Method | CAGR | Vol | Sharpe | MaxDD | Calmar | Vol-target RMSE |
137
+ |---|---|---|---|---|---|---|
138
+ | **Squeeze Kernel (default)** | **12.6%** | **13.6%** | **0.92** | **-34.3%** | **0.37** | **7.05%** |
139
+ | Ledoit-Wolf (252d) | 11.7% | 14.6% | 0.80 | -38.7% | 0.30 | 7.51% |
140
+
141
+ Reproduce from the repo alone (the 300-stock panel ships as a parquet; survivorship and provenance are documented in the script):
142
+
143
+ ```bash
144
+ pip install squeeze-kernel pandas pyarrow scikit-learn matplotlib
145
+ python examples/vol_targeted_portfolio.py # ~1 minute for the 26-year stream
146
+ ```
147
+
148
+ ## Installation
149
+
150
+ ```bash
151
+ pip install squeeze-kernel # NumPy only
152
+ pip install "squeeze-kernel[full]" # + SciPy (faster Cholesky factorisations for the mixture)
153
+ ```
154
+
155
+ ## Quickstart
156
+
157
+ ```python
158
+ import numpy as np
159
+ from squeeze_kernel import SqueezeKernel, estimate_squeeze_cov
160
+
161
+ returns = np.random.default_rng(42).normal(0.0, 0.01, size=(500, 30))
162
+
163
+ sk = SqueezeKernel() # lam=0.996 (anchor half-life ~173 days)
164
+ for r_t in returns:
165
+ w = sk.update(r_t) # returns the day's kernel weight
166
+ cov, corr = sk.covariance(), sk.correlation()
167
+ sk.state() # kernel scale, per-timescale effective sizes, mixture tilt
168
+
169
+ # batch mode: full panel in, covariance path out
170
+ cov_path, corr_path, weights = estimate_squeeze_cov(returns, with_weights=True)
171
+ ```
172
+
173
+ Missing values: pass `NaN` (or `mask=` on `update`). Newly listed, delisted or halted assets need no imputation and no complete-case subsetting.
174
+
175
+ Units: pass returns in decimal units (`0.01` = 1%). The numerical floors are absolute (`ε = 1e-8` in squared-return units), so percent-unit returns give a different path. A panel whose first day carries many exact-zero returns starts with a transient that the slow timescale remembers; start a day later.
176
+
177
+ ### Diagnostics
178
+
179
+ Read-only views of state the estimator already keeps; none changes the forecast.
180
+
181
+ ```python
182
+ sk.rung_correlations() # (3, n, n) raw, unshrunk correlation state per timescale, fastest first
183
+ st = sk.state()
184
+ st["m_t"], st["n_t"] # the day's Mahalanobis distance under the previous forecast, on n_t observed assets
185
+ st["clock_t"] # the day's per-asset clock increments, in [0, 1)
186
+ st["rung_nu"] # effective size per timescale (panel clock)
187
+ st["asset_nu"] # (3, n) effective sizes per asset, counting only the days it was observed
188
+ ```
189
+
190
+ The fastest timescale forgets with a calendar half-life of a quarter of the anchor's, about 43 days at the default `lam`. Days enter with clock weights below one, so its effective size is smaller than a plain exponential average's: a median of 89 against 125 on the 300-stock example panel. The per-timescale states are raw correlations; the forecast pools each with its shrinkage targets, and a timescale whose effective size is below `n` is close to singular, so use them as diagnostics, not as forecasts.
191
+
192
+ To whiten a return against the current forecast (under a correctly specified elliptical model its direction is uniform on the sphere):
193
+
194
+ ```python
195
+ import scipy.linalg
196
+
197
+ L = np.linalg.cholesky(sk.covariance())
198
+ u = scipy.linalg.solve_triangular(L, r, lower=True) # u @ u is the Mahalanobis distance
199
+ ```
200
+
201
+ ## How it works
202
+
203
+ ```mermaid
204
+ flowchart LR
205
+ R["return r_t<br/>(NaN = missing)"] --> V["variance ladder<br/>3 rungs per asset,<br/>pooled panel-wide"]
206
+ V --> Z["standardised<br/>surprise z_t"]
207
+ Z --> W["per-asset clocks<br/>from the correlation<br/>neighbourhood"]
208
+ W --> Q["diagonal-congruence update<br/>of 3 correlation timescales,<br/>outer product scaled by n/m"]
209
+ Q --> S["per-timescale shrinkage<br/>raw / equicorrelation /<br/>Hadamard square"]
210
+ S --> B["blend across timescales<br/>by the gradient of<br/>its own log score"]
211
+ B --> O["Σ_t"]
212
+ ```
213
+
214
+ One daily update, in words:
215
+
216
+ 1. **Volatility with self-selected memory.** Each asset's variance runs on a three-rung ladder of half-lives (`h/16, h/4, h`), pooled panel-wide by weights that move on saturated evidence, so one spike day cannot hand a stale rung weeks of weight. The day's return is standardised by it.
217
+ 2. **Per-asset clocks.** Each asset reads its activity as the neighbourhood mean of squared surprises, weighted by the Hadamard square of yesterday's correlation (under conditional Gaussianity that square *is* the correlation of squared returns, so the neighbourhood is the asset's own cluster, no labels needed). A saturating kernel maps activity to a clock increment in `[0, 1)`: an unbounded shock is squeezed into at most one unit of trading time.
218
+ 3. **Magnitude once, direction once.** The day's Mahalanobis norm under the estimator's own forecast, `m = r'Σ⁻¹r`, sets the clocks; the innovation then enters with weight `n/m`, so a day's direction moves the state and its size only says how much trading time it carried. Score-driven and robust estimators down-weight such a day as contamination; this one reads it as time.
219
+ 4. **Diagonal-congruence flow on three timescales.** Each correlation state advances by a congruence plus a rank-one term on the clocks, with decays `(lam⁴, lam, lam^¼)`. In closed form it is an exponentially weighted Gram matrix of clock-weighted returns: pairs accrue at the geometric mean of their two clock increments, which is exactly the Cauchy–Schwarz bound on how far two clocks can overlap and the most positive semi-definiteness allows. No eigenvalue clipping, no nearest-PSD repair, any missing-data pattern.
220
+ 5. **Self-tuning, label-free shrinkage.** Each timescale's shrunk correlation is a pool of its raw correlation, its equicorrelation level and its Hadamard square. The Hadamard square suppresses cross-cluster noise quadratically (0.10 → 0.01) while keeping intra-cluster blocks (0.60 → 0.36). The pool's prior weights come from a closed-form intensity rule read off two online statistics; the blend gradient corrects them.
221
+ 6. **Blend by the gradient of the blend's own score.** The timescale weights follow an exponentiated-gradient step on the blend's log score (not any single timescale's, which would select rather than blend), at a temperature calibrated so that uninformative evidence leaves the mix within a factor *e* of its prior. Nothing in either mixture is fitted.
222
+
223
+ The paper gives the derivations (natural-gradient and Gram-matrix forms of the flow, the Fisher–Rao form of the mixture), the guarantees (PSD at every step, a conditioning floor, strict positive definiteness whenever a positively weighted timescale has its intensity strictly inside (0, 1), exact reductions to the published special cases) and the full evaluation.
224
+
225
+ ### What derives from `lam`
226
+
227
+ | quantity | value |
228
+ |---|---|
229
+ | timescale ladder | decays `(lam⁴, lam, lam^¼)` — half-lives `(h/4, h, 4h)`, `h = -1/log2(lam)` |
230
+ | kernel scale | state: `κ_t = ⅓ · EWMA(activity)` at the anchor rate |
231
+ | shrinkage intensity | per timescale, `α = min(1,c) · g̃²/(g̃² + (1−g̃)²·max(0, 1/c − 1))` from the online concentration `c = n/ν` and target-fit `g̃` |
232
+ | timescale weights | prior ∝ √h, moved by exponentiated gradient on the blend log score at the null temperature, fast-rung memory |
233
+ | shrinkage split | per timescale, a learned pool of the raw correlation, its equicorrelation level and its Hadamard square; prior `(1−α, α(1−α), α²)`, moved by the blend gradient |
234
+ | observation weight | state: `ω_t = n_t/m_t`, the day's observed count over its Mahalanobis distance under yesterday's forecast, from the mixture's own factorisation |
235
+ | volatility memory | ladder `(h/16, h/4, h)`, pooled panel-wide by the same rule on tanh-saturated evidence, uniform prior |
236
+ | structural constants | K=3, b=4, θ=½, κ-scale ⅓, Schur power 2, intensity exponent 2 — each bracketed by ablation in the paper |
237
+ | fitted constants | `lam` itself (0.996, chosen on data to 2021); nothing else is fitted |
238
+
239
+
240
+ ## Development
241
+
242
+ ```bash
243
+ uv sync --extra full --extra dev
244
+ uv run python -m pytest # test suite
245
+ uv run python -m ruff check . # lint
246
+ uv run mypy # strict type check (src/squeeze_kernel)
247
+ uv build # build sdist + wheel
248
+ ```
249
+
250
+ ## Citation
251
+
252
+ ```bibtex
253
+ @article{kende2026squeeze,
254
+ title = {The Squeeze Kernel Covariance Estimator},
255
+ author = {Kende, Robert},
256
+ year = {2026},
257
+ note = {Working paper. Available at SSRN: \url{https://ssrn.com/abstract=6455918}}
258
+ }
259
+ ```
260
+
261
+ See also [`CITATION.cff`](CITATION.cff).
262
+
263
+ ## License
264
+
265
+ MIT
@@ -0,0 +1,6 @@
1
+ squeeze_kernel/__init__.py,sha256=gLReZMSeC_u6ivxQxRabO8Xeq5cPZcd0UKLzxJ719CQ,913
2
+ squeeze_kernel/batch.py,sha256=a55ttjCqBO1wma-QpK6q1clZJris4k27l7WzTTi2fx8,1635
3
+ squeeze_kernel/core.py,sha256=TjI9IKlkb3rT8cIMGR3YEQ3FN_pol72C-_64_zJXcdI,27021
4
+ squeeze_kernel-1.0.0.dist-info/WHEEL,sha256=-gI5GRFdiNNn2CFz-ptlExISMINC-k8bFxeojAlHbrM,81
5
+ squeeze_kernel-1.0.0.dist-info/METADATA,sha256=rab6g7RwYyBXSF_535Zo8uzSwl--6Ryb0w_X7RGxaVo,18114
6
+ squeeze_kernel-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.13.10
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any