# Skforecast

> Python library for time series forecasting using scikit-learn compatible models, statistical methods, and foundation models

This document is for skforecast v0.27.0+. If you are using an older version, check the documentation at skforecast.org.

Skforecast is a Python library for time series forecasting using scikit-learn compatible models, statistical methods, and foundation models. It works with any estimator compatible with the scikit-learn API (LightGBM, XGBoost, CatBoost, Keras, etc.).

## Quick Info

- Version: 0.27.0
- License: BSD-3-Clause
- Python: 3.10, 3.11, 3.12, 3.13, 3.14
- Repository: https://github.com/skforecast/skforecast
- Documentation: https://skforecast.org
- PyPI: https://pypi.org/project/skforecast/

## Installation

```bash
pip install skforecast
```

Optional dependencies:
```bash
pip install skforecast[stats]        # For ARIMA, SARIMAX, ETS models
pip install skforecast[plotting]     # For visualization
pip install skforecast[deeplearning] # For RNN/LSTM models
```

## Project Structure

```
skforecast/
├── base/                    # ForecasterBase - abstract parent class for all forecasters
├── recursive/               # ForecasterRecursive, ForecasterRecursiveMultiSeries,
│                            # ForecasterRecursiveClassifier, ForecasterStats, ForecasterEquivalentDate
├── direct/                  # ForecasterDirect, ForecasterDirectMultiVariate
├── deep_learning/           # ForecasterRnn, create_and_compile_model
├── foundation/              # FoundationModel, ForecasterFoundation, get_model_info, list_adapters
│                            # (zero-shot: Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2)
├── stats/                   # Arima, Sarimax, Ets, Arar, acf, pacf, calculate_lag_autocorrelation
├── preprocessing/           # TimeSeriesDifferentiator, RollingFeatures, CalendarFeatures,
│                            # QuantileBinner, ConformalIntervalCalibrator, reshape_* functions
├── model_selection/         # backtesting_forecaster, grid/random/bayesian search, TimeSeriesFold
├── feature_selection/       # select_features, select_features_multiseries
├── metrics/                 # MASE, RMSSE, sMAPE, CRPS, coverage, pinball loss
├── datasets/                # 30+ built-in datasets (fetch_dataset, load_demo_dataset)
├── drift_detection/         # RangeDriftDetector, PopulationDriftDetector
├── utils/                   # Shared validation and transformation functions
├── exceptions/              # Custom warnings and exceptions
├── plot/                    # plot_residuals, plot_prediction_intervals, plot_prediction_distribution,
│                            # plot_multivariate_time_series_corr, set_dark_theme, backtesting_gif_creator
└── experimental/            # Experimental features (API may change)
```

### Module Relationships

- **Forecasters inheriting from `ForecasterBase`**: ForecasterRecursive, ForecasterRecursiveMultiSeries, ForecasterRecursiveClassifier, ForecasterDirect, ForecasterDirectMultiVariate, ForecasterRnn
- **Standalone forecasters (no inheritance)**: ForecasterStats, ForecasterEquivalentDate, ForecasterFoundation
- Statistical models in `stats/` are wrapped by `ForecasterStats` (in `recursive/`)
- `ForecasterFoundation` (in `foundation/`) wraps a `FoundationModel`, which delegates to an adapter class (`ChronosAdapter`, `TimesFM25Adapter`, `TimesFM3Adapter`, `MoiraiAdapter`, `TabICLAdapter`, `TabPFNAdapter`, `T0Adapter`, `NoriAdapter`, `TSICLAdapter`, `TimestralAdapter`, `TiRex2Adapter`) resolved from the HuggingFace `model_id`
- `model_selection/` functions work with all forecaster types
- `preprocessing/` classes can be passed to forecasters via `transformer_y`, `transformer_exog`, `window_features`

## Core Forecasters

| Forecaster | Use Case |
|------------|----------|
| ForecasterRecursive | Single series, recursive multi-step forecasting |
| ForecasterDirect | Single series, direct multi-step forecasting |
| ForecasterRecursiveMultiSeries | Multiple series forecasting (global model) |
| ForecasterDirectMultiVariate | Multivariate forecasting (multiple series as features) |
| ForecasterRnn | Deep learning (RNN/LSTM) forecasting |
| ForecasterStats | Statistical models (ARIMA, SARIMAX, ETS, ARAR) |
| ForecasterFoundation | Zero-shot forecasting with pre-trained foundation models (Chronos-2, TimesFM 2.5/3.0, Moirai-2, TabICL, TabPFN-TS, TFC-T0, Synthefy Nori, TS-ICL, Timestral, TiRex-2) |
| ForecasterRecursiveClassifier | Classification-based forecasting |
| ForecasterEquivalentDate | Baseline forecaster using equivalent past dates |

To choose between model families, compare them on the same folds: each family has its own backtesting function (`backtesting_forecaster`, `backtesting_forecaster_multiseries`, `backtesting_stats`, `backtesting_foundation`), and passing the same `TimeSeriesFold` to all of them makes the results comparable. The scaled metrics (`mean_absolute_scaled_error`, `root_mean_squared_scaled_error`) scale each error with the one-step naive forecast over the observations before its forecast origin, the same for every forecaster. The user guide [Comparing forecasting models](https://skforecast.org/latest/user_guides/comparing-forecasting-models.html) does this for the seasonal naive, Ridge, LightGBM, Chronos-2, AutoARIMA, AutoETS and an LSTM on three datasets, reporting MASE, interval coverage and computation time.

## Basic Usage Example

```python
# Single series forecasting with ForecasterRecursive
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from skforecast.recursive import ForecasterRecursive
from skforecast.model_selection import backtesting_forecaster, TimeSeriesFold

# Load data: y must be a pandas Series with DatetimeIndex and frequency set
data = pd.read_csv('data.csv', index_col='date', parse_dates=True)
data = data.asfreq('h')  # IMPORTANT: always set frequency before using skforecast

# Create and train forecaster
forecaster = ForecasterRecursive(
    estimator=RandomForestRegressor(n_estimators=100, random_state=123),
    lags=24  # Use last 24 observations as features
)
forecaster.fit(y=data['target'])

# Predict next 10 steps
predictions = forecaster.predict(steps=10)

# Define cross-validation strategy for backtesting
cv = TimeSeriesFold(
    steps=10,
    initial_train_size=len(data) - 100,
    refit=False,
    fixed_train_size=False
)

# Backtesting for model evaluation
metric, predictions_backtest = backtesting_forecaster(
    forecaster=forecaster,
    y=data['target'],
    cv=cv,
    metric='mean_absolute_error'
)
```

## Multi-Series Forecasting Example

```python
# Multiple series with global model
from skforecast.recursive import ForecasterRecursiveMultiSeries
from lightgbm import LGBMRegressor

# Data: DataFrame with multiple series as columns
# series = pd.DataFrame({'series_1': [...], 'series_2': [...], ...})

forecaster = ForecasterRecursiveMultiSeries(
    estimator=LGBMRegressor(n_estimators=100, random_state=123),
    lags=24,
    encoding='ordinal'  # 'ordinal', 'ordinal_category', 'onehot', or None
)
forecaster.fit(series=series)

# Predict all series
predictions = forecaster.predict(steps=10)

# Predict specific series
predictions = forecaster.predict(steps=10, levels=['series_1', 'series_2'])
```

## With Exogenous Variables

```python
forecaster = ForecasterRecursive(
    estimator=LGBMRegressor(),
    lags=24
)

# Fit with exogenous variables
forecaster.fit(y=y_train, exog=exog_train)

# Predict - exog must cover the forecast horizon
predictions = forecaster.predict(steps=10, exog=exog_test)
```

## Categorical Exogenous Variables

All ML forecasters (ForecasterRecursive, ForecasterDirect, ForecasterRecursiveMultiSeries, ForecasterDirectMultiVariate, ForecasterRecursiveClassifier) include a `categorical_features` parameter to handle categorical exogenous variables automatically.

```python
forecaster = ForecasterRecursive(
    estimator=LGBMRegressor(),
    lags=24,
    categorical_features='auto',  # Default: auto-detect non-numeric columns after transformer_exog
)
forecaster.fit(y=y_train, exog=exog_train)
```

**`categorical_features` options:**
- `'auto'` (default): Non-numeric columns (after `transformer_exog`) are automatically detected and encoded using an internal `OrdinalEncoder`. Native categorical support is configured automatically for compatible estimators (LightGBM, CatBoost, XGBoost, HistGradientBoostingRegressor).
- `list`: Explicit list of column names to treat as categorical (including numeric columns).
- `None`: No categorical encoding is applied.

**Important:** When `categorical_features` is not `None` do not set categorical features directly on the estimator or via `fit_kwargs`. The forecaster manages categorical configuration internally and overwrites any estimator-level settings.

**Choosing an encoding strategy:**

| Method | API | Best for |
|--------|-----|----------|
| Built-in `categorical_features` | `categorical_features='auto'` or `list` | Gradient boosting (LightGBM, XGBoost, CatBoost, HistGBR), simplest workflow |
| One-hot / Ordinal encoding | `transformer_exog` | Linear models, SVMs, non-gradient-boosting trees |
| Target encoding | Outside forecaster | High-cardinality features (applied manually to avoid leakage) |

**`categorical_features` and `transformer_exog` interaction:**
`transformer_exog` is applied **before** `categorical_features` detection. They can be used together, e.g., scale numeric columns with `transformer_exog` while `categorical_features='auto'` handles the categorical ones. Avoid applying both mechanisms to the same columns.

```python
from sklearn.compose import make_column_transformer
from sklearn.preprocessing import StandardScaler

# Scale numeric columns, leave categorical columns untouched
transformer_exog = make_column_transformer(
    (StandardScaler(), ['temp', 'hum']),
    remainder='passthrough',
    verbose_feature_names_out=False
).set_output(transform='pandas')

forecaster = ForecasterRecursive(
    estimator=LGBMRegressor(),
    lags=24,
    transformer_exog=transformer_exog,
    categorical_features='auto',  # Detects remaining non-numeric columns
)
```

## Handling Missing Values

All ML forecasters (ForecasterRecursive, ForecasterDirect, ForecasterRecursiveMultiSeries, ForecasterDirectMultiVariate, ForecasterRecursiveClassifier) include a `dropna_from_series` parameter to control how NaN values in the training data are handled. Not applicable to ForecasterStats, ForecasterEquivalentDate, or ForecasterRnn.

When `y`, `series`, or `exog` contain interspersed NaN values, the training matrices (`X_train`, `y_train`) will also contain NaNs. The `dropna_from_series` parameter determines what happens next.

**`dropna_from_series` options:**
- `False` (default): NaN rows are kept in the training matrices. A `MissingValuesWarning` is issued. Only use with NaN-tolerant estimators.
- `True`: Rows containing NaN in `X_train` (and the corresponding rows in `y_train`) are dropped before fitting.

**NaN-tolerant estimators** (support `dropna_from_series=False`):
- LightGBM (`LGBMRegressor`, `LGBMClassifier`)
- CatBoost (`CatBoostRegressor`, `CatBoostClassifier`)
- XGBoost (`XGBRegressor`, `XGBClassifier`)
- scikit-learn tree-based models (`HistGradientBoosting`, `RandomForest`, `ExtraTrees`, `DecisionTree`, `ExtraTree`, both regressors and classifiers)

**Choosing a strategy:**

| Scenario | Recommended strategy |
|:---------|:---------------------|
| Using LightGBM, CatBoost, XGBoost, or a scikit-learn tree-based model | `dropna_from_series=False`: let the estimator handle NaNs. No data loss. |
| Estimator does not support NaN (LinearRegression, SVR, GradientBoosting...) | `dropna_from_series=True`: drop incomplete rows before fitting. |
| Few or small gaps in the series | `dropna_from_series=True`: simple and data loss is negligible. |
| Large gaps, need to preserve all training data | Imputation + `weight_func`: fill NaNs and down-weight imputed observations. |
| Multi-series with different lengths | `ForecasterRecursiveMultiSeries` with `dropna_from_series=True`. |

```python
from lightgbm import LGBMRegressor

# NaN-tolerant estimator: keep all rows including NaN
forecaster = ForecasterRecursive(
    estimator=LGBMRegressor(random_state=123, verbose=-1),
    lags=14,
    dropna_from_series=False,  # Default: NaN rows kept for NaN-tolerant estimators
)
forecaster.fit(y=y_train, suppress_warnings=True)  # Suppress MissingValuesWarning

# Non-NaN-tolerant estimator: drop rows with NaN
forecaster = ForecasterRecursive(
    estimator=RandomForestRegressor(random_state=123),
    lags=14,
    dropna_from_series=True,  # Drop NaN rows before fitting
)
forecaster.fit(y=y_train)
```

## Window Features (Rolling Statistics)

```python
from skforecast.preprocessing import RollingFeatures

# Create rolling features
rolling_features = RollingFeatures(
    stats=['mean', 'std', 'min', 'max'],
    window_sizes=7  # int applies to all stats, or list with same length as stats
)

forecaster = ForecasterRecursive(
    estimator=LGBMRegressor(),
    lags=24,
    window_features=rolling_features
)
```

## Prediction Intervals

```python
# Predict with confidence intervals
# Since v0.23.0 `interval` is expressed as quantiles in (0, 1), not percentiles
predictions = forecaster.predict_interval(
    steps=10,
    interval=[0.1, 0.9],  # 80% prediction interval
    method='bootstrapping',  # or 'conformal'
    n_boot=500
)
# Returns DataFrame with columns: pred, lower_bound, upper_bound
```

## Backtesting

Backtesting evaluates forecaster performance using time series cross-validation.

```python
from skforecast.model_selection import backtesting_forecaster, TimeSeriesFold

# Define cross-validation strategy
cv = TimeSeriesFold(
    steps=10,
    initial_train_size=len(data) - 100,
    refit=False,
    fixed_train_size=False
)

metric, predictions = backtesting_forecaster(
    forecaster=forecaster,                      # Forecaster object to evaluate
    y=data['target'],                           # Time series data (pandas Series with DatetimeIndex)
    cv=cv,                                      # TimeSeriesFold with CV configuration
    metric='mean_absolute_error',               # Metric(s): str, callable, or list
    exog=exog,                                  # Exogenous variables (optional)
    interval=[0.1, 0.9],                        # Prediction intervals as quantiles in (0, 1) (optional)
    interval_method='bootstrapping',            # 'bootstrapping' or 'conformal'
    n_boot=250,                                 # Bootstrap iterations (only if method='bootstrapping')
    use_in_sample_residuals=True,               # Use training residuals for intervals
    use_binned_residuals=True,                  # Select residuals based on predicted values
    random_state=123,                           # Seed for reproducibility
    return_predictors=False,                    # Return predictor values used in each fold
    n_jobs='auto',                              # Parallel jobs (-1 for all cores, 'auto' for automatic)
    verbose=False,                              # Print fold information
    show_progress=True,                         # Show progress bar
    suppress_warnings=False                     # Suppress skforecast warnings
)
# predictions columns: fold, step, y_true, pred, lower_bound, upper_bound
# metric columns: mean_absolute_error, coverage, interval_width, n_evaluated
```

The predictions of the four backtesting functions (`backtesting_forecaster`, `backtesting_forecaster_multiseries`, `backtesting_stats` and `backtesting_foundation`) always include, after `fold`, the column `step` (step of the forecast horizon at which each prediction was made, from `gap + 1` to `gap + steps`) and `y_true` (true value), before the predictions: `level, fold, step, y_true, pred, ...` with multiple series, and `estimator_id, fold, step, y_true, pred, ...` in `backtesting_stats` with several estimators. The dates without an observed value (missing values of `y` in the test set) stay in the predictions with `y_true` NaN and are left out of the metrics, with one series and with several; in the multi-series backtesting, every prediction column is NaN at those dates too. With overlapping folds (`fold_stride < steps`) every prediction is kept, so a date can appear several times with different `step`. The last column of `metric` is `n_evaluated`: the points used for the metrics (true value and prediction not missing, each date once with the prediction of its last fold), per level in multi-series and the sum in the aggregated rows; `weighted_average` is weighted by it. Metric names must be unique (they are the columns of `metric`; `create_mean_pinball_loss(alpha)` is named `mean_pinball_loss_q_{alpha}`) and cannot be `n_evaluated`.

```python
# Error and coverage by step of the horizon (group by ['level', 'step'] with multiple series)
predictions = predictions.dropna(subset=['y_true'])
predictions.assign(
    absolute_error=(predictions['y_true'] - predictions['pred']).abs(),
    covered=predictions['y_true'].between(predictions['lower_bound'], predictions['upper_bound']),
).groupby('step')[['absolute_error', 'covered']].mean()
```

When the predictions define one interval, the backtesting functions add two columns to `metric`, after the requested metrics: `coverage` (share of true values inside the interval) and `interval_width` (mean width of the interval, in the units of the series). One interval means a float `interval` such as `0.8`, or two quantiles, optionally with the median: `interval=[0.1, 0.9]` or `[0.1, 0.5, 0.9]`, and the same in `quantiles` of `backtesting_foundation`. Compare `coverage` with the nominal level (0.8 for `[0.1, 0.9]`) and read it together with `interval_width`: a wide interval covers more. Multi-series backtesting reports them per level and in the aggregated rows, and `backtesting_stats` per estimator (also with `alpha`). With other quantiles (for example `[0.05, 0.1, 0.9, 0.95]`), `interval='bootstrapping'` or a distribution, they are not added; use CRPS or the pinball loss instead. A custom metric cannot be named `coverage` or `interval_width` when they are added.

## Cross-Validation Strategies

Skforecast provides two cross-validation strategies for time series: `TimeSeriesFold` for multi-step ahead validation and `OneStepAheadFold` for one-step ahead validation.

### TimeSeriesFold

Class to split time series data into train and test folds for backtesting and hyperparameter search.

```python
from skforecast.model_selection import TimeSeriesFold

cv = TimeSeriesFold(
    steps=12,                        # (required) Number of observations to predict in each fold (forecast horizon)
    initial_train_size=100,          # Number of observations for initial training. Can be int, str (date), or pd.Timestamp
    fold_stride=None,                # Observations between consecutive test set starts. If None, equals steps (no overlap)
    window_size=None,                # Observations needed for autoregressive predictors (set automatically by forecaster; when calling split() directly, use forecaster.window_size, which includes differentiation)
    refit=False,                     # Whether to refit forecaster each fold: True, False, or int (refit every n folds)
    fixed_train_size=True,           # If True, the training window rolls with a fixed size; if False, it expands each fold (only with refit)
    gap=0,                           # Observations between end of training and start of test set
    skip_folds=None,                 # Folds to leave out: int (keep one of every n folds, starting with the first) or list of fold indexes to skip
    allow_incomplete_fold=True,      # Whether to allow last fold with fewer observations than steps
    return_all_indexes=False,        # Whether to return all indexes or only start/end of each fold
    verbose=True                     # Whether to print information about generated folds
)

# View the folds
folds = cv.split(X=data, as_pandas=True)
print(folds)
```

**Key behaviors:**
- If `fold_stride == steps`: test sets are back-to-back without overlap
- If `fold_stride < steps`: test sets overlap (multiple forecasts for same observations)
- If `fold_stride > steps`: gaps between consecutive test sets
- `differentiation` (both folds) and `window_size` (`OneStepAheadFold`) are deprecated since 0.27.0: they have no effect, emit a `FutureWarning` and will be removed in 0.29.0

### OneStepAheadFold

Class for one-step-ahead forecasting validation. Faster than `TimeSeriesFold` as it doesn't require recursive predictions.

```python
from skforecast.model_selection import OneStepAheadFold

cv = OneStepAheadFold(
    initial_train_size=100,          # (required) Number of observations for initial training. Can be int, str (date), or pd.Timestamp
    return_all_indexes=False,        # Whether to return all indexes or only start/end of each fold
    verbose=True                     # Whether to print information about generated folds
)

# View the fold
fold = cv.split(X=data, as_pandas=True)
print(fold)
```

**When to use:**
- `TimeSeriesFold`: When you need to evaluate multi-step forecasting performance (realistic backtesting)
- `OneStepAheadFold`: When you need fast hyperparameter tuning (less accurate but much faster)

## Hyperparameter Tuning

Three search strategies are available: `grid_search_forecaster`, `random_search_forecaster`, and `bayesian_search_forecaster` (Optuna-based). All accept `TimeSeriesFold` or `OneStepAheadFold`. Multi-series variants: `grid_search_forecaster_multiseries`, `random_search_forecaster_multiseries`, `bayesian_search_forecaster_multiseries`.

Results are sorted by the first metric, best first, and `return_best=True` refits the forecaster with the first row. The direction comes from the metric: scikit-learn metrics ending in `_score` (`r2_score`, `accuracy_score`) are maximized; errors and losses are minimized. A custom callable is minimized in regression and maximized in classification unless it sets the attribute `greater_is_better` (`True` or `False`). In the Bayesian searches, `kwargs_create_study={'direction': ...}` overrides it.

The results of every search include, after the metrics, the column `n_evaluated` (the `n_evaluated` of the backtesting metrics: points in the metrics of each candidate, summed over the levels in multi-series; also a `user_attr` of each Optuna trial and a column of the `output_file`). In the multi-series searches, a candidate with a larger `window_size` does not predict a series with `window_size` observations or fewer before a fold, so its metrics can use fewer points; a single `MissingValuesWarning` at the end of the search reports the candidates with less than 95% of the points of the most complete one and the series that every candidate evaluates on the same points. To compare them on the same points, pass those series in `levels`, or remove the larger windows. The single series searches raise the same warning with `OneStepAheadFold`, `dropna_from_series=True` and gaps in `y` (larger windows drop more test rows): fill the gaps or remove the larger windows. Metric names must be unique and cannot be `n_evaluated` in any search (`ValueError`).

Candidates (or Bayesian trials) whose evaluation raises an error, for example lags not smaller than `initial_train_size`, are skipped: they are left out of the results and reported in a single `RuntimeWarning` ("Parameters skipped"), grouped by error, that `suppress_warnings=True` does not hide. Bayesian trials are marked as failed in the study and listed by number; errors in `search_space` stop the search. With `ForecasterRecursiveMultiSeries` and `return_best=True`, the refit leaves out the series with `window_size` observations or fewer for the best candidate (another `RuntimeWarning`): they are not in `series_names_in_`.

```python
from skforecast.model_selection import bayesian_search_forecaster, TimeSeriesFold

cv = TimeSeriesFold(steps=12, initial_train_size=len(data) - 100, refit=False)

# Bayesian Search: lags can be included in search_space
def search_space(trial):
    return {
        'lags': trial.suggest_categorical('lags', [3, 5, [1, 2, 3, 20]]),
        'n_estimators': trial.suggest_int('n_estimators', 50, 200),
        'max_depth': trial.suggest_int('max_depth', 3, 15),
        'learning_rate': trial.suggest_float('learning_rate', 0.01, 0.3, log=True)
    }

results, study = bayesian_search_forecaster(
    forecaster=forecaster,
    y=data['target'],
    cv=cv,
    search_space=search_space,
    metric='mean_absolute_error',
    n_trials=50,
    random_state=123,
    return_best=True,
    n_jobs='auto',
    show_progress=True
)
# Access the best trial with study.best_trial
```

## Statistical Models (ARIMA, ETS, ARAR)

Statistical models are wrapped by `ForecasterStats` for a sklearn-compatible interface. Available models: `Arima`, `Sarimax`, `Ets`, `Arar`.
Autocorrelation utilities are also available in `skforecast.stats`: `acf`, `pacf`, and `calculate_lag_autocorrelation`.

```python
from skforecast.recursive import ForecasterStats
from skforecast.stats import Arima, Ets, Sarimax, Arar
from skforecast.stats import acf, pacf, calculate_lag_autocorrelation

# ARIMA model (order=(p,d,q), seasonal_order=(P,D,Q), m=seasonal_period)
forecaster = ForecasterStats(estimator=Arima(order=(1, 1, 1), seasonal_order=(1, 1, 1), m=12))
forecaster.fit(y=data['target'])
predictions = forecaster.predict(steps=10)

# Auto ARIMA (automatic order selection) - set order=None and seasonal_order=None
forecaster = ForecasterStats(estimator=Arima(order=None, seasonal_order=None, m=12))

# ETS model (model string: 1st=Error, 2nd=Trend, 3rd=Seasonal; A=Add, M=Mult, N=None; 'ZZZ'=Auto)
forecaster = ForecasterStats(estimator=Ets(m=12, model='AAA'))
```

## Foundation Models (Zero-Shot)

Pre-trained time series foundation models that forecast without task-specific training. Each model requires its own backend library installed separately (`chronos-forecasting`, `timesfm`, `uni2ts`, `tabicl`, `tabpfn-time-series`, `tfc-t0[torch]` (>= 0.6), `synthefy-nori`, `tsicl`, `tirex-2` (Python >= 3.11), `timestral`, installed from git with `pip install "timestral @ git+https://github.com/mistralai/timestral.git"`). Models are downloaded from HuggingFace on first use.

`FoundationModel` is the low-level interface; `ForecasterFoundation` wraps it to integrate with the rest of the skforecast ecosystem (backtesting, model selection, uniform `predict` / `predict_interval` / `predict_quantiles` API).

```python
from skforecast.foundation import FoundationModel, ForecasterFoundation

# Zero-shot single-series forecasting with Chronos-2
model = FoundationModel(
    model_id='autogluon/chronos-2-small',
    context_length=2048,
    device_map='auto',
)
forecaster = ForecasterFoundation(estimator=model)
forecaster.fit(series=data['target'])  # Only stores context; no training
predictions = forecaster.predict(steps=24)  # Long-format: columns ['level', 'pred']

# Prediction intervals (native quantile output, no bootstrapping needed)
predictions = forecaster.predict_interval(steps=24, interval=[0.1, 0.9])
predictions = forecaster.predict_quantiles(steps=24, quantiles=[0.1, 0.5, 0.9])

# Multi-series (global zero-shot model): pass a wide DataFrame
forecaster.fit(series=series_df)
predictions = forecaster.predict(steps=24, levels=['series_1', 'series_2'])
```

Supported adapters (selected automatically from `model_id`). Query them programmatically with `get_model_info` and `list_adapters` (see below):

| Adapter | `model_id` prefix | Exog | Default `context_length` | Quantiles |
|---------|-------------------|------|--------------------------|-----------|
| ChronosAdapter (Amazon) | `autogluon/chronos-2` | Yes (past & future covariates) | 8192 | Any in `(0, 1)` |
| TimesFM25Adapter (Google, v2.5) | `google/timesfm-2.5` | No | 512 | `[0.1, 0.2, ..., 0.9]` |
| TimesFM3Adapter (Google, v3.0) | `google/timesfm-3.0` | Yes (past & known-future covariates) | 2048 | `[0.1, 0.2, ..., 0.9]` |
| MoiraiAdapter (Salesforce) | `Salesforce/moirai-2` | No | 2048 | `[0.1, 0.2, ..., 0.9]` |
| TabICLAdapter (Soda-INRIA) | `soda-inria/tabicl` | Yes (known-future covariates) | 4096 | Any in `(0, 1)` |
| TabPFNAdapter (Prior Labs) | `priorlabs/tabpfn` | Yes (known-future covariates) | 32768 | Any in `(0, 1)` |
| T0Adapter (The Forecasting Company) | `theforecastingcompany/t0` | Yes (future-known covariates) | 8192 | Any in `(0, 1)` |
| NoriAdapter (Synthefy) | `Synthefy/Nori` | Yes (known-future covariates) | 4096 | Any in `(0, 1)` |
| TSICLAdapter (EDF Lab) | `taharnbl/TS-ICL` | Yes (past & future covariates) | 4096 | Subset of `[0.01, 0.02, ..., 0.99]` |
| TimestralAdapter (Mistral AI) | `mistralai/Timestral` | Yes (past, known-future and categorical covariates) | 4096 | Subset of `[0.01, 0.05, 0.1, ..., 0.95, 0.99]` (21 levels) |
| TiRex2Adapter (NX-AI) | `NX-AI/TiRex-2` | Yes (past & known-future covariates) | 2048 | `[0.1, 0.2, ..., 0.9]` |

```python
from skforecast.foundation import get_model_info, list_adapters

# Capabilities of a model without installing its backend or loading weights
info = get_model_info('google/timesfm-3.0-pytorch')
info.adapter                  # 'TimesFM3Adapter'
info.allow_exog               # True
info.supported_quantiles      # (0.1, 0.2, ..., 0.9); None means any level in (0, 1)
info.backend_package          # 'timesfm[torch]'
info.license                  # SPDX id ('Apache-2.0') or model card license name (see info.license_url)
info.commercial_use_restricted  # True if the license restricts commercial use (LicenseWarning on load)
info.requires_hf_auth         # True if the weights are gated on the Hugging Face Hub
info.requires_provider_auth   # True if the provider needs its own account/license acceptance (TabPFN)
info.weights_repo_id          # Hugging Face repo the weights are downloaded from (may differ from
                              # model_id, e.g. 'jingang/TabICL' for 'soda-inria/tabicl')
info.weights_in_hf_cache      # False if the weights are not stored in the HF Hub cache (TabPFN)

# One FoundationModelInfo per adapter (described by its default_model_id)
[(i.adapter, i.default_model_id) for i in list_adapters()]

# Same information as a DataFrame, one row per adapter (index 'adapter')
list_adapters(as_frame=True)
```

Key points:
- `fit()` only stores the last `context_length` observations and metadata. It does **not** train the model.
- The index must have a frequency (`data.asfreq(...)`), same requirement as other skforecast forecasters.
- `predict(..., context=...)` lets you override the stored context (used internally by backtesting).
- Use `backtesting_foundation` (not `backtesting_forecaster`) to evaluate a `ForecasterFoundation`. It deep-copies `cv` and forces `refit=True`, `fixed_train_size=False`, so the context window expands with each fold up to `context_length`; no weights are ever trained.
- Use `bayesian_search_foundation` (not `bayesian_search_forecaster`) to tune inference-time parameters such as `context_length`. Only `TimeSeriesFold` is supported.
- Loading a model whose weights are released under a license that restricts commercial use (TimesFM 3.0, Moirai-2, TabPFN-TS, TS-ICL, Timestral) raises a `LicenseWarning` naming the license and a link to the model card; review the link, since terms vary (e.g. TabPFN-TS permits commercial use under an enterprise license; Timestral grants no rights to companies above USD 20 million of monthly revenue). Absence of the warning does not guarantee a model's license is unrestricted. Suppress it like any other skforecast warning (`suppress_warnings=True` or `warnings.simplefilter`).
- At predict time, the columns of the future `exog` are validated per series against the historical exog (the one passed to `fit`, or `context_exog`). A future column with no historical values raises a `ValueError`. A historical column with no future values is a past-only covariate: used as such when `forecaster.supports_past_only_covariates` is `True` (Chronos-2, TS-ICL, TimesFM 3.0, Timestral, TiRex-2), ignored with an `IgnoredArgumentWarning` otherwise (TabICL, TabPFN-TS, TFC-T0, Nori): the forecast is then the same as without that column.
- Multi-series input may be heterogeneous: series can have different lengths, a different subset of exog columns each, and NaN values. Each series is forecast with its own exog columns only. When the backend needs identical covariate columns in a batch (`forecaster.supports_heterogeneous_covariates` is `False`: Chronos-2, TS-ICL, TabICL, TimesFM 3.0, TFC-T0, Timestral), the series are grouped by their exog columns and the backend is called once per group, so the forecast of a series never depends on the exog of the others. `forecaster.supports_nan_in_series` tells whether the backend accepts NaN in the context.
- Timestral: with a known covariate that is constant over the context and changes over the horizon (a price, or a 0/1 indicator that is 0 over the whole context), the upper quantiles can become very large (mistralai/timestral#7); a `FeatureOutOfRangeWarning` names the affected series and columns, and setting their historical values to NaN avoids it.
- TiRex-2: each checkpoint forecasts at most `future_len` steps ahead (320 for `NX-AI/TiRex-2`, 928 for the gifteval checkpoints), so a longer `steps` raises a `ValueError` (the backend would silently return a shorter forecast). All the series go to the backend in the same call whatever their exog, in calls of at most 64 series.
- In `backtesting_foundation`, a series is predicted in a fold only if it has at least one observed value in that fold's test window and its context window (the last `context_length` observations up to the end of the train span) is not entirely NaN; the context keeps interior and trailing NaN, so every prediction is dated inside the fold.
- User guide for heterogeneous multi-series input (different lengths, exog columns and NaN): https://skforecast.org/latest/user_guides/foundation-forecasting-with-heterogeneous-series.html

## Feature Selection

Use any selector compatible with the scikit-learn API (RFECV, SelectFromModel, etc.) to identify relevant lags, window features, exogenous variables and calendar features. Multi-series variant: `select_features_multiseries`.

```python
from sklearn.feature_selection import RFECV
from skforecast.feature_selection import select_features

selected_lags, selected_window_features, selected_exog, selected_calendar_features = select_features(
    forecaster=forecaster,
    selector=RFECV(estimator=RandomForestRegressor(), step=1, cv=3),
    y=y_train,
    exog=exog_train,
    select_only=None,              # 'autoreg', 'exog', 'calendar', a list of them, or None (all features)
    force_inclusion=None,          # Features to always include (list or regex str)
    subsample=0.5,                 # Proportion of records in (0, 1], sampled without replacement and in random order (random cv folds)
    random_state=123,
    verbose=True
)
forecaster.set_lags(selected_lags)
```

## Drift Detection

Two drift detection tools for monitoring data distribution changes during deployment.

```python
from skforecast.drift_detection import RangeDriftDetector, PopulationDriftDetector

# RangeDriftDetector: lightweight, checks out-of-range values vs training ranges
detector = RangeDriftDetector()
detector.fit(series=y_train, exog=exog_train)
flag_out_of_range, out_of_range_series, out_of_range_exog = detector.predict(
    last_window=new_data, exog=new_exog
)

# PopulationDriftDetector: statistical tests (KS, Chi-Square, Jensen-Shannon)
detector = PopulationDriftDetector(chunk_size=100, threshold=3, threshold_method='std')
detector.fit(X=reference_data)
results, summary = detector.predict(X=new_data)
```

## Key Classes and Imports

**Note:** In versions prior to 0.14.0, `ForecasterRecursive` was named `ForecasterAutoreg` and `ForecasterRecursiveMultiSeries` was named `ForecasterAutoregMultiSeries`. Always use the current names shown below.

```python
# Forecasters
from skforecast.recursive import ForecasterRecursive
from skforecast.recursive import ForecasterRecursiveMultiSeries
from skforecast.recursive import ForecasterRecursiveClassifier
from skforecast.recursive import ForecasterStats
from skforecast.recursive import ForecasterEquivalentDate
from skforecast.direct import ForecasterDirect
from skforecast.direct import ForecasterDirectMultiVariate
from skforecast.deep_learning import ForecasterRnn
from skforecast.deep_learning import create_and_compile_model
from skforecast.foundation import FoundationModel
from skforecast.foundation import ForecasterFoundation
from skforecast.foundation import FoundationModelInfo
from skforecast.foundation import get_model_info
from skforecast.foundation import list_adapters

# Model Selection
from skforecast.model_selection import backtesting_forecaster
from skforecast.model_selection import backtesting_forecaster_multiseries
from skforecast.model_selection import backtesting_stats
from skforecast.model_selection import backtesting_foundation
from skforecast.model_selection import bayesian_search_foundation
from skforecast.model_selection import grid_search_forecaster
from skforecast.model_selection import grid_search_forecaster_multiseries
from skforecast.model_selection import random_search_forecaster
from skforecast.model_selection import random_search_forecaster_multiseries
from skforecast.model_selection import bayesian_search_forecaster
from skforecast.model_selection import bayesian_search_forecaster_multiseries
from skforecast.model_selection import grid_search_stats
from skforecast.model_selection import random_search_stats
from skforecast.model_selection import grid_search_equivalent_date
from skforecast.model_selection import TimeSeriesFold
from skforecast.model_selection import OneStepAheadFold

# Preprocessing
from skforecast.preprocessing import RollingFeatures
from skforecast.preprocessing import RollingFeaturesClassification
from skforecast.preprocessing import TimeSeriesDifferentiator
from skforecast.preprocessing import CalendarFeatures
from skforecast.preprocessing import create_calendar_features
from skforecast.preprocessing import calculate_distance_from_holiday
from skforecast.preprocessing import QuantileBinner
from skforecast.preprocessing import ConformalIntervalCalibrator
# Data reshaping utilities
from skforecast.preprocessing import reshape_series_wide_to_long
from skforecast.preprocessing import reshape_series_long_to_dict
from skforecast.preprocessing import reshape_exog_long_to_dict
from skforecast.preprocessing import reshape_series_exog_dict_to_long

# Feature Selection
from skforecast.feature_selection import select_features
from skforecast.feature_selection import select_features_multiseries

# Datasets
from skforecast.datasets import fetch_dataset
from skforecast.datasets import load_demo_dataset
from skforecast.datasets import show_datasets_info

# Metrics
from skforecast.metrics import mean_absolute_scaled_error
from skforecast.metrics import root_mean_squared_scaled_error
from skforecast.metrics import symmetric_mean_absolute_percentage_error
from skforecast.metrics import add_y_train_argument
from skforecast.metrics import crps_from_predictions
from skforecast.metrics import crps_from_quantiles
from skforecast.metrics import calculate_coverage
from skforecast.metrics import create_mean_pinball_loss
from skforecast.metrics import winkler_score
from skforecast.metrics import weighted_interval_score

# Statistical models (used with ForecasterStats)
from skforecast.stats import Arima, Ets, Sarimax, Arar
from skforecast.stats import acf, pacf, calculate_lag_autocorrelation

# Drift Detection
from skforecast.drift_detection import RangeDriftDetector
from skforecast.drift_detection import PopulationDriftDetector

# Plotting
from skforecast.plot import plot_residuals
from skforecast.plot import plot_multivariate_time_series_corr
from skforecast.plot import plot_prediction_distribution
from skforecast.plot import plot_prediction_intervals
from skforecast.plot import backtesting_gif_creator
from skforecast.plot import set_dark_theme

# Exceptions and Warnings
from skforecast.exceptions import DataTypeWarning
from skforecast.exceptions import DataTransformationWarning
from skforecast.exceptions import ExogenousInterpretationWarning
from skforecast.exceptions import FeatureOutOfRangeWarning
from skforecast.exceptions import IgnoredArgumentWarning
from skforecast.exceptions import InputTypeWarning
from skforecast.exceptions import LicenseWarning
from skforecast.exceptions import LongTrainingWarning
from skforecast.exceptions import MissingExogWarning
from skforecast.exceptions import MissingValuesWarning
from skforecast.exceptions import OneStepAheadValidationWarning
from skforecast.exceptions import ResidualsUsageWarning
from skforecast.exceptions import SaveLoadSkforecastWarning
from skforecast.exceptions import SkforecastVersionWarning
from skforecast.exceptions import UnknownLevelWarning
from skforecast.exceptions import set_warnings_style
from skforecast.exceptions import warn_skforecast_categories
from skforecast.exceptions import runtime_deprecated

```

## Available Datasets

30+ built-in datasets covering multiple frequencies (15min, 30min, hourly, daily, monthly, quarterly). Most commonly used:

```python
from skforecast.datasets import fetch_dataset, show_datasets_info

data = fetch_dataset(name='h2o')             # Monthly, single series
data = fetch_dataset(name='items_sales')     # Daily, 3 series (multi-series)
data = fetch_dataset(name='bike_sharing')    # Hourly, with exogenous variables
data = fetch_dataset(name='store_sales')     # Daily, 50 products x 10 stores
data = fetch_dataset(name='h2o_exog')        # Monthly, with exogenous variables

# See all available datasets
show_datasets_info()
```

## Tips for Best Results

1. **Always set frequency**: Use `data.asfreq('h')` or similar, skforecast requires a DatetimeIndex with frequency
2. **Handle missing values**: Use `dropna_from_series=True` to drop NaN rows, or `dropna_from_series=False` (default) with NaN-tolerant estimators (LightGBM, CatBoost, HistGradientBoosting)
3. **Scale data**: Use `transformer_y` for better model performance
4. **Use backtesting**: Always validate with realistic train/test splits
5. **Consider differentiation**: For non-stationary series, use `differentiation` parameter
6. **Start simple**: Begin with ForecasterRecursive before trying complex models

## Documentation

- Quick Start: https://skforecast.org/latest/quick-start/quick-start-skforecast.html
- User Guides: https://skforecast.org/latest/user_guides/table-of-contents.html
- API Reference: https://skforecast.org/latest/api/forecasterrecursive.html
- Examples: https://skforecast.org/latest/examples/examples_english.html
- Release Notes: https://skforecast.org/latest/releases/releases.html

## Citation

```
Amat Rodrigo, J., & Escobar Ortiz, J. skforecast [Computer software]. https://doi.org/10.5281/zenodo.8382787
```
