rheon.spec.holt¶
- rheon.spec.holt(name: str, *, targets: Sequence[str | Target | FormulaTarget | _Expr], trend_half_life: float | timedelta | str | _Expr | None = None, trend: bool = True, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
Holt’s linear trend, which extrapolates the target’s own level and slope.
Use it as the baseline a model with features should beat: it takes no features, so a regression that cannot outperform “the series is going up at about this rate” has features that are not earning their place. Run it in the same bank as the regression, with
emit_sigma=Trueon both, and compare theirsigma_<slot>fields. Or add aseqtest()whoseaandbname the two specs, to test which predicts closer.Parameters
The stream parameters every builder takes, such as
clock,half_life,gap_cap,min_weight,groupand the diagnostics, are inrheon.spec.The level forgets at the spec’s
half_life(orlam), in clock units,infincluded: one parameter under one name, as for every model.level_half_lifeis refused, with a message naminghalf_life.fit_intercepthas nothing to act on, since the level is the prediction’s intercept.There is no seasonal term. For a seasonal index, make a column of the phase (the hour of the day, say) with Polars’
with_columnsin the query before the bank, and pass it asgroup=: the bank then fits a level and trend for each phase.This model’s own parameters:
trend_half_lifeHow fast the trend forgets, in clock units, above 0. Default four times the level’s half-life, so the trend forgets four times more slowly than the level.
infis the whole history’s drift, not a trend pinned at zero: the line fit’s gain on the slope, which is the weighted least-squares slope exactly only when the level does not decay either. Beside a finite level half-life the slope learns from residuals against a level that forgets, and lands near the line fit’s: 0.2% to 1% of it off at a level half-life of 5 over 3,000 rows.trendFalsefits the level alone: the trend is held at zero and the prediction is flat, which is simple exponential smoothing. The level is then the weighted mean of the observations, each at its weight times0.5 ** (age / half_life), which is pandas’ewm(adjust=True)for unit weights.trend_half_lifeis refused beside it. DefaultTrue.
Output
One output column, named after the spec, whose value in each row is a record of these fields. docs/OUTPUTS.md#holt gives each field’s type and when it is null:
pred_<t>,resid_<t>Per target: the prediction, and
y - predwhere the target is not null.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.
withheld_reasonWhy the row’s predictions were withheld, null where they were not: a reason of the shared gates (
rheon.spec), such asbelow_min_weighton the first row under the defaultmin_weight. A target’s first observation has no prediction, since it sets the level: withmin_weight=0,pred_<t>andwithheld_reasonboth read null there.coef[level, trend]per target after the row is learned, the two numbers a prediction reads, whichcoef_index()names. Null for a target not yet observed, which has no level to report. The trend is 0 undertrend=False.
plus the fields of the diagnostics switched on, as
rheon.specdescribes them.Raises
As every builder does (
rheon.spec);TypeErrorforfeatures, which this model does not take, and forlevel_half_life, whose name ishalf_life; andValueErrornaming the problem for atrend_half_lifenot above 0, andtrend_half_lifebesidetrend=False.The update
Per row and target,
sis the clock since the target was last observed, this row’s step included, each step capped atgap_cap(orsession_gapat a session change), sosis the row’s own step on a stream with no gaps.wis the row’s weight,e = y - predthe residual,landbthe level and the trend, andW,Vthe weight the level and the trend have gathered. Each decays on its own half-life:λ_l = 0.5 ** (s / half_life)(lam ** sunderlam), the spec’s own, andλ_blikewise attrend_half_life.S0,aandQare the line fit’s weight, mean age and spread of ages (The line fit in Notes):pred = l + b * s extrapolate s clock units ahead textbook: g_t = w / (λ_l * W + w) W' = λ_l * W + w h_t = w / (λ_b * V + w) * g / s V' = λ_b * V + w (s > 0) line fit: S0' = S0 + w a' = S0 * (a + s) / S0' Q' = Q + S0 * w * (a + s)**2 / S0' g_f = w * (1 / S0' + a'**2 / Q') h_f = w * a' / Q' l' = pred + g * e g = g_f under half_life = inf, else max(g_f, g_t) b' = b + h * e h = h_f under trend_half_life = inf or at s = 0, else max(h_f, h_t)Under
trend=Falsethe line fit is not used:g = g_tat every half-life,infincluded, andb = 0.A target’s first observation sets
l = y,W = S0 = wanda = Q = 0, and predicts nothing. The trend starts at 0.Example
This code fits a series that starts at 10 and rises 0.5 a row, and prints the level and trend found at the last row beside the truth:
import numpy as np rng = np.random.default_rng(7) t = np.arange(2_000) y = 10.0 + 0.5 * t + rng.standard_normal(2_000) pl.DataFrame({"y": y}).write_parquet("trend.parquet") holt = rp.spec.holt("holt", targets=["y"], half_life=200.0) # no features bank = rp.ModelBank([holt]) bank.fit(pl.scan_parquet("trend.parquet")) # learn every row, keep no output coef = {r["term"]: r["coef"] for r in bank.coef().iter_rows(named=True)} print(f"level: true {10.0 + 0.5 * t[-1]:.1f}, found {coef['level']:.1f}") print(f"trend: true 0.50, found {coef['trend']:.2f}")
level: true 1009.5, found 1009.5 trend: true 0.50, found 0.50
See also
seqtest(), to test whether a regression predicts closer than this baseline.ewridge(), a regression on features to set against it.rheon.polars.ModelBank.predict(), which extrapolates the level and trend to the row’s clock.
Notes
The textbook gains. The textbook form is Holt’s recursion in its error-correction form, whose smoothing constants are
1 - λ_lon the level and1 - λ_bon the trend once the weights reach their steady state. Its gains here are weighted means, as every running sum here is: a row at weightwcountswtimes. Where they win,l'is(λ_l * W * pred + w * y) / (λ_l * W + w), andb'the weighted mean ofband the slope the level moved at,(l' - l) / s. Once the weights reach their steady state they are those fixed constants.The line fit. The line fit’s gains are those of the weighted least-squares line through every observation so far, on the clock, read at the last.
S0is its weight,athe observations’ weighted mean age andQthe spread of their ages about it, none decayed. With every observation at one clock (Q = 0) no slope is determined:g_f = w / S0'andh_f = 0.Which gain a row takes. A row takes the larger gain, on the level and on the slope. Under
half_life = infthe level takes the line fit’s gain, so without decay the model is the weighted line fit, to rounding (statsmodels’WLSagrees to 1e-15). Undertrend_half_life = infthe slope takes the line fit’s gain. Under a half-life the line fit’s gains fall as1/nand1/n**2(nthe number of observations), and the textbook’s reach their fixed values. So after a warm-up of a few half-lives every row takes the textbook’s, and statsmodels’Holtagrees from there. The warm-up follows a new series sooner than the textbook would. Without the line fit, gains of1/non both level and trend would pin the trend to the first observation. The level would carry that observation’s noise timesln n: 11 off a flat series after 40,000 rows without decay, at a noise of 0.5, the worst of 50 seeds.Rows at one clock, and rows that learn nothing. A row at the last row’s clock is a second observation the level takes in. The textbook trend holds, since a move over no clock has no slope, and the line fit’s slope moves by its own gain, as a least-squares slope does. A row with a null target or a zero weight leaves
landbwhere the last observation put them and carries its clock to the next one. So it gives the same level, trend and predictions as if it were absent. A row with a null target still adds its weight toweight_sum.Extrapolating over the clock. The trend is per clock unit, so an irregular clock extrapolates the right distance.
rheon.polars.ModelBank.predict()extrapolates over the clock distance from the row the model last learned, capped bygap_cap.