Skip to content

Conformal prediction intervals

Calibrate prediction intervals from cross-validation errors on the point forecast instead of a model's native quantile head. Pass a ConformalIntervals object as prediction_intervals when you create a model, then request level (or quantiles) in forecast() as usual. See Conformal prediction for the full API.

!UV_CONSTRAINT= UV_BUILD_CONSTRAINT= uv pip install -q "foundationforecast[plot]"

Dataset: M4 Hourly, the same panel as the mlforecast prediction-intervals guide. The file has 414 hourly series; this example keeps the first 8. Horizon length is 48 hours (h=48).

Why conformal here: many foundation models predict a fixed set of quantile knots. Tafsut and Chronos-Bolt both stop at the 0.1 and 0.9 quantiles, so any level wider than 80% is clamped to the 80% interval: their "95%" interval is really an 80% one. Conformal intervals are built from the model's own past errors, so they can be as wide as the data requires.

Models in this example: Tafsut and Chronos-Bolt, each three times: native quantiles, conformal_distribution, and conformal_error. Copies of the same class share the point forecast, so any difference comes from the intervals.

Caveats:

  • Calibration costs about one panel forecast per n_windows, on top of the final forecast.
  • Each series needs at least h + (n_windows - 1) * step_size + 1 observations (step_size defaults to h).
  • cross_validation() recalibrates the conformal models at every cutoff, using only data before it. detect_anomalies() keeps using native quantiles.

How conformal intervals are built

Calibration is a panel cross_validation() of the point forecast (one forecast per window for all series). Let \(T\) be the last observed timestamp, \(h\) the horizon and \(W\) = n_windows. With the default step_size=h (non-overlapping windows):

1. Backtest the point forecast. For each window \(w = 1, \dots, W\) the model forecasts \(h\) steps from the cutoff \(t_w = T - (W - w + 1)\,h\), using only data up to \(t_w\), and we keep the absolute error at every horizon step \(j = 1, \dots, h\):

\[ e_{w,j} = \left|\, y_{t_w + j} - \hat{y}_{t_w + j \mid t_w} \right| \]

2. Forecast. The model produces the point forecast \(\hat{y}_{T+j}\) from the full history, unchanged.

3. Build the interval. For a level \(L\) (in percent) let \(\alpha = 1 - L/100\). The default conformal_distribution method forms \(2W\) synthetic outcomes around the point forecast,

\[ S_j = \{\hat{y}_{T+j} - e_{w,j}\}_{w=1}^{W} \cup \{\hat{y}_{T+j} + e_{w,j}\}_{w=1}^{W}, \]

and returns their symmetric quantiles as the interval:

\[ \Big[\, \mathrm{Quantile}_{\alpha/2}(S_j),\; \mathrm{Quantile}_{1-\alpha/2}(S_j) \,\Big] \]

conformal_error instead adds and subtracts \(\hat{q}_j = \mathrm{Quantile}_{1-\alpha}(e_{1,j}, \dots, e_{W,j})\). Either way, every series and every horizon step gets its own width, and wider levels reach further into the error distribution instead of stopping at a fixed knot.

Import libraries

import pandas as pd

from foundationforecast import ConformalIntervals, FoundationForecast

Load the dataset

The DataFrame must include at least the following columns:

  • unique_id: series identifier (string)
  • ds: timestamp (datetime)
  • y: target (float)

The pandas frequency is inferred from ds when freq is omitted.

df = pd.read_parquet(
    "https://timecopilot.s3.amazonaws.com/public/data/m4-hourly.parquet"
)
df = df[df["unique_id"].isin(df["unique_id"].unique()[:8])]
df.head()
unique_id ds y
0 H1 2000-01-01 00:00:00 605.0
1 H1 2000-01-01 01:00:00 586.0
2 H1 2000-01-01 02:00:00 586.0
3 H1 2000-01-01 03:00:00 559.0
4 H1 2000-01-01 04:00:00 511.0

Plot the data

FoundationForecast.plot(df, max_insample_length=48 * 3, plot_random=False)

Import the models

from foundationforecast.models import Chronos, Tafsut

Create a FoundationForecast

Each class appears three times with a distinct alias: native quantiles, conformal_distribution, and conformal_error.

n_windows=10 calibrates on ten non-overlapping 48-hour windows, which gives \(W = 10\) errors per horizon step. More windows make the tails, and therefore wide levels like 95%, more stable at the cost of more forecasts. The calibration horizon is the h passed to forecast() / cross_validation().

n_windows = 10
models = [
    Tafsut(alias="Tafsut", context_length=2048),
    Tafsut(
        alias="Tafsut-distribution",
        context_length=2048,
        prediction_intervals=ConformalIntervals(
            n_windows=n_windows, method="conformal_distribution"
        ),
    ),
    Tafsut(
        alias="Tafsut-error",
        context_length=2048,
        prediction_intervals=ConformalIntervals(
            n_windows=n_windows, method="conformal_error"
        ),
    ),
    Chronos(repo_id="amazon/chronos-bolt-small", alias="Chronos-Bolt"),
    Chronos(
        repo_id="amazon/chronos-bolt-small",
        alias="Chronos-Bolt-distribution",
        prediction_intervals=ConformalIntervals(
            n_windows=n_windows, method="conformal_distribution"
        ),
    ),
    Chronos(
        repo_id="amazon/chronos-bolt-small",
        alias="Chronos-Bolt-error",
        prediction_intervals=ConformalIntervals(
            n_windows=n_windows, method="conformal_error"
        ),
    ),
]

ff = FoundationForecast(models=models)

Cross validation

cross_validation() evaluates the models on the last two 48-hour windows of each series. For the conformal models, every window is recalibrated on the 10 windows before its cutoff, so the evaluation never sees the data it is scored on.

h = 48
level = [80, 95]

cv_df = ff.cross_validation(df=df, h=h, n_windows=2, level=level)
cv_df.head()

The clamping is easy to check: for the native fixed-knot models, the 95% bounds are identical to the 80% ones.

for alias in [
    "Tafsut",
    "Chronos-Bolt",
    "Tafsut-distribution",
    "Tafsut-error",
    "Chronos-Bolt-distribution",
    "Chronos-Bolt-error",
]:
    same = (cv_df[f"{alias}-lo-95"] == cv_df[f"{alias}-lo-80"]).all()
    print(f"{alias:<24} 95% interval == 80% interval: {same}")
Tafsut                   95% interval == 80% interval: True
Chronos-Bolt             95% interval == 80% interval: True
Tafsut-distribution      95% interval == 80% interval: False
Tafsut-error             95% interval == 80% interval: False
Chronos-Bolt-distribution 95% interval == 80% interval: False
Chronos-Bolt-error       95% interval == 80% interval: False
ff.plot(
    df,
    cv_df.drop(columns=["cutoff", "y"]),
    models=["Tafsut", "Tafsut-distribution"],
    level=level,
    max_insample_length=48 * 3,
    plot_random=False,
)

Evaluation

Coverage is the share of actuals that fall inside each interval; a well-calibrated \(L\)% interval should cover about \(L/100\) of them. We also report MASE (point accuracy, identical across copies of the same class because they share the point forecast) and scaled CRPS computed from the interval bounds.

from functools import partial

from utilsforecast.evaluation import evaluate
from utilsforecast.losses import coverage, mase, scaled_crps
eval_df = evaluate(
    cv_df.drop(columns=["cutoff"]),
    train_df=df,
    metrics=[partial(mase, seasonality=24), scaled_crps, coverage],
    level=level,
)
eval_df.groupby("metric").mean(numeric_only=True).T.round(3)
metric coverage_level80 coverage_level95 mase scaled_crps
Tafsut 0.822 0.822 0.775 0.024
Tafsut-distribution 0.806 0.928 0.775 0.023
Tafsut-error 0.812 0.930 0.775 0.023
Chronos-Bolt 0.862 0.862 0.759 0.023
Chronos-Bolt-distribution 0.828 0.928 0.759 0.022
Chronos-Bolt-error 0.840 0.928 0.759 0.022

Reading the results:

  • Native 95% coverage matches 80% coverage, because the 95% interval is clamped to the outermost 0.1 / 0.9 knots.
  • Both conformal methods restore coverage close to the nominal 80% and 95% levels. Compare conformal_distribution vs conformal_error in the table: they share the point forecast (same MASE) and differ only in how they turn calibration errors into bounds.
  • Scaled CRPS, computed here from only two interval levels, can be slightly worse for conformal models because the intervals are wider. Conformal intervals buy calibration: they don't make the model sharper.

Cross-validation covers 2 windows × 8 series (16 forecasts of 48 hours).

Forecast

Forecast the next 48 hours from the full history. Conformal models calibrate on the last n_windows holdouts of df before producing their intervals.

fcst_df = ff.forecast(df=df, h=h, level=level)
fcst_df.head()

Plot forecast

ff.plot(
    df,
    fcst_df,
    models=["Chronos-Bolt", "Chronos-Bolt-distribution"],
    level=level,
    max_insample_length=48 * 3,
    plot_random=False,
)

A forecast with finite corrected intervals

Start with a plain 24-hour forecast on the first M4 Hourly series. With n_windows=19, both the 80% and 95% bounds are finite and can be plotted directly. The 19 calibration windows plus the final prediction cost about 20 point forecasts; at h=24 with non-overlapping windows, at least 457 historical observations are needed. This series has enough history.

import numpy as np

from foundationforecast import ConformalIntervals
from foundationforecast.models import Chronos

finite_df = df[df["unique_id"] == df["unique_id"].iloc[0]].copy()
finite_model = Chronos(
    repo_id="amazon/chronos-bolt-tiny",
    alias="Chronos-Bolt-corrected",
    prediction_intervals=ConformalIntervals(
        n_windows=19, method="conformal_error_finite_sample"
    ),
)
finite_forecast = finite_model.forecast(df=finite_df, h=24, level=[80, 95])
bound_cols = [c for c in finite_forecast if "-lo-" in c or "-hi-" in c]
assert np.isfinite(finite_forecast[bound_cols]).all().all()

finite_fig = finite_model.plot(
    df=finite_df,
    forecasts_df=finite_forecast,
    level=[80, 95],
    max_insample_length=24 * 7,
    plot_random=False,
)
finite_fig

Finite-sample correction: rolling-origin coverage check

The opt-in conformal_error_finite_sample method selects the exact corrected rank instead of interpolating absolute errors. This check compares it with conformal_error using Chronos-Bolt tiny, the first 4 M4 Hourly series, a 24-hour horizon, and 4 held-out evaluation windows. Calibration uses either 2 or 19 non-overlapping 24-hour windows before each evaluation cutoff. Every series has enough history for both.

At 95%, 19 calibration windows are the minimum for a finite radius. With only 2 windows, corrected 80% and 95% bounds are infinite and forecast() emits a UserWarning naming the unsupported levels and required window counts: coverage of 1 then comes with infinite width, which is not an informative forecast. We report empirical coverage, mean interval width (in the original target units), and the fraction of finite intervals together. These are descriptive results on a small dependent time-series panel, not evidence of exchangeability or a universal coverage guarantee. No future evaluation values are used in calibration.

import numpy as np
import pandas as pd

from foundationforecast import ConformalIntervals, FoundationForecast
from foundationforecast.models import Chronos

coverage_df = df[df["unique_id"].isin(df["unique_id"].unique()[:4])].copy()
coverage_models = []
coverage_settings = []
for calibration_windows in [2, 19]:
    for method in ["conformal_error", "conformal_error_finite_sample"]:
        alias = f"{method}-{calibration_windows}"
        coverage_models.append(
            Chronos(
                repo_id="amazon/chronos-bolt-tiny",
                alias=alias,
                prediction_intervals=ConformalIntervals(
                    n_windows=calibration_windows, method=method, step_size=24
                ),
            )
        )
        coverage_settings.append((alias, method, calibration_windows))

coverage_ff = FoundationForecast(models=coverage_models)
coverage_cv = coverage_ff.cross_validation(
    df=coverage_df, h=24, freq="h", n_windows=4, step_size=24, level=[80, 95]
)
coverage_rows = []
for alias, method, calibration_windows in coverage_settings:
    for requested_level in [80, 95]:
        lo = coverage_cv[f"{alias}-lo-{requested_level}"]
        hi = coverage_cv[f"{alias}-hi-{requested_level}"]
        coverage_rows.append(
            {
                "method": method,
                "calibration_windows": calibration_windows,
                "level": requested_level,
                "coverage": coverage_cv["y"].between(lo, hi).mean(),
                "mean_width": (hi - lo).mean(),
                "finite_fraction": (np.isfinite(lo) & np.isfinite(hi)).mean(),
            }
        )

coverage_summary = pd.DataFrame(coverage_rows)
coverage_summary.round(3)
method calibration_windows level coverage mean_width finite_fraction
conformal_error 2 80 0.706 187.737 1.0
conformal_error 2 95 0.729 207.409 1.0
conformal_error_finite_sample 2 80 1.000 inf 0.0
conformal_error_finite_sample 2 95 1.000 inf 0.0
conformal_error 19 80 0.875 285.157 1.0
conformal_error 19 95 0.979 407.708 1.0
conformal_error_finite_sample 19 80 0.904 303.086 1.0
conformal_error_finite_sample 19 95 0.987 504.383 1.0

The two methods share point forecasts. For the 80% and 95% levels used here, with the same calibration windows, corrected ranks give intervals at least as wide as the uncorrected interpolated quantiles; coverage on those same evaluation observations cannot decrease. This width ordering need not hold below 50%. A corrected interval can still miss its nominal target on time series. Compare the 19-window rows for useful finite bounds, and the 2-window rows for the cost of requesting unsupported tail coverage with very little calibration data. Widths depend on the series scales.