polars_online.spec.rcov¶
- polars_online.spec.rcov(name: str, *, features: list[str], kind: Literal['kernel', 'preavg', 'plain'] = 'kernel', kernel: Literal['parzen'] = 'parzen', bandwidth: int | None = None, jitter: int | None = None, theta: float | None = None, psd: bool = True, block_rows: int | None = None, max_bandwidth: int | None = None, preavg_rows: int | None = None, noise_stride: int | None = None, iv_stride: int | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
A block’s realized covariance of the features, robust to microstructure noise.
Use it for the covariance of returns over each block of a tick stream, such as a trading day, where the noise in each price biases a plain realized covariance. Use
ew_cov()for running moments that decay and are read on every row.Parameters
The stream parameters every builder takes, such as
clock,gap_capandmin_weight, are inpolars_online.spec. This model readsfeatures, whose rows are returns: compute them with Polars’diff()in the query before the bank (.diff().over(by)afterpolars_online.stream.refresh_time()). It takes notargets, andfit_intercepthas nothing to act on, as there is no regression. It requiresgroupandgroup_close, since the estimate rides in the row the close emits. It refuseshalf_lifeandlam, sincegroup_closeends each block and no decay applies.weightis taken only as 0 or 1, since a sum over returns has no fractional row, and a zero-weight row advances the clock and enters no ring (the recent returns the model keeps to form its lagged products). Each switch that reads residuals is refused, as isemit_feature_health. This model’s own:kind,kernelThe estimator:
"plain","kernel"(the default) or"preavg", as The update gives them.kerneltakes only"parzen".bandwidth,block_rows,max_bandwidthbandwidthis a fixedH. Left out, it is chosen from the block, as Bandwidth in Notes says, and it needsblock_rows: the ring has to be sized before the first row, and a block’s length is known only at the close.block_rowsis a sizing hint, not a limit: a longer block runs, its bandwidth clipped to the ring, and reportsrcov_bandwidth_used.max_bandwidthfixes the ring depth itself (defaultceil(c* block_rows^(3/5)),c* = 3.5134the Parzen kernel’s constant, under the automatic bandwidth, the depth at which the noise equals the block’s integrated variance), and must not cap the ring below a fixedbandwidth. The ring’s lagged products,(ring + 1) * k^2doubles forkfeatures, are held to 256 MiB before the first row.bandwidthandmax_bandwidthapply under"kernel"alone, and are refused under the other kinds.block_rowsalso sizes"preavg"’s window.jitterObservations averaged at each end. Default 2, and
1is no jitter.jittervalues from 1 to 4, which Barndorff-Nielsen, Hansen, Lunde and Shephard try, move the estimate by under 0.5%."kernel"only: the other kinds read no ends, and refuse it.theta,psd,preavg_rows"preavg"’s window scale (default 1.0, finite and above 0), form and override.thetaandpreavg_rowsare refused under the other kinds, which read no window. Under"preavg",psd = Falseis the balanced, bias-corrected form (optimal rate, not guaranteed positive semi-definite), andpsd = True(the default) the longer windowk_n = ceil(theta * block_rows^0.6)without the bias term. Under every kind,psd = Trueclips any negative eigenvalue of the estimate, reportingrcov_psd_repaired.preavg_rowsfixesk_ninstead of deriving it fromblock_rows: at least 2, and at least 3 underpsd = False, where a window of 2 leaves nothing once the bias is subtracted. A windowthetaderives is at least 2, at least 3 underpsd = False, and no longer thanblock_rows. Besidepreavg_rows, which fixes the window,thetahas no effect: it is deprecated there, issuing aPolarsOnlineDeprecationWarning, and is accepted and ignored until the next major version, which refuses it.noise_stride,iv_strideThe strides of two subsampled grids, defaults 1 (every return) and 20, each at least 1. The dense one gives the noise variance
rcov_omega2, deliberately biased upward as Barndorff-Nielsen, Hansen, Lunde and Shephard accept, and the sparse one the integrated variancercov_iv_sparse, each averaged over the stride’s offsets. Both are reported under every kind, and an automatic bandwidth reads them.
Output
One output column, named after the spec, whose value in each row is a record holding
weight_sumalone. docs/OUTPUTS.md#rcov gives its type. The estimate is in the rowpolars_online.ModelBank.closed_groups()returns when the group closes:rcov,rcorrThe covariance and correlation estimates, as the upper triangle, row by row: for two features,
[var0, cov01, var1].rcov_n,rcov_kind,rcov_bandwidth_usedThe effective returns, the estimator, and the
Hused. The effective returns are the returns under"plain"; the jittered returns under"kernel",n - 2 * jitter + 2of a block ofnwith no clock break; and the pre-averaged terms under"preavg",n - k_n + 2per stretch.rcov_omega2,rcov_iv_sparseThe noise variance and the sparse integrated variance, per feature, from the grids
noise_strideandiv_strideset. An automatic bandwidth reads them.rcov_iqPer feature, the realized quarticity
(n / 3) * sum(x**4)on the sparse grid ofiv_stride, averaged over its offsets, withnthe grid’s returns: a proxy for the integrated quarticity, and named as one.rcov_psd_repairedWhether a negative eigenvalue was clipped. Null where the repair could not run, an entry that is not finite or an eigendecomposition that failed. The matrix is then reported as it stands.
For a block too short to estimate from,
rcovandrcorrare null, and the other fields say what the block held.min_weight(default 0) withholds them the same way from a block with fewer returns thanmin_weight. A row’s weight is 0 or 1, so the block’sweight_sumis its count of returns: a block of 40 returns undermin_weight=50reports nullrcovandrcorrbeside itsrcov_nand the noise fields.Raises
As every builder does (
polars_online.spec),TypeErrorfortargets, andValueErrornaming the problem for:half_lifeorlam, and a missinggrouporgroup_close;a
kindother than its three words, and akernelother than"parzen";an automatic bandwidth without
block_rows, and"preavg"with neitherblock_rowsnorpreavg_rows;a
block_rows,jitteror stride of 0, and athetathat is not finite or not above 0;a
max_bandwidthbelow a fixedbandwidth, and apreavg_rowsbelow 2, or below 3 underpsd = False;a
bandwidth,max_bandwidthorpreavg_rowsaboveblock_rows, and athetawhose window is longer thanblock_rows;a ring, window,
jitteror stride above 2^20 (1,048,576), the most this model sizes a ring, and lagged products past 256 MiB;bandwidth,max_bandwidthorjitterunder a kind other than"kernel", andthetaorpreavg_rowsunder one other than"preavg";a switch that reads residuals, such as
emit_sigma, andemit_feature_health.
And, from a call that learns,
ValueErrorfor aweightother than 0 or 1, naming the row.The update
Each row’s returns
xenter the block’s sums over lags, and at the close the estimator reads them."plain"issum(x x'), which at close equalsntimes the uncentered second moment of anew_cov(lam=1), to the bit: the cross-check, and the reference the other two are measured against."kernel"(the default) is Barndorff-Nielsen, Hansen, Lunde and Shephard’s multivariate realized kernel, with the Parzen weightkand bandwidthH:K = sum_{h=-H}^{H} k(h / (H + 1)) * Gamma_h Gamma_h = sum_j x_j x'_{j-h}, Gamma_{-h} = Gamma_h'The end points are jittered by averaging the first and last
jitterobservations."preavg"is Christensen, Kinnebrock and Podolskij’s modulated realized covariance: the returns are pre-averaged overk_nrows withg(x) = min(x, 1 - x), which averages the noise away. By default (psd = True) the window is the longerk_n = ceil(theta * block_rows^0.6)and no bias term is subtracted, their positive semi-definite form.psd = Falseis the balancedk_n = floor(theta * sqrt(block_rows))with the residual bias subtracted, and rescaled as their footnote 1 says. Over the block’snreturns and itsrcov_npre-averaged terms, with their finite-samplepsi1andpsi2(1 and 1/12 in the limit):Ybar_i = sum_{j=1}^{k_n - 1} g(j / k_n) x_{i+j} MRC = n / rcov_n / (psi2 k_n) * sum_i Ybar_i Ybar_i' b = psi1 / (2 psi2 k_n^2) psd = True: MRC psd = False: (MRC - b * sum_j x_j x_j') / (1 - b)Example
This code plants two prices whose returns have a variance of 1e-4 a tick and a correlation of 0.5, and adds noise to each price. Over the first block of 5,000 ticks, whose true variance is 0.5, it prints what the default kernel and the plain sum find:
import numpy as np rng = np.random.default_rng(8) n = 20_000 # 4 blocks of 5,000 ticks a, b = rng.standard_normal(n), rng.standard_normal(n) p0 = np.cumsum(0.01 * a) # two prices, correlated 0.5 p1 = np.cumsum(0.01 * (0.5 * a + np.sqrt(0.75) * b)) noise = 0.01 * rng.standard_normal((2, n)) # noise on each price block = np.arange(n) // 5_000 prices = pl.DataFrame({"p0": p0 + noise[0], "p1": p1 + noise[1], "block": block}) prices.write_parquet("ticks_noisy.parquet") returns = pl.scan_parquet("ticks_noisy.parquet").with_columns( pl.col("p0", "p1").diff().over("block") # rows are returns ).drop_nulls() common = dict( features=["p0", "p1"], group="block", group_close="monotone", block_rows=5_000, ) bank = po.ModelBank([ po.spec.rcov("rk", **common), # the kernel, the default po.spec.rcov("plain", kind="plain", **common), # the plain sum, for comparison ]) bank.fit(returns) # each estimate comes at its close print("the first block's truth: variance 0.50, correlation 0.50") for r in bank.closed_groups().filter(pl.col("group") == "0").iter_rows(named=True): print(f"{r['spec']}: variance {r['rcov'][0]:.2f}, correlation {r['rcorr'][1]:.2f}")
the first block's truth: variance 0.50, correlation 0.50 rk: variance 0.51, correlation 0.46 plain: variance 1.50, correlation 0.17
See also
ew_cov(), running moments that decay, read before each row.polars_online.stream.refresh_time(), to put the prices of several series on one grid before taking returns.polars_online.ModelBank.closed_groups(), which returns each block’s estimate.
Notes
Why it is not the plain sum. A plain realized covariance over ticks is biased by noise (each price is the efficient one plus an error, and the error’s variance accumulates with every tick) and attenuated by asynchrony. Both are estimated away by published estimators that are sums over lags, which is exactly what a stream can accumulate. There is no decay and no output on a row but
weight_sum, because the estimate describes a whole block and exists only once the block closes.The kernel. The Parzen kernel is a positive-definite function, so
Kis positive semi-definite up to rounding, and 0.97 efficient against the quadratic spectral’s 0.93. The Bartlett kernel is not consistent here and is not offered.Bandwidth. Left out,
bandwidthis Barndorff-Nielsen, Hansen, Lunde and Shephard’sH = ceil(c* xi^(4/5) n^(3/5))withc* = 3.5134, computed per feature withxi^2 = omega2 / iv_sparseand averaged over the features, and 1 where no feature has one.Pre-averaging.
thetasets the window and nothing else: the bias term and its rescaling read theta from the window actually run,k_n / sqrt(n)over the block’s ownnrows (the paper’s Eq. 7).sum(x x')holds the block’s integrated covariance as well as the noise, so subtractingbof it removesbof the covariance too. Dividing by1 - brestores it, where the undivided estimate averages 0.84 of the covariance atk_n = 6.Clock breaks in a block. A gap over
gap_cap, or a session change, splits the block into stretches: the returns on either side of it are not adjacent, and a covariance of adjacent returns is the whole statistic. Each stretch is closed as the last one is (leading jitter, interior, trailing jitter), and the lagged sums add over stretches, so no product pairs two returns across the clock break. The two subsampled grids start again at the clock break as well, so no step ofomega2,iv_sparseoriqsums returns across it either. Undersession_gap = "reset"a session change starts the block over instead, and drops the returns before it. A stretch too short to reach its trailing jitter contributes only what it had already emitted, andrcov_nsays how many effective returns there were in total. Nothing reads a future row: the jittered end point is formed at close from observations already in the state.