rheon.spec.ew_cov

rheon.spec.ew_cov(name: str, *, features: list[str], stats: list[Literal['mean', 'var', 'std', 'cov', 'corr', 'partial_corr', 'mahal', 'lag_corr']] | None = None, bias: bool = False, precision_prior: float | None = None, mahal_quantiles: list[float] | None = None, pca: int | None = None, pca_every: float | timedelta | str | _Expr | None = None, max_rows_between_pcas: int | None = None, lags: list[int] | None = None, gram_threads: int | Literal['auto'] | None = None, window_size: float | timedelta | str | _Expr | None = None, closed: Literal['right', 'both'] = 'right', snapshot_every: float | timedelta | str | _Expr | None = None, max_rows_between_snapshots: int | None = None, window_budget: dict[Literal['thin', 'refuse'], float] | None = None, **common: Unpack[CommonKwargs]) → dict[str, Any][source]

Exponentially weighted moments of the feature columns, and the statistics read off them.

Use it for the running means, spreads, correlations, principal components or Mahalanobis distances of a stream’s columns, read before each row, so an output can be a feature for that same row without leaking it. It fits no target: use ewridge() for a regression on the same co-moments, and rcov() for a block’s covariance under microstructure noise.

Parameters

The stream parameters every builder takes, such as clock, half_life, gap_cap, min_weight and group, are in rheon.spec. This model reads features and takes no targets. fit_intercept has nothing to act on, as there is no regression. Nothing that reads residuals applies, and each such switch is refused by name: emit_sigma, emit_metrics, conformal, emit_drift and the rest. coef_every and max_rows_between_coefs are refused, as there are no coefficients. This model’s own:

stats

Which statistics to write, from mean, var, std, cov, corr, partial_corr, mahal and lag_corr. Default ["mean", "std", "corr"], so a single feature needs stats without cov, corr and partial_corr, which need two columns. partial_corr and mahal need precision_prior, lag_corr needs lags, and mahal_quantiles needs mahal. [] writes no statistic, only weight_sum, settled_frac and withheld_reason, and learns all the same. The spec’s value is then its state, read back with rheon.polars.ModelBank.gram() and rheon.polars.ModelBank.describe(). That is the form for a wide set of columns, where even the means are k values a row (k the number of features) that nobody reads.

bias

Polars’ bias, with its default False: var, std and cov are then Polars’ ewm_var and ewm_std and the covariance they imply, on a clock of one row a step and with Polars’ default adjust=True. That multiplies the weighted means by the factor c of The update, Bessel’s correction at Kish’s effective size (Bias in Notes). True reports the weighted means as kept, which is what rheon.polars.ModelBank.gram() returns under either. Under False, a second moment is null while the moments hold a single row, of any weight, as Polars’ is. Under True it reads 0.

precision_prior

A ridge on the co-moments, in the features’ squared units, finite and above 0: it makes the precision matrix P of The update solvable on each row it is read (O(k³), only when asked for). Like rls()’s prior it fades as rows arrive. Default None, no ridge. Needed by partial_corr and mahal alone: the other statistics read the co-moments themselves, which need no inverse, so None adds no ridge to them. ew_class() and hmm() require it, since every row they predict reads an inverse.

mahal_quantiles

Levels in (0, 1) at which to keep the exponentially weighted quantile of the past mahal distances (mahal_q<p>), at the model’s half-life and each row’s weight, within tanh(1/128) (0.78%) of the exact one. That is a threshold from the stream’s own history instead of a table, so mahal > mahal_q0.99 is one row in a hundred without assuming a distribution. The row’s own distance joins after it is read.

pca

Track the top pca principal components of the covariance, at least 1 and at most the number of features. Per component j:

field

what it holds

pc<j>_var

its eigenvalue

pc<j>_share

its share of the total variance

pc<j>_loading_<feature>

its unit loading on each column

pc<j>_score

the row’s coordinate v_j . (x - m)

The first refresh makes each component’s largest loading in magnitude positive. Each later refresh turns a component to within 90° of its previous loadings, so a component and its score never flip sign from one refresh to the next (Principal components in Notes).

pca_every, max_rows_between_pcas

How often the eigendecomposition, O(k³), is refreshed after the row is learned: every pca_every clock units or every max_rows_between_pcas rows, whichever comes first, as solve_every and max_rows_between_solves schedule a regression’s solve. pca_every is a number of the clock’s units, a duration on a temporal clock ("5m"), or 0 for every row, finite and at least 0. max_rows_between_pcas is at least 1. With neither given, every row. Both are refused without pca. Between refreshes the loadings are frozen, so a row’s scores never depend on the chunking.

lags

Lagged cross-moments beside the contemporaneous ones (Lags in Notes). Lags are counted in learned rows within the group, not clock units, and must be strictly increasing, >= 1 and at most 2^20 (1,048,576), the ring being sized before the first row. The list order is the output order. Add "lag_corr" to stats to write lag_corr_l<l>_<a>_<b> = C_l[a,b] / sqrt(C_0[a,a] * C_0[b,b]) per lag and ordered pair, the auto terms included. That is k² fields a lag, since a lagged matrix is not symmetric. Or read lags and lag_comoments (an (L, k, k) array) from rheon.polars.ModelBank.gram().

gram_threads

The largest number of the bank’s threads that learning one row into the k x k co-moments may use: a whole number of at least 1, or "auto", as ewridge()’s gram_threads is. It never adds a thread to the bank’s. Default "auto", which splits a row’s learning only where the bank has idle threads. The output is the same to the bit at every count (Threads in Notes).

window_size, closed

A hard window on the history, in clock units, finite and above 0: a row window_size old or older contributes nothing at all, where the exponential weight alone would still leave 0.5 ** (age / half_life) of it, 12.5% at three half-lives. closed is "right" (the default) or "both", which keeps the row exactly that old, as for ewridge(). Inside the hard window the weights are still exponential, so this is not a flat mean over its rows: each row keeps the weight it has without one. window_size is refused beside lags and mahal_quantiles, which run over a history it does not cut (The hard window in Notes).

snapshot_every, max_rows_between_snapshots, window_budget

The hard window’s snapshots, as for ewridge(). snapshot_every spaces them on the clock ("1m", or a number of the clock’s units) and max_rows_between_snapshots caps the rows between them, whichever comes first. window_budget bounds each ring in MiB and thins or refuses past the bound. By default a snapshot on every row, and no budget. closed="both" and these three are refused without window_size.

Output

One output column, named after the spec, whose value in each row is a record of these fields, read before the row is learned. docs/OUTPUTS.md#ew_cov gives each field’s type and when it is null:

mean_<column>, var_<column>, std_<column>

Per column, as stats asks: the mean, the variance and the standard deviation, as mean_x0.

cov_<column>_<column>, corr_<column>_<column>, partial_corr_<column>_<column>

Per pair, unordered, i < j, as corr_x0_x1.

lag_corr_l<l>_<a>_<b>

Per lag and ordered pair, under lags.

mahal, mahal_q<p>

The row’s Mahalanobis distance from the mean, and the quantiles of its past values mahal_quantiles asks for.

pc<j>_var, pc<j>_share, pc<j>_loading_<feature>, pc<j>_score

Under pca, as the table under pca says.

weight_sum

The weight the model has accumulated before the row and before the row’s own decay.

settled_frac

How far the model had come toward its steady state under decay before the row.

withheld_reason

Why the row’s statistics were withheld, null where they were not.

The statistics are null until min_weight, which defaults to the number of features plus one and which the bank floors at 2: a variance needs two rows, so a lower min_weight, 0 included, is taken as 2, and is not refused. The rows the floor holds back read below_min_weight, as the gate’s do. The moments themselves are rheon.polars.ModelBank.gram()’s means, comoments, lags and lag_comoments, the weighted means as kept whatever bias is, with n_kish to correct them by. A group that closes writes them to rheon.polars.ModelBank.closed_groups() with eig_vals and eig_vecs of those comoments under pca.

Raises

As every builder does (rheon.spec), TypeError for targets, which this model does not take, and ValueError naming the problem for:

  • a statistic not in the list, cov, corr or partial_corr over one column, partial_corr or mahal without precision_prior, and lag_corr without lags;

  • a precision_prior not finite or not above 0;

  • an empty lags, one that does not increase, or a lag below 1 or above 2^20;

  • an empty mahal_quantiles, one without mahal, or a level outside (0, 1);

  • a pca of 0 or past the features, a pca_every below 0 or not finite, a max_rows_between_pcas of 0, and pca_every or max_rows_between_pcas without pca;

  • a gram_threads of 0, or a string other than "auto";

  • a statistic or a mahal_quantiles level listed twice;

  • a window_size not finite or not above 0, window_size beside lags or mahal_quantiles, a closed of "left" or "none", a snapshot_every below 0 or not finite, a max_rows_between_snapshots below 1, a window_budget that is not one key, "thin" or "refuse", or whose MiB is not above 0, and closed="both", snapshot_every, max_rows_between_snapshots or window_budget without window_size;

  • a switch that reads residuals, such as emit_sigma, and coef_every.

The update

Per row, w is the row’s weight, λ = 0.5 ** (Δclock / half_life) its decay (lam ** Δclock under lam), and x the row’s features. Δclock is the clock’s step since the last row the model did not skip, capped at gap_cap, or session_gap at a session change. The means m and the centered co-moments C are kept as weighted means, in Welford’s form, beside the weight W and the sum of the squared weights Q:

W'     = λ * W + w
Q'     = λ**2 * Q + w**2
a      = λ * W / W'        b = w / W'        (a + b = 1)
delta  = x - m
m'     = m + b * delta
C'_ij  = a * C_ij + a * b * delta_i * delta_j

The second moments are read off C times a factor c, and corr_ij = C_ij / sqrt(C_ii C_jj), from which c cancels:

c       = W**2 / (W**2 - Q)       (1 under bias=True)
var_i   = c * C_ii        std_i = sqrt(var_i)        cov_ij = c * C_ij

With P = (c * (C + s * precision_prior * I))^-1, read before the row, and s the prior’s scale (1 on the first row, times a on each row after):

partial_corr_ij = -P_ij / sqrt(P_ii P_jj)
mahal           = sqrt((x - m)' P (x - m))

With W and m the weight and mean before the row, and both deviations against that mean, each lag l of lags keeps:

C_l' = a * C_l + a * b * (x_t - m) (x_{t-l} - m)'

Example

This code plants two columns with spreads 2 and 1 and a correlation of 0.6, and prints what the model reads before the last row:

import numpy as np

rng = np.random.default_rng(5)
a, b = rng.standard_normal(10_000), rng.standard_normal(10_000)
x0 = 2.0 * a                                    # spread 2
x1 = 0.6 * a + 0.8 * b                          # correlation 0.6 with x0
pl.DataFrame({"x0": x0, "x1": x1}).write_parquet("pair.parquet")

mv = rp.spec.ew_cov(
    "mv", features=["x0", "x1"], half_life=float("inf"),
    stats=["std", "corr"],                      # std_x0, std_x1 and corr_x0_x1
)
out = pl.scan_parquet("pair.parquet").rheon.fit_predict([mv]).collect().unnest("mv")
last = out.row(-1, named=True)                  # read before the last row is learned
print("planted: std_x0 2.00, corr 0.60")
print(f"found: std_x0 {last['std_x0']:.2f}, corr {last['corr_x0_x1']:.2f}")
planted: std_x0 2.00, corr 0.60
found: std_x0 2.01, corr 0.60

See also

Notes

Precision. A variance stays accurate when the columns sit on a large offset, where the raw E[x^2] - m^2 form loses it.

Against Polars. Learning a row in O(k²) replaces the O(k²) passes a pure-Polars pairwise exponentially weighted correlation needs. For moments on data that fits in memory, Polars can compute the same moments under a window_size when you weight each row yourself in df.rolling(clock, period=window_size).agg(...). There each row is weighted 2 ** (-age / half_life) from the window’s last row, c comes from those weights, and the result is shifted one row, since a row’s moments are read before the row. On 20,000 rows about a minute apart, a three-hour hard window (window_size="3h", about 180 rows) and a half-life of 30 minutes, the mean of a column near 100 agreed to 8.5e-14, its variance to 6.4e-14 and its correlation with a second column to 4.3e-14. The reason to reach for the spec is a stream, a saved state, or the work: Polars recomputes each window, so its work grows with n rows times the rows of a window, where this model’s grows with n.

Bias. The factor c is n / (n - 1) at Kish’s effective size n = W**2 / Q, the number of equally weighted rows the moments are worth: Bessel’s correction, ddof=1 for n unit rows with no decay. At a half-life of 20 rows it is 1.018 in steady state, at 2 rows 1.207. c multiplies the ridge on the co-moments with them, so it divides mahal by sqrt(c), multiplies pc<j>_var by its value at the refresh, and moves no correlation, share, loading or score.

Principal components. The components are the same to the bit whatever the bank’s thread count (RHEON_MAX_THREADS): the eigensolver runs at a fixed parallel degree of eight. A row of weight zero advances both refresh schedules, as the hard window’s snapshot cadence counts it, and a gap capped at gap_cap counts as the cap. Without a clock column the clock is the row’s number.

Lags. C_l uses the same a and b the co-moments use, so lag 0 would be comoments exactly. The lagged statistics are defined by this recursion, both legs centered at the mean before each row, not as a lagged covariance of the whole stream about the final mean, which a frame in memory would compute. The ring of past rows is emptied on a clock break: a row whose clock step gap_cap shortened, whether the step follows one row or a run of skipped rows, or a session change. After a clock break, “the row l back” is not a row l ago. A zero-weight row ages the matrices and does not enter the ring. A group’s first rows read lag_corr null until min_weight, at least two rows of weight, since one row has no variance to divide by. C_l starts at 0 and takes its first product when a learned row has one l rows back, so after those rows lag_corr reads 0.0, not null, while the group has learned no more than l rows before the row.

Threads. Learning a row is bound by memory: at 2,000 features a spec that wrote no statistic learned 2.5 times as fast on eight threads and 3.1 times on fourteen (measured on 2026-10-08). Below 725 features learning a row stays on one thread, and the lagged cross-moments of lags always do.

The hard window. It is exact, because an exponentially weighted sum contains its own past. Everything at or before a time u is lam ** (t - u) times the running sums as they stood at u, so subtracting that leaves precisely the rest. What the model keeps is a ring of snapshots, one per row by default, so its memory grows with the snapshots the hard window keeps rather than with the state alone. A snapshot is k² + k + 3 eight-byte numbers, so a 1,000-row hard window over 20 columns is about 3 MB per group. Spacing the snapshots with snapshot_every or max_rows_between_snapshots divides the memory, and a clock spacing alone holds a ring to at most window_size / snapshot_every + 2 snapshots whatever the row rate. Four things to know before reading the numbers under a hard window:

the caveat

why

the guarantee is one-sided

the boundary is the oldest snapshot still inside the hard window, so what is dropped is always a superset of what the hard window excludes; under a coarser cadence the hard window kept is shorter than asked by at most one snapshot’s spacing, never longer: in [window_size - snapshot_every, window_size] in clock units, exactly, under a clock spacing, with snapshot_every the spacing in force (a thinning budget doubles it)

the clock is the decayed one

window_size is measured on the clock the decay uses, after gap_cap caps a gap and after a session_gap is applied

the edge is a discontinuity

a row aging out drops its whole weight at once, so the series has small steps an exponentially weighted mean without a hard window does not

it is a subtraction

precision falls with the fraction discarded: negligible at window_size = 3 * half_life (an eighth of the mass), worse as the hard window shortens toward the half-life

weight_sum becomes the weight inside the hard window, which stops growing once the hard window fills, so min_weight withholds on a quantity with a ceiling. A clock gap longer than window_size empties it. The row after the gap reads the hard window as the row before the gap left it, since a row’s fields are read before its own decay, as weight_sum is. The rows after it report nulls rather than stale numbers, until the hard window holds min_weight again. mahal, partial_corr and the principal components read the hard window’s moments too, bias’s factor is the hard window’s W and Q, and the refresh of the principal components waits on the hard window’s weight.