polars_online.spec.ew_cov¶
- polars_online.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, andrcov()for a block’s covariance under microstructure noise.Parameters
The stream parameters every builder takes, such as
clock,half_life,gap_cap,min_weightandgroup, are inpolars_online.spec. This model readsfeaturesand takes notargets.fit_intercepthas 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_driftand the rest.coef_everyandmax_rows_between_coefsare refused, as there are no coefficients. This model’s own:statsWhich statistics to write, from
mean,var,std,cov,corr,partial_corr,mahalandlag_corr. Default["mean", "std", "corr"], so a single feature needsstatswithoutcov,corrandpartial_corr, which need two columns.partial_corrandmahalneedprecision_prior,lag_corrneedslags, andmahal_quantilesneedsmahal.[]writes no statistic, onlyweight_sum,settled_fracandwithheld_reason, and learns all the same. The spec’s value is then its state, read back withpolars_online.ModelBank.gram()andpolars_online.ModelBank.describe(). That is the form for a wide set of columns, where even the means arekvalues a row (kthe number of features) that nobody reads.biasPolars’
bias, with its defaultFalse:var,stdandcovare then Polars’ewm_varandewm_stdand the covariance they imply, on a clock of one row a step and with Polars’ defaultadjust=True. That multiplies the weighted means by the factorcof The update, Bessel’s correction at Kish’s effective size (Bias in Notes).Truereports the weighted means as kept, which is whatpolars_online.ModelBank.gram()returns under either. UnderFalse, a second moment is null while the moments hold a single row, of any weight, as Polars’ is. UnderTrueit reads 0.precision_priorA ridge on the co-moments, in the features’ squared units, finite and above 0: it makes the precision matrix
Pof The update solvable on each row it is read (O(k³), only when asked for). Likerls()’s prior it fades as rows arrive. DefaultNone, no ridge. Needed bypartial_corrandmahalalone: the other statistics read the co-moments themselves, which need no inverse, soNoneadds no ridge to them.ew_class()andhmm()require it, since every row they predict reads an inverse.mahal_quantilesLevels in
(0, 1)at which to keep the exponentially weighted quantile of the pastmahaldistances (mahal_q<p>), at the model’s half-life and each row’s weight, withintanh(1/128)(0.78%) of the exact one. That is a threshold from the stream’s own history instead of a table, somahal > mahal_q0.99is one row in a hundred without assuming a distribution. The row’s own distance joins after it is read.pcaTrack the top
pcaprincipal components of the covariance, at least 1 and at most the number of features. Per componentj:field
what it holds
pc<j>_varits eigenvalue
pc<j>_shareits share of the total variance
pc<j>_loading_<feature>its unit loading on each column
pc<j>_scorethe 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_pcasHow often the eigendecomposition, O(k³), is refreshed after the row is learned: every
pca_everyclock units or everymax_rows_between_pcasrows, whichever comes first, assolve_everyandmax_rows_between_solvesschedule a regression’s solve.pca_everyis a number of the clock’s units, a duration on a temporal clock ("5m"), or0for every row, finite and at least 0.max_rows_between_pcasis at least 1. With neither given, every row. Both are refused withoutpca. Between refreshes the loadings are frozen, so a row’s scores never depend on the chunking.lagsLagged 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,
>= 1and 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"tostatsto writelag_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 isk²fields a lag, since a lagged matrix is not symmetric. Or readlagsandlag_comoments(an(L, k, k)array) frompolars_online.ModelBank.gram().gram_threadsThe largest number of the bank’s threads that learning one row into the
k x kco-moments may use: a whole number of at least 1, or"auto", asewridge()’sgram_threadsis. 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,closedA hard window on the history, in clock units, finite and above 0: a row
window_sizeold or older contributes nothing at all, where the exponential weight alone would still leave0.5 ** (age / half_life)of it, 12.5% at three half-lives.closedis"right"(the default) or"both", which keeps the row exactly that old, as forewridge(). 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_sizeis refused besidelagsandmahal_quantiles, which run over a history it does not cut (The hard window in Notes).snapshot_every,max_rows_between_snapshots,window_budgetThe hard window’s snapshots, as for
ewridge().snapshot_everyspaces them on the clock ("1m", or a number of the clock’s units) andmax_rows_between_snapshotscaps the rows between them, whichever comes first.window_budgetbounds 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 withoutwindow_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
statsasks: the mean, the variance and the standard deviation, asmean_x0.cov_<column>_<column>,corr_<column>_<column>,partial_corr_<column>_<column>Per pair, unordered,
i < j, ascorr_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_quantilesasks for.pc<j>_var,pc<j>_share,pc<j>_loading_<feature>,pc<j>_scoreUnder
pca, as the table underpcasays.weight_sumThe weight the model has accumulated before the row and before the row’s own decay.
settled_fracHow far the model had come toward its steady state under decay before the row.
withheld_reasonWhy 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 lowermin_weight,0included, is taken as 2, and is not refused. The rows the floor holds back readbelow_min_weight, as the gate’s do. The moments themselves arepolars_online.ModelBank.gram()’smeans,comoments,lagsandlag_comoments, the weighted means as kept whateverbiasis, withn_kishto correct them by. A group that closes writes them topolars_online.ModelBank.closed_groups()witheig_valsandeig_vecsof thosecomomentsunderpca.Raises
As every builder does (
polars_online.spec),TypeErrorfortargets, which this model does not take, andValueErrornaming the problem for:a statistic not in the list,
cov,corrorpartial_corrover one column,partial_corrormahalwithoutprecision_prior, andlag_corrwithoutlags;a
precision_priornot 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 withoutmahal, or a level outside(0, 1);a
pcaof 0 or past the features, apca_everybelow 0 or not finite, amax_rows_between_pcasof 0, andpca_everyormax_rows_between_pcaswithoutpca;a
gram_threadsof 0, or a string other than"auto";a statistic or a
mahal_quantileslevel listed twice;a
window_sizenot finite or not above 0,window_sizebesidelagsormahal_quantiles, aclosedof"left"or"none", asnapshot_everybelow 0 or not finite, amax_rows_between_snapshotsbelow 1, awindow_budgetthat is not one key,"thin"or"refuse", or whose MiB is not above 0, andclosed="both",snapshot_every,max_rows_between_snapshotsorwindow_budgetwithoutwindow_size;a switch that reads residuals, such as
emit_sigma, andcoef_every.
The update
Per row,
wis the row’s weight,λ = 0.5 ** (Δclock / half_life)its decay (lam ** Δclockunderlam), andxthe row’s features.Δclockis the clock’s step since the last row the model did not skip, capped atgap_cap, orsession_gapat a session change. The meansmand the centered co-momentsCare kept as weighted means, in Welford’s form, beside the weightWand the sum of the squared weightsQ: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
Ctimes a factorc, andcorr_ij = C_ij / sqrt(C_ii C_jj), from whichccancels: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, andsthe prior’s scale (1 on the first row, timesaon each row after):partial_corr_ij = -P_ij / sqrt(P_ii P_jj) mahal = sqrt((x - m)' P (x - m))
With
Wandmthe weight and mean before the row, and both deviations against that mean, each lagloflagskeeps: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 = po.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").online.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
ewridge(), a regression on the same running co-moments.ew_class()andhmm(), which classify rows by Gaussians on these moments.rcov(), a block’s covariance robust to microstructure noise.polars_online.ModelBank.gram(), to read the moments back.
Notes
Precision. A variance stays accurate when the columns sit on a large offset, where the raw
E[x^2] - m^2form 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_sizewhen you weight each row yourself indf.rolling(clock, period=window_size).agg(...). There each row is weighted2 ** (-age / half_life)from the window’s last row,ccomes 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 withnrows times the rows of a window, where this model’s grows withn.Bias. The factor
cisn / (n - 1)at Kish’s effective sizen = W**2 / Q, the number of equally weighted rows the moments are worth: Bessel’s correction,ddof=1fornunit rows with no decay. At a half-life of 20 rows it is 1.018 in steady state, at 2 rows 1.207.cmultiplies the ridge on the co-moments with them, so it dividesmahalbysqrt(c), multipliespc<j>_varby 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 (
POLARS_ONLINE_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 atgap_capcounts as the cap. Without a clock column the clock is the row’s number.Lags.
C_luses the sameaandbthe co-moments use, so lag 0 would becomomentsexactly. 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 stepgap_capshortened, whether the step follows one row or a run of skipped rows, or a session change. After a clock break, “the rowlback” is not a rowlago. A zero-weight row ages the matrices and does not enter the ring. A group’s first rows readlag_corrnull untilmin_weight, at least two rows of weight, since one row has no variance to divide by.C_lstarts at 0 and takes its first product when a learned row has onelrows back, so after those rowslag_corrreads 0.0, not null, while the group has learned no more thanlrows 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
lagsalways do.The hard window. It is exact, because an exponentially weighted sum contains its own past. Everything at or before a time
uislam ** (t - u)times the running sums as they stood atu, 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 isk² + k + 3eight-byte numbers, so a 1,000-row hard window over 20 columns is about 3 MB per group. Spacing the snapshots withsnapshot_everyormax_rows_between_snapshotsdivides the memory, and a clock spacing alone holds a ring to at mostwindow_size / snapshot_every + 2snapshots 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, withsnapshot_everythe spacing in force (a thinning budget doubles it)the clock is the decayed one
window_sizeis measured on the clock the decay uses, aftergap_capcaps a gap and after asession_gapis appliedthe 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-lifeweight_sumbecomes the weight inside the hard window, which stops growing once the hard window fills, somin_weightwithholds on a quantity with a ceiling. A clock gap longer thanwindow_sizeempties 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, asweight_sumis. The rows after it report nulls rather than stale numbers, until the hard window holdsmin_weightagain.mahal,partial_corrand the principal components read the hard window’s moments too,bias’s factor is the hard window’sWandQ, and the refresh of the principal components waits on the hard window’s weight.