rheon.spec.garch¶
- rheon.spec.garch(name: str, *, targets: Sequence[str | Target | FormulaTarget | _Expr], vol: Literal['garch', 'gjr', 'egarch', 'figarch'] = 'garch', dist: Literal['normal', 't', 'skewt'] = 'normal', truncation: int | None = None, variance_targeting: bool = False, start_rows: int | None = None, start_span: float | timedelta | str | _Expr | None = None, horizon: int = 1, max_state_bytes: int | None = None, **common: Unpack[CommonKwargs]) dict[str, Any][source]¶
A conditional variance for each target, from the GARCH family, fitted online by recursive quasi-maximum likelihood.
Use it on returns, or on any zero-mean residual whose size clusters in time: each row’s variance is forecast from the rows before it, and the process’s parameters are learned one row at a time, from a start fitted by batch likelihood on the first rows. Each target is its own series, with its own parameters.
Parameters
The stream parameters every builder takes, such as
clock,min_weightandgroup, are inrheon.spec;half_lifeandlamare refused, since the recursion is per observation and the estimate weighs every row it has learned. A row’sweightscales its evidence: its score, its information and its term in the start’s likelihood. Scaling every weight changes nothing butweight_sum. A row of weight 0, or whose target is null, steps nothing: the next row’s lags are those of the last row learned, as if it were not there; it is still read.This model’s own parameters:
volThe process:
"garch", the default, GARCH(1,1);"gjr", with a leverage term for negative returns;"egarch", in the logarithm of the variance;"figarch", fractionally integrated, with a long memory of the squared returns.distThe innovations:
"normal", the default;"t", Student’s t, whose degrees of freedom are learned;"skewt", Hansen’s skewed t, which learns a skew too. The t takesvol="garch"and"gjr", the skewed t"garch"alone: under skewed innovations GJR’s persistence readsE[z² 1(z < 0)], not the half ofE[z²]the forecast uses.truncationFIGARCH’s lags: its weights over the last this many squared returns. Default 1,000, as
arch’s; 8 bytes a lag in each group.variance_targetingSet the level by the running mean square,
ω = v̄ (1 - α - β), and learnαandβalone, with a Huber-clipped score:vol="garch"with normal innovations only. It is a different estimate from the default’s,ωa moment rather than a likelihood one, and it needs returns with a finite fourth moment. It is not the safer choice: on persistent series (α + β = 0.98) it forecasts worse than the default, since its level rides on one running mean the whole stream shares. Default False.start_rowsThe rows the start buffers and fits, each target’s own; they report nothing (
withheld_reasonbelow_warm_rows). Default 2,000, at least 50, and at least 2,000 forvol="figarch". A start whose rows do not tell its process from a constant variance, by the test under “The start” below, waits for twice the rows and refits, at most twice, whilemax_state_bytesholds the doubled buffer, and then buffers afresh, reporting nothing (not_identified) until a start passes. A start that passes but whose fit is not at its optimum, or sits on a bound of the process’s parameters, waits and refits the same way, and with no doubling left is stepped from. Refused besidestart_span.start_spanThe start as a span of the clock in place of
start_rows, in clock units: a number of the clock column’s units, or a duration such as"1d"on a temporal clock. It closes at the first row at or past the span from its first row, once it holds 50 rows; a refit waits for twice the span. How many rows that is, the data decides, so its bytes are checked as the rows go in (seemax_state_bytes).horizonReport the variance this many rows ahead too, as
forecast_<t>. Default 1, the variance alone.vol="egarch"takes 1 only: its forecast past one row has no closed form.max_state_bytesThe bytes a group’s state may hold, the start’s buffer included (16 bytes a row until it is fitted). A spec whose start or FIGARCH ring is past it is refused. A
start_spanstart is checked as the rows go in: the first row to take a group past half of it raises a warning, once for the group, and the row that would take it past the cap stops the run with an error naming the group and the bytes. Default 256 KB,262144; at most 64 MiB.
Output
One output column, named after the spec, holds a record of these fields in each row. docs/OUTPUTS.md#garch gives each field’s type and when it is null:
variance_<t>Per target: the variance of the row’s return given the rows before it, read before the row is learned. Null before the target’s start is fitted, and below
min_weight.std_resid_<t>Per target: the row’s return over the square root of its variance, null where either is.
forecast_<t>Per target, with
horizonabove 1: the variancehorizon - 1rows past this one, from the same rows asvariance_<t>.weight_sumThe weight the model has learned before the row: every learned row’s weight, the start’s included, with no decay.
settled_frac,withheld_reasonAs every model reports them (
rheon.spec).coefPer target, after the row:
omega, thenalpha,gamma(gjr,egarch) andbeta, or FIGARCH’somega,phi,dandbeta; thennufor a t, andlambdafor a skewed t. Null before the start.coef_index()names them.
Raises
As every builder does (
rheon.spec);TypeErrorforfeatures, which this model does not take; andValueErrornaming the problem forvolordistnot one of the words above, a t onegarchorfigarch, a skewed t ongjr,variance_targetingon any form butgarchwith normal innovations,truncationon a process but FIGARCH or below 1,start_rowsbelow its floor or besidestart_span,start_spannot finite or not above 0,horizonbelow 1 or above 1 onegarch,half_lifeorlam, and a state pastmax_state_bytes, or amax_state_bytesof 0 or past 64 MiB.The update
With
s_tthe variance of rowt’s returne_tgiven the rows before it, andz_t = e_t / sqrt(s_t):garch s_t = ω + α e²_{t-1} + β s_{t-1} gjr s_t = ω + α e²_{t-1} + γ 1[e_{t-1} < 0] e²_{t-1} + β s_{t-1} egarch ln s_t = ω + α (|z_{t-1}| - sqrt(2/π)) + γ z_{t-1} + β ln s_{t-1} figarch s_t = ω / (1 - β) + Σ_{j=1..M} λ_j e²_{t-j}, λ_1 = φ - β + d, λ_j = β λ_{j-1} + δ_j - φ δ_{j-1}, δ_j = d Π_{i=2..j} (i - 1 - d) / iBefore the first row every lag is
arch’s backcast, the0.94^i-weighted mean of the first 75 squared returns. Each learned row of weightw_tsteps the parameters by the score of its log-likelihoodl_t = log f(z_t) - ½ ln s_t,g_t = ½ w ∂ln s_t / ∂θ(w = z² - 1under the normal, a boundedwunder a t), with the sensitivity∂ln s_t / ∂θcarried by its own recursion:a_t = w_t / W_t W_t the weight learned, the start's included H ← H + a_t (I_t - H) I_t = ½ ∂ln s ∂ln sᵀ, or the score's outer product under a t θ ← Proj_H(θ + a_t H⁻¹ g_t)
Proj_Hprojects onto the process’s admissible set,arch’s with the persistence at most1 - 1e-4, inH’s own metric. A t’sνis stepped asln(ν - 2), so no step crosses 2. EGARCH’s guard keeps the filter that runs contracting:α ≥ |γ|andα ≤ 1, its variance within a factor1e6of the 0.94-weighted mean square, asarch’s is, and the mean ofln |β - (α |z| + γ z)/2|over the residuals the filter has met held below 0, a step that would break it cut back along the step. It agrees witharchwhereverarch’s own filter contracts, and carries no proof that the estimate it guards is consistent. The state is8 * (2k + m + n(n + 1)/2 + 9)bytes a target forkprocess parameters,mshape parameters andnstepped coordinates, EGARCH’s 512 bytes of bins beside them, plus FIGARCH’s ring,8 M, whatever the stream’s length.Example
This code simulates a GARCH(1,1) at
(ω, α, β) = (0.05, 0.08, 0.9)and prints the fit after 20,000 rows:import numpy as np rng = np.random.default_rng(7) e, s, r = 0.0, 2.5, [] for z in rng.standard_normal(20_000): s = 0.05 + 0.08 * e * e + 0.9 * s e = np.sqrt(s) * z r.append(e) pl.DataFrame({"r": r}).write_parquet("returns.parquet") model = rp.spec.garch("g", targets=["r"]) bank = rp.ModelBank([model]) bank.fit(pl.scan_parquet("returns.parquet")) coef = {row["term"]: row["coef"] for row in bank.coef().iter_rows(named=True)} print(f"alpha: true 0.08, found {coef['alpha']:.2f}") print(f"beta: true 0.90, found {coef['beta']:.2f}")
alpha: true 0.08, found 0.07 beta: true 0.90, found 0.91
See also
ew_cov(), for an exponentially weighted variance with a fixed decay rather than a fitted one.hawkes(), for the clustering of events rather than of sizes.
Notes
The estimator. It is the recursive prediction-error method: with the gain
1/Wand a batch start, its estimate agrees with the batch fit of the same rows to first order, so the gap between the two, measured in the batch fit’s standard errors, shrinks as rows arrive. Againstarch’s batch fit of 10,000 rows, over 50 simulated series a form, every parameter was within two ofarch’s standard errors on 46 to 50 of them, and the out-of-sample log-likelihood lost toarch’s path was at its expected size,(k/2)(ln(n/n₀) + 1)forkparameters andn₀rows of start.The projection. A Newton step projected onto the bounds in the Euclidean metric is no ascent where the bounds hold parameters the likelihood barely tells apart (
α + βnear 1, FIGARCH’sφandβ); projected inH’s own metric it is.The start. Its rows report nothing, and its fit is made by the model’s own projected Newton on their likelihood, from a small grid, run until a step is at the parameters’ rounding: where a step’s gain is under the likelihood’s own rounding, whether it is taken is read from the slopes at its two ends, not from the likelihood’s last bits. A fit is at its optimum when its Newton decrement
½ gᵀ M⁻¹ g(Mthe observed curvature) is at most10⁻⁶nats. 2,000 rows keep a series from starting far enough off that the1/Wgain takes the rest of the stream to recover; a FIGARCH needs them for its ring of 1,000 lags to hold returns rather than the backcast.The test before a start reports. A series with no conditional variance to find leaves the likelihood flat along a ridge, where
βis not identified onceαis 0, and any fit there is noise. So the start’s fit is stepped from only when its likelihood-ratio statistic against a constant variance (the normal’s, or the t’s with its own shape fitted),2 (l_fit - l_const), reaches χ² at 0.999 for the restrictions a constant variance puts on the process: 13.8 forgarchand the variance-targeted GARCH (α = β = 0), 16.3 forgjrandegarch(α = γ = β = 0) andfigarch(d = 0,φ = β). The weights enter at Kish’s count, the statistic read as2 (l_fit - l_const) Σw / Σw², so scaling every weight changes nothing. On simulated series of persistence 0.97 to 0.985, and of 0.90, it passed every 2,000-row start; on returns with no conditional variance it passed none, at starts of 500 to 2,000 rows.