Anofox Forecast Extension - API Reference

July 10, 2026 · View on GitHub

Complete function and macro reference for time series analysis and forecasting in DuckDB

Version: 0.4.0 DuckDB Version: >= v1.5.1 Forecasting Engine: anofox-fcst-core (Rust)


Overview

The Anofox Forecast extension brings comprehensive time series analysis and forecasting capabilities directly into DuckDB. It enables analysts and data scientists to perform sophisticated time series operations using familiar SQL syntax, without needing external tools or data movement.

Key Benefits:

  • SQL-native: All operations are expressed as SQL functions and macros
  • High Performance: Core algorithms implemented in Rust for speed and safety
  • Comprehensive: 32 forecasting models, 117 features, seasonality detection, changepoint detection
  • Flexible API: Three API styles to fit different workflows

All computations are performed by the anofox-fcst-core library, implemented in Rust.

Quick Start

-- Load the extension
LOAD anofox_forecast;

-- Generate forecasts for multiple products
SELECT * FROM ts_forecast_by('sales', product_id, date, quantity, 'AutoETS', 30, '1d');

-- Analyze seasonality
SELECT ts_detect_periods(LIST(quantity ORDER BY date)) FROM sales GROUP BY product_id;

-- Compute time series statistics
SELECT * FROM ts_stats('sales', product_id, date, quantity);

API Variants

The extension provides three API styles to accommodate different use cases:

1. Scalar Functions (Array-Based)

Low-level functions that operate on arrays. Composable with GROUP BY and LIST().

SELECT product_id, ts_stats(LIST(value ORDER BY date)) AS stats
FROM sales GROUP BY product_id;

2. Table Macros (Table-Based)

High-level macros that operate directly on tables. Column names are passed as identifiers (unquoted).

SELECT * FROM ts_forecast_by('sales', product_id, date, value, 'AutoETS', 12, '1d');

3. Aggregate Functions

Aggregate functions for use with custom GROUP BY patterns.

SELECT product_id, ts_forecast_agg(ts, value, 'ETS', 12, MAP{}) AS forecast
FROM sales GROUP BY product_id;

Parameter Syntax (v0.4.0+)

Table macros support both MAP and STRUCT syntax for parameters:

-- STRUCT allows mixed types (recommended)
SELECT * FROM ts_backtest_auto('sales', id, date, value, 7, 3, '1d',
    {'method': 'Naive', 'gap': 2, 'clip_horizon': true});

-- MAP requires homogeneous string values (legacy)
SELECT * FROM ts_backtest_auto('sales', id, date, value, 7, 3, '1d',
    MAP{'method': 'Naive', 'gap': '2', 'clip_horizon': 'true'});

Function Naming Conventions

All functions are available with two naming patterns:

  • ts_* - Short form (e.g., ts_stats, ts_mae)
  • anofox_fcst_ts_* - Prefixed form (e.g., anofox_fcst_ts_stats)

Both forms are identical in functionality.


API Reference by Category

Core Documentation

CategoryDescriptionDocumentation
API Design GuideNaming conventions and patterns00-api-design.md
Table MacrosHigh-level API overview01-table-macros.md
HierarchicalMulti-key hierarchy functions02-hierarchical.md
StatisticsTime series statistics and data quality03-statistics.md
Data PreparationFiltering, cleaning, imputation04-data-preparation.md
Period DetectionPeriod detection and seasonality05-period-detection.md
DecompositionSeasonal decomposition and classification05a-decomposition.md
Peak DetectionPeak detection and timing analysis05b-peak-detection.md
Changepoint DetectionStructural break detection06-changepoint-detection.md
Forecasting32 forecasting models07-forecasting.md
Cross-ValidationBacktesting and CV functions08-cross-validation.md
Evaluation MetricsForecast accuracy metrics09-evaluation-metrics.md
Feature Extraction117 tsfresh-compatible features20-feature-extraction.md
Conformal PredictionDistribution-free prediction intervals11-conformal-prediction.md

Quick Reference

Most Common Functions

FunctionPurposeExample
ts_forecast_byForecast multiple seriests_forecast_by('tbl', id, date, val, 'AutoETS', 12, '1d')
ts_backtest_autoOne-liner backtestingts_backtest_auto('tbl', id, date, val, 7, 3, '1d')
ts_statsCompute 34 statisticsts_stats(LIST(val ORDER BY date))
ts_detect_periodsDetect seasonalityts_detect_periods(LIST(val ORDER BY date))
ts_detect_periods_byDetect seasonality (multi-series)ts_detect_periods_by('tbl', id, date, val)
ts_featuresExtract 117 featurests_features(date, value)

Forecasting Models (33 Models)

CategoryModelsReference
BaselineNaive, SMA, SeasonalNaive, RandomWalkDrift, SeasonalWindowAveragebaseline/
Exponential SmoothingSES, SESOptimized, Holt, HoltWinters, SeasonalES, SeasonalESOptimizedexponential-smoothing/
State SpaceETS, ARIMA, AutoETS, AutoARIMAstate-space/
ThetaTheta, OptimizedTheta, DynamicTheta, DynamicOptimizedTheta, AutoThetatheta/
Multi-SeasonalMFLES, AutoMFLES, MSTL, AutoMSTL, TBATS, AutoTBATSmulti-seasonal/
Intermittent DemandCrostonClassic, CrostonOptimized, CrostonSBA, ADIDA, IMAPA, TSBintermittent/
DistributionalLaplace (variants: auto, auto_aid, skaters)distributional/laplace.md

Evaluation Metrics (12 Metrics)

Available as both scalar functions and _by table macros:

MetricScalar FunctionTable Macro
MAEts_mae(actual, pred)ts_mae_by(source, group, date, actual, forecast)
MSEts_mse(actual, pred)ts_mse_by(...)
RMSEts_rmse(actual, pred)ts_rmse_by(...)
MAPEts_mape(actual, pred)ts_mape_by(...)
sMAPEts_smape(actual, pred)ts_smape_by(...)
ts_r2(actual, pred)ts_r2_by(...)
Biasts_bias(actual, pred)ts_bias_by(...)
MASEts_mase(actual, pred, baseline)ts_mase_by(..., baseline)
rMAEts_rmae(actual, pred1, pred2)ts_rmae_by(..., pred1, pred2)
Coveragets_coverage(actual, lower, upper)ts_coverage_by(..., lower, upper)
Quantile Lossts_quantile_loss(actual, pred, q)ts_quantile_loss_by(..., quantile)
MQLossts_mqloss(actual, quantiles, levels)

Notes

Array-Based Design

All scalar functions operate on DOUBLE[] arrays. To convert table data to arrays:

SELECT product_id, ts_stats(LIST(value ORDER BY date)) AS stats
FROM sales GROUP BY product_id;

Important: Always use ORDER BY in LIST() to ensure correct temporal ordering.

NULL Handling

  • Statistics functions: NULLs are typically excluded
  • Imputation functions: Designed to fill NULLs (ts_fill_nulls_*)
  • Forecasting: Impute NULLs before forecasting

Minimum Data Requirements

Function TypeMinimumRecommended
Basic statisticsn ≥ 2n ≥ 10
Seasonality detectionn ≥ 2 × periodn ≥ 4 × period
Forecasting (simple)n ≥ 3n ≥ 20
Forecasting (seasonal)n ≥ 2 × periodn ≥ 3 × period
Feature extractionn ≥ 10n ≥ 50

Performance Tips

  1. Use table macros - optimized for batch processing
  2. Filter early - apply WHERE clauses before forecast functions
  3. Limit horizon - forecasts beyond 2-3 seasonal periods have high uncertainty
  4. Batch processing - process multiple series in one query

Last Updated: 2026-01-19 API Version: 0.4.0