Skip to main content

Crate backshift

Crate backshift 

Source
Expand description

Time-series forecasting that also runs on devices without a heap: ARIMA, ETS, Theta, VAR, Croston and TSB, GARCH and changepoint detection, each with a streaming filter.

Fit a model with Arima::fit (feature alloc), then stream new values through a Filter, which lives inline with no allocation, and forecast with prediction intervals. The other families follow the same split: a fit where there is an allocator, and a heap-free filter that continues from it. Likelihoods, innovations, forecasts and intervals match statsmodels to 1e-9.

use backshift::{Arima, Filter};

let history = [0.3, 1.1, 0.4, -0.2, 0.9, 1.4, 0.6, 0.1, -0.5, 0.2, 0.8, 1.0, 0.3, -0.1, 0.4];
let fitted = Arima::new(1, 0, 0).fit(&history).unwrap();
println!("AIC {:.2}", fitted.aic());

// The device side needs only the coefficients.
let mut filter = Filter::<4>::new(&fitted.spec()).unwrap();
filter.warm_up(&history);
let innovation = filter.update(0.7).unwrap();
assert!(innovation.variance > 0.0);

let (mut mean, mut lower, mut upper) = ([0.0; 3], [0.0; 3], [0.0; 3]);
filter.forecast_interval_into(0.95, &mut mean, &mut lower, &mut upper);
assert!(lower[0] < mean[0] && mean[0] < upper[0]);

The crate also has the building blocks: autocorrelation (acorr, acov) and, with alloc, differencing and the Yule–Walker, Burg and Hannan–Rissanen estimators.

The crate is no_std. Its features:

  • std (default): floating-point functions from the standard library. Implies alloc.
  • libm: floating-point functions from the pure-Rust libm crate, for targets without std.
  • alloc: the functions that return a Vec, such as pacf, difference, yule_walker and burg. Without it the crate never touches a heap, so firmware needs no global allocator.

Enable std or libm. A firmware build is default-features = false, features = ["libm"], plus "alloc" if it has an allocator.

Structs§

Accuracy
The accuracy of a forecast against the actual values, as R’s accuracy reports it on the test set.
ArCoefficients
The fitted coefficients of an AR(p) model.
Arima
A seasonal ARIMA(p, d, q)(P, D, Q, s) model to fit.
ArimaSpec
The parameters of a seasonal ARIMA(p, d, q)(P, D, Q, s) model.
ArmaCoefficients
AR and MA coefficients of an ARMA(p, q) model.
AutoArima
An automatic ARIMA model search.
AutoEts
R’s automatic ETS selection, as ets(y): every combination of an additive or multiplicative error, no, additive or damped trend, and no, additive or multiplicative season that R allows, ranked by AICc by default. Multiplicative models need positive values, and R forbids a multiplicative season with an additive error; like R, the search leaves out multiplicative trends.
AutoFit
The best model of a search.
Bocpd
Bayesian online changepoint detection with at most R run-length hypotheses, stored inline with no heap; O(R) work per value.
Conformal
Conformal intervals for forecasts up to H steps ahead, calibrated on the last N errors per horizon. It lives inline with no heap.
CrostonFilter
Croston’s method on a stream of demand values, with no heap.
Cusum
Page’s two-sided cumulative sum on standardised values z:
Decomposition
The components of an STL decomposition: values = seasonal + trend + remainder.
Ets
An ETS model to fit, in R’s taxonomy: simple exponential smoothing by default, with an optional additive or damped trend, an optional additive or multiplicative season, and an additive or multiplicative error.
EtsFilter
A streaming ETS filter with room for M seasonal states, stored inline with no heap.
EtsFit
A fitted ETS model.
EtsSpec
An ETS model with its smoothing parameters and current states.
FamilySelection
The outcome of select_family.
Filter
A streaming ARIMA filter with room for R states and M regressors, stored inline with no heap.
Fitted
A fitted seasonal ARIMA model.
Fixed
Which whole parts of a model Arima::fit_fixed keeps at their start values.
FourierFit
The best model of an AutoArima::fit_fourier search.
Garch
GARCH(1,1) to fit to a zero-mean series.
GarchFilter
A streaming GARCH(1,1) filter: the conditional variance of each value given the ones before it, with O(1) work and no heap.
GarchFit
A fitted GARCH(1,1) model.
GarchSpec
A GARCH(1,1) model at its current state.
Innovation
The one-step-ahead prediction error for one observation.
MstlArima
A series decomposed by MSTL, with an ARIMA model of its seasonally adjusted part.
MstlFilter
A streaming MSTL plus ARIMA forecaster: a Filter with room for R states on the seasonally adjusted series, and room for L seasonal values, the sum of the periods.
MstlForecast
Forecasts with central prediction intervals, one entry per step ahead.
MultiDecomposition
The components of an MSTL decomposition: values = sum(seasonal) + trend + remainder.
NormalGamma
The Normal-Gamma prior of a segment’s mean mu and precision lambda: lambda ~ Gamma(shape, rate) and mu | lambda ~ N(mean, 1 / (precision lambda)).
OnlineAr
An AR(M) predictor that learns its coefficients online (ARMA-ONS), inline with no heap.
OnlineArOptions
The tuning of an OnlineAr.
OnlineVar
A streaming VAR filter for K series with room for D regressors (D >= K p + 1), stored inline with no heap.
PeriodCandidate
A seasonal period candidate of find_period.
Pmm2Fit
A PMM2 fit and the innovation moments it used.
Refit
The result of a refit: the new model and how well it fits the window.
RefitOptions
How ArimaSpec::refit estimates.
Refitter
A heap-free refitter with its buffers inline: SCRATCH values of scratch and room for COEFFICIENTS coefficients.
Seasonal
The seasonal part (P, D, Q, s) of a seasonal ARIMA model.
TestResult
A test statistic with its p-value.
Theta
The Theta method to fit, optionally on a seasonal series.
ThetaFilter
A streaming Theta filter with room for M seasonal indices, stored inline with no heap.
ThetaFit
A fitted Theta method.
ThetaSpec
A Theta model at its current state.
TimeSeries
TsbFilter
The method of Teunter, Syntetos and Babai (TSB) on a stream of demand values, with no heap.
Var
A VAR(p) model to fit, optionally with exogenous regressors (VARX).
VarFit
A fitted VAR or VARX model.
VarForecast
The forecasts of a VarFit.
VarOrders
The lag orders each criterion picks, as statsmodels’ select_order(maxlags).
VarSpec
A VAR(p) model on k series.

Enums§

Criterion
The information criterion that ranks candidate models.
CrostonVariant
Which bias correction a CrostonFilter applies to Croston’s ratio.
Estimator
Defines the estimator to use.
Family
A forecasting family select_family compares.
FilterError
Why a model could not be turned into a filter.
FitError
Why a model could not be fitted.
Form
How an ETS component combines: added to the forecast, or multiplying it.
FourierError
Why Fourier regressors could not be generated.
KpssNull
The null hypothesis of a kpss test.
Method
How Arima::fit estimates the coefficients.
MstlFilterError
Why an MstlFilter could not be built.
OnlineArError
Why an OnlineAr could not be built.
Shift
The direction of a shift that Cusum reports.
TimeSeriesError
Trend
The trend of an ETS model.

Constants§

MAX_SEASONAL_PERIODS
The most seasonal periods an MstlFilter holds.
MSTL_ITERATIONS
statsmodels’ default number of MSTL passes.
SEASONAL_STRENGTH_THRESHOLD
The seasonal strength above which a series counts as seasonal: the threshold of R’s nsdiffs with its default seasonal-strength test, and of coreforecast.

Functions§

accuracy
Measures the accuracy of forecast against actual, with the MASE scaled by the training values training and season length period, as R’s accuracy(forecast, actual) does for a forecast of training.
acorr
Calculates the autocorrelation coefficient with a given lag.
acov
Calculates the autocovariance with a given lag.
box_cox
The Box–Cox transform of every value: expm1(lambda ln y) / lambda, or ln y at lambda = 0, as scipy’s special.boxcox.
box_cox_lambda
The lambda that maximises the Box–Cox log-likelihood of values, as scipy’s stats.boxcox(values) (and statsmodels’ MSTL(lmbda="auto")) chooses it.
burg
Fits an AR(p) model with Burg’s method.
corr
Calculates the correlation coefficient.
cov
Calculates the covariance.
cross_validation_errors
The forecast errors from every origin of y, as R’s tsCV(y, forecastfunction, h = horizon, initial = initial).
difference
Differences x d times: each pass replaces the series with x[t + 1] - x[t].
find_period
Ranks seasonal period candidates of values up to max_period, strongest first.
fourier
Fourier regressors for several seasonal periods, rows rows from time t0, row-major.
fourier_columns
The number of regressor columns of k harmonics at period: 2k, or 2k - 1 when 2k == period, because the Nyquist sine is left out.
fourier_row
Writes the Fourier regressors of k harmonics at period for time t into row.
hannan_rissanen
Hannan–Rissanen estimates of an ARMA(p, q) model for the series x, which is demeaned first.
innovations
Runs the filter over diff(y, d) - mean from the stationary start and returns every innovation: y.len() - d of them, or none if y is shorter.
innovations_exog
Like innovations, for a model with regressors: regressors holds one row of spec.exog.len() values per observation, row-major, and the ARIMA part models y - x . beta. Matches statsmodels ARIMA(y, exog=X, ...) with simple differencing.
integrate
Undoes difference: turns values on the d-times differenced scale back into values that continue history on the original scale.
jarque_bera
The Jarque–Bera test for normality of residuals.
kpss
The KPSS test (Kwiatkowski, Phillips, Schmidt & Shin 1992) of stationarity.
kpss_lags
statsmodels’ “legacy” KPSS lag choice, ceil(12 (n / 100)^(1/4)), capped at n - 1.
kpss_short_lags
The short KPSS lag rule, trunc(4 (n / 100)^(1/4)), capped at n - 1.
ljung_box
The Ljung–Box test for autocorrelation in residuals up to lags.
loglike
The exact Gaussian log-likelihood of y under the model.
loglike_exog
Like loglike, for a model with regressors; regressors as in innovations_exog.
mstl
MSTL with statsmodels’ defaults: periods in ascending order, the seasonal smoother of the i-th period (from 1) 7 + 4i, non-robust STL, and iterate passes (one for a single period).
ndiffs
The number of differences that make x level-stationary by KPSS, at most max_d.
normal_quantile
The standard normal quantile z with P(Z <= z) = p, the inverse of the normal CDF.
nsdiffs
The number of seasonal differences, at most max_seasonal_d, by seasonal strength.
pacf
Calculates the partial autocorrelation for lags 0..=max_lags.
select_family
Picks the forecasting family with the lowest out-of-sample error on y, and forecasts the next horizon values with it.
select_var_order
Picks the VAR lag order of y (row-major, k values per row) up to max_lags, as statsmodels’ VAR(y, exog).select_order(max_lags): every order from 0 is fitted on the same rows, those after the first max_lags, and each criterion picks its lowest, the smallest order on a tie.
stl
STL with statsmodels’ defaults: a seasonal smoother of 7, the trend and low-pass windows derived from period, degree-1 LOESS throughout, and five non-robust inner passes.
stl_with
STL like stl, with the seasonal smoother seasonal_window instead of 7.
trend_regressors
The trend regressors of trend_row for rows consecutive times from t0, row-major with knots.len() + 1 columns. Pass them to Arima::fit_exog with t0 = 0, and the rows from t0 = n on to the forecasts: the trend continues at its last slope.
trend_row
Writes the trend regressors of time t into row: t itself, then the hinge max(0, t - s) of each changepoint s of knots, in order. The function needs no heap, so a device can build the row of each new value as it arrives.
yule_walker
Fits an AR(p) model by solving the Yule–Walker equations.