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-column ew_cov(), so a row takes O(p * T) time for p features and T targets, where one ew_cov over every column takes O((p + T)²). Use ew_cov() for the joint covariance of a few columns, and ewridge() or lasso() 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_weight and group, are in rheon.spec. coef_every and max_rows_between_coefs are refused, as there are no coefficients, and fit_intercept has 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_weight defaults to 3: two rows give a correlation of ±1 whatever the data, and three give the first one with content. Below a target’s min_weight its pairs’ corr, beta, t_stat, t_stat_serial, lag correlations, phi_x, phi_y and split (split_gain, split_at and split_gain_t) are null, and so is every pair’s while settled_frac is below min_settled_frac. The moments and n_serial are reported either way. This model’s own:

lags, cross_lags, serial_rule

The pair’s moments at each lag of lags too: 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_xx and lag_corr_yy are the two series’ own autocorrelations. lag_corr_xy is the feature now against the target l rows back, and lag_corr_yx the target now against the feature l rows back (Leads and lags in Notes). The pair is the same statistic ew_cov(lags=) computes, to the bit. As there, a lagged moment starts at 0 and takes its first product when a learned row has one l rows back, so each lag reads 0.0, not null, while a group has learned no more than l rows. Below min_weight the lag correlations are null, as corr is, and so are phi_x and phi_y, which are fitted from them.

cross_lags keeps the two cross-correlations at fewer lags: strictly increasing, each one of lags, and [] for none, which leaves the lag_corr_xy and lag_corr_yx columns out. By default they are kept at every lag. lag_corr_xy and lag_corr_yx are then lists over cross_lags, in its order. The autocorrelations, and n_serial built 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_rule turns the lags into a count of rows that allows for serial dependence, n_serial, and t_stat_serial, the statistic against it (The serial count in Notes). Default none: no n_serial or t_stat_serial. The rule says how the count sums the kept lags:

rule

the bracket

n_serial and t_stat_serial null when

"truncated"

the kept lags as they are

the bracket is zero or below (two series whose autocorrelations have opposite signs)

"bartlett"

lag l weighted by 1 - l / (L + 1), L the longest kept lag, as Newey and West do: the long lags, whose estimates are the noisiest, count less, and over every lag 1..L the bracket stays positive where the lagged products form a positive-definite sequence

with lags missing it can still reach zero, as under "truncated"

"geometric"

rho(l) = phi^l fitted per series by least squares on log rho over the kept lags with rho > 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 fitted phi_x and phi_y are reported

fewer than two kept lags are positive on either side

bins, bin_rule, bin_warm_rows, bin_edges, bin_budget

The nonlinear view. Every statistic of a pair named so far (corr, beta, t_stat and the lag correlations) is linear, and a feature can be strongly related to a target with corr at zero: a threshold, a V, a saturation. Default none: no bins. With bins = 16 each pair also reports the target’s weight, mean and variance inside each of the feature’s bins, its response curve, in bin_edges, bin_n, bin_mean_y and bin_var_y. It reports the best single cut of that curve too. split_gain is the fraction of the target’s variance the cut removes, a regression stump’s gain, directly comparable with corr². split_at is where it falls. split_gain_t is the t_stat a corr would need to match it. Read split_gain_t as a ranking, not a p-value: the cut was chosen by maximizing over bins - 1 candidates, which the statistic does not know. It uses n_serial in place of n_kish when serial_rule gives one.

The edges are fixed once and never move, so a bin means the same thing for the life of the stream. bin_edges sets them outright, as a list per feature in features order or a dict keyed by feature name: exact, and comparable across runs and groups. bins, bin_rule and bin_warm_rows describe learning them, and are refused beside it. Otherwise they are learned from the first bin_warm_rows learned rows (default 1,000) under bin_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 whatever bins says, 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_budget bounds the memory, per group, and per half-life when half_life is a list (every one keeps its own):

what

about

the hold, until the edges are fixed

bin_warm_rows * (8 * features + 16 * targets + 64) bytes

the histogram, for good

32 * features * targets * bins bytes

Each is refused up front past bin_budget MiB, 256 by default and float("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_delta

Each 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, as huber() weighs a regression’s rows. bin_huber_delta is 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_y is the location and bin_n the rows’ weight, as under the mean. bin_var_y is the weighted mean square of the deviations clipped at the cut, the variance where nothing is clipped. split_gain is read from those (The Huber location in Notes).

bin_refit_rows, refit_budget

The refit of the first rows under "huber": once bin_refit_rows learned 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 is max(500, 30 * bins), bins the most any feature has: a bin needs about 30 rows at the refit. 0 turns the refit off. Under "mean", or bin_huber_delta=inf, there is nothing to refit, so the default is 0, and either key given is refused. refit_budget bounds the rows the refit holds over all of a spec’s groups, in MiB, 320 by default and float("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, and rheon.polars.ModelBank.summary()’s refit_given_up counts their targets.

shards

Split 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’s threads sizes: shards cuts 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, closed

A hard window on the rows the pairs are computed from, in clock units, as for ewridge(): a row window_size old or older counts for nothing, and closed="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), so corr, beta and t_stat describe the hard window and nothing else. That matters most for a screen: two regimes of opposite sign average to nothing over a long history. The weight_sum the output column writes and the one the table reports are the weight inside the hard window. lags under a hard window take window_lags=True (its entry gives the memory). bins or bin_edges and window_size are refused together, since each snapshot would hold the whole histogram.

snapshot_every, max_rows_between_snapshots, window_budget

As for ewridge(): snapshot_every spaces the hard window’s snapshots on the clock, in clock units, max_rows_between_snapshots caps the rows between them, whichever comes first, and window_budget bounds each ring in MiB. Each is refused without window_size.

window_lags

Accept lags under a window_size, and the memory that takes. Default False. Each of the hard window’s snapshots then also holds the lag moments, in doubles, for L lags, C cross lags, p features and T targets:

a snapshot holds

doubles

without lags

(3*p + 5)*T

the lag moments beside them

2*L*T + 2*(L + C)*p*T, about 2*(L + C) / 3 times its size: the lagged products and, beside each lag, the lagged rows’ own sums

with cross_lags=[], the least

2*L*(p + 1)*T; n_serial does not read the cross terms

So, 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. Without window_lags, lags and window_size together are refused with this spec’s own numbers. window_lags=True without both window_size and lags is refused (Lags under a hard window in Notes).

feature_moments

Where 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_x and var_x are the feature’s over every learned row, and cov is the target’s rows centered on that mean, so corr, beta and t_stat move with it. That is sound where the absence says nothing about the feature (Shared feature moments in Notes). Refused with a window_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, and rheon.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 columns lags and bins add. That method documents every column. A group that closes writes the same pairs to rheon.polars.ModelBank.closed_groups() as pair_* columns, one entry per pair.

Raises

As every builder does (rheon.spec), and ValueError naming the problem for:

  • bin_edges that 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_rule or bin_warm_rows beside bin_edges, bin_rule or bin_warm_rows without bins, and bins or bin_edges beside window_size;

  • bins below 2, or a bin_warm_rows below bins;

  • an empty lags (leave lags out for none), serial_rule or cross_lags without lags, lags or cross_lags that do not increase, a lag below 1 or past 2^20, and a cross lag not in lags;

  • lags beside window_size without window_lags, and window_lags without both;

  • bin_budget without bins or not above 0, and bins past bin_budget;

  • bin_stat="huber" without bins, and bin_huber_delta under "mean" or not above 0;

  • bin_refit_rows or refit_budget under "mean" or bin_huber_delta=inf, and a refit_budget not above 0;

  • shards below 1, or a string other than "auto";

  • feature_moments="shared" beside window_size;

  • a serial_rule, bin_rule, bin_stat or feature_moments not in the list;

  • a window_size not finite or not above 0, 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.

The update

Per row, w is the row’s weight and λ = 0.5 ** (Δclock / half_life) its decay (lam ** Δclock under lam), Δclock the clock’s step since the last row the model did not skip, capped at gap_cap (or session_gap at a session change). Per target t, on a row where y_t is present, with W_t the target’s weight before the row, Q_t the sum of its squared weights, m_y and m_x[t,j] the means and S_yy, S_xx and S_xy the 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", a and b are the row’s mix over the model’s weight W, taken on every learned row, and a_t, b_t the 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 location m and its weight Omega move 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_t is the target’s robust scale, read before the row: the exponentially weighted median of |y - m_t| over 0.6745, m_t the target’s own location by the same recursion.

Example

This code screens three features against a target that moves with x0, not at all with x1, and by a step where |x2| passes 1, which no correlation sees. It prints each pair’s corr and 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

Notes

Against ew_cov. The arithmetic is ew_cov’s, so a pair’s means and variances equal those an ew_cov(bias=True) over the two columns reports, to the bit, and its cov and corr agree with that ew_cov’s within a few roundings. The pair’s variances and cov are the weighted means as kept, with no correction for bias, where ew_cov’s default bias=False multiplies them by its correction. The pair rounds each row’s product as (a * b * (x_j - m_x)) * (y_t - m_y), and ew_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 its corr leads the target, and one whose lag_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 target l rows back is built partly from the feature’s newest l rows, so a feature built from the same news shows lag_corr_xy above corr however it is sampled.

The serial count. t_stat is built on n_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 not 1/n but [1 + 2 * sum_l rho_x(l) * rho_y(l)] / n (Bartlett 1935). n_serial is n_kish divided by that bracket, and t_stat_serial the statistic against it. It was measured on 1,000 pairs of independent AR(1) series, phi_x = 0.9 and phi_y = 0.8, each 3,000 rows with no decay, lags = [1, 2, 3, 5, 8, 13] and "geometric". There t_stat spread with a standard deviation of 2.52, near Bartlett’s sqrt(1 + 2 * 0.72 / (1 - 0.72)) = 2.48, and passed 1.96 on 45% of them: significance that is not there. t_stat_serial spread 1.04 and passed on 5.4%, its n_serial a median 511 of n_kish = 3000. The lags add (L + 2C) * p * T + L * T doubles beside the pair moments, for L lags of which C keep the cross terms. They also hold a ring of max(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_cap decays it by the same factor as them. The bins take O(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 is c * w / (λ * Omega + omega). The scale sigma_t is 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, as huber()’s does, so a rescaled target rescales the cuts and the locations to rounding. A bin’s first row is judged against m_t. Until the target has a scale above 0, its first two rows, nothing is clipped, as huber() 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’ RLM fits a constant with scale_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_sum and 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. With bin_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 shards its 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 to load, 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 l back 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 first l rows take the rows before it as partners, where statsmodels’ acf of 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, corr moved by at most 0.0065 and var_x by 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). With lags it keeps the feature’s autocovariance per feature too, and at ten targets runs 4.6 times as fast with no cross lags.