rheon.spec.marginal¶
- rheon.spec.marginal(name: str, *, targets: Sequence[str | Target | FormulaTarget | _Expr], features: list[str], lags: list[int] | None = None, cross_lags: list[int] | None = None, serial_rule: Literal['truncated', 'bartlett', 'geometric'] | None = None, bins: int | None = None, bin_rule: Literal['quantile', 'fixed'] | None = None, bin_warm_rows: int | None = None, bin_edges: dict[str, list[float]] | list[list[float]] | None = None, bin_budget: float | None = None, bin_stat: Literal['mean', 'huber'] = 'mean', bin_huber_delta: float | None = None, bin_refit_rows: int | None = None, refit_budget: float | None = None, shards: 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, window_lags: bool = False, feature_moments: Literal['per_target', 'shared'] = 'per_target', **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
Each feature’s exponentially weighted moments with each target, read back as a table.
Use it to screen thousands of features against a few targets in one pass: each pair
(x_j, y_t)is its own two-columnew_cov(), so a row takesO(p * T)time forpfeatures andTtargets, where oneew_covover every column takesO((p + T)²). Useew_cov()for the joint covariance of a few columns, andewridge()orlasso()for a joint fit of the target on every feature.Parameters
The stream parameters every builder takes, such as
clock,half_life,gap_cap,min_weightandgroup, are inrheon.spec.coef_everyandmax_rows_between_coefsare refused, as there are no coefficients, andfit_intercepthas nothing to act on. The model makes no prediction, so no diagnostic that reads residuals applies, and each such switch is refused by name. A column may not be both a target and a feature.min_weightdefaults to 3: two rows give a correlation of ±1 whatever the data, and three give the first one with content. Below a target’smin_weightits pairs’corr,beta,t_stat,t_stat_serial, lag correlations,phi_x,phi_yand split (split_gain,split_atandsplit_gain_t) are null, and so is every pair’s whilesettled_fracis belowmin_settled_frac. The moments andn_serialare reported either way. This model’s own:lags,cross_lags,serial_ruleThe pair’s moments at each lag of
lagstoo: a strictly increasing list, each lag at least 1 and at most 2^20 (1,048,576), since the ring of rows is sized before the first row. Default none, no lags. A lag counts learned rows within the group, not rows where that target was present, since the ring is shared: for a sparsely present target the lag is a row distance, not an observation distance. They add four list columns per pair to the table.lag_corr_xxandlag_corr_yyare the two series’ own autocorrelations.lag_corr_xyis the feature now against the targetlrows back, andlag_corr_yxthe target now against the featurelrows back (Leads and lags in Notes). The pair is the same statisticew_cov(lags=)computes, to the bit. As there, a lagged moment starts at 0 and takes its first product when a learned row has onelrows back, so each lag reads 0.0, not null, while a group has learned no more thanlrows. Belowmin_weightthe lag correlations are null, ascorris, and so arephi_xandphi_y, which are fitted from them.cross_lagskeeps the two cross-correlations at fewer lags: strictly increasing, each one oflags, and[]for none, which leaves thelag_corr_xyandlag_corr_yxcolumns out. By default they are kept at every lag.lag_corr_xyandlag_corr_yxare then lists overcross_lags, in its order. The autocorrelations, andn_serialbuilt from them, are kept at every lag whatever it says, and are the same to the bit. A lead or lag of a row or two is the usual question, and the cross terms are two thirds of the lag work.lags=[1, 2, 5, 10, 20, 50], cross_lags=[1]keeps the serial correction over fifty rows and the lead and lag at one row, at eight lagged moments per pair instead of eighteen.serial_ruleturns the lags into a count of rows that allows for serial dependence,n_serial, andt_stat_serial, the statistic against it (The serial count in Notes). Default none: non_serialort_stat_serial. The rule says how the count sums the kept lags:rule
the bracket
n_serialandt_stat_serialnull when"truncated"the kept lags as they are
the bracket is zero or below (two series whose autocorrelations have opposite signs)
"bartlett"lag
lweighted by1 - l / (L + 1),Lthe longest kept lag, as Newey and West do: the long lags, whose estimates are the noisiest, count less, and over every lag1..Lthe bracket stays positive where the lagged products form a positive-definite sequencewith lags missing it can still reach zero, as under
"truncated""geometric"rho(l) = phi^lfitted per series by least squares onlog rhoover the kept lags withrho > 0, and the tail summed in closed form: the right choice when both series are exponentially weighted, and the reason the lags need not be dense; the fittedphi_xandphi_yare reportedfewer than two kept lags are positive on either side
bins,bin_rule,bin_warm_rows,bin_edges,bin_budgetThe nonlinear view. Every statistic of a pair named so far (
corr,beta,t_statand the lag correlations) is linear, and a feature can be strongly related to a target withcorrat zero: a threshold, a V, a saturation. Default none: no bins. Withbins = 16each pair also reports the target’s weight, mean and variance inside each of the feature’s bins, its response curve, inbin_edges,bin_n,bin_mean_yandbin_var_y. It reports the best single cut of that curve too.split_gainis the fraction of the target’s variance the cut removes, a regression stump’s gain, directly comparable withcorr².split_atis where it falls.split_gain_tis thet_statacorrwould need to match it. Readsplit_gain_tas a ranking, not a p-value: the cut was chosen by maximizing overbins - 1candidates, which the statistic does not know. It usesn_serialin place ofn_kishwhenserial_rulegives one.The edges are fixed once and never move, so a bin means the same thing for the life of the stream.
bin_edgessets them outright, as a list per feature infeaturesorder or a dict keyed by feature name: exact, and comparable across runs and groups.bins,bin_ruleandbin_warm_rowsdescribe learning them, and are refused beside it. Otherwise they are learned from the firstbin_warm_rowslearned rows (default 1,000) underbin_rule."quantile"(the default) gives equal weight per bin. A value that carries more than a bin’s share, such as an indicator’s zero, fills a bin of its own, and the remaining bins share what is left."fixed"gives equal widths between the smallest and largest value seen. A feature keeps only the bins it can support, so the lists are ragged: a binary feature gets two bins whateverbinssays, and a constant one a single bin and no split. Until the edges are fixed the bin columns are empty and the split columns null (The warm-up of the bins in Notes).bin_budgetbounds the memory, per group, and per half-life whenhalf_lifeis a list (every one keeps its own):what
about
the hold, until the edges are fixed
bin_warm_rows * (8 * features + 16 * targets + 64)bytesthe histogram, for good
32 * features * targets * binsbytesEach is refused up front past
bin_budgetMiB, 256 by default andfloat("inf")for no bound. At the warm-up’s last row the two exist at once, while the held rows are replayed into the histogram, so that row’s peak is their sum.bin_stat,bin_huber_deltaEach bin’s location.
"mean", the default, is the weighted mean, which one spike in a thin bin moves by its size times its share: a row of 50 among twenty rows near 0 moves it by 2.4, a shape where there is none."huber"is Huber’s M-estimate of location, learned in one pass (The update): a row’s weight is cut back by how far it lies from the bin’s location before it, ashuber()weighs a regression’s rows.bin_huber_deltais the cut in units of the target’s robust scale, default 1.345,huber()’s, and above 0.float("inf")clips nothing, which is the mean to the bit. Under"huber",bin_mean_yis the location andbin_nthe rows’ weight, as under the mean.bin_var_yis the weighted mean square of the deviations clipped at the cut, the variance where nothing is clipped.split_gainis read from those (The Huber location in Notes).bin_refit_rows,refit_budgetThe refit of the first rows under
"huber": oncebin_refit_rowslearned rows (rows of positive weight) are in, every target’s location and scale and every bin’s location are refit to the converged batch fit of those rows, once (The refit of the first rows in Notes). The default ismax(500, 30 * bins),binsthe most any feature has: a bin needs about 30 rows at the refit.0turns the refit off. Under"mean", orbin_huber_delta=inf, there is nothing to refit, so the default is 0, and either key given is refused.refit_budgetbounds the rows the refit holds over all of a spec’s groups, in MiB, 320 by default andfloat("inf")for no bound. Each new group reserves its hold when it first appears. The group that would pass the bound keeps the one pass, as does every new group after it. A readiness warning says so once, andrheon.polars.ModelBank.summary()’srefit_given_upcounts their targets.shardsSplit the pair work across the bank’s threads: a count of ranges of features, or
"auto"for as many as the width keeps busy. Default none, so the pairs run row by row on the group’s thread. The threads are the bank’s, which the bank’sthreadssizes:shardscuts one spec’s work so that more of them can take it, and never adds a thread. Every number is the same to the bit whatever the count, so it is a setting and not part of the state (Shards in Notes).window_size,closedA hard window on the rows the pairs are computed from, in clock units, as for
ewridge(): a rowwindow_sizeold or older counts for nothing, andclosed="both"keeps the one exactly that old. Inside the hard window the weights are still exponential. Every moment a pair is built from is cut at the hard window (the weight, both means and the three centered second moments), socorr,betaandt_statdescribe the hard window and nothing else. That matters most for a screen: two regimes of opposite sign average to nothing over a long history. Theweight_sumthe output column writes and the one the table reports are the weight inside the hard window.lagsunder a hard window takewindow_lags=True(its entry gives the memory).binsorbin_edgesandwindow_sizeare refused together, since each snapshot would hold the whole histogram.snapshot_every,max_rows_between_snapshots,window_budgetAs for
ewridge():snapshot_everyspaces the hard window’s snapshots on the clock, in clock units,max_rows_between_snapshotscaps the rows between them, whichever comes first, andwindow_budgetbounds each ring in MiB. Each is refused withoutwindow_size.window_lagsAccept
lagsunder awindow_size, and the memory that takes. DefaultFalse. Each of the hard window’s snapshots then also holds the lag moments, in doubles, forLlags,Ccross lags,pfeatures andTtargets:a snapshot holds
doubles
without lags
(3*p + 5)*Tthe lag moments beside them
2*L*T + 2*(L + C)*p*T, about2*(L + C) / 3times its size: the lagged products and, beside each lag, the lagged rows’ own sumswith
cross_lags=[], the least2*L*(p + 1)*T;n_serialdoes not read the cross termsSo, for many features, a snapshot is 2.3 times the size at one lag, and 7.7 times at five lags with the default cross lags (every lag). The snapshots count in
window_budget. Withoutwindow_lags,lagsandwindow_sizetogether are refused with this spec’s own numbers.window_lags=Truewithout bothwindow_sizeandlagsis refused (Lags under a hard window in Notes).feature_momentsWhere the feature’s mean and variance are kept.
"per_target", the default, keeps them per pair, over the rows the pair’s target was present."shared"keeps one per feature, over every learned row, and each pair only its covariance (The update). Where every target is on every learned row the two report the same numbers, to the bit. Where a target is absent on some rows,"shared"is a different estimator:mean_xandvar_xare the feature’s over every learned row, andcovis the target’s rows centered on that mean, socorr,betaandt_statmove with it. That is sound where the absence says nothing about the feature (Shared feature moments in Notes). Refused with awindow_size.
Output
One output column, named after the spec, whose value in each row is a record of one field,
weight_sum: the weight the model has accumulated before the row and before the row’s own decay. docs/OUTPUTS.md#marginal gives its type. The pairs live in the state, andrheon.polars.ModelBank.marginal()reads them: one row per (group, instance, feature, target), an instance being the part of the model that fits one half-life, with the moments,corr,beta,t_stat,n_kish, and the columnslagsandbinsadd. That method documents every column. A group that closes writes the same pairs torheon.polars.ModelBank.closed_groups()aspair_*columns, one entry per pair.Raises
As every builder does (
rheon.spec), andValueErrornaming the problem for:bin_edgesthat miss or add a feature, that are not finite and increasing, or that give no feature an edge (every feature one open bin, with no response curve and no cut; one feature without edges beside others is taken, and reports a single bin);bins,bin_ruleorbin_warm_rowsbesidebin_edges,bin_ruleorbin_warm_rowswithoutbins, andbinsorbin_edgesbesidewindow_size;binsbelow 2, or abin_warm_rowsbelowbins;an empty
lags(leavelagsout for none),serial_ruleorcross_lagswithoutlags,lagsorcross_lagsthat do not increase, a lag below 1 or past 2^20, and a cross lag not inlags;lagsbesidewindow_sizewithoutwindow_lags, andwindow_lagswithout both;bin_budgetwithout bins or not above 0, and bins pastbin_budget;bin_stat="huber"without bins, andbin_huber_deltaunder"mean"or not above 0;bin_refit_rowsorrefit_budgetunder"mean"orbin_huber_delta=inf, and arefit_budgetnot above 0;shardsbelow 1, or a string other than"auto";feature_moments="shared"besidewindow_size;a
serial_rule,bin_rule,bin_statorfeature_momentsnot in the list;a
window_sizenot finite or not above 0, 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.
The update
Per row,
wis the row’s weight andλ = 0.5 ** (Δclock / half_life)its decay (lam ** Δclockunderlam),Δclockthe clock’s step since the last row the model did not skip, capped atgap_cap(orsession_gapat a session change). Per targett, on a row wherey_tis present, withW_tthe target’s weight before the row,Q_tthe sum of its squared weights,m_yandm_x[t,j]the means andS_yy,S_xxandS_xythe centered second moments, each a weighted mean:W'_t = λ * W_t + w a = λ * W_t / W'_t b = w / W'_t Q'_t = λ^2 * Q_t + w^2 S'_yy = a * S_yy + a * b * (y_t - m_y)^2 S'_xx[t,j] = a * S_xx[t,j] + a * b * (x_j - m_x[t,j])^2 S'_xy[t,j] = a * S_xy[t,j] + a * b * (x_j - m_x[t,j]) * (y_t - m_y) m' = m + b * (value - m) for m_y and each m_x[t,j]
The deviations are from the means before the row. A null target decays that target (
W_t *= λ,Q_t *= λ^2) and learns nothing for it, and a null feature skips the row.Under
feature_moments="shared",aandbare the row’s mix over the model’s weightW, taken on every learned row, anda_t,b_tthe target’s:dx_j = x_j - m_x[j] the shared mean before the row S'_xx[j] = a * S_xx[j] + a * b * dx_j**2 m_x[j] += b * dx_j S'_xy[t,j] = a_t * S_xy[t,j] + a_t * b_t * dx_j * (y_t - m_y) on t's rows
Under
bin_stat="huber", a bin’s locationmand its weightOmegamove as:c = bin_huber_delta * sigma_t the cut omega = w * min(1, c / |y - m|) Omega' = λ * Omega + omega m' = m + (omega / Omega') * (y - m)
sigma_tis the target’s robust scale, read before the row: the exponentially weighted median of|y - m_t|over 0.6745,m_tthe target’s own location by the same recursion.Example
This code screens three features against a target that moves with
x0, not at all withx1, and by a step where|x2|passes 1, which no correlation sees. It prints each pair’scorrand the gain of its best cut:import numpy as np rng = np.random.default_rng(4) x0, x1, x2 = rng.standard_normal((3, 5_000)) y = 0.5 * x0 + np.where(np.abs(x2) > 1.0, 1.0, -0.5) + rng.standard_normal(5_000) pl.DataFrame({"x0": x0, "x1": x1, "x2": x2, "y": y}).write_parquet("screen.parquet") pairs = rp.spec.marginal( "pairs", targets=["y"], features=["x0", "x1", "x2"], half_life=float("inf"), bins=8, # each pair's response curve, and its best cut ) bank = rp.ModelBank([pairs]) bank.fit(pl.scan_parquet("screen.parquet")) # learn every row, keep no output for r in bank.marginal("pairs").iter_rows(named=True): print(f"{r['feature']}: corr {r['corr']:+.2f}, split_gain {r['split_gain']:.2f}")
x0: corr +0.38, split_gain 0.09 x1: corr +0.00, split_gain 0.00 x2: corr -0.00, split_gain 0.08
See also
rheon.polars.ModelBank.marginal(), the table of pairs and every column it holds.ew_cov(), the joint covariance whose arithmetic each pair uses.huber(), whose weightingbin_stat="huber"gives each bin.
Notes
Against ew_cov. The arithmetic is
ew_cov’s, so a pair’s means and variances equal those anew_cov(bias=True)over the two columns reports, to the bit, and itscovandcorragree with thatew_cov’s within a few roundings. The pair’s variances andcovare the weighted means as kept, with no correction for bias, whereew_cov’s defaultbias=Falsemultiplies them by its correction. The pair rounds each row’s product as(a * b * (x_j - m_x)) * (y_t - m_y), andew_cov, which keeps one triangle of its symmetric matrix, multiplies the other way round.Leads and lags. For two series that describe the same moment, a feature whose
lag_corr_yx[0]exceeds itscorrleads the target, and one whoselag_corr_xy[0]does follows it. That reading does not hold against a target that looks ahead, one built from the rows after its own. There the targetlrows back is built partly from the feature’s newestlrows, so a feature built from the same news showslag_corr_xyabovecorrhowever it is sampled.The serial count.
t_statis built onn_kish, which is right for unequal weights and silent about serial dependence. On a smooth stream consecutive rows are nearly the same observation, and the variance of a sample correlation is not1/nbut[1 + 2 * sum_l rho_x(l) * rho_y(l)] / n(Bartlett 1935).n_serialisn_kishdivided by that bracket, andt_stat_serialthe statistic against it. It was measured on 1,000 pairs of independent AR(1) series,phi_x = 0.9andphi_y = 0.8, each 3,000 rows with no decay,lags = [1, 2, 3, 5, 8, 13]and"geometric". Theret_statspread with a standard deviation of 2.52, near Bartlett’ssqrt(1 + 2 * 0.72 / (1 - 0.72)) = 2.48, and passed 1.96 on 45% of them: significance that is not there.t_stat_serialspread 1.04 and passed on 5.4%, itsn_seriala median 511 ofn_kish = 3000. The lags add(L + 2C) * p * T + L * Tdoubles beside the pair moments, forLlags of whichCkeep the cross terms. They also hold a ring ofmax(lags)learned rows.The warm-up of the bins. The rows of the bins’ warm-up are held, not spent. The moment the edges exist every one of them is replayed with its own decay, so the histogram is what it would have been had the edges been known before the first row. That holds to the bit, or to about 1e-15 of the data’s scale where rows of weight zero fall inside the warm-up, whose decays are carried to the next held row as one product. Decay reaches the histogram as it reaches the pair moments, so a clock step capped at
gap_capdecays it by the same factor as them. The bins takeO(bins)of state per pair, one search of the edges per feature per row, and a constant per pair.The Huber location. Its fixed point is the Huber M-location of the bin’s decayed sample, and one row moves it by at most
c * w / Omega', that isc * w / (λ * Omega + omega). The scalesigma_tis one per target, not per feature: a cut is for a row far from the target’s spread, the same row whichever feature bins it, and per feature it would take a quantile sketch per pair. The sketch keeps each deviation in units of the first, ashuber()’s does, so a rescaled target rescales the cuts and the locations to rounding. A bin’s first row is judged againstm_t. Until the target has a scale above 0, its first two rows, nothing is clipped, ashuber()down-weights nothing before its scale exists. It was measured against statsmodels’ batch M-location of each bin on 20,000 rows in 16 bins, with no decay and spikes of 50 on 1%, 5% and 12% of the rows, the worst of five seeds. With the default refit of the first 500 rows it lands within 0.0002, 0.0012 and 0.003 of the target’s scale, and in one pass with no refit (bin_refit_rows=0) within 0.0008, 0.002 and 0.03, where the mean is off by 0.45, 1.5 and 3. It keeps a fifth more per cell, 40 bytes in place of 32, and up to 9 KB per target, and a row takes 0.75 to 0.9 times the mean’s throughput.The refit of the first rows. One pass weighs each row against the location and the scale before it, and over the first rows those are still moving. A share of spikes then pulls the first locations, the scale learns the pulled deviations, the cut is drawn wide, and the spikes go on entering at nearly full weight. Without decay the bins stay there: captured. Measured on 16 bins with spikes of about 20 of the target’s scales and no decay, the worst of 50 streams had a bin 1.3 scales from statsmodels’ M-location after 2,000 rows at 12% spikes, and 3.5 at 20%. So the refit fits the target’s location and MAD scale jointly, as statsmodels’
RLMfits a constant withscale_est="mad". Its scale is rebuilt from the converged deviations, and each bin’s location is solved exactly at the cut that scale gives. Then the stream goes on in one pass. The refit runs after the row is learned, on a count of rows, so it is the same whatever the chunking. It moves no weight:bin_n,weight_sumand every pair moment are those of the one pass. With it the same worst streams were 0.015 and 0.14 scales away after 2,000 rows, and 0.004 and 0.057 after 20,000.A bin whose rows are mostly spikes at the refit has its location among them, rightly for those rows, and the rows after it bring it back only slowly. At 20% spikes, 12.5 rows a bin left 6 of 50 streams half a scale off after 20,000 rows, and 31 rows a bin left none. These figures are at the default cut,
bin_huber_delta=1.345. A wider cut converges more slowly: at 2.5 with 12% spikes, the worst of 50 streams was 0.30 scales off after 1,000 rows with the refit, against 1.25 without it.With learned edges the warm-up already holds its rows: the refit runs when the edges are fixed, over every held row, if the count is within
bin_warm_rows, and holds no row of its own. Withbin_edges, or a count past the warm-up, the model holds the rows until the count:bin_refit_rows * (8 * features + 16 * targets + 64)bytes per group, 4 MB at 1,000 features. The refit itself runs once, in about 1 ms at 10 features, 13 ms at 1,000 and 110 ms at 10,000 over 500 rows, and a row after it takes the time it took before the refit.Shards. The bank’s threads run its groups and specs in parallel already, so one wide spec on one group is one thread’s work while the rest wait. With
shardsits pairs are cut into ranges of features, and each range runs on a thread of its own, a block of rows at a time. A saved bank resumes under the count of the specs given toload, or under the saved one when given none."auto"sizes itself to the machine it runs on. It estimates the pair work of a block of rows from the width, the lags and the bins, and splits the block into as many ranges as hold a tenth of a millisecond each, up to twice the bank’s threads. The moments alone of fewer than about 1,300 pairs stay whole. Through the bank at 10,000 features on 14 threads,"auto"ran 1.2 times as fast at one target and 4.9 times with nine targets, lags and bins. The bank’s own work on each row does not split (measured on 2026-09-25).Lags under a hard window. Each lag correlation under a hard window is that of the rows inside it, each row’s product with the row
lback taken about the hard window’s own means. The moments are kept about a fixed origin, each series’ first value, and read about the hard window’s means when asked. A hard window’s firstlrows take the rows before it as partners, wherestatsmodels’acfof the hard window’s rows stops its products at the edge: on 50 AR(1) series, 500 rows a hard window, the two parted by 0.0068 at most.Shared feature moments. With a tenth of a target’s rows absent at a half-life of 69 rows, measured,
corrmoved by at most 0.0065 andvar_xby 2.5% at the median. At 20,000 pairs"shared"runs 2.7 times as fast at ten targets and 3.2 times at thirty, the same at one, and a ten-target state is under half the size (measured on 2026-09-29). Withlagsit keeps the feature’s autocovariance per feature too, and at ten targets runs 4.6 times as fast with no cross lags.