rheon.spec¶
Spec builders: rheon.spec.ewridge("m", targets=[...], ...).
A spec is what a model bank runs: one model, the columns it reads, and the
parameters every model shares – the clock, the decay, the groups, the weights
and the warm-up. It is a plain dict, JSON-able, and the same thing as a
[[specs]] entry in the CLI’s TOML. A builder assembles one, checks it and
returns it. rheon.polars.ModelBank, the rheon namespaces and
the rheon command line take lists of them.
The builders are the documented way to write a spec. A dict written by hand is checked the same way when it is used. Only a builder can tell a misspelt keyword from a missing one at the call.
The stream parameters
Every builder takes these after its own parameters, with the meaning, units and refusals below. What every spec takes shows them at work.
targets,featuresColumn names. A target is what the model predicts. A feature is what it reads from the same row. A model with no target (
ew_cov,kmeans,micro,deco,bocpd,corrchange,hmmandrcov) takesfeaturesalone, andaudittakescolumnsin their place.ew_classtakes alabelcolumn in the target’s place.holtandseqtesttake no features. A target computed from its own row’s columns, such as a return against the mid, is a column: make it with Polars’with_columnsbefore the bank. A log ratio(pl.col("price_5m") / pl.col("mid")).log()or a difference sits about zero, wherehit_ratetakes its sign. Arheon.target()is a column under a name of its own. A target may also be a window expression looking ahead (rheon.polars.ops), named by its alias:(rp.ewm_mean("mid", half_life="10s", window_size="1m", reverse=True) - pl.col("mid")).alias("fwd"). The bank resolves it when the row’s window closes, and learns the row then, under theembargo.fit_predictasks the embargo to cover the longest forwardwindow_size. Undergroupit needs aclock.rheon.polars.stream.with_windows()withlike=the spec writes the same target as a column.fit_interceptWhether the fit has a level of its own: a constant 1 is put in front of the features. Default
True. Without it nothing is centred, and a fit through the origin is least squares through the origin.clockWhy: rows are not evenly spaced, and forgetting should follow the stream’s own time. What: a column that never runs backwards within a group; the row count when
None. ADatetime,DateorDurationcolumn is a temporal clock, and the parameters measured in clock units are then durations (Clock units, below). A numeric column is a clock in its own units, and need not be a time. Sort by a feature and clock on it:half_lifebecomes a bandwidth in that feature’s units, and the fit a local regression in it.half_life,lamWhy: a stream drifts, so older rows should count less. What: the decay.
half_lifeis the clock distance over which a row’s weight halves;lamis the factor per clock unit,0.5 ** (1 / half_life).infforgets nothing. A list of half-lives fits one instance per value, side by side. Units: clock units.gap_capWhy: a gap in the stream, a weekend or a feed that stopped, would otherwise forget everything at once. What: a ceiling on the clock step between two rows a model learns from, finite and above
0, and required withclock. The ceiling also caps the step a run of skipped rows hands the row after them, however long the run. A step the ceiling cut is a break.ew_covandmarginalclear their lagged co-moments there, andrcovandcorrchangetheir rings, because a lag counts rows, and the row before such a gap is not one row back from the row after it. A break releases nothing anembargoholds (its entry, below). For no forgetting at all, sethalf_life = "inf". Units: clock units.restart_after_step_backWhat a clock that runs backwards within a group means. Why: a step back can be a new start, such as a replayed day or a restarted feed. Or it can be a late row: a transposed pair, a row a minute late, two sources never merged. Only the caller knows which size is which. What: unset (the default), every step back is refused: the chunk is refused naming the row, and the bank is untouched. Given, a step back no larger than it is a late row, refused the same way. A larger one starts the model over;
0starts over at every step back. Needsclock. It guards learning:predictscores a row before the last learned clock against the state as it stands, either way. Units: clock units.session,session_gapWhy: a stream in market-data-like sessions has boundaries where the clock stops measuring time – overnight, over a weekend. What:
sessionnames a column whose value changes at such a boundary.session_gapis the clock step to apply there, finite and at least 0, and capped atgap_caplike any other step;"reset"starts the model over instead. Units: clock units.weightA row-weight column. A row of weight 0 is scored, advances the clock and teaches nothing; a null weight skips the row.
seqtestandauditrefuse a weight column, andrcovtakes only weights of 0 and 1, since each counts rows: a chunk with another weight is refused, naming the row.min_weightWhy: a model should report only once it has seen enough data to have converged, so it never reports a number it is not yet informed enough to give. What: the weight a model must have seen before its outputs stop being null; the model learns from every row either way. A list gives one threshold per target. Thirteen models keep a weight per target:
ewridge,lasso,kalman,huber,quantile,expectile,holt,sgd,pa,ftrl,rls,glmandmarginal, whose table’scorr,betaandt_statare gated per target. Each checks a target’s threshold against that target’s own weight: the rows it was present on, at their raw weights, decayed, and inside the window under one.rlslearns only from rows on which every target is present, so its targets’ weights are equal. The other models check the sharedweight_sum. Theweight_sumfield is the shared weight in every model. So a target that is often null is gated on its own rows, and its first prediction comes later than the others’. Units:weight_sumunits, not rows.rcovreports nothing per row, and itsmin_weightwithholds a closed block’srcovandrcorr: each row weighs 0 or 1 there, so the floor is a count of the block’s returns, and a block with fewer is reported as one too short to estimate from. A finite number: a floor atinfwould withhold every row for good while the model learned from each. The default depends on the model:the default
models
one per unknown: the features, and the intercept when there is one
lasso,kalman,huber,quantile,expectile,rls,sgd,pa,ftrl,glmthe feature count plus one (1 for
holt)ew_cov,ew_class,kmeans,micro,holt3
marginal,deco1
bocpd0, each having a gate of its own or nothing to gate
ewridge,seqtest,rcov,hmm,corrchange,audit,hawkes,garchmin_settled_fracWhy: a history shorter than the half-life may not represent the process, such as regimes or seasons the half-life was chosen to average across. What: predictions are withheld while
settled_frac, how far the decay window has filled toward its steady state (1 - 2 ** (-T / half_life),Tthe decay time seen), is below it. A fraction in[0, 1):0.5waits one half-life,0.75two. Default0, off, since a fit kept as weighted means is unbiased from its first row when the process is stationary. Needs a decay: a finitehalf_life, orlambelow 1.marginalpredicts nothing, so it withholds its table’scorr,beta,t_stat,t_stat_serialand split instead, asmin_weightdoes, at the fraction the next row would read.max_error_inflationewridge,rls,kalmanandlasso. Why: a fit from too little data adds its estimation error to every prediction’s. What: predictions are withheld whilesqrt(1 + estimation variance / noise)is at or above it, the factor by which estimation error is expected to inflate the prediction error over the noise floor. Per model:ewridge sqrt(1 + edf / n_kish) default sqrt(2) rls sqrt(1 + k_total / n_kish) off unless set lasso sqrt(1 + df / n_kish) off unless set, per path point kalman sqrt(1 + z' P⁻ z / R) off unless set, per row
edfis the effective degrees of freedom the last solve used, at mostk_total(rls’s fading prior makes its bound conservative);dfthe active coefficients plus the intercept (Zou, Hastie and Tibshirani 2007);n_kishKish’s effective sample size.kalman’s is exact and per row:P⁻the coefficients’ covariance carried through the row’s clock gap,Rthe noise,obs_varor the residual variance, so a row far from the design reads larger. A ratio above 1;infswitches it off. It reads Kish’s count, so uneven weights withhold for longer, and adding a feature moves the gate with the model.emit_error_inflationewridge,rlsandkalman: writeerror_inflation_<slot>, the same factor for the row’s own features (What a spec writes, below). DefaultFalse. Notlasso, which keeps no factor to read a row’s leverage from.coef_every,max_rows_between_coefsHow often the
coeffield is filled, assolve_everyandmax_rows_between_solvesschedule a solve.coef_everywrites acoefrow once the clock has moved that far since the group’s last one, or since the group’s first row before the first. It is a number of the clock’s units, a duration on a temporal clock ("5m"), or0for every row.max_rows_between_coefswrites one after that many rows the group’s stream accepts: a row whose features and weight are usable, rows of weight zero and rows with a null target included. With both, whichever comes first. The clock is the one the models are stepped on, so a gap capped atgap_capcounts as the cap. Without a clock column it is the row’s number, the first row being 1:coef_every=10writes the tenth row, the twentieth and so on. A reset of the clock starts the count over. Under either, thecoefrows are the same however the stream is chunked.predictreads neither: it fillscoefon each chunk’s last accepted row of each group. With neither, the default,coefis filled on each group’s last row within every chunk: one row per group per chunk, not one per chunk. Only that schedule follows the chunking; every other field is chunk-invariant, so one chunk or a thousand gives the same numbers. Refused on a model that reports no coefficients. Units: clock units, and accepted rows.embargoWhy: a target that is a forward quantity over
hclock units is not known at the row it sits on. Learning it there hands the modelhof the future before it predicts the rows in between. What: each row is scored where it sits and held back from learning until the clock has moved this much further on. The residual,sigma, the metrics, drift, the conformal band,weight_sumandmin_weightall see it then. The delay counts the time that passed on the clock column, skipped rows included, not the capped step the models decay by. Where a session change restarts the clock it countssession_gap. A row exactly the delay later releases a row, and the time is held exactly: in integer nanoseconds on a temporal clock, and by one subtraction of the two rows’ values on a number clock, in integers on an integer clock. A break releases nothing early: its events wait with the row after it, and run when that row is learned. A reset drops the held rows. Units: clock units, or without aclockthe group’s rows, a skipped row included.label_clock,max_held_rows,held_overflowWhy: when each label arrives at a time of its own, a flight’s delay at its landing, one delay for every row learns some labels before they are known and others late. What: a column of each row’s label time, on the clock’s own type. Each row is scored where it sits, from the labels known by then, and held until the first row whose clock reaches its label time, exactly at the time included. Then its label is scored against the prediction, interval and spread the row was served with, and the row is learned at its label time, so a short delay can be learned before an earlier long one.
residon the row is its label less that served prediction.embargo=dis the caselabel_clock = clock + d, and gives the same numbers wherever the clock adds up exactly. A row with weight 0 is held like any row and learned at its label time, where it moves the clock and teaches nothing, asembargolearns it; it counts againstmax_held_rows. A row whose label time is null is scored and not held: its label never arrives, andsummary()counts it inlabels_missing. A null label time is how to keep a row that is only to be scored out of the held rows. A label time before its row’s clock is refused, naming the row. A list gives one column per target; this version takes a list only when every entry names the same column.max_held_rowsbounds the rows a group holds; past itheld_overflow="refuse"(the default) refuses the chunk and"drop_oldest"drops the row that arrived first, counted inlabels_dropped, as a clock reset’s drop is. Rows still held at the end are not learned unless the state is saved and resumed. Refused besideembargo, a window-expression target,group_close, asessioncolumn anddrift_action="reset", and forholt,kalman,hmmandmicro, whose score reaches from the newest learned row. Cost: a held row is placed in label-time order by bisection, moving the shorter side of the buffer, 0.006 microseconds a row with about 100 rows held and 0.38 with about 800 (Apple M4 Pro).group,group_closeOne model state per value of the
groupcolumn.group_closesays when a key is finished, so its state can be dropped."monotone": the key column never decreases, so a key below the largest one fed is done."session": a key’s span ends where itssessionvalue changes. A finished group’s accumulators are emitted throughrheon.polars.ModelBank.closed_groups(), which is what keeps a bank over an unbounded key space bounded. Without it every key ever seen stays in memory.- the diagnostics
emit_sigma,emit_zscore,emit_se_coef,emit_selected,emit_averagedwithaverage_eta,emit_metrics,conformalwithconformal_rate(default 0.05, or"auto"),resid_quantiles,emit_autocorrwithresid_autocorr_lag,emit_driftwithdrift_delta,drift_threshold,drift_action,drift_kindanddrift_options,emit_calibrationwithcalibration_half_life,emit_breakswithbreaks_half_life,emit_robust_sewithrobust_se_half_lifeandrobust_se_lags,emit_specificationwithspecification_half_lifeandljung_box_lags,horizon_rowsbeside any of those four,emit_tailswithtails_half_life,emit_influencewithinfluence_half_life,emit_feature_healthwithfeature_health_half_life, andemit_clocks. Each adds fields to the output, listed below. A model with no residual refuses them by name, all butemit_clocks. A*_half_lifebeside a switch is that diagnostic’s own memory, in clock units: when left out, four times the fit’s memory for the calibration and the fit’s memory for the others;infis the run-once form, which forgets nothing. The fit’s memory is the instance’s half-life, with two exceptions. Underwindow_sizeit is the half-life whose exponential weights have the window’s Kish sizen,ln 2 / ln((n + 1) / (n - 1))rows. With nothing decaying inside the windowniswindow_size, and the half-life is aboutwindow_size / 2.885rows, orwindow_size * ln 2 / 2clock units on a clock column. Beside a decaynis the Kish size of the decayed weights inside the window, taken in its continuous form on a clock column. The windowed CUSUM’s null share reads the window itself instead, since a window absorbs a level as a mean over its rows (emit_breaksbelow). Forkalmanthe fit’s memory is itscoef_half_life, the shortest finite one where a list gives one per coefficient; the windowed CUSUM’s null share reads the list’s intercept entry instead, the memory at which a level is absorbed, and a pinned intercept leaves the plain sum. A diagnostic folds a row only once the instance is ready: the row’s prediction past every gate, the stream 95% settled on the longest finite memory the model keeps where it forgets, and a standardizingsgdorpapast its scaler’s warm-up. That memory is the fit’s, butholt’s trend (trend_half_life, four times its level’s by default), the longest ofkalman’scoef_half_lifeandhalf_life,ewridge’slong_half_life,lasso’sselect_half_lifeand the Huber scale’shuber_scale_half_lifeofhuberandsgd. The twin fits ofbreak_waldand feature health read no prediction, and fold every row.horizon_rowsis the target’s horizon in rows: the rows a target that looks ahead shares its shocks over, so that its residuals overlap. Without a clock column it defaults toembargo, rounded up; with one it is 0 unless given, sinceembargois in clock units there, and each diagnostic that reads it says so once in arheon.ReadinessWarning. Under it the calibration’s, Breusch and Pagan’s and RESET’s tests take Newey and West’s variance at twice it in lags, the CUSUMs andbreak_waldthe long-run variance, and Ljung and Box skip the lags inside it.se_coef_hac’s lags default to twice the horizon too: anembargoof 2.5 is a horizon of 3 rows, and 6 lags. A horizon read fromembargogives at most 64 lags, and arheon.ReadinessWarningsays so past it. docs/DIAGNOSTICS.md orders them by the question each answers, with their thresholds, false-alarm rates, costs and the theory behind them, and a recipe for each.
standardize, which eight models take, defaults to False in ewridge,
huber and quantile, and to True in kalman, sgd, pa,
kmeans and micro. Each builder says what it scales.
Clock units
A parameter measured in clock units is written one of two ways, and the clock column decides which:
the clock |
a clock parameter is |
for example |
|---|---|---|
none |
a number of rows |
|
a numeric column |
a number of the column’s own units |
|
a |
a duration |
|
A duration is a polars expression that reads no column, such as
pl.duration(minutes=10), or a datetime.timedelta. It may also be
polars’ duration text, such as "10m" or "1h30m": whole numbers of
ns, us, ms, s, m, h, d or w, added up in any
order, as polars reads them ("30m1h" is "1h30m"). A month, a quarter
and a year have no fixed length, so "1mo", "1q" and "1y" are
refused. The spec keeps a duration as text, the form the command line’s TOML
takes. A half_life grid names its instances by it (@h10m). 0 and
inf mean the same in every unit, so they may stay numbers beside durations;
the word "inf" (or "infinity", in any case) is kept as the number.
The clock parameters are half_life, gap_cap, restart_after_step_back,
session_gap, coef_every and embargo above, drift_threshold
and each diagnostic’s own *_half_life below, and in the models
window_size,
snapshot_every, solve_every, ew_cov’s pca_every, micro’s
prune_every and the model half-lives: long_half_life,
select_half_life, coef_half_life,
revert_half_life, trend_half_life and huber_scale_half_life,
hawkes’ kernel_half_lives, a list of them, garch’s
start_span, glm’s and expectile’s refit_span, and
kmeans’ warm_span, update_every and split_merge_every,
hmm’s and bocpd’s warm_span, bocpd’s hazard,
corrchange’s permute_every, huber’s and sgd’s
huber_refit_span and quantile’s quantile_refit_span. Each that
counts rows where the quantity has a meaning on the clock has its count
beside it, such as warm_rows beside warm_span and bocpd’s
hazard_rows beside hazard, and the two are refused together.
Each mixture is refused, naming the column, the parameter and the fix: a
temporal clock with a clock parameter given as a plain number, a numeric clock
with a duration, and one spec that gives both. A rate per clock unit has no
duration form, so a temporal clock refuses one too: lam, kalman’s
q and hawkes’ kernel_decays. Give the half-life the rate stands
for as a duration instead.
A temporal clock is read in its own integer nanoseconds, and a duration in
seconds, so the column’s own unit never reaches the fit. The same instants as
Datetime("ms"), Datetime("us") or Datetime("ns") give the same
numbers. A model reads only the gap between consecutive rows. The bank takes
that gap in integer nanoseconds before it becomes seconds, so a nanosecond
timestamp keeps its nanoseconds whatever the stream’s age. The previous row’s
instant is part of the state, so a loaded bank goes on exactly. A clock must
lie between the years 1677 and 2262, the range nanoseconds in a 64-bit integer
cover. A Date or a coarse Datetime past that is refused, naming the
row. A time zone changes nothing, because a Datetime is stored in UTC, so a
change of clocks for summer time neither stretches nor folds the clock. Where a
clock quantity reaches an output, it is in seconds: holt’s trend is per
second. rheon.polars.ModelBank.summary(),
rheon.polars.ModelBank.groups() and
rheon.polars.ModelBank.closed_groups() give clock values in the clock
column’s own type, as emit_clocks’ two fields do. A Time column is
refused, because a time of day starts again at midnight.
What a spec writes
A bank adds one struct column per spec, named after the spec. Every field but
coef, support_coef and the standard errors (se_coef,
se_coef_hc0 and se_coef_hac) is computed from the state before the
row updates it, so a prediction is out-of-sample and a diagnostic never sees
the row it describes. Those fields report the fit after the row: coef on
row t is the fit row t + 1 is predicted with. Under an embargo the
row’s own update waits for the delay, so coef on row t is the fit after
the rows t released, and row t + 1 is predicted with it only when t + 1
releases none. A regression writes, with <t> a target:
pred_<t>The prediction. Null until
min_weightis reached, and on a row the model skipped (a null feature or weight).resid_<t>y - pred; null where the target is null.weight_sumThe accumulated weight before this row’s update and before its own decay.
0on a stream’s first row. One behind the row count while nothing is forgotten.1 / (1 - lam**d)once forgetting balances arrival, for unit rowsdclock units apart (lam = 0.5 ** (1 / half_life)). A weight, not a count of rows: at a half-life of 600 with rows 0.1 apart it settles near 8,657, and Kish’sn_kishis the sample size.coefThe coefficients of the fit after the row’s update, the ones the next row is predicted with (under an
embargo, as above). They are one flat list: per (target, grid combination) slot in the order thepredfields declare them, the intercept and then one entry per feature. Null on rows where it is not filled (coef_every), which are most rows, and a list stores nothing for a null row.coef_index()maps each position to its term, and.list.get(position)reads it. For an(n, k)matrix,kbeingcoef_index()’s height, keep the rows that carry it and fix the width:.list.to_array(k), thento_numpy().coef_fields()names the column each becomes when the struct is unnested.settled_fracHow far the decay window had filled toward steady state before this row:
1 - 2 ** (-T / half_life)withTthe decay time the models have seen, so0.5at one half-life,0.75at two, whatever the row rate. Null where nothing decays. Whatmin_settled_fracgates on.withheld_reasonWhich gate withheld the row’s predictions, as an
Enum, and null where no gate did.below_min_settled_frac,below_min_weight,above_max_error_inflation,below_warm_rows,ill_conditioned,unstable_rateandnot_identifiedare named in that order, the first that withheld anything.below_warm_rowsis the model’s own warm-up: the rowskmeans,hmmandbocpdhold to seed their centres, states or prior from (warm_rows), a count of rows, wheremin_weightis a weight, the rowskalmantakes a target’s prior from before it is sized, and the rowsgarchbuffers for a target’s start.ill_conditionedis anewridgefit withheld because its normal equations are past the condition at which a solve keeps a digit: itscoefandsupport_coefare null too, and the solve is counted insolve_failures. The estimate and the limit are in theewridgebuilder’s docstring.unstable_rateis ansgdtarget whose learning rate is past its stability bound: its recent steps’ gainsqhave a mean square above twice their mean, so each step grows its own row’s residual in mean square, and the fit diverges; thesgdbuilder’s docstring has the gain.not_identifiedis agarchstart whose rows do not yet tell its variance process from a constant variance, so it buffers more rows before it reports; thegarchbuilder’s docstring has the test. Fields null for another reason, such as a skipped row or a statistic not yet due, leave it null. AnEnumrather than a string, because a string column costs sixteen bytes a row even when every value is null.support_coefEach coefficient’s data share, how much of it the data determined rather than the ridge: on
coef’s rows, of the same fit after the row, forewridge,huberandquantile. It is1 - ridge * (S^-1)_jjin[0, 1], withSthe system the solve inverts (for the robust models, the Gram as the loss weighs the rows), laid out likecoef. A duplicated pair reads0.5each, a clean design1, a column the standardiser dropped0; the intercept is not a share and is null. Notlasso, whose L1 penalty has no such matrix.
A model that is not a regression writes fields of its own, which its builder
describes. Per model, the fields of the plainest spec are listed in
docs/OUTPUTS.md, and
output_fields() lists them for the exact spec you built.
A grid writes one set of fields per instance or slot, suffixed. A grid is a
list of half-lives, a list of ridge values, two or more feature_sets,
or penalties. A half-life grid is one instance per entry, and suffixes
every field (@h…). The other grids are slots within an instance, and suffix
the fields of each slot, pred, resid and the per-slot diagnostics, by
its combination. lasso also writes the path point it has selected, once per
instance. emit_selected and emit_averaged choose across every slot of a
target, so their fields take no suffix:
pred_{target}{combo}{instance} combo = "" single ridge, no feature sets
resid_{target}{combo}{instance} | __r{ridge} ridge grid
sigma_{target}{combo}{instance} | __{set} feature sets, single ridge
weight_sum{instance} | __{set}_r{ridge}
settled_frac{instance} | __p{penalty} penalties point
withheld_reason{instance}
coef{instance} instance = "" single half-life
support_coef{instance} | @h{half-life} half-life grid (@h600, @h10m)
se_coef{instance} emit_se_coef
se_coef_hc0{instance}, se_coef_hac{instance} emit_robust_se
penalty_selected_{target}{instance} lasso: the path point in force
selected_{target} emit_selected: the chosen slot
pred_{target}__selected emit_selected: its prediction
pred_{target}__averaged emit_averaged
Every name follows one grammar, which is stable. Read left to right, a
name is the kind (pred, abs_resid, lag_corr), then its qualifier,
then the target or the columns it is about, then the grid point after __
and the instance after @. A qualifier is a number glued to the letter that
says what it is: q a quantile level, l a lag (abs_resid_q0.05_y,
mahal_q0.99, lag_corr_l1_x0_x1). The grid point uses letters too:
r a ridge and p a lasso penalty, and the instance h, a half-life.
A thing the spec has several of is numbered where it is named, glued to its
word: a principal component pc0 (pc0_var, pc0_loading_x0), an
hmm state state0 (filtered_state0), a kmeans centre
cluster0 (coef_cluster0_x1).
<slot> below is a target with its suffix. output_index() gives every
field with the values its name encodes, so a field is reached without building
its name. Avoid __ and @ in target names and feature-set labels if you
parse the names downstream.
The diagnostics add, per slot:
switch |
fields |
what they hold |
|---|---|---|
|
|
The EW standard deviation of the slot’s out-of-sample residuals.
Its weight ages on every row the model sees, a row with no
prediction or with weight 0 included, so it forgets across a gap
as the clock says. Under a |
|
|
|
|
|
|
|
|
On |
|
|
Beside |
|
|
The row’s own clock, and the clock of the newest row the models had
learned from, at a positive weight, when the row was scored. Without
a delay that is the previous learned row; under |
|
|
The grid slot with the lowest EW out-of-sample squared error so
far, an |
|
|
Every slot’s prediction averaged with weights
|
|
|
Exponentially weighted correlation of prediction with target,
out-of-sample R² against the running mean, and the share of rows
whose sign the prediction got right, a row whose target or
prediction is exactly 0 left out, as |
|
|
An interval |
|
|
The exponentially weighted quantile of |
|
|
The EW correlation of each residual with the one
|
|
|
True on the row a Page-Hinkley detector on
Their settings go in |
|
|
Mincer and Zarnowitz’s regression of the outcome on the
out-of-sample prediction, |
|
|
Where the relationship broke. |
|
|
What the fit is missing, each at |
|
|
The EW skewness and excess kurtosis of the recursive residuals,
|
|
|
How far the row moves the fit, in the fit’s own metric: an online
DFFITS, |
|
|
Each feature’s EW standard deviation at |
Errors
A builder raises TypeError for a name that is not a str, a keyword it has
not got, or a value of the wrong shape, naming the parameter and what it
takes:
spec "m": max_rows_between_coefs must be an int, got float 1.5
It raises ValueError, naming the spec, the parameter and the value, for a
value the model refuses:
a count below 0, or below 1 for a count there must be one of (
lags,cross_lags,resid_autocorr_lag,ljung_box_lags,k,shards,gram_threads,max_iter,max_clusters, the*_every_rowscounts and themax_rows_between_*caps), or past what the Rust side holds it in (2^32 - 1for themax_rows_between_*caps,max_iter,update_every_rowsandsplit_merge_every_rows;2^64 - 1for the other counts), orNaNanywhere;a count that sizes memory before the first row past its ceiling: a lag or
n_permpast 2^20,horizon_rowspast 2^19,kmeans’kpast 2^16,hmm’skpast 2^10, akmeansorbocpdwarm-up buffer past 256 MiB,rcov’s lagged products past 256 MiB;infwhere it means nothing (it is allowed where it does –half_life,average_eta,max_error_inflation,window_budget, each diagnostic’s*_half_lifeand the model parameters that say so);neither
half_lifenorlamon a model that decays (all butseqtest,audit,rcov,corrchangeandbocpd), or both; alamoutside(0, 1], and an emptyhalf_lifegrid or one that repeats a value;clockwithoutgap_cap, or agap_capof0orinf;a
session_gapbelow 0 or infinite, andsessionwithoutsession_gapunlessgroup_close = "session";group_closewithoutgroup, besideembargoor beside a window target, andgroup_close = "session"withoutsessionor besidesession_gap;emit_driftwith aclockand nodrift_threshold, underdrift_kind"page_hinkley"or"cusum";a
drift_optionskey thedrift_kinddoes not read,drift_deltaordrift_thresholdbeside a kind that does not read them, and a"ddm"or"eddm"withouterror_above;a window target beside
groupwithoutclock;a column listed twice, or as both target and feature;
a
min_weightlist whose length is not the number of targets, and amin_weightofinf, which would withhold every row for good;emit_selectedoremit_averagedwith one slot per target;emit_feature_healthon a model with no features (holt);a level outside
(0, 1), or an option not in the list the message gives;and each model’s own rules, which its builder lists.
A parameter whose switch is off is refused rather than ignored:
drift_delta,drift_threshold,drift_kind,drift_optionsordrift_action = "reset"withoutemit_drift;average_etawithoutemit_averaged;resid_autocorr_lagwithoutemit_autocorr;a diagnostic’s
*_half_life, or its lags (robust_se_lags,ljung_box_lags), without its switch;long_half_lifewithoutsession_shrink;session_gapwithoutsession;gap_caporrestart_after_step_backwithoutclock;conformal_ratewithoutconformal, andhorizon_rowswithout a diagnostic that reads it;snapshot_every,max_rows_between_snapshots,window_budgetorclosed = "both"withoutwindow_size;sgd’shuber_delta,huber_scale,huber_scale_half_life,huber_refit_rows,refit_budget,quantileorepsbeside a loss that does not use it, itsstrict_binarybeside a loss other than"logistic", and itspowerbeside a schedule other than"inv_scaling";ftrl’sstrict_binarybesideloss = "squared";holt’strend_half_lifebesidetrend = False;kmeans’dead_fracabove 0 besidesplit_merge = 0, and its andmicro’sscale_floorbesidestandardize = False;bocpd’srobust_betabesidecovariance_type = "full";hmm’stransitionortransition_priorbesidetvtp_coef, and itswarm_rows,initorseedbeside givenmeansandcovs;rcov’sbandwidth,max_bandwidthorjitterunder a kind other than"kernel", and itsthetaorpreavg_rowsunder one other than"preavg";kalman’scoef_half_lifebesideq, which it would derive;and
coef_everyormax_rows_between_coefson a model that reports no coefficients.
Names and lists are checked too: a feature set named twice, a column twice in
one set, an empty set, an empty feature_sets or blocks, an empty target
name, an empty mahal_quantiles or resid_quantiles, and a ridge
value listed twice. So is a spec named "", "spec" or "group", names
the bank’s tables use for their own columns.
A spec that came back from a builder is valid. One edited afterwards is
checked again wherever it is used, and a key no spec has is refused there
rather than ignored. Every way in checks a spec the same way, so a spec one of
them refuses is refused by all of them. rheon.polars.ModelBank,
output_fields(), output_index(), coef_fields() and a run
config each fill its defaults and build its models.
Regressions¶
Models that predict each target from the features, or from the target’s own past.
Exponentially weighted ridge regression on running sums. |
|
Recursive least squares, which solves the ridge fit exactly on every row. |
|
A lasso or elastic-net path on running sums, with the penalty chosen as the stream runs. |
|
A regression whose coefficients drift, tracked by a Kalman filter. |
|
Stochastic gradient descent under a choice of losses, with one gradient step a row. |
|
Passive-aggressive regression, which moves the fit by the smallest step that brings each row within a margin of its target. |
|
Logistic regression for a 0/1 target, or a sparse linear regression, by FTRL-proximal. |
|
A generalized linear model, fitted one row at a time by reweighted least squares. |
|
Holt’s linear trend, which extrapolates the target’s own level and slope. |
Robust regressions¶
Regressions whose fit an outlying row cannot pull far.
Huber regression on running sums, which down-weights the rows a prediction misses by far. |
|
Quantile regression on running sums, the fit that a share |
|
Expectile regression, fitted one row at a time by reweighted least squares. |
Covariance and regimes¶
Moments and correlations of a stream’s columns, what the columns hold, and which regime the stream is in.
Exponentially weighted moments of the feature columns, and the statistics read off them. |
|
Each feature’s exponentially weighted moments with each target, read back as a table. |
|
Engle and Kelly’s dynamic equicorrelation, one number for the whole correlation matrix of the features. |
|
A block’s realized covariance of the features, robust to microstructure noise. |
|
A count of what a stream’s columns hold, read in one pass by a spec that fits nothing and predicts nothing. |
|
A Gaussian hidden Markov model of the features, filtered one row at a time. |
|
A conditional variance for each target, from the GARCH family, fitted online by recursive quasi-maximum likelihood. |
Changepoints and sequential tests¶
Tests that read a stream row by row and say when it has changed, or whether a sign, or one spec against another, favors one side.
A sequential test of a target’s sign by betting, whose evidence can be read at any row. |
|
Tests of whether the correlations between the feature columns have changed, by three kinds of test. |
|
Bayesian online changepoint detection, a posterior over how long the current regime has lasted. |
|
A self-exciting point process, fitted exactly by least squares. |
Clustering and classification¶
Models that place each row in a cluster or a class.
Exponentially weighted k-means over the feature columns. |
|
Density-based clustering over the feature columns, by small decayed summaries linked into clusters. |
|
A Gaussian classifier on exponentially weighted moments, one set per class. |
Reading a spec’s fields¶
The names of the fields a bank’s output carries, and where each coefficient
sits in coef.
List the names of the fields a spec writes, in order. |
|
List every field a spec writes, with the values its name encodes. |
|
List every coefficient a spec reports, with its place in |
|
List the layout of a spec’s |
Typed keyword sets¶
The keywords every builder shares, as a typed dictionary a type checker can read.
The keyword parameters every spec builder shares, as one TypedDict
(PEP 692).
The builders in rheon.spec take the shared parameters as
**common, annotated as Unpack[CommonKwargs]. So an editor completes
them and a type checker finds a misspelled one, where **kwargs: Any
would show nothing and leave a typo to be found when the call runs. A
TypedDict has no defaults: each builder’s signature gives them, and
rheon.spec describes each parameter.
- class rheon._kwargs.CommonKwargs[source]¶
Bases:
TypedDictWhat the builders take as
**common: every parameter the models share, the group and its close policy among them.- fit_intercept: bool¶
- clock: str | None¶
- half_life: float | timedelta | str | _Expr | list[float | timedelta | str | _Expr] | None¶
- lam: float | None¶
- gap_cap: float | timedelta | str | _Expr | None¶
- restart_after_step_back: float | timedelta | str | _Expr | None¶
- session: str | None¶
- session_gap: float | timedelta | str | _Expr | None¶
- weight: str | None¶
- min_weight: float | list[float] | None¶
- min_settled_frac: float | None¶
- max_error_inflation: float | None¶
- emit_error_inflation: bool¶
- emit_se_coef: bool¶
- emit_clocks: bool¶
- coef_every: float | timedelta | str | _Expr | None¶
- max_rows_between_coefs: int | None¶
- emit_sigma: bool¶
- emit_zscore: bool¶
- emit_selected: bool¶
- emit_averaged: bool¶
- average_eta: float | None¶
- emit_metrics: bool¶
- conformal: float | None¶
- conformal_rate: float | Literal['auto'] | None¶
- resid_quantiles: list[float] | None¶
- emit_autocorr: bool¶
- resid_autocorr_lag: int | None¶
- emit_drift: bool¶
- drift_delta: float | None¶
- drift_threshold: float | timedelta | str | _Expr | None¶
- drift_action: Literal['flag', 'reset']¶
- drift_kind: Literal['page_hinkley', 'cusum', 'adwin', 'ddm', 'eddm', 'kswin'] | None¶
- drift_options: Mapping[str, float | int | bool] | None¶
- emit_calibration: bool¶
- calibration_half_life: float | timedelta | str | _Expr | None¶
- emit_breaks: bool¶
- breaks_half_life: float | timedelta | str | _Expr | None¶
- emit_robust_se: bool¶
- robust_se_half_life: float | timedelta | str | _Expr | None¶
- robust_se_lags: int | None¶
- emit_specification: bool¶
- specification_half_life: float | timedelta | str | _Expr | None¶
- ljung_box_lags: int | None¶
- horizon_rows: int | None¶
- emit_tails: bool¶
- tails_half_life: float | timedelta | str | _Expr | None¶
- emit_influence: bool¶
- influence_half_life: float | timedelta | str | _Expr | None¶
- emit_feature_health: bool¶
- feature_health_half_life: float | timedelta | str | _Expr | None¶
- embargo: float | timedelta | str | _Expr | None¶
- label_clock: str | Sequence[str] | None¶
- max_held_rows: int | None¶
- held_overflow: Literal['refuse', 'drop_oldest'] | None¶
- group: str | None¶
- group_close: Literal['monotone', 'session'] | None¶