polars_online.spec.deco¶
- polars_online.spec.deco(name: str, *, features: list[str], dynamics: Literal['ew', 'linear'] = 'ew', alpha: float | None = None, beta: float | None = None, blocks: dict[str, list[str]] | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
Engle and Kelly’s dynamic equicorrelation, one number for the whole correlation matrix of the features.
Use it to track how correlated many series are on average, at
O(n)a row fornfeatures, where keeping alln(n-1)/2correlations moving takesO(n²). Useew_cov()for each pair’s correlation, and this model’sblocksfor one number per block of features and per pair of blocks.Parameters
The stream parameters every builder takes, such as
clock,half_life,gap_cap,min_weightandgroup, are inpolars_online.spec. This model readsfeatures, at least two, and takes notargets.fit_intercepthas nothing to act on, as there is no regression, and each switch that reads residuals is refused, as isemit_feature_health.half_lifeorlamis required: both the standardizer and the level decay on it. This model’s own:dynamicsHow the level follows the rows’ estimates:
"ew"(the default, since it runs on the clock and needs no parameters of its own), an exponentially weighted mean of them on the clock, or"linear", the linear dynamics of The update, which step once per row."linear"needsalphaandbeta, and"ew"refuses them.alpha,betaThe linear dynamics’ weights on the row’s estimate and on the previous level, each at least 0, with
alpha + beta < 1. Default none: required under"linear", refused under"ew".blocksA name to a subset of
features: the model then estimates one number per block and one per pair of blocks, which is the useful middle between one correlation and all of them. Every feature must be in exactly one block, and a block needs at least two. Default none: one block of every feature.
Output
One output column, named after the spec, whose value in each row is a record of these fields, all but
coefread from the state before the row, so they are safe as features for that same row. docs/OUTPUTS.md#deco gives each field’s type and when it is null:uThe row’s own estimate of the equicorrelation. Null on a row where fewer than two of its block’s columns have a positive variance before the row, or where every standardized value is 0.
rhoThe level as it stood before the row.
loglikThe row’s Gaussian log-density in standardized coordinates under that level. Null on a row where any column has no positive variance before the row, and where the levels hold no correlation matrix that the density can be solved for (Blocks in Notes).
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, null where nothing decays.
withheld_reasonWhy the row’s fields were withheld, null where they were not:
below_min_weighton the rows beforeweight_sumreachesmin_weight. A field the model has no value for yet reads null with no reason beside it:uuntil a block’s columns have a variance (the first two rows of a group), andrhountil the row after the firstu. The defaultmin_weightwithholds those rows anyway.coefThe levels after the row, in the order of the
rhofields:coefon a row isrhoon the next.
With
Knamed blocks,ubecomesu_<A>per block thenu_<A>_<B>per pair, andrholikewise, with oneloglikover all of them.Raises
As every builder does (
polars_online.spec),TypeErrorfortargets, andValueErrornaming the problem for:fewer than two features, or no
half_lifeorlam;a
dynamicsother than"ew"or"linear";alphaorbetaunder"ew", either missing under"linear", either below 0 or not a number, andalpha + betaof 1 or more;blocksthat name no block, leave a feature out of every block, put one in two, list one twice in a block, name a column not infeatures, or hold a block of fewer than two;a switch that reads residuals, such as
emit_sigma, andemit_feature_health.
The update
The row is standardized against the means
m_iand variancesv_ithat exponentially weighted running sums hold before the row,zeta_i = (x_i - m_i) / sqrt(v_i). WithS1 = sum(zeta)andS2 = sum(zeta * zeta)over thenfeatures, the row’s estimate is Engle and Kelly’s Lemma 2.3:u = (S1**2 - S2) / ((n - 1) * S2) = mean_{i != j} zeta_i zeta_j / mean_i zeta_i**2which lies in
[-1 / (n - 1), 1], both ends reached. Between two blocksAandBthe estimate isu_AB = S1_A S1_B / sqrt(n_A n_B S2_A S2_B). The level then follows one of two dynamics, withwthe row’s weight andλ = 0.5 ** (Δclock / half_life)its decay (lam ** Δclockunderlam).Δclockis the clock’s step since the last row the model did not skip, capped atgap_cap, orsession_gapat a session change:"ew": W' = λ * W + w, b = w / W' rho' = rho + b * (u - rho) (rho = u at W = 0) "linear": rho' = (1 - alpha - beta) * rho_bar' + alpha * u + beta * rho rho' = u (on the first row) rho' = rho (at w = 0)where
rho_baris the"ew"recursion run alongside as the target of the linear one.Example
This code plants eight series whose pairs are correlated 0.2 for 10,000 rows and 0.6 after, and prints the level before the last row of each half. It moves with the correlation and stays below it, the estimate’s downward bias (The estimate’s downward bias in Notes):
import numpy as np rng = np.random.default_rng(6) c = np.repeat([0.2, 0.6], 10_000) # the pairs' correlation, row by row common = rng.standard_normal(20_000) cols = { f"r{i}": np.sqrt(c) * common + np.sqrt(1 - c) * rng.standard_normal(20_000) for i in range(8) } pl.DataFrame(cols).write_parquet("returns.parquet") eq = po.spec.deco("eq", features=list(cols), half_life=500.0) out = pl.scan_parquet("returns.parquet").online.fit_predict([eq]).collect().unnest("eq") print(f"correlation 0.2: rho {out['rho'][9_999]:.2f}") print(f"correlation 0.6: rho {out['rho'][-1]:.2f}")
correlation 0.2: rho 0.15 correlation 0.6: rho 0.39
See also
ew_cov(), every pair’s correlation, atO(n²)a row.corrchange(), a test for a change in a pair’s correlation.
Notes
The clock. The
"ew"dynamics run on the clock. The linear one steps once per row, as a DCC model’s does (Engle’s dynamic conditional correlation, a GARCH-like recursion on the correlation matrix). So across a gap capped atgap_capits own terms take one row’s step, as across a millisecond, and onlyrho_barmoves on the clock. A row of weight 0 moves neither: it advances the clock and learns nothing, as everywhere. Otherwise the linear recursion has no row weights, as the paper’s has none: a positive weight reachesrhoonly throughrho_bar, so rows of weight 0.5 and 2 move it by the samealpha * u.Departures from the paper. Two from Engle and Kelly (2012), on purpose. Its eq. 21 has a free intercept and applies correlation targeting to the DCC
Qrecursion, not to the linear one. Writing the intercept as(1 - alpha - beta) * rho_baris this library’s reparameterization, chosen because a streaming model has no sample to fit a free intercept on. And the paper permitsalpha + betaslightly above 1 under numerical bounds, where this model refuses it.The estimate’s downward bias. The paper notes that
uis a downward biased estimate of the equicorrelation (E[u]is about 0.20 for a true 0.30 atn = 6series). It offers an alternative,1 - (1 / (n - 1)) * sum((zeta_i - zeta_bar)**2), which this does not compute. Useuas a signal that moves with the market’s correlation, not as the correlation.rhois not anew_cov’scorrover the columns, since the mean of a ratio is not the ratio of means.A constant column. A column whose variance is exactly zero, constant from its first row (the only way an exponentially weighted variance is exactly zero), has no standardized value. It is left out of its block’s sums, so
ncounts the columns that have one. Its block reads the correlation among its other columns, and so does a pair it is in. A block left with fewer than two has nouon the row, nor a pair with an empty side. Nor does a row whoseS2is 0. Each value keeps its own weightW: one with nouon a row learns nothing and does not decay, while the others learn.loglikneeds every column, and is null on such a row.Blocks.
loglikis null where the levels hold no correlation matrix, or hold one too close to singular for its density to keep a digit: each level can be inside(-1, 1)while the blocks’ levels together are not. Then the factor of theK x Ksystem the density solves needs a shift on its diagonal, or its condition passes the point where the solve’s forward-error bound reaches 1. Such levels come from the first rows of a warm-up, when they rest on one or two rows. One block never reaches that point.