squeeze-kernel 3.1.0__tar.gz → 3.2.0__tar.gz
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.
Potentially problematic release.
This version of squeeze-kernel might be problematic. Click here for more details.
- {squeeze_kernel-3.1.0 → squeeze_kernel-3.2.0}/PKG-INFO +20 -14
- {squeeze_kernel-3.1.0 → squeeze_kernel-3.2.0}/README.md +19 -13
- {squeeze_kernel-3.1.0 → squeeze_kernel-3.2.0}/pyproject.toml +1 -1
- {squeeze_kernel-3.1.0 → squeeze_kernel-3.2.0}/pyproject.toml.orig +1 -1
- {squeeze_kernel-3.1.0 → squeeze_kernel-3.2.0}/src/squeeze_kernel/__init__.py +1 -1
- {squeeze_kernel-3.1.0 → squeeze_kernel-3.2.0}/src/squeeze_kernel/core.py +2 -0
- {squeeze_kernel-3.1.0 → squeeze_kernel-3.2.0}/src/squeeze_kernel/estimator.py +72 -15
- {squeeze_kernel-3.1.0 → squeeze_kernel-3.2.0}/src/squeeze_kernel/batch.py +0 -0
- {squeeze_kernel-3.1.0 → squeeze_kernel-3.2.0}/src/squeeze_kernel/kernels.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: squeeze-kernel
|
|
3
|
-
Version: 3.
|
|
3
|
+
Version: 3.2.0
|
|
4
4
|
Summary: Streaming, PSD-by-construction covariance estimator with Fisher-kernel weighting and adaptive shrinkage
|
|
5
5
|
Keywords: covariance,correlation,ewma,kernel,risk,streaming
|
|
6
6
|
Author: Robert Kende
|
|
@@ -35,6 +35,7 @@ Description-Content-Type: text/markdown
|
|
|
35
35
|
[](https://pypi.org/project/squeeze-kernel/)
|
|
36
36
|
[](https://pypi.org/project/squeeze-kernel/)
|
|
37
37
|
[](LICENSE)
|
|
38
|
+
[](https://doi.org/10.5281/zenodo.19170801)
|
|
38
39
|
|
|
39
40
|
A **streaming covariance estimator for panels of financial returns** whose entire public surface is **one number** — the decay `lam` of the anchor correlation timescale. Every other quantity is derived from it, fixed by a structural argument, or computed online from the estimator's own state. An `O(Kn²)` state update per day, positive semi-definite **by construction**, missing values handled **natively**, no tuning, no refits. Only dependency: NumPy.
|
|
40
41
|
|
|
@@ -47,20 +48,21 @@ for r_t in returns: # NaN marks missing assets
|
|
|
47
48
|
cov = sk.covariance()
|
|
48
49
|
```
|
|
49
50
|
|
|
50
|
-
Reference: *
|
|
51
|
+
Reference: Kende (2026), *The Squeeze Kernel Covariance Estimator* — [SSRN abstract 6455918](https://ssrn.com/abstract=6455918). The 3.x estimator is described in the paper's September 2026 revision, *The Squeeze Kernel Covariance Estimator: A Diagonal-Congruence Flow in Per-Asset Trading Time*.
|
|
51
52
|
|
|
52
53
|
## Why
|
|
53
54
|
|
|
54
55
|
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, so a hot cluster (say precious metals and FX) advances its correlation state while an idle one (agriculture) does not, without anyone identifying a cluster. On those clocks it runs a single recursion that:
|
|
55
56
|
|
|
56
|
-
- **is PSD at every step, structurally** — the correlation state evolves by a diagonal-congruence flow (a congruence plus a rank-one term); no eigenvalue clipping, no nearest-PSD repair, and no factorisation anywhere in the state update. (The adaptive
|
|
57
|
-
- **learns in market time and forgets in calendar time** — observations enter with a saturating, self-studentising weight (no day counts more than one unit of trading time); memory decays at fixed per-day rates on a geometric ladder of three timescales `(lam⁴, lam, lam^¼)`. Pairs accrue covariance at the geometric mean of their two clock increments, which is the most positive semi-definiteness allows and exactly the Cauchy–Schwarz bound on how far two assets' clocks can overlap;
|
|
58
|
-
- **
|
|
59
|
-
- **
|
|
57
|
+
- **is PSD at every step, structurally** — the correlation state evolves by a diagonal-congruence flow (a congruence plus a rank-one term); no eigenvalue clipping, no nearest-PSD repair, and no factorisation anywhere in the state update. (The adaptive mixture is the one exception: it reads the gradient of the blend's own log score, which costs one Cholesky factorisation of the blend and a positive-definiteness check of each timescale's block per day. Switch it off on `SqueezeKernelEstimator` and the estimator is pure `O(Kn²)`.)
|
|
58
|
+
- **learns in market time and forgets in calendar time** — observations enter with a saturating, self-studentising weight (no day counts more than one unit of trading time); memory decays at fixed per-day rates on a geometric ladder of three timescales `(lam⁴, lam, lam^¼)`. Pairs accrue covariance at the geometric mean of their two clock increments, which is the most positive semi-definiteness allows and exactly the Cauchy–Schwarz bound on how far two assets' clocks can overlap. In closed form, each timescale's correlation is that of an exponentially weighted Gram matrix of the clock-weighted returns `√w·z`: day `s` enters the pair `(i, j)` with weight `√(w_i,s·w_j,s)` (market time) and is discounted by `lam_k^(t−s)` (calendar time). That makes it the natural-gradient step of the Gaussian log score, taken as a chord in calendar time on clock-weighted data; the geodesic along the same gradient would be an unbounded time change;
|
|
59
|
+
- **uses each day's magnitude once** — the day's Mahalanobis norm under the estimator's own forecast, `m = r'Σ⁻¹r`, sets the clock and is then removed from the observation: the innovation carries the weight `ω = n/m`, the posterior mean of the inverse trading-time increment under a scale-free prior (Tyler's weight; the Student-t score-driven weight is the same posterior mean under an inverse-gamma prior). A day's direction moves the state; its size only says how much trading time it carried. One dot product from the factorisation the mixture already performs, no constant;
|
|
60
|
+
- **regularises itself** — each timescale's shrinkage intensity is computed from two online statistics, the concentration `n/ν` (dimension per unit trading time) and the de-noised fraction of correlation dispersion the target explains; the target is the Hadamard square of the running correlation, which is exactly the correlation matrix of the *squared* returns (cluster-respecting, PSD by the Schur product theorem, and sign-blind by construction — the signs are carried by the unshrunk term). The intensity rule is the *prior* of a learned split: each timescale's shrunk correlation is a pool of its raw correlation, its equicorrelation level and its Hadamard square, whose weights are pulled toward the rule's `(1−α, α(1−α), α²)` by a fixed share and corrected online by the blend gradient;
|
|
61
|
+
- **adapts its memory to regime breaks, in both stages** — the timescale mix moves by an exponentiated-gradient step on the *blend's* own log score (not on any single timescale's, which would select rather than blend): each weight follows the Fisher–Rao inner product of its timescale with the day's natural gradient, at a temperature calibrated so that uninformative evidence leaves the mix within a factor e of its prior; the marginal variance is tracked on its own three-rung ladder, two octaves below the correlation ladder, and pooled panel-wide by the same rule on saturated evidence, so one spike day cannot hand a stale rung weeks of weight. Nothing in either mixture is fitted: the ladders are derived from `lam`, the evidence memory is the fastest rung's, and the temperature is the null's;
|
|
60
62
|
- **ingests missing values natively** — listings, delistings, halts enter as `NaN`;
|
|
61
|
-
- **is
|
|
63
|
+
- **is cheap, with no solver** — `O(Kn²)` state work plus `K + 1` Cholesky factorisations a day, no iterative optimisation anywhere; a thirty-year daily pass at n = 300 takes about two minutes single-threaded (the mixture's factorisation also certifies the spectral floor of the scored blend inactive on almost every day, and supplies the observation weight for one dot product). CM-IEWMA as released by its authors takes 11–41 times as long on the same panels, most of it a daily convex programme that is infeasible on up to 19% of days at n = 300; DCC and DCC-NL are cheaper still.
|
|
62
64
|
|
|
63
|
-
**Evidence.** On thirty years of S&P 500 constituents against
|
|
65
|
+
**Evidence.** On thirty years of S&P 500 constituents against a ten-method field, every baseline fitted on a tuning block (EWMA, DCC, DCC-NL, Ledoit–Wolf, OAS, nonlinear shrinkage, RMT filtering, Gerber, IEWMA, CM-IEWMA), it leads at every universe size from 50 to 300 and is the **sole member of the 90% model confidence set at every size**. Frozen on data to 2021, it leads the best baseline on 2022–2026 by 1.7, 3.7, 11.1 and 19.2 NLL per day at n = 50, 100, 200 and 300. On twenty-four pre-registered universes of small and mid caps sealed before any scoring (two draws of twelve) it is first on every one against a field fitted to each universe, by 13 to 18 NLL per day at n = 300; the second draw was sealed for the observation weight, which improved the estimator on eleven of the twelve, by 0.6 to 1.8 NLL per day at n ≥ 200. Carried **zero-shot** to a diversified panel of 121 futures across eight asset classes it beats the five baselines that run there, *calibrated on that panel's own history*, by 11.3 to 121 NLL per day out-of-time (the weight costs 0.5 per day on that block, its one trade-off); on the public FF49 industry panel of Johansson et al. it has the lowest regret on their own metric. The ranking holds under the Student-t and density-power scores.
|
|
64
66
|
|
|
65
67
|
## See the difference
|
|
66
68
|
|
|
@@ -73,7 +75,7 @@ A passive strategy any allocator would recognize: long-only minimum-variance ove
|
|
|
73
75
|
|
|
74
76
|
| Method | CAGR | Vol | Sharpe | MaxDD | Calmar | Vol-target RMSE |
|
|
75
77
|
|---|---|---|---|---|---|---|
|
|
76
|
-
| **Squeeze Kernel (default)** | **12.
|
|
78
|
+
| **Squeeze Kernel (default)** | **12.5%** | **13.6%** | **0.92** | **-34.5%** | **0.36** | **7.05%** |
|
|
77
79
|
| Ledoit-Wolf (252d) | 11.7% | 14.6% | 0.80 | -38.7% | 0.30 | 7.51% |
|
|
78
80
|
|
|
79
81
|
Reproduce from the repo alone (the 300-stock panel ships as a parquet; survivorship and provenance are documented in the script):
|
|
@@ -87,7 +89,7 @@ python examples/vol_targeted_portfolio.py # ~2 minutes
|
|
|
87
89
|
|
|
88
90
|
```bash
|
|
89
91
|
pip install squeeze-kernel # NumPy only
|
|
90
|
-
pip install "squeeze-kernel[full]" # + SciPy (faster
|
|
92
|
+
pip install "squeeze-kernel[full]" # + SciPy (faster Cholesky factorisations for the mixture)
|
|
91
93
|
```
|
|
92
94
|
|
|
93
95
|
## Quickstart
|
|
@@ -110,6 +112,8 @@ cov_path, corr_path, weights = estimate_squeeze_cov(returns, with_weights=True)
|
|
|
110
112
|
|
|
111
113
|
Missing values: pass `NaN` (or `mask=` on `update`). Newly listed, delisted or halted assets need no imputation and no complete-case subsetting.
|
|
112
114
|
|
|
115
|
+
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.
|
|
116
|
+
|
|
113
117
|
## What derives from `lam`
|
|
114
118
|
|
|
115
119
|
| quantity | value |
|
|
@@ -118,15 +122,17 @@ Missing values: pass `NaN` (or `mask=` on `update`). Newly listed, delisted or h
|
|
|
118
122
|
| kernel scale | state: `κ_t = ⅓ · EWMA(activity)` at the anchor rate |
|
|
119
123
|
| 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̃` |
|
|
120
124
|
| timescale weights | prior ∝ √h, moved by exponentiated gradient on the blend log score at the null temperature, fast-rung memory |
|
|
125
|
+
| 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 |
|
|
126
|
+
| 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 |
|
|
121
127
|
| volatility memory | ladder `(h/16, h/4, h)`, pooled panel-wide by the same rule on tanh-saturated evidence, uniform prior |
|
|
122
|
-
| structural constants | K=3, b=4, θ=½, κ-scale ⅓, Schur power 2 — each bracketed by ablation in the paper |
|
|
123
|
-
| fitted constants |
|
|
128
|
+
| structural constants | K=3, b=4, θ=½, κ-scale ⅓, Schur power 2, intensity exponent 2 — each bracketed by ablation in the paper |
|
|
129
|
+
| fitted constants | `lam` itself (0.996, chosen on data to 2021); nothing else is fitted |
|
|
124
130
|
|
|
125
|
-
`from squeeze_kernel import CONSTANTS` exposes the structural constants for research. The published v1 estimator (all its knobs) remains available as `SqueezeKernelEstimator` / `SqueezeKernel.v1(...)`; every 2.0
|
|
131
|
+
`from squeeze_kernel import CONSTANTS` exposes the structural constants for research. The published v1 estimator (all its knobs) remains available as `SqueezeKernelEstimator` / `SqueezeKernel.v1(...)`; every mechanism since 2.0 is also an estimator-level switch for ablation. See [MIGRATION.md](MIGRATION.md).
|
|
126
132
|
|
|
127
133
|
## How it works
|
|
128
134
|
|
|
129
|
-
One daily update: variance on a three-rung ladder per asset, pooled by panel-wide self-adapting weights → standardised surprise → per-asset clock increments from the Schur-square-weighted neighbourhood mean of squared surprises → diagonal-congruence update of each timescale's correlation state on those clocks → per-timescale shrinkage as a learned pool of the raw correlation, its equicorrelation level and its Hadamard square, with the self-tuning intensity rule as the prior and the blend gradient as the correction → blend across timescales, moved by the gradient of the blend's own log score → covariance. The paper gives the derivations, guarantees (PSD, conditioning floor, exact reductions to the published special cases), and the full evaluation.
|
|
135
|
+
One daily update: variance on a three-rung ladder per asset, pooled by panel-wide self-adapting weights → standardised surprise → per-asset clock increments from the Schur-square-weighted neighbourhood mean of squared surprises → diagonal-congruence update of each timescale's correlation state on those clocks, the day's outer product scaled by `n/m` → per-timescale shrinkage as a learned pool of the raw correlation, its equicorrelation level and its Hadamard square, with the self-tuning intensity rule as the prior and the blend gradient as the correction → blend across timescales, moved by the gradient of the blend's own log score → covariance. The paper gives the derivations (the natural-gradient and Gram-matrix forms of the flow, the Fisher–Rao form of the mixture), the guarantees (PSD, conditioning floor, exact reductions to the published special cases), and the full evaluation.
|
|
130
136
|
|
|
131
137
|
## Development
|
|
132
138
|
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
[](https://pypi.org/project/squeeze-kernel/)
|
|
5
5
|
[](https://pypi.org/project/squeeze-kernel/)
|
|
6
6
|
[](LICENSE)
|
|
7
|
+
[](https://doi.org/10.5281/zenodo.19170801)
|
|
7
8
|
|
|
8
9
|
A **streaming covariance estimator for panels of financial returns** whose entire public surface is **one number** — the decay `lam` of the anchor correlation timescale. Every other quantity is derived from it, fixed by a structural argument, or computed online from the estimator's own state. An `O(Kn²)` state update per day, positive semi-definite **by construction**, missing values handled **natively**, no tuning, no refits. Only dependency: NumPy.
|
|
9
10
|
|
|
@@ -16,20 +17,21 @@ for r_t in returns: # NaN marks missing assets
|
|
|
16
17
|
cov = sk.covariance()
|
|
17
18
|
```
|
|
18
19
|
|
|
19
|
-
Reference: *
|
|
20
|
+
Reference: Kende (2026), *The Squeeze Kernel Covariance Estimator* — [SSRN abstract 6455918](https://ssrn.com/abstract=6455918). The 3.x estimator is described in the paper's September 2026 revision, *The Squeeze Kernel Covariance Estimator: A Diagonal-Congruence Flow in Per-Asset Trading Time*.
|
|
20
21
|
|
|
21
22
|
## Why
|
|
22
23
|
|
|
23
24
|
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, so a hot cluster (say precious metals and FX) advances its correlation state while an idle one (agriculture) does not, without anyone identifying a cluster. On those clocks it runs a single recursion that:
|
|
24
25
|
|
|
25
|
-
- **is PSD at every step, structurally** — the correlation state evolves by a diagonal-congruence flow (a congruence plus a rank-one term); no eigenvalue clipping, no nearest-PSD repair, and no factorisation anywhere in the state update. (The adaptive
|
|
26
|
-
- **learns in market time and forgets in calendar time** — observations enter with a saturating, self-studentising weight (no day counts more than one unit of trading time); memory decays at fixed per-day rates on a geometric ladder of three timescales `(lam⁴, lam, lam^¼)`. Pairs accrue covariance at the geometric mean of their two clock increments, which is the most positive semi-definiteness allows and exactly the Cauchy–Schwarz bound on how far two assets' clocks can overlap;
|
|
27
|
-
- **
|
|
28
|
-
- **
|
|
26
|
+
- **is PSD at every step, structurally** — the correlation state evolves by a diagonal-congruence flow (a congruence plus a rank-one term); no eigenvalue clipping, no nearest-PSD repair, and no factorisation anywhere in the state update. (The adaptive mixture is the one exception: it reads the gradient of the blend's own log score, which costs one Cholesky factorisation of the blend and a positive-definiteness check of each timescale's block per day. Switch it off on `SqueezeKernelEstimator` and the estimator is pure `O(Kn²)`.)
|
|
27
|
+
- **learns in market time and forgets in calendar time** — observations enter with a saturating, self-studentising weight (no day counts more than one unit of trading time); memory decays at fixed per-day rates on a geometric ladder of three timescales `(lam⁴, lam, lam^¼)`. Pairs accrue covariance at the geometric mean of their two clock increments, which is the most positive semi-definiteness allows and exactly the Cauchy–Schwarz bound on how far two assets' clocks can overlap. In closed form, each timescale's correlation is that of an exponentially weighted Gram matrix of the clock-weighted returns `√w·z`: day `s` enters the pair `(i, j)` with weight `√(w_i,s·w_j,s)` (market time) and is discounted by `lam_k^(t−s)` (calendar time). That makes it the natural-gradient step of the Gaussian log score, taken as a chord in calendar time on clock-weighted data; the geodesic along the same gradient would be an unbounded time change;
|
|
28
|
+
- **uses each day's magnitude once** — the day's Mahalanobis norm under the estimator's own forecast, `m = r'Σ⁻¹r`, sets the clock and is then removed from the observation: the innovation carries the weight `ω = n/m`, the posterior mean of the inverse trading-time increment under a scale-free prior (Tyler's weight; the Student-t score-driven weight is the same posterior mean under an inverse-gamma prior). A day's direction moves the state; its size only says how much trading time it carried. One dot product from the factorisation the mixture already performs, no constant;
|
|
29
|
+
- **regularises itself** — each timescale's shrinkage intensity is computed from two online statistics, the concentration `n/ν` (dimension per unit trading time) and the de-noised fraction of correlation dispersion the target explains; the target is the Hadamard square of the running correlation, which is exactly the correlation matrix of the *squared* returns (cluster-respecting, PSD by the Schur product theorem, and sign-blind by construction — the signs are carried by the unshrunk term). The intensity rule is the *prior* of a learned split: each timescale's shrunk correlation is a pool of its raw correlation, its equicorrelation level and its Hadamard square, whose weights are pulled toward the rule's `(1−α, α(1−α), α²)` by a fixed share and corrected online by the blend gradient;
|
|
30
|
+
- **adapts its memory to regime breaks, in both stages** — the timescale mix moves by an exponentiated-gradient step on the *blend's* own log score (not on any single timescale's, which would select rather than blend): each weight follows the Fisher–Rao inner product of its timescale with the day's natural gradient, at a temperature calibrated so that uninformative evidence leaves the mix within a factor e of its prior; the marginal variance is tracked on its own three-rung ladder, two octaves below the correlation ladder, and pooled panel-wide by the same rule on saturated evidence, so one spike day cannot hand a stale rung weeks of weight. Nothing in either mixture is fitted: the ladders are derived from `lam`, the evidence memory is the fastest rung's, and the temperature is the null's;
|
|
29
31
|
- **ingests missing values natively** — listings, delistings, halts enter as `NaN`;
|
|
30
|
-
- **is
|
|
32
|
+
- **is cheap, with no solver** — `O(Kn²)` state work plus `K + 1` Cholesky factorisations a day, no iterative optimisation anywhere; a thirty-year daily pass at n = 300 takes about two minutes single-threaded (the mixture's factorisation also certifies the spectral floor of the scored blend inactive on almost every day, and supplies the observation weight for one dot product). CM-IEWMA as released by its authors takes 11–41 times as long on the same panels, most of it a daily convex programme that is infeasible on up to 19% of days at n = 300; DCC and DCC-NL are cheaper still.
|
|
31
33
|
|
|
32
|
-
**Evidence.** On thirty years of S&P 500 constituents against
|
|
34
|
+
**Evidence.** On thirty years of S&P 500 constituents against a ten-method field, every baseline fitted on a tuning block (EWMA, DCC, DCC-NL, Ledoit–Wolf, OAS, nonlinear shrinkage, RMT filtering, Gerber, IEWMA, CM-IEWMA), it leads at every universe size from 50 to 300 and is the **sole member of the 90% model confidence set at every size**. Frozen on data to 2021, it leads the best baseline on 2022–2026 by 1.7, 3.7, 11.1 and 19.2 NLL per day at n = 50, 100, 200 and 300. On twenty-four pre-registered universes of small and mid caps sealed before any scoring (two draws of twelve) it is first on every one against a field fitted to each universe, by 13 to 18 NLL per day at n = 300; the second draw was sealed for the observation weight, which improved the estimator on eleven of the twelve, by 0.6 to 1.8 NLL per day at n ≥ 200. Carried **zero-shot** to a diversified panel of 121 futures across eight asset classes it beats the five baselines that run there, *calibrated on that panel's own history*, by 11.3 to 121 NLL per day out-of-time (the weight costs 0.5 per day on that block, its one trade-off); on the public FF49 industry panel of Johansson et al. it has the lowest regret on their own metric. The ranking holds under the Student-t and density-power scores.
|
|
33
35
|
|
|
34
36
|
## See the difference
|
|
35
37
|
|
|
@@ -42,7 +44,7 @@ A passive strategy any allocator would recognize: long-only minimum-variance ove
|
|
|
42
44
|
|
|
43
45
|
| Method | CAGR | Vol | Sharpe | MaxDD | Calmar | Vol-target RMSE |
|
|
44
46
|
|---|---|---|---|---|---|---|
|
|
45
|
-
| **Squeeze Kernel (default)** | **12.
|
|
47
|
+
| **Squeeze Kernel (default)** | **12.5%** | **13.6%** | **0.92** | **-34.5%** | **0.36** | **7.05%** |
|
|
46
48
|
| Ledoit-Wolf (252d) | 11.7% | 14.6% | 0.80 | -38.7% | 0.30 | 7.51% |
|
|
47
49
|
|
|
48
50
|
Reproduce from the repo alone (the 300-stock panel ships as a parquet; survivorship and provenance are documented in the script):
|
|
@@ -56,7 +58,7 @@ python examples/vol_targeted_portfolio.py # ~2 minutes
|
|
|
56
58
|
|
|
57
59
|
```bash
|
|
58
60
|
pip install squeeze-kernel # NumPy only
|
|
59
|
-
pip install "squeeze-kernel[full]" # + SciPy (faster
|
|
61
|
+
pip install "squeeze-kernel[full]" # + SciPy (faster Cholesky factorisations for the mixture)
|
|
60
62
|
```
|
|
61
63
|
|
|
62
64
|
## Quickstart
|
|
@@ -79,6 +81,8 @@ cov_path, corr_path, weights = estimate_squeeze_cov(returns, with_weights=True)
|
|
|
79
81
|
|
|
80
82
|
Missing values: pass `NaN` (or `mask=` on `update`). Newly listed, delisted or halted assets need no imputation and no complete-case subsetting.
|
|
81
83
|
|
|
84
|
+
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.
|
|
85
|
+
|
|
82
86
|
## What derives from `lam`
|
|
83
87
|
|
|
84
88
|
| quantity | value |
|
|
@@ -87,15 +91,17 @@ Missing values: pass `NaN` (or `mask=` on `update`). Newly listed, delisted or h
|
|
|
87
91
|
| kernel scale | state: `κ_t = ⅓ · EWMA(activity)` at the anchor rate |
|
|
88
92
|
| 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̃` |
|
|
89
93
|
| timescale weights | prior ∝ √h, moved by exponentiated gradient on the blend log score at the null temperature, fast-rung memory |
|
|
94
|
+
| 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 |
|
|
95
|
+
| 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 |
|
|
90
96
|
| volatility memory | ladder `(h/16, h/4, h)`, pooled panel-wide by the same rule on tanh-saturated evidence, uniform prior |
|
|
91
|
-
| structural constants | K=3, b=4, θ=½, κ-scale ⅓, Schur power 2 — each bracketed by ablation in the paper |
|
|
92
|
-
| fitted constants |
|
|
97
|
+
| structural constants | K=3, b=4, θ=½, κ-scale ⅓, Schur power 2, intensity exponent 2 — each bracketed by ablation in the paper |
|
|
98
|
+
| fitted constants | `lam` itself (0.996, chosen on data to 2021); nothing else is fitted |
|
|
93
99
|
|
|
94
|
-
`from squeeze_kernel import CONSTANTS` exposes the structural constants for research. The published v1 estimator (all its knobs) remains available as `SqueezeKernelEstimator` / `SqueezeKernel.v1(...)`; every 2.0
|
|
100
|
+
`from squeeze_kernel import CONSTANTS` exposes the structural constants for research. The published v1 estimator (all its knobs) remains available as `SqueezeKernelEstimator` / `SqueezeKernel.v1(...)`; every mechanism since 2.0 is also an estimator-level switch for ablation. See [MIGRATION.md](MIGRATION.md).
|
|
95
101
|
|
|
96
102
|
## How it works
|
|
97
103
|
|
|
98
|
-
One daily update: variance on a three-rung ladder per asset, pooled by panel-wide self-adapting weights → standardised surprise → per-asset clock increments from the Schur-square-weighted neighbourhood mean of squared surprises → diagonal-congruence update of each timescale's correlation state on those clocks → per-timescale shrinkage as a learned pool of the raw correlation, its equicorrelation level and its Hadamard square, with the self-tuning intensity rule as the prior and the blend gradient as the correction → blend across timescales, moved by the gradient of the blend's own log score → covariance. The paper gives the derivations, guarantees (PSD, conditioning floor, exact reductions to the published special cases), and the full evaluation.
|
|
104
|
+
One daily update: variance on a three-rung ladder per asset, pooled by panel-wide self-adapting weights → standardised surprise → per-asset clock increments from the Schur-square-weighted neighbourhood mean of squared surprises → diagonal-congruence update of each timescale's correlation state on those clocks, the day's outer product scaled by `n/m` → per-timescale shrinkage as a learned pool of the raw correlation, its equicorrelation level and its Hadamard square, with the self-tuning intensity rule as the prior and the blend gradient as the correction → blend across timescales, moved by the gradient of the blend's own log score → covariance. The paper gives the derivations (the natural-gradient and Gram-matrix forms of the flow, the Fisher–Rao form of the mixture), the guarantees (PSD, conditioning floor, exact reductions to the published special cases), and the full evaluation.
|
|
99
105
|
|
|
100
106
|
## Development
|
|
101
107
|
|
|
@@ -4,7 +4,7 @@ build-backend = "uv_build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "squeeze-kernel"
|
|
7
|
-
version = "3.
|
|
7
|
+
version = "3.2.0"
|
|
8
8
|
description = "Streaming, PSD-by-construction covariance estimator with Fisher-kernel weighting and adaptive shrinkage"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "MIT"
|
|
@@ -4,7 +4,7 @@ build-backend = "uv_build"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "squeeze-kernel"
|
|
7
|
-
version = "3.
|
|
7
|
+
version = "3.2.0"
|
|
8
8
|
description = "Streaming, PSD-by-construction covariance estimator with Fisher-kernel weighting and adaptive shrinkage"
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
license = "MIT"
|
|
@@ -121,6 +121,7 @@ class SqueezeKernel:
|
|
|
121
121
|
vol_ladder=True,
|
|
122
122
|
weights="eg_blend",
|
|
123
123
|
split_learn=True,
|
|
124
|
+
obs_weight="tyler",
|
|
124
125
|
epsilon=c.epsilon,
|
|
125
126
|
)
|
|
126
127
|
|
|
@@ -177,6 +178,7 @@ class SqueezeKernel:
|
|
|
177
178
|
"rung_nu": nu,
|
|
178
179
|
"detector_tilt": 0.0 if det is None else det.tilt,
|
|
179
180
|
"split": det.v.copy() if isinstance(det, _BlendGradient) and det.split else None,
|
|
181
|
+
"omega_t": est._last_omega,
|
|
180
182
|
}
|
|
181
183
|
|
|
182
184
|
# ── v1 escape hatch ──────────────────────────────────────────────────
|
|
@@ -153,6 +153,18 @@ class _BlendGradient:
|
|
|
153
153
|
"""
|
|
154
154
|
|
|
155
155
|
_JITTER = 1e-12
|
|
156
|
+
_FLOOR = 1e-8 # spectral floor of the scored blend
|
|
157
|
+
_CERT = 10.0 # certify lambda_min >= _CERT * _FLOOR before skipping the floor
|
|
158
|
+
|
|
159
|
+
@staticmethod
|
|
160
|
+
def _solve(sig: np.ndarray, r: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
|
|
161
|
+
"""(sig^-1 r, sig^-1) from one Cholesky factorisation."""
|
|
162
|
+
if _cho_factor is not None:
|
|
163
|
+
cf = _cho_factor(sig, lower=True, check_finite=False)
|
|
164
|
+
return (_cho_solve(cf, r, check_finite=False),
|
|
165
|
+
_cho_solve(cf, np.eye(sig.shape[0]), check_finite=False))
|
|
166
|
+
sinv = np.linalg.inv(sig)
|
|
167
|
+
return sinv @ r, sinv
|
|
156
168
|
|
|
157
169
|
def __init__(self, half_lives: np.ndarray, prior: np.ndarray,
|
|
158
170
|
split: bool = False, n_experts: int = 3) -> None:
|
|
@@ -181,10 +193,17 @@ class _BlendGradient:
|
|
|
181
193
|
self.prev_vol: np.ndarray | None = None
|
|
182
194
|
self.prev_v: np.ndarray | None = None
|
|
183
195
|
self._gc: np.ndarray | None = None
|
|
196
|
+
# The day's Mahalanobis distance under the forecast, m = r' Sigma^-1 r
|
|
197
|
+
# on the observed subvector, and that subvector's size: read by the
|
|
198
|
+
# 3.2 observation weight; NaN on a day the gradient abstains.
|
|
199
|
+
self.m_last = float("nan")
|
|
200
|
+
self.n_last = 0
|
|
184
201
|
|
|
185
202
|
def score(self, r_t: np.ndarray, finite: np.ndarray) -> np.ndarray | None:
|
|
186
203
|
"""Gradient of the previous blend's log score at ``r_t`` (observed
|
|
187
204
|
subvector), one entry per rung; ``None`` on a degenerate day."""
|
|
205
|
+
self.m_last = float("nan")
|
|
206
|
+
self.n_last = 0
|
|
188
207
|
if self.prev_sig is None or self.prev_w is None:
|
|
189
208
|
return None
|
|
190
209
|
idx = np.flatnonzero(finite)
|
|
@@ -224,23 +243,33 @@ class _BlendGradient:
|
|
|
224
243
|
for k in range(K):
|
|
225
244
|
sig += self.prev_w[k] * self.prev_sig[k][np.ix_(idx, idx)]
|
|
226
245
|
sig = 0.5 * (sig + sig.T)
|
|
227
|
-
#
|
|
228
|
-
# engine's scoring path does: a near-singular early
|
|
229
|
-
# otherwise hand the running scale one enormous
|
|
230
|
-
# silence the mixer for years.
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
246
|
+
# The spectrum is floored at _FLOOR before factorising, exactly as
|
|
247
|
+
# the research engine's scoring path does: a near-singular early
|
|
248
|
+
# blend would otherwise hand the running scale one enormous
|
|
249
|
+
# gradient and silence the mixer for years. The floor acts only
|
|
250
|
+
# when lambda_min < _FLOOR, so factorise first and certify: the
|
|
251
|
+
# inverse gives lambda_min >= 1/||sig^-1||_F, and a certified day
|
|
252
|
+
# is bit-identical to the floored path (no floor, same factor).
|
|
253
|
+
# Uncertified or failed days take the eigenvalue floor as before.
|
|
254
|
+
sol: tuple[np.ndarray, np.ndarray] | None = None
|
|
234
255
|
try:
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
else:
|
|
240
|
-
sinv = np.linalg.inv(sig)
|
|
241
|
-
u = sinv @ r_t[idx]
|
|
256
|
+
sol = self._solve(sig, r_t[idx])
|
|
257
|
+
fro = float(np.linalg.norm(sol[1]))
|
|
258
|
+
if not (np.isfinite(fro) and fro * self._CERT * self._FLOOR <= 1.0):
|
|
259
|
+
sol = None
|
|
242
260
|
except (np.linalg.LinAlgError, ValueError):
|
|
243
|
-
|
|
261
|
+
sol = None
|
|
262
|
+
if sol is None:
|
|
263
|
+
min_eig = float(np.linalg.eigvalsh(sig).min())
|
|
264
|
+
if min_eig < self._FLOOR:
|
|
265
|
+
sig = sig + np.eye(idx.size) * (self._FLOOR - min_eig)
|
|
266
|
+
try:
|
|
267
|
+
sol = self._solve(sig, r_t[idx])
|
|
268
|
+
except (np.linalg.LinAlgError, ValueError):
|
|
269
|
+
return None
|
|
270
|
+
u, sinv = sol
|
|
271
|
+
self.m_last = float(r_t[idx] @ u)
|
|
272
|
+
self.n_last = int(idx.size)
|
|
244
273
|
g = np.empty(K)
|
|
245
274
|
self._gc = None
|
|
246
275
|
if self.split and self.prev_comps is not None:
|
|
@@ -422,6 +451,7 @@ class SqueezeKernelEstimator:
|
|
|
422
451
|
vol_ladder: bool = False,
|
|
423
452
|
weights: str = "cusum",
|
|
424
453
|
split_learn: bool = False,
|
|
454
|
+
obs_weight: str | None = None,
|
|
425
455
|
):
|
|
426
456
|
self.n_assets = n_assets
|
|
427
457
|
if weights not in ("cusum", "eg_blend"):
|
|
@@ -430,6 +460,21 @@ class SqueezeKernelEstimator:
|
|
|
430
460
|
if split_learn and weights != "eg_blend":
|
|
431
461
|
raise ValueError("split_learn requires weights='eg_blend'.")
|
|
432
462
|
self.split_learn = bool(split_learn)
|
|
463
|
+
# 3.2: the joint observation weight. "tyler" scales each day's
|
|
464
|
+
# correlation innovation by omega = n/m, m = r' Sigma^-1 r the
|
|
465
|
+
# day's Mahalanobis distance under the estimator's own forecast of
|
|
466
|
+
# the day before (n the observed count): the posterior mean of the
|
|
467
|
+
# inverse common trading-time increment under the scale-invariant
|
|
468
|
+
# prior, Tyler's shape weight, the nu -> 0 limit of the Student-t
|
|
469
|
+
# score weight. The day's norm then enters the state once, through
|
|
470
|
+
# the clock, and its direction through the outer product. None
|
|
471
|
+
# keeps the 3.1 path bit-for-bit.
|
|
472
|
+
if obs_weight not in (None, "tyler"):
|
|
473
|
+
raise ValueError("obs_weight must be None or 'tyler'.")
|
|
474
|
+
if obs_weight is not None and (weights != "eg_blend" or clock != "asset"):
|
|
475
|
+
raise ValueError("obs_weight='tyler' requires weights='eg_blend' and clock='asset'.")
|
|
476
|
+
self.obs_weight = obs_weight
|
|
477
|
+
self._last_omega = 1.0
|
|
433
478
|
self.vol_ladder = bool(vol_ladder)
|
|
434
479
|
self.lambda_vol = lambda_vol
|
|
435
480
|
self.lambda_corr = lambda_corr
|
|
@@ -728,6 +773,16 @@ class SqueezeKernelEstimator:
|
|
|
728
773
|
finite,
|
|
729
774
|
self._kap_lam * kap_a + (1.0 - self._kap_lam) * a_act,
|
|
730
775
|
kap_a)
|
|
776
|
+
# 3.2 observation weight: sqrt(omega) on the innovation, omega =
|
|
777
|
+
# n/m from the gradient's own solve of the forecast at r_t; one
|
|
778
|
+
# on a day the gradient abstained.
|
|
779
|
+
sq_omega = 1.0
|
|
780
|
+
if w_vec is not None and self.obs_weight == "tyler":
|
|
781
|
+
assert isinstance(detector, _BlendGradient)
|
|
782
|
+
m_day = detector.m_last
|
|
783
|
+
if np.isfinite(m_day) and m_day > 1e-12:
|
|
784
|
+
sq_omega = float(np.sqrt(detector.n_last / m_day))
|
|
785
|
+
self._last_omega = sq_omega * sq_omega
|
|
731
786
|
s_eff = 0.0
|
|
732
787
|
for k in range(corr_lam.size):
|
|
733
788
|
S_list[k] = corr_lam[k] * S_list[k] + w_t
|
|
@@ -739,6 +794,8 @@ class SqueezeKernelEstimator:
|
|
|
739
794
|
eta_v = w_vec / S_a[k]
|
|
740
795
|
o = np.sqrt(1.0 - eta_v)
|
|
741
796
|
u = np.sqrt(eta_v) * z_t
|
|
797
|
+
if sq_omega != 1.0:
|
|
798
|
+
u = u * sq_omega
|
|
742
799
|
np.multiply.outer(o, o, out=self._scratch_had)
|
|
743
800
|
Q_list[k] *= self._scratch_had
|
|
744
801
|
np.multiply.outer(u, u, out=self._scratch_had)
|
|
File without changes
|
|
File without changes
|