rheon.spec.quantile

rheon.spec.quantile(name: str, *, targets: Sequence[str | Target | FormulaTarget | _Expr], features: list[str], quantile: float, ridge: float | None = None, standardize: bool = False, solve_every: float | timedelta | str | _Expr | None = None, max_rows_between_solves: int | None = None, quantile_eps: float | None = None, quantile_refit_rows: int | None = None, quantile_refit_span: float | timedelta | str | _Expr | None = None, max_state_bytes: int | None = None, refit_budget: float | None = None, **common: Unpack[CommonKwargs]) → dict[str, Any][source]

Quantile regression on running sums, the fit that a share tau of the targets fall below.

Use it for a conditional median, which outliers cannot pull, or for a tail, such as the 0.9 quantile of a return, where a mean says nothing. Use huber() for a mean that outliers should not pull, and sgd() with loss="quantile" where learning a row must take O(k) time for k features: this model takes O(k²).

Parameters

The stream parameters every builder takes, such as clock, half_life, gap_cap, min_weight, group and the diagnostics, are in rheon.spec. This model’s own:

quantile

The level tau, in (0, 1); required. 0.5 is a median regression.

ridge, standardize, solve_every, max_rows_between_solves

As for ewridge(): the penalty (default 1e-6, finite and at least 0), correlation-form solving, and the solve schedule. ridge is on the mean-form Gram, in the features’ squared units, and dimensionless under standardize, which solves in correlation form.

quantile_eps

The band’s half-width in units of the residuals’ scale s, finite and above 0. Default 0.2, at which the band holds about a sixth of the rows of normal noise at the median and a seventh at the 0.9 quantile. A much narrower band converges more slowly, and a much wider one smooths the quantile toward the mean (The band in Notes).

quantile_refit_rows

The learned rows (each of positive weight, with its target) after which each target’s first rows are refit to convergence, once (The refit of the first rows in Notes). Default max(500, 10 * features) up to 100 features, and off above 100, where a refit of 10 * features rows would run for seconds a target. A count given is taken up to 2 ** 20, since each target’s buffer is allocated at its full size at its first learned row, but one below three rows a coefficient, the rows the warm-up takes as least squares, is refused. 0 turns the refit off. A group shorter than the count never refits and holds its rows to the end.

quantile_refit_span

The same refit over a span of the clock in place of a count of rows: each target’s rows from its first learned row through the first row at least quantile_refit_span after it, once they hold a row per coefficient (three a coefficient under the quantile loss). A number of the clock’s units, or of rows where the spec has no clock, or a duration such as "1h" on a temporal clock; finite and above 0. The span is read off the rows’ exact stamps, and a row of weight 0 is no row of it, so on a clock of one unit a row it holds quantile_refit_span + 1 rows: the refit of quantile_refit_rows = quantile_refit_span + 1, to the bit. Its buffers grow as the rows come rather than being held at a count’s full size, and are held to max_state_bytes as they fill. Refused beside quantile_refit_rows.

max_state_bytes

The bytes a group’s refit buffers may hold. Under quantile_refit_span the data decides how many rows the buffers hold, so they are checked as they fill: the first row to take a group past half of it raises a warning, once for the group, naming the group and the bytes, and the row that would take it past the cap stops the run with an error naming the group and the bytes, the bank having learned part of the chunk. Default 256 KB, 262144; at most 64 MiB, 67108864.

refit_budget

A bound in MiB on the refit buffers of all the spec’s groups together, above 0, or inf for none. Default 320. As for huber(): each new group reserves the most its targets’ buffers can hold when it first appears, and keeps it for the life of the bank. The group that would cross the bound, and every new group after it, keeps its one-pass fit. A readiness warning says so once, and bank.summary()’s refit_given_up counts the targets of each instance, the part of the model that fits one half-life (The refit’s memory in Notes).

min_weight counts the rows the target was present on, at their weights, decayed. The band’s weight, which a half-life caps at the band’s share of the sample, is not what it reads. It withholds the output alone: the fit learns from the prediction it made on a row the gate withholds, so it is the same fit at any min_weight. A target’s first prediction, reported or learned from, waits for its own first row per coefficient, the model’s floor, since a fit of fewer rows than unknowns is the ridge’s alone. A min_weight below that withholds nothing more.

Output

One output column, named after the spec, whose value in each row is a record of these fields. docs/OUTPUTS.md#quantile gives each field’s type and when it is null:

pred_<t>, resid_<t>

Per target: the prediction, the conditional quantile, and y - pred where the target is not null. A residual is signed against the quantile, so once the fit has converged a share tau of them are negative, and 1 - tau positive.

weight_sum

The weight the model has accumulated before the row and before the row’s own decay.

settled_frac

How far the model had come toward its steady state under decay before the row.

withheld_reason

Why the row’s predictions were withheld, null where they were not.

coef

Per target, the intercept then one entry per feature (coef_index()).

support_coef

On coef’s rows, each coefficient’s data share, laid out like coef: how much of the fit after the row the data, as the loss weighs the rows, determined rather than the ridge (rheon.spec).

plus the fields of the diagnostics switched on, as rheon.spec describes them.

Raises

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

  • a quantile not strictly between 0 and 1;

  • a quantile_eps not finite or not above 0;

  • a quantile_refit_rows other than 0 below three rows a coefficient, or above 2 ** 20, and a refit_budget not above 0;

  • a ridge below 0 or not finite, a solve_every below 0, and a max_rows_between_solves of 0.

The update

One Newton step per row on the check loss smoothed by a uniform kernel, linearized at the fit the row was predicted with, so it stays out-of-sample. Per row, e is the target’s residual, psi(e) = tau - 1{e < 0}, s the target’s residual scale and w the row’s weight. h = quantile_eps * s is the band’s half-width (never below the floor of The band in Notes), A the band’s system, u the row’s deviation from the means, and z the features with the intercept in front:

|e| <  h:  a least-squares row, with target y + 2h (tau - 1/2)
|e| >= h:  no weight in the sums; w * 2h * psi(e) * z into the cross-moment,
           over the band's weight, capped at |e| / (1 + u' A^-1 u)

The cap reads the row’s full leverage against A: a nudge brings the row’s own prediction at most to its target, and never past it. Under three rows per coefficient, and until a target has an s above 0, the fit is ordinary least squares (Warm-up and rebuilding in Notes).

Example

This code fits the 0.9 quantile of a line with normal noise of spread 1, whose intercept is 1 + 1.28, and prints the line found:

import numpy as np

rng = np.random.default_rng(4)
x = rng.standard_normal(20_000)
y = 1.0 + 2.0 * x + rng.standard_normal(20_000)   # the 0.9 quantile is 2.28 + 2x
pl.DataFrame({"x": x, "y": y}).write_parquet("tail.parquet")

q90 = rp.spec.quantile(
    "q90", targets=["y"], features=["x"], half_life=float("inf"),
    quantile=0.9,                                  # the level to fit
)
bank = rp.ModelBank([q90])
bank.fit(pl.scan_parquet("tail.parquet"))          # learn every row, keep no output
print("the true line: intercept 2.28, slope 2.00")
c = {r["term"]: r["coef"] for r in bank.coef().iter_rows(named=True)}
print(f"found: intercept {c['intercept']:.2f}, slope {c['x']:.2f}")
the true line: intercept 2.28, slope 2.00
found: intercept 2.31, slope 1.99

See also

  • huber(), the robust fit of the mean, whose scale sketch this model reads.

  • ewridge(), the least-squares fit on the same sums.

  • sgd() with loss="quantile", a step per row in O(k) time.

Notes

Why a Newton step. The smoothed loss has the same curvature on either side of the fit, so the rows’ own history cancels and the fit converges to the quantile regression. Reweighting the rows by the check loss’s iteratively reweighted least squares (IRLS) weight, psi(e) / e, does not converge to it. That weight is the secant of this step where the step is its tangent, and it is unbounded as e goes to zero. A row whose residual against the fit before it happened to be near zero then holds the fit near the fit it was predicted by. Measured at the median of a skewed noise after 20 000 rows against statsmodels’ QuantReg, the step is 0.005 away, inside QuantReg’s own standard error of 0.007, where the weights ended 0.164 short.

The scale. s is the MAD of the target’s residuals: their exponentially weighted median of |e| over Phi^-1(3/4) = 0.6745, which is the standard deviation for normal residuals, aged on the model’s clock. A wild row moves a median by its weight, not by its size, so the rows the band is there to bound cannot widen it. In their root mean square they did: at 5% of the rows lifted by a hundred noise deviations, all on one side, the root mean square stood near 11 against a noise of 0.5. The band held every clean row as a least-squares row and gave every wild row a pull of the band’s width. Every one of 50 streams of 20,000 rows ended more than 0.05 from statsmodels’ QuantReg on the same rows, the worst 0.098 at 5% and 0.98 at 20%. In the MAD none did, the worst 0.006 at 5% and 0.026 at 20%, with or without a half-life of 5,000. The median is read from huber()’s sketch, whose buckets are fixed at a unit of 1 until the refit of the first rows sets their unit at the median of its converged residuals. From then a rescaled target rescales the band and the fit to rounding. With the refit off, a decimal factor can move the scale by up to a bucket of the sketch, about 1.6%, and moved the fit by up to 0.044 of the target’s spread where measured.

The band. h is quantile_eps * s. The rows inside the band are the curvature the step leans on, so a much narrower band converges more slowly and a much wider one smooths the quantile toward the mean. The band is never narrower than (k / n) ** 0.4 of s, the smoothed-quantile bandwidth rate. Here k is the number of coefficients, and n the target’s present rows counted one each, decayed, whatever their weights. Under a half-life the band’s share of the sample is a few rows, and the floor is what keeps the step fed there. A long stream leaves the floor behind. Coverage at quantile = 0.9 on normal noise reads 0.895 at half_life = 30 and 0.900 from 200 up.

Warm-up and rebuilding. Under three rows per coefficient of the rows the target was present on, the fit is ordinary least squares: a Newton step needs a Hessian, and a band around a fit built from a handful of rows is not one. The same rule rebuilds the fit after a gap or a reset has aged the weight away. A band holding under one row per coefficient, in rows of the target’s mean weight, takes least-squares rows too, until it holds rows again. That is what rebuilds a fit a row at the input bound leaves behind. Such a row sets the sums at its own scale, and every later row is outside the band. Only nudges arrive, each w * 2h * psi * z over the band’s weight. They cannot move the fit until that weight has decayed to nothing, and each is then a step that outgrows the band. From one row up an outside row’s step lands inside the band, and the floor keeps a band at its steady state well clear of one row, so the rule does not fire in steady state. Both rules count rows, so a weight’s scale reaches neither. Rules that compared the rows’ weight with a row count would let rows at weight 100 leave the warm-up on their first row, where the fit reached 1e51.

Until a target has an s above 0, its rows are least squares too. That is before its first residual, or while every residual so far is exactly zero, and the band, a width in units of s, has nothing to be drawn in. An s taken as 1 there would draw the band past the warm-up in the target’s own units, and throw a target in millionths far off.

The refit of the first rows. One pass takes each row as the fit before it sees it, and without decay a row stays in the sums as it was taken, at full weight. The warm-up’s rows are least-squares rows, and so are the rows inside a band drawn around a fit that wild rows have pulled. So wild targets in the first rows keep pulling, where a batch fit reads them as outliers whose pull the band’s width bounds, and they leave only as the rows after them outweigh them. Over 50 streams of 8,000 rows with no decay, three targets 1e4 off at the start left the worst stream 0.22 from statsmodels’ QuantReg on the same rows, and wild targets on a fifth of the first 500 rows left it 0.038 off. So on the row a target’s count of learned rows reaches quantile_refit_rows, those rows are refit to the minimum of the smoothed check loss at the band the stream would draw:

v_i  = w_i * (the decay factors of the rows after i)
r_i  = y_i - z_i'b                       against the pass's fit
s    = weighted median of |r_i| at v_i, over 0.6745
h    = s * max(quantile_eps, (k / n) ** 0.4)
F(b) = sum_i v_i rho_h(r_i) + the ridge's penalty
rho_h(r) = r**2 / (4h) + (tau - 1/2) r + h/4   if |r| < h
         = tau * r  or  (tau - 1) * r           otherwise

rho_h is the check loss smoothed by the uniform kernel, the loss each row’s step is taken on. Each pass is a Newton step of F: the rows inside the band are least-squares rows at target y + 2h (tau - 1/2), and each row outside adds w * 2h * psi(r) * z, with no cap. A step that would increase F is halved until it does not, since the band’s rows measure the curvature at the pass’s fit and not at the next. A band of fewer rows than coefficients has no curvature to step on, and such a pass takes a majorizer’s step instead: it moves every prediction toward its row by at most the band’s width. The passes stop when the step moves no row’s fit z_i'b by more than 1e-10 of s, beyond the rounding of a fit that size, or when no step along it lowers F past its rounding, or after 200.

The target’s sums are then rebuilt as the stream takes each row predicted by the converged fit at its band. Where that band holds fewer rows than coefficients, they are rebuilt as the majorizer’s step takes each row instead, every row a least-squares row at its weight, so the sums keep a weight and solve to that fit. s is rebuilt from that fit’s residuals, and the stream goes on online. With the refit, the same streams ended at most 0.0053 and 0.0085 off, beside 0.0052 from a clean start. A shift of every one of the first rows is no outlier among them, so the refit keeps them, and they leave as before: a shift of 20 in the first 500 rows was 0.061 off at 8,000 rows, where it was 0.093. The refit runs after the row’s own prediction and moves its own target’s fit alone.

The refit’s memory. A target’s rows are held until its refit, at (features + 10) * 8 bytes a learned row. Each row’s residual is kept beside it for the scale: a quantile fit’s band is drawn in the MAD, which is read exactly from the held residuals while the refit waits. A run of rows that only aged the target (its value null) takes 32 bytes, and consecutive such rows at the same clock step are one run. Once its runs number more than 4 for each row of the count, as on a target present on fewer than about one row in five under an irregular clock, the target gives its refit up and keeps its one-pass fit. A buffer whose rows, counted one each and decayed, are still fewer than the warm-up’s is left as the stream built it. The refit takes 0.09 to 2.3 ms once, for 1 to 50 features and 500 to 1,000 rows (an Apple M4 Pro under other load, best of 9), and the rows after it cost what they did. Under refit_budget, each new group reserves (features + 26) * 8 bytes a target of each model instance (a half-life grid reserves once per value) for each row of the count.