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. Impliesalloc.libm: floating-point functions from the pure-Rustlibmcrate, for targets withoutstd.alloc: the functions that return aVec, such aspacf,difference,yule_walkerandburg. 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
accuracyreports 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.
- Arima
Spec - The parameters of a seasonal ARIMA(p, d, q)(P, D, Q, s) model.
- Arma
Coefficients - AR and MA coefficients of an ARMA(p, q) model.
- Auto
Arima - 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 byAICcby 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
Rrun-length hypotheses, stored inline with no heap;O(R)work per value. - Conformal
- Conformal intervals for forecasts up to
Hsteps ahead, calibrated on the lastNerrors per horizon. It lives inline with no heap. - Croston
Filter - 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
Mseasonal states, stored inline with no heap. - EtsFit
- A fitted ETS model.
- EtsSpec
- An ETS model with its smoothing parameters and current states.
- Family
Selection - The outcome of
select_family. - Filter
- A streaming ARIMA filter with room for
Rstates andMregressors, stored inline with no heap. - Fitted
- A fitted seasonal ARIMA model.
- Fixed
- Which whole parts of a model
Arima::fit_fixedkeeps at their start values. - Fourier
Fit - The best model of an
AutoArima::fit_fouriersearch. - Garch
- GARCH(1,1) to fit to a zero-mean series.
- Garch
Filter - A streaming GARCH(1,1) filter: the conditional variance of each value given the ones
before it, with
O(1)work and no heap. - Garch
Fit - A fitted GARCH(1,1) model.
- Garch
Spec - A GARCH(1,1) model at its current state.
- Innovation
- The one-step-ahead prediction error for one observation.
- Mstl
Arima - A series decomposed by MSTL, with an ARIMA model of its seasonally adjusted part.
- Mstl
Filter - A streaming MSTL plus ARIMA forecaster: a
Filterwith room forRstates on the seasonally adjusted series, and room forLseasonal values, the sum of the periods. - Mstl
Forecast - Forecasts with central prediction intervals, one entry per step ahead.
- Multi
Decomposition - The components of an MSTL decomposition:
values = sum(seasonal) + trend + remainder. - Normal
Gamma - The Normal-Gamma prior of a segment’s mean
muand precisionlambda:lambda ~ Gamma(shape, rate)andmu | lambda ~ N(mean, 1 / (precision lambda)). - Online
Ar - An AR(
M) predictor that learns its coefficients online (ARMA-ONS), inline with no heap. - Online
ArOptions - The tuning of an
OnlineAr. - Online
Var - A streaming VAR filter for
Kseries with room forDregressors (D >= K p + 1), stored inline with no heap. - Period
Candidate - 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.
- Refit
Options - How
ArimaSpec::refitestimates. - Refitter
- A heap-free refitter with its buffers inline:
SCRATCHvalues of scratch and room forCOEFFICIENTScoefficients. - Seasonal
- The seasonal part
(P, D, Q, s)of a seasonal ARIMA model. - Test
Result - A test statistic with its p-value.
- Theta
- The Theta method to fit, optionally on a seasonal series.
- Theta
Filter - A streaming Theta filter with room for
Mseasonal indices, stored inline with no heap. - Theta
Fit - A fitted Theta method.
- Theta
Spec - A Theta model at its current state.
- Time
Series - 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
kseries.
Enums§
- Criterion
- The information criterion that ranks candidate models.
- Croston
Variant - Which bias correction a
CrostonFilterapplies to Croston’s ratio. - Estimator
- Defines the estimator to use.
- Family
- A forecasting family
select_familycompares. - Filter
Error - 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.
- Fourier
Error - Why Fourier regressors could not be generated.
- Kpss
Null - The null hypothesis of a
kpsstest. - Method
- How
Arima::fitestimates the coefficients. - Mstl
Filter Error - Why an
MstlFiltercould not be built. - Online
ArError - Why an
OnlineArcould not be built. - Shift
- The direction of a shift that
Cusumreports. - Time
Series Error - Trend
- The trend of an ETS model.
Constants§
- MAX_
SEASONAL_ PERIODS - The most seasonal periods an
MstlFilterholds. - 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
nsdiffswith its default seasonal-strength test, and of coreforecast.
Functions§
- accuracy
- Measures the accuracy of
forecastagainstactual, with the MASE scaled by the training valuestrainingand season lengthperiod, as R’saccuracy(forecast, actual)does for a forecast oftraining. - 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, orln yatlambda = 0, as scipy’sspecial.boxcox. - box_
cox_ lambda - The
lambdathat maximises the Box–Cox log-likelihood ofvalues, as scipy’sstats.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’stsCV(y, forecastfunction, h = horizon, initial = initial). - difference
- Differences
xdtimes: each pass replaces the series withx[t + 1] - x[t]. - find_
period - Ranks seasonal period candidates of
valuesup tomax_period, strongest first. - fourier
- Fourier regressors for several seasonal periods,
rowsrows from timet0, row-major. - fourier_
columns - The number of regressor columns of
kharmonics atperiod:2k, or2k - 1when2k == period, because the Nyquist sine is left out. - fourier_
row - Writes the Fourier regressors of
kharmonics atperiodfor timetintorow. - hannan_
rissanen - Hannan–Rissanen estimates of an ARMA(
p,q) model for the seriesx, which is demeaned first. - innovations
- Runs the filter over
diff(y, d) - meanfrom the stationary start and returns every innovation:y.len() - dof them, or none ifyis shorter. - innovations_
exog - Like
innovations, for a model with regressors:regressorsholds one row ofspec.exog.len()values per observation, row-major, and the ARIMA part modelsy - x . beta. Matches statsmodelsARIMA(y, exog=X, ...)with simple differencing. - integrate
- Undoes
difference: turns values on thed-times differenced scale back into values that continuehistoryon 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 atn - 1. - kpss_
short_ lags - The short KPSS lag rule,
trunc(4 (n / 100)^(1/4)), capped atn - 1. - ljung_
box - The Ljung–Box test for autocorrelation in
residualsup tolags. - loglike
- The exact Gaussian log-likelihood of
yunder the model. - loglike_
exog - Like
loglike, for a model with regressors;regressorsas ininnovations_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, anditeratepasses (one for a single period). - ndiffs
- The number of differences that make
xlevel-stationary by KPSS, at mostmax_d. - normal_
quantile - The standard normal quantile
zwithP(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 nexthorizonvalues with it. - select_
var_ order - Picks the VAR lag order of
y(row-major,kvalues per row) up tomax_lags, as statsmodels’VAR(y, exog).select_order(max_lags): every order from 0 is fitted on the same rows, those after the firstmax_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 smootherseasonal_windowinstead of 7. - trend_
regressors - The trend regressors of
trend_rowforrowsconsecutive times fromt0, row-major withknots.len() + 1columns. Pass them toArima::fit_exogwitht0 = 0, and the rows fromt0 = non to the forecasts: the trend continues at its last slope. - trend_
row - Writes the trend regressors of time
tintorow:titself, then the hingemax(0, t - s)of each changepointsofknots, 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.