anofox-forecast
Technical depth grading and code quality analysis powered by pmat
Time series forecasting library for Rust.
Provides 50+ forecasting models, 76+ statistical features, automatic model selection, ensemble methods, seasonality decomposition, changepoint detection, anomaly detection, hierarchical reconciliation, and model serialization.
Use Cases
Need to run this on 10GB of data? Use our DuckDB extension for SQL-native forecasting at scale.
Need to use this in a React Dashboard? Use our npm package for WebAssembly-powered forecasting in the browser.
import init from '@sipemu/anofox-forecast';
await ;
const ts = ;
const model = ;
model.;
const forecast = model.;
console.log;
Features
Forecasting
-
Forecasting Models (50+)
- ARIMA, SARIMA, and AutoARIMA with automatic order selection
- Exponential Smoothing: SES, Holt's Linear, Holt-Winters, SeasonalES
- ETS (Error-Trend-Seasonal) state-space framework with AutoETS
- Baseline methods: Naive, Seasonal Naive, Random Walk with Drift, SMA, Window Average
- Theta family: Theta, Optimized Theta, Dynamic Theta, AutoTheta
- Intermittent demand: Croston, ADIDA, TSB, IMAPA
- TBATS/AutoTBATS for complex seasonality
- MFLES (Multiple Frequency Locally Estimated Scatterplot)
- MSTL-based forecasting with configurable trend/seasonal methods and pre-regression exogenous support
- GARCH for volatility modeling
- VAR (Vector Autoregression) for multivariate forecasting with Granger causality
- Kalman filter / state-space models (local level, local linear trend, custom)
- Exogenous regressor support across model families with OLS coefficient extraction (
exog_coefficients()) FeatureGenerator: deterministic regressor generation (Fourier harmonics, day-of-week, month-of-year, quarter, holiday indicators, cyclical sin/cos encoding, binary calendar indicators)RegressionForecaster:anofox-regressionbackends asForecaster— 11 regression backends (OLS, Ridge, ElasticNet, Quantile, WLS, RLS, Tweedie, Poisson, BLS, NNLS, Dynamic), configurable trend/seasonal/structural features, recursive multi-step prediction, auto-lag selection (BIC/AIC), differencing and seasonal differencing
-
Automatic Model Selection
AutoForecast: Unified selection across ARIMA, ETS, and Theta families (parallel withparallelfeature)AutoEnsemble: Automatic ensemble of top-K best models- Selection by cross-validation error
- Builder API:
AutoForecast::builder().seasonal_period(12).include_arima(true).build() fit_predict()convenience method on all models
-
Ensemble Methods
- Mean, Median, Weighted MSE, InverseAIC, Stacking, HorizonAdaptive combination strategies
- Widest-envelope interval combination for ensemble prediction intervals
- Automatic ensemble construction from model registry
ensemble_best_k(): Auto-select top-k models by holdout performance
-
Hierarchical Forecasting
HierarchyTree: Define parent-children structure for grouped series- Bottom-up, top-down, MiddleOut, MinTrace OLS, and MinTrace Shrink (Ledoit-Wolf) reconciliation
- Ensures coherent forecasts across hierarchical levels
Analysis & Decomposition
-
Seasonality & Decomposition
SeasonalComponent/TrendComponenttraits — composable, dual-purpose (standalone + feature extraction)- STL (Seasonal-Trend decomposition using LOESS) with
StlBuilderfor ergonomic configuration - MSTL (Multiple Seasonal-Trend decomposition) for complex seasonality, with pre-regression exogenous regressor support
- Prophet-style Fourier seasonality (
FourierSeasonality) with flexible harmonic modeling - Dummy (one-hot) seasonality (
DummySeasonality) — captures arbitrary seasonal shapes without smoothness assumptions - Seasonal differencing (
SeasonalDifference) — standalone transform with strength/variance-reduction features - Hodrick-Prescott filter (
HodrickPrescottFilter) — smooth trend extraction with cycle decomposition - Piecewise linear trend (
PiecewiseLinearTrend) — PELT-based changepoint detection + per-segment regression - Polynomial trend (
PolynomialTrend) — degree 1-3, Vandermonde + Cholesky solve - Exponential trend (
ExponentialTrend) — log-linear regression for growth/decay - Logistic trend (
LogisticTrend) — S-curve fitting with auto or fixed capacity - Theil-Sen trend (
TheilSenTrend) — robust median-of-pairwise-slopes estimator AutoTrend— automatic selection of best trend component via AICc/BICAutoSeasonal— automatic selection of best seasonal component via AICc/BICRecency— fit on recent data only (last N, last X%, full, or Auto via PELT changepoint detection) for trend-aware forecastingTimeSeries::seasonal_strength()/trend_strength()— quick strength assessment- Convenience:
deseasonalize(),detrend(),seasonal_adjust(),recompose()
-
Time Series Feature Extraction (76+ features)
- Basic statistics (mean, variance, quantiles, energy, etc.)
- Distribution features (skewness, kurtosis, symmetry)
- Autocorrelation and partial autocorrelation
- Entropy features (approximate, sample, permutation, binned, Fourier)
- Complexity measures (C3, CID, Lempel-Ziv)
- Trend analysis and stationarity tests (ADF, KPSS)
- Automated feature selection (variance threshold, correlation filter, top-K)
-
Spectral Analysis
- Welch's periodogram for reduced variance spectral estimation
- For comprehensive periodicity detection, see fdars
-
Changepoint Detection
- PELT algorithm with O(n) average complexity
- Builder API:
Pelt::new(CostFunction::L2).min_size(5).penalty(5.0).detect(&data) - Multiple cost functions: L1, L2, Normal, Poisson, LinearTrend, MeanVariance, Cusum
-
Anomaly Detection & Outlier Handling
- Statistical methods (IQR, z-score, modified z-score)
- Automatic threshold selection
TimeSeries::with_outliers_replaced()— automatic outlier replacement with local median
Evaluation & Uncertainty
-
Model Comparison & Evaluation
compare_models(): Side-by-side model evaluation with timingcompare_registry(): Compare all registered models at oncefit_all_and_compare(): Fit all registry models, rank by holdout accuracycross_validate_all(): CV all registry models at once with aggregated metrics- Accuracy metrics: MAE, MSE, RMSE, MAPE, sMAPE, MASE, WAPE, MDA, Theil's U, RMSSE, WRMSSE, MSIS, coverage, skill scores
ForecastMetrics::compute(): All 10 core metrics in a single call- Time series cross-validation: backward-anchored folds, n_folds-driven, expanding/rolling windows, gap/purge/embargo
rolling_forecast(): Walk-forward evaluation with rolling/expanding windows- Streaming CV aggregation with early stopping (
cross_validate_early_stop()) ModelDiagnostics: Ljung-Box, Jarque-Bera, Breusch-Pagan residual diagnosticsIntermittentDiagnostics: Syntetos-Boylan demand classification (Smooth/Erratic/Intermittent/Lumpy)AidAnalyzer: Automatic Identification of Demand — distribution fitting, demand type classification, and per-observation anomaly detection (stockouts, lifecycle events, outliers)
-
Probabilistic Postprocessing
- Conformal Prediction: Distribution-free intervals with coverage guarantees
- Per-horizon-step conformal: separate interval widths per forecast step (tighter at h=1, wider at h=12)
- Binned Conformal Prediction: Heteroscedastic intervals — bins residuals by predicted magnitude for wider intervals where uncertainty is larger
- Bootstrap Prediction Intervals: Model-agnostic residual resampling with cumulative error paths (IID and block bootstrap)
- Historical Simulation: Non-parametric empirical error distribution
- Normal Predictor: Gaussian error assumption baseline
- IDR: Isotonic Distributional Regression (state-of-the-art calibration)
- QRA: Quantile Regression Averaging for ensemble combining
- Backtesting: Rolling/expanding window evaluation with horizon-aware calibration
-
Bootstrap Confidence Intervals
- Residual bootstrap and block bootstrap methods
- Empirical confidence intervals for any model
- Configurable sample size and reproducibility
-
Forecast Constraints
NonNegative,LowerBound,UpperBound,Bounds,IntegerRound,Custom- Convenience methods:
forecast.non_negative(),.clamp(lo, hi),.round_to_integer() - Constraints apply to point forecasts and prediction intervals
-
Forecast Explainability
Explainabletrait withForecastExplanation(level, trend, seasonal, residual, named components)- Implemented for ETS, Theta, and MSTL models
- Components sum to forecast values for verification
Data Processing & Pipeline
-
Parallelism
compare_models()/compare_registry(): Parallel model comparison- Cross-validation folds run in parallel when
parallelfeature is enabled - Bootstrap sampling uses
par_iterwhenparallelis enabled
-
Data Transformations
Pipeline: composable transform chains around anyForecaster—Pipeline::builder().transform(BoxCoxTransform::auto()).transform(DifferenceTransform::new(1)).model(Box::new(Naive::new())).build()Transformtrait:DifferenceTransform,SeasonalDifferenceTransform,BoxCoxTransform,ScaleTransform,LogTransform- Scaling: standardization, min-max, robust scaling
- Box-Cox transformation with automatic lambda selection
- Window functions: rolling mean, std, min, max, median
- Exponential weighted moving averages
-
Missing Value Imputation
- Policy-based: Drop, Fill, ForwardFill, BackwardFill, FillMean, FillMedian, Interpolate
- Advanced: moving average imputation, seasonal median imputation
- Convenience: forward-backward fill, regressor imputation
- Metadata: missing mask, per-dimension missing counts
-
TimeSeries Temporal Aggregation
aggregate(period, method)— Sum, Mean, Median, First, Last, Min, Maxdownsample(factor)— decimation with timestamp preservationupsample(factor, method)— Linear, ForwardFill, BackwardFill, Zero interpolationsliding_window_aggregate(window, step, method)— configurable sliding windows
Persistence & Interoperability
-
Model Serialization (optional
serdefeature)- Save/load models to JSON with
to_json()/from_json() - Binary serialization with
to_bincode()/from_bincode()for compact storage - File persistence with
save_to_file()/load_from_file() - Round-trip serialization for all major model families
- Save/load models to JSON with
-
Model Warm-Starting
ETS::with_initial_states()— start from pre-fitted level/trend/seasonal statesSES::with_alpha()— use pre-fitted smoothing parameterARIMA::with_coefficients()— use pre-fitted AR/MA coefficientsTheta::with_theta_value()— use specified theta parameterForecaster::fitted_params()— extract fitted parameters for transfer
Installation
Add this to your Cargo.toml:
[]
= "0.4"
Optional Features
[]
# Parallel AutoARIMA (4-8x speedup via rayon, opt-in for embedding contexts like DuckDB)
= { = "0.4", = ["parallel"] }
# Model serialization (save/load to JSON)
= { = "0.4", = ["serde"] }
# Probabilistic postprocessing (conformal, IDR, QRA — enabled by default)
= { = "0.4", = false } # to disable
| Feature | Default | Description |
|---|---|---|
postprocess |
Yes | Conformal prediction, IDR, QRA, historical simulation |
parallel |
No | Rayon-based parallelism for AutoARIMA, AutoForecast, bootstrap, and cross-validation (not available on WASM) |
serde |
No | JSON and bincode serialization/deserialization for models |
Quick Start
Creating a Time Series
use *;
use ;
// Create timestamps
let timestamps: =
.map
.collect;
// Create values
let values: = .map.collect;
// Build the time series
let ts = builder
.timestamps
.values
.build?;
Automatic Model Selection
use *;
use AutoForecast;
// Automatically selects the best model across ARIMA, ETS, and Theta
let mut model = new;
model.fit?;
let forecast = model.predict?;
println!;
ARIMA Forecasting
use *;
use ARIMA;
// Create and fit an ARIMA(1,1,1) model
let mut model = ARIMAnew;
model.fit?;
// Generate forecasts with 95% confidence intervals
let forecast = model.predict_with_intervals?;
println!;
println!;
println!;
Holt-Winters Forecasting
use HoltWinters;
// Create Holt-Winters with additive seasonality (period = 12)
let mut model = additive;
model.fit?;
let forecast = model.predict?;
Model Comparison
use ;
use ;
// Compare all registered models side-by-side
let config = default;
let table = compare_registry?;
println!;
Feature Extraction
use ;
let values = ts.values;
let m = mean;
let v = variance;
let s = skewness;
let ae = approximate_entropy?;
println!;
STL Decomposition
use Stl;
// Decompose with seasonal period of 12
let stl = new?;
let decomposition = stl.decompose?;
println!;
println!;
println!;
Transform Pipeline
use ;
use ;
use Naive;
// Chain transforms around any model — Pipeline itself implements Forecaster
let mut pipeline = builder
.transform
.transform
.model
.build;
pipeline.fit?;
let forecast = pipeline.predict?;
Exogenous Regressors
use FeatureGenerator;
// Generate deterministic regressors from timestamps
let gen = new
.fourier // Weekly Fourier terms
.day_of_week // Day-of-week indicators
.holiday;
gen.add_to; // Attach features to TimeSeries
let mut model = ARIMAnew;
model.fit?;
// Inspect OLS pre-regression coefficients
if let Some = model.exog_coefficients
Changepoint Detection
use ;
let pelt = new?;
let changepoints = pelt.detect?;
println!;
Spectral Analysis
use welch_periodogram;
// Welch's periodogram with overlapping windows
let psd = welch_periodogram;
// Find dominant period
if let Some = psd.iter.max_by
For comprehensive periodicity detection (ACF, FFT, Autoperiod, CFD-Autoperiod, SAZED), see the fdars crate.
Probabilistic Postprocessing
use ;
// Historical forecasts and actuals for calibration
let train_forecasts = from_values;
let train_actuals = vec!;
// Create a conformal predictor with 90% coverage
let processor = conformal;
// Backtest with horizon-aware calibration
let config = new
.initial_window
.step
.horizon
.horizon_aware;
let results = processor.backtest?;
println!;
// Train calibrated model and predict
let trained = processor.train?;
let new_forecasts = from_values;
let intervals = processor.predict_intervals?;
println!;
println!;
API Reference
Core Types
| Type | Description |
|---|---|
TimeSeries |
Main data structure for univariate/multivariate time series |
Forecast |
Prediction results with optional confidence intervals |
Forecaster |
Trait implemented by all forecasting models (exog_coefficients() for OLS inspection) |
Pipeline |
Composable transform → model chain, itself implements Forecaster |
FeatureGenerator |
Deterministic regressor generation (Fourier, DOW, MOY, quarter, holidays) |
AccuracyMetrics |
Model evaluation metrics (MAE, MSE, RMSE, MAPE, etc.) |
Forecasting Models
| Family | Models |
|---|---|
| Auto Selection | AutoForecast, AutoEnsemble |
| ARIMA | ARIMA, SARIMA, AutoARIMA |
| Exponential Smoothing | SES, Holt, HoltWinters, SeasonalES, ETS, AutoETS |
| Theta | Theta, OptimizedTheta, DynamicTheta, AutoTheta |
| Baseline | Naive, Mean, SeasonalNaive, RandomWalkWithDrift, SMA, WindowAverage, SeasonalWindowAverage |
| Intermittent | Croston, TSB, ADIDA, IMAPA |
| Complex Seasonality | TBATS, AutoTBATS, MFLES, MSTLForecaster |
| Volatility | GARCH |
| Multivariate | VAR (Vector Autoregression) |
| State-Space | KalmanFilter, StateSpaceModel (local level, local linear trend) |
| Ensemble | Ensemble (Mean, Median, Weighted MSE, InverseAIC, Stacking, HorizonAdaptive) |
| Regression | RegressionForecaster (OLS, Ridge, ElasticNet, Quantile, WLS, RLS, Tweedie, Poisson, BLS, Dynamic) |
| Hierarchical | HierarchyTree (BottomUp, TopDown, MiddleOut, MinTraceOls, MinTraceShrink) |
Utilities
| Function / Type | Description |
|---|---|
compare_models() |
Compare forecasters on the same data with timing |
compare_registry() |
Compare all registered models at once |
cross_validate() |
Time series cross-validation (parallel with parallel feature) |
cross_validate_early_stop() |
CV with convergence-based early stopping |
rolling_forecast() |
Walk-forward evaluation with rolling/expanding windows |
StreamingCVAggregator |
Online metric aggregation using Welford's algorithm |
bootstrap_forecast() |
Bootstrap confidence intervals for any model |
diagnose_residuals() |
Unified residual diagnostics (Ljung-Box, DW, Jarque-Bera) |
ModelDiagnostics |
Comprehensive diagnostics: Ljung-Box, Jarque-Bera, Breusch-Pagan |
IntermittentDiagnostics |
Syntetos-Boylan demand classification with model recommendations |
AidAnalyzer |
Automatic Identification of Demand: distribution fitting, anomaly detection |
rmsse() / wrmsse() |
Root Mean Squared Scaled Error and Weighted RMSSE (M5 competition metric) |
bias() / periods_in_stock() |
Signed bias and inventory-focused PIS metric |
ForecastMetrics::compute() |
All 10 metrics in one call (MAE through Theil's U) |
fit_all_and_compare() |
Fit all registry models, rank by holdout accuracy |
cross_validate_all() |
CV all registry models with aggregated metrics |
ensemble_best_k() |
Auto-select top-k models into an ensemble |
SeasonalComponent / TrendComponent |
Composable traits for seasonal/trend components (standalone + features) |
DummySeasonality |
One-hot seasonal encoding — arbitrary seasonal shapes |
SeasonalDifference |
Standalone seasonal differencing with strength/variance features |
HodrickPrescottFilter |
Smooth trend extraction with cycle decomposition |
PiecewiseLinearTrend |
PELT-based piecewise linear trend with per-segment regression |
PolynomialTrend |
Polynomial trend (degree 1-3) with Cholesky solve |
ExponentialTrend |
Log-linear exponential growth/decay trend |
LogisticTrend |
Logistic S-curve trend with auto/fixed capacity |
TheilSenTrend |
Robust Theil-Sen median-slope trend estimator |
AutoTrend |
Automatic best-trend selection via AICc/BIC/holdout |
AutoSeasonal |
Automatic best-seasonal selection via AICc/BIC |
Recency |
Fit on recent data only (Window, Fraction, Full, Auto via PELT) |
BinnedConformalPredictor |
Heteroscedastic prediction intervals binned by predicted magnitude |
RegressionForecaster |
Multi-backend regression: OLS, Ridge, ElasticNet, Quantile, WLS, RLS, Tweedie, Poisson, BLS, Dynamic |
RegressionBackend |
Backend selection enum with convenience constructors (ridge(), quantile(), wls_decay(), etc.) |
RegressionFeatures |
Feature builder for regression models (trend, seasonal, lags, structural, exog) |
FeatureSafety |
Feature leakage classification: Deterministic, DataDependent, Structural, External |
StructuralFeature |
Trait for forward-filled features during prediction (changepoints, outlier indicators) |
ChangepointFeature |
Structural feature for regime indicators (StepFunctions, RegimeIndex, CumulativeCount) |
Pipeline / PipelineBuilder |
Composable transform → model chains (BoxCox → Difference → Model → inverse) |
Transform trait |
Reversible transforms: DifferenceTransform, SeasonalDifferenceTransform, BoxCoxTransform, ScaleTransform, LogTransform |
FeatureGenerator |
Deterministic feature generation: fourier(), day_of_week(), month_of_year(), quarter(), holiday() |
OLSResult / exog_coefficients() |
Inspect OLS pre-regression coefficients (intercept, betas, regressor names) |
deseasonalize() / seasonal_adjust() |
Remove seasonal component from data or TimeSeries |
select_features() |
Automated feature selection (variance, correlation, top-K) |
to_json() / from_json() |
Serialization for models, Forecast, and TimeSeries (requires serde feature) |
to_bincode() / from_bincode() |
Binary serialization (requires serde feature) |
Feature Categories
| Category | Examples |
|---|---|
| Basic | mean, variance, minimum, maximum, quantile |
| Distribution | skewness, kurtosis, variation_coefficient |
| Autocorrelation | autocorrelation, partial_autocorrelation |
| Entropy | approximate_entropy, sample_entropy, permutation_entropy |
| Complexity | c3, cid_ce, lempel_ziv_complexity |
| Trend | linear_trend, adf_test, ar_coefficient, hp_trend_strength, piecewise_n_segments |
| Seasonality | dummy_seasonal_strength, seasonal_diff_strength, seasonal_diff_variance_reduction |
| Selection | select_features, rank_features |
Postprocessing Types
| Type | Description |
|---|---|
PostProcessor |
Unified API for all postprocessing methods |
ConformalPredictor |
Distribution-free prediction intervals |
BinnedConformalPredictor |
Heteroscedastic intervals — bins by predicted magnitude |
HistoricalSimulator |
Empirical error distribution |
IDRPredictor |
Isotonic Distributional Regression |
QRAPredictor |
Quantile Regression Averaging |
Examples
48 runnable examples covering all major features, each with a companion .md description. See examples/README.md for the full categorized index.
Guides
- Model Selection Guide — Which model to use for your data
Dependencies
- chrono - Date and time handling
- trueno - Linear algebra operations
- anofox-statistics - Statistical hypothesis tests (DM, MCS, SPA)
- statrs - Statistical distributions and functions
- thiserror - Error handling
- rand - Random number generation
- rustfft - Fast Fourier Transform for spectral analysis
Acknowledgments
The postprocessing module is a Rust port of PostForecasts.jl. Feature extraction is inspired by tsfresh. Forecasting models are validated against StatsForecast by Nixtla. See THIRDPARTY_NOTICE.md for full attribution and references to the research papers that inspired this implementation.
License
MIT License - see LICENSE for details.