Skip to content

foundationforecast.core.conformal

Cross-validation settings for distribution-free prediction intervals.

Parameters:

Name Type Description Default
n_windows int

Number of rolling backtest windows used to estimate residuals. Must be at least 2.

2
method str | ConformalMethod

conformal_distribution builds bounds from mean ± error paths; conformal_error uses quantiles of absolute errors per horizon step. conformal_error_finite_sample selects the ceil((n_windows + 1) * level / 100)-th smallest absolute error, without interpolation. If the rank exceeds n_windows, the bounds are infinite and forecast() emits a UserWarning. The usual marginal coverage lower bound requires exchangeable calibration and future errors; rolling backtests do not establish that assumption. A parameterized method object such as PID(...) or ACI(...) replays the calibration windows online under distribution shift.

'conformal_distribution'
step_size int | None

Gap between consecutive calibration cutoffs. None (default) uses the forecast horizon (non-overlapping windows).

None

n_windows class-attribute instance-attribute

n_windows: int = 2

method class-attribute instance-attribute

method: str | ConformalMethod = 'conformal_distribution'

step_size class-attribute instance-attribute

step_size: int | None = None

__post_init__

__post_init__() -> None
Source code in foundationforecast/core/conformal.py
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
def __post_init__(self) -> None:
    if self.n_windows < 2:
        raise ValueError(
            "You need at least two windows to compute conformal intervals"
        )
    if self.step_size is not None and self.step_size < 1:
        raise ValueError("step_size must be a positive integer")
    if isinstance(self.method, ConformalMethod):
        self.method.validate(self.n_windows, self.step_size)
        return
    allowed = (
        "conformal_distribution",
        "conformal_error",
        "conformal_error_finite_sample",
    )
    if self.method not in allowed:
        raise ValueError(f"method must be one of {allowed}")

Bases: ABC

Base class for parameterized conformal calibration methods.

Pass an instance as ConformalIntervals(method=...) (for example PID or ACI). Instances are called with the point forecasts and the signed cross-validation errors y - y_hat of the calibration windows, and return the forecast frame with -lo-{level} / -hi-{level} columns added.

Calibration errors arrive as cs_df[model] reshaped to (cs_n_windows, n_series, cs_h); window 0 is the oldest cutoff and consecutive windows are step_size observations apart.

validate

validate(n_windows: int, step_size: int | None) -> None

Raise ValueError if the method cannot run with these settings.

Source code in foundationforecast/core/conformal.py
29
30
31
def validate(self, n_windows: int, step_size: int | None) -> None:
    """Raise ``ValueError`` if the method cannot run with these settings."""
    return None

__call__ abstractmethod

__call__(
    fcst_df: DataFrame,
    cs_df: DataFrame,
    model_names: list[str],
    level: list[int | float],
    cs_n_windows: int,
    cs_h: int,
    n_series: int,
    horizon: int,
    step_size: int,
) -> DataFrame
Source code in foundationforecast/core/conformal.py
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@abstractmethod
def __call__(
    self,
    fcst_df: pd.DataFrame,
    cs_df: pd.DataFrame,
    model_names: list[str],
    level: list[int | float],
    cs_n_windows: int,
    cs_h: int,
    n_series: int,
    horizon: int,
    step_size: int,
) -> pd.DataFrame:
    ...

Bases: ConformalMethod

Conformal PID control for online interval calibration under shift.

Implements the proportional and integral modules of Angelopoulos, Candes and Tibshirani (2023). Starting from the oldest calibration window the method replays the backtest in time order. Per horizon it tracks the error quantile directly on the score scale:

  • P (quantile tracking) moves the threshold up after a miss and down after a cover, by lr times the recent range of the errors.
  • I (error integration) feeds the cumulative miscoverage through a saturating tan so that persistent coverage bias is corrected.

Errors are delay-aware: the error at horizon h of a window is only used h observations after its forecast origin, so step_size < h windows never see the future. The forecast being calibrated sees every window.

Parameters:

Name Type Description Default
symmetric bool

False (default) tracks the lower and upper tails separately (each targets alpha / 2 misses), so intervals can be asymmetric. True tracks the absolute error.

False
lr float

Base learning rate of quantile tracking, scaled internally by the range of recent errors.

0.1
integrate bool

Include the error-integration term.

True
KI float | None

Integrator scale. None uses the largest absolute calibration error of each series.

None
Csat float | None

Integrator saturation constant. None derives it from Tg and delta so the absolute coverage is at least 1 - alpha - delta by time Tg.

None
Tg float | None

Target time for the coverage guarantee. None uses n_windows.

None
delta float

Tolerated absolute coverage gap in (0, 1).

0.01
ncal int | None

Initial windows used to warm start the tracker, and the trailing window of the learning-rate range when rolling. None uses max(1, n_windows // 2).

None
rolling bool

Use only the last ncal errors for the learning-rate range instead of every error observed so far.

False
init Literal['quantile', 'zero']

"quantile" starts each tracker from the empirical quantile of the first ncal windows and replays the rest, which works with the few backtest windows typical for foundation models. "zero" starts from zero and replays every window (the reference formulation; needs many windows to warm up).

'quantile'
Example
from foundationforecast import ConformalIntervals, PID

ConformalIntervals(n_windows=20, method=PID(lr=0.1))

Each level is tracked independently. Thresholds are then floored at zero (intervals always contain the point forecast) and sorted across levels so wider levels contain narrower ones. When the integrator saturates (the realized miss rate is far from the target) the bound becomes infinite and forecast() emits a UserWarning. The scorecasting (D) module is not implemented.

symmetric class-attribute instance-attribute

symmetric: bool = False

lr class-attribute instance-attribute

lr: float = 0.1

integrate class-attribute instance-attribute

integrate: bool = True

KI class-attribute instance-attribute

KI: float | None = None

Csat class-attribute instance-attribute

Csat: float | None = None

Tg class-attribute instance-attribute

Tg: float | None = None

delta class-attribute instance-attribute

delta: float = 0.01

ncal class-attribute instance-attribute

ncal: int | None = None

rolling class-attribute instance-attribute

rolling: bool = False

init class-attribute instance-attribute

init: Literal['quantile', 'zero'] = 'quantile'

__post_init__

__post_init__() -> None
Source code in foundationforecast/core/conformal_pid.py
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
def __post_init__(self) -> None:
    if not self.lr > 0:
        raise ValueError("lr must be positive")
    if self.KI is not None and not self.KI >= 0:
        raise ValueError("KI must be non-negative")
    if self.Csat is not None and not self.Csat > 0:
        raise ValueError("Csat must be positive")
    if self.Tg is not None and not self.Tg > 1:
        raise ValueError("Tg must be greater than 1")
    if not 0 < self.delta < 1:
        raise ValueError("delta must be in (0, 1)")
    if self.ncal is not None and self.ncal < 1:
        raise ValueError("ncal must be a positive integer")
    if self.init not in ("quantile", "zero"):
        raise ValueError("init must be 'quantile' or 'zero'")

resolve_ncal

resolve_ncal(n_windows: int) -> int
Source code in foundationforecast/core/conformal_pid.py
213
214
def resolve_ncal(self, n_windows: int) -> int:
    return self.ncal if self.ncal is not None else max(1, n_windows // 2)

resolve_csat

resolve_csat(n_windows: int) -> float

Integrator saturation constant, or inf if the integrator is off.

Source code in foundationforecast/core/conformal_pid.py
216
217
218
219
220
221
222
223
224
225
226
227
228
229
def resolve_csat(self, n_windows: int) -> float:
    """Integrator saturation constant, or ``inf`` if the integrator is off."""
    if self.Csat is not None:
        return self.Csat
    if not self.integrate:
        return math.inf
    tg = self.Tg if self.Tg is not None else float(n_windows)
    try:
        return default_csat(tg, self.delta)
    except ValueError as exc:
        raise ValueError(
            f"{exc} (n_windows={n_windows}); use more windows, "
            "or set Tg/Csat or integrate=False"
        ) from exc

validate

validate(n_windows: int, step_size: int | None) -> None

Raise ValueError if the method cannot run with these settings.

Source code in foundationforecast/core/conformal_pid.py
231
232
233
234
235
236
237
def validate(self, n_windows: int, step_size: int | None) -> None:
    self.resolve_csat(n_windows)
    if self.init == "quantile" and self.resolve_ncal(n_windows) >= n_windows:
        raise ValueError(
            f"PID ncal={self.resolve_ncal(n_windows)} must be smaller than "
            f"n_windows={n_windows} so some windows remain to be replayed"
        )

thresholds

thresholds(
    errors: ndarray,
    level: list[int | float],
    step_size: int,
    final_gap: int,
) -> tuple[ndarray, ndarray]

Lower and upper thresholds (n_levels, n_series, h) for errors.

errors are signed y - y_hat with shape (n_windows, n_series, h), oldest window first. The interval is [y_hat - lower, y_hat + upper].

Source code in foundationforecast/core/conformal_pid.py
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def thresholds(
    self,
    errors: np.ndarray,
    level: list[int | float],
    step_size: int,
    final_gap: int,
) -> tuple[np.ndarray, np.ndarray]:
    """Lower and upper thresholds ``(n_levels, n_series, h)`` for ``errors``.

    ``errors`` are signed ``y - y_hat`` with shape
    ``(n_windows, n_series, h)``, oldest window first. The interval is
    ``[y_hat - lower, y_hat + upper]``.
    """
    n_windows = errors.shape[0]
    self.validate(n_windows, step_size)
    alpha = 1 - np.asarray(level, dtype=float) / 100
    csat = self.resolve_csat(n_windows)
    ki = (
        np.full(errors.shape[1], self.KI, dtype=float)
        if self.KI is not None
        else np.abs(errors).max(axis=(0, 2))
    )
    kwargs: dict[str, Any] = dict(
        step_size=step_size,
        final_gap=final_gap,
        lr=self.lr,
        ki=ki,
        csat=csat,
        ncal=self.resolve_ncal(n_windows),
        rolling=self.rolling,
        integrate=self.integrate,
        warm_start=self.init == "quantile",
    )
    if self.symmetric:
        radius = track_quantiles(np.abs(errors), alpha, **kwargs)
        return radius, radius
    lower = track_quantiles(-errors, alpha / 2, **kwargs)
    upper = track_quantiles(errors, alpha / 2, **kwargs)
    return lower, upper

radii

radii(
    errors: ndarray,
    level: list[int | float],
    step_size: int,
    final_gap: int,
) -> tuple[ndarray, ndarray]

thresholds floored at zero and nested across level.

level must be sorted ascending. Warns when a bound is infinite.

Source code in foundationforecast/core/conformal_pid.py
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
def radii(
    self,
    errors: np.ndarray,
    level: list[int | float],
    step_size: int,
    final_gap: int,
) -> tuple[np.ndarray, np.ndarray]:
    """`thresholds` floored at zero and nested across ``level``.

    ``level`` must be sorted ascending. Warns when a bound is infinite.
    """
    lower, upper = self.thresholds(errors, level, step_size, final_gap)
    lower = np.maximum.accumulate(np.maximum(lower, 0.0), axis=0)
    upper = np.maximum.accumulate(np.maximum(upper, 0.0), axis=0)
    if np.isinf(lower).any() or np.isinf(upper).any():
        warnings.warn(
            "PID error integration saturated: some bounds are infinite. "
            "Use more calibration windows, a larger Csat or Tg, or "
            "integrate=False.",
            UserWarning,
            stacklevel=3,
        )
    return lower, upper

__call__

__call__(
    fcst_df: DataFrame,
    cs_df: DataFrame,
    model_names: list[str],
    level: list[int | float],
    cs_n_windows: int,
    cs_h: int,
    n_series: int,
    horizon: int,
    step_size: int,
) -> DataFrame
Source code in foundationforecast/core/conformal_pid.py
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
def __call__(
    self,
    fcst_df: pd.DataFrame,
    cs_df: pd.DataFrame,
    model_names: list[str],
    level: list[int | float],
    cs_n_windows: int,
    cs_h: int,
    n_series: int,
    horizon: int,
    step_size: int,
) -> pd.DataFrame:
    fcst_df = ufp.copy_if_pandas(fcst_df, deep=False)
    lo_cols_suffix = list(reversed(level))
    for model in model_names:
        mean = fcst_df[model].to_numpy().reshape(1, n_series, -1)
        errors = cs_df[model].to_numpy().reshape(cs_n_windows, n_series, cs_h)
        lower, upper = self.radii(
            errors[:, :, :horizon], level, step_size, final_gap=cs_h
        )
        bounds = np.vstack([mean - lower[::-1], mean + upper]).reshape(
            2 * len(level), -1
        )
        lo_cols = [f"{model}-lo-{lv}" for lv in lo_cols_suffix]
        hi_cols = [f"{model}-hi-{lv}" for lv in level]
        fcst_df = ufp.assign_columns(fcst_df, lo_cols + hi_cols, bounds.T)
    return fcst_df

Bases: ConformalMethod

Adaptive conformal inference reconstructed from calibration windows.

Replays the Gibbs and Candes (2021) update alpha_next = alpha + gamma * (target_alpha - miss) separately for each series, horizon step, and level, starting at target_alpha = 1 - level/100. Scores are absolute point-forecast errors. An interval uses the inverse empirical CDF of previously revealed scores, without interpolation or the finite-sample rank correction of conformal_error_finite_sample.

Parameters:

Name Type Description Default
gamma float

Adaptation rate in (0, 1] (default 0.01). A miss decreases alpha and requests a higher quantile; a cover increases alpha.

0.01
ncal int | None

Initial windows used only to seed the score distribution (no alpha updates). None uses max(1, n_windows // 2). Must be smaller than n_windows. A warm-up score enters the CDF when revealed, even if it was not yet observable at the first replay origin.

None
rolling bool

Use only the latest ncal revealed scores for the CDF (True), or all revealed scores (False, default).

False

Feedback at horizon step j is used only after j observations have passed since its forecast origin. Pending scores are checked against the intervals actually issued during replay, so overlapping windows do not leak future errors. No state persists across calls or models.

Alpha is not clipped: alpha <= 0 produces an unbounded interval and alpha >= 1 an empty interval. Empty intervals are represented by lower +inf and upper -inf. Output radii are widened across sorted levels to make intervals nested. Non-finite output bounds emit a UserWarning.

Resetting replay on each call, delayed feedback, and output nesting mean this API does not inherit the continuous online algorithm's long-run coverage guarantee. Measure coverage and width on held-out backtests.

Example
from foundationforecast import ACI, ConformalIntervals

ConformalIntervals(n_windows=20, method=ACI(gamma=0.005))

gamma class-attribute instance-attribute

gamma: float = 0.01

ncal class-attribute instance-attribute

ncal: int | None = None

rolling class-attribute instance-attribute

rolling: bool = False

__post_init__

__post_init__() -> None
Source code in foundationforecast/core/conformal_aci.py
108
109
110
111
112
113
114
115
116
117
118
119
120
def __post_init__(self) -> None:
    if (
        isinstance(self.gamma, bool)
        or not math.isfinite(self.gamma)
        or not 0 < self.gamma <= 1
    ):
        raise ValueError("ACI gamma must be finite and in (0, 1]")
    if self.ncal is not None and (
        isinstance(self.ncal, bool)
        or not isinstance(self.ncal, Integral)
        or self.ncal < 1
    ):
        raise ValueError("ACI ncal must be a positive integer")

resolve_ncal

resolve_ncal(n_windows: int) -> int
Source code in foundationforecast/core/conformal_aci.py
122
123
def resolve_ncal(self, n_windows: int) -> int:
    return int(self.ncal) if self.ncal is not None else max(1, n_windows // 2)

validate

validate(n_windows: int, step_size: int | None) -> None

Raise ValueError if the method cannot run with these settings.

Source code in foundationforecast/core/conformal_aci.py
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
def validate(self, n_windows: int, step_size: int | None) -> None:
    if (
        isinstance(n_windows, bool)
        or not isinstance(n_windows, Integral)
        or n_windows < 2
    ):
        raise ValueError("ACI n_windows must be an integer of at least 2")
    if self.resolve_ncal(n_windows) >= n_windows:
        raise ValueError("ACI ncal must be smaller than n_windows to replay errors")
    if step_size is not None and (
        isinstance(step_size, bool)
        or not isinstance(step_size, Integral)
        or step_size < 1
    ):
        raise ValueError("ACI step_size must be a positive integer")

thresholds

thresholds(
    errors: ndarray,
    level: Sequence[int | float],
    step_size: int,
    final_gap: int,
) -> ndarray

Return raw symmetric radii of shape (n_levels, n_series, h).

Errors have shape (n_windows, n_series, h) and are oldest first. final_gap is the distance from the last calibration origin to the forecast origin; forecast() passes its calibration horizon here. This mathematical helper does not nest radii or warn about edge sets.

Source code in foundationforecast/core/conformal_aci.py
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
def thresholds(
    self,
    errors: np.ndarray,
    level: Sequence[int | float],
    step_size: int,
    final_gap: int,
) -> np.ndarray:
    """Return raw symmetric radii of shape ``(n_levels, n_series, h)``.

    Errors have shape ``(n_windows, n_series, h)`` and are oldest first.
    ``final_gap`` is the distance from the last calibration origin to the
    forecast origin; ``forecast()`` passes its calibration horizon here.
    This mathematical helper does not nest radii or warn about edge sets.
    """
    errors = np.asarray(errors, dtype=float)
    if errors.ndim != 3 or min(errors.shape) < 1:
        raise ValueError("ACI errors must have shape (n_windows, n_series, h)")
    self.validate(errors.shape[0], step_size)
    if (
        isinstance(final_gap, bool)
        or not isinstance(final_gap, Integral)
        or final_gap < 1
    ):
        raise ValueError("ACI final_gap must be a positive integer")
    if not np.isfinite(errors).all():
        raise ValueError("ACI requires finite calibration errors")
    levels = np.asarray(level, dtype=float)
    if (
        levels.ndim != 1
        or levels.size == 0
        or not np.isfinite(levels).all()
        or np.any((levels < 0) | (levels > 100))
    ):
        raise ValueError("ACI levels must be finite and in [0, 100]")
    return _replay_aci(
        np.abs(errors),
        1 - levels / 100,
        step_size=step_size,
        final_gap=final_gap,
        gamma=self.gamma,
        ncal=self.resolve_ncal(errors.shape[0]),
        rolling=self.rolling,
    )

__call__

__call__(
    fcst_df: DataFrame,
    cs_df: DataFrame,
    model_names: list[str],
    level: list[int | float],
    cs_n_windows: int,
    cs_h: int,
    n_series: int,
    horizon: int,
    step_size: int,
) -> DataFrame
Source code in foundationforecast/core/conformal_aci.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
def __call__(
    self,
    fcst_df: pd.DataFrame,
    cs_df: pd.DataFrame,
    model_names: list[str],
    level: list[int | float],
    cs_n_windows: int,
    cs_h: int,
    n_series: int,
    horizon: int,
    step_size: int,
) -> pd.DataFrame:
    fcst_df = ufp.copy_if_pandas(fcst_df, deep=False)
    unbounded = np.zeros(len(level), dtype=bool)
    empty = np.zeros(len(level), dtype=bool)
    for model in model_names:
        mean = fcst_df[model].to_numpy().reshape(1, n_series, horizon)
        errors = cs_df[model].to_numpy().reshape(cs_n_windows, n_series, cs_h)
        raw = self.thresholds(errors[:, :, :horizon], level, step_size, cs_h)
        radius = np.maximum.accumulate(raw, axis=0)
        unbounded |= np.isposinf(radius).any(axis=(1, 2))
        empty |= np.isneginf(radius).any(axis=(1, 2))
        bounds = np.vstack([mean - radius[::-1], mean + radius]).reshape(
            2 * len(level), -1
        )
        columns = [f"{model}-lo-{lv}" for lv in reversed(level)]
        columns += [f"{model}-hi-{lv}" for lv in level]
        fcst_df = ufp.assign_columns(fcst_df, columns, bounds.T)
    descriptions = []
    for mask, kind in [(unbounded, "unbounded"), (empty, "empty")]:
        if mask.any():
            affected = ", ".join(
                f"{lv:g}" for lv, bad in zip(level, mask, strict=False) if bad
            )
            descriptions.append(f"{kind} intervals at level(s) {affected}")
    if descriptions:
        warnings.warn(
            "ACI replay produced "
            + "; ".join(descriptions)
            + f" (n_windows={cs_n_windows}, "
            + f"ncal={self.resolve_ncal(cs_n_windows)}, gamma={self.gamma:g}). "
            "Unbounded bounds are -inf/+inf; empty "
            "bounds are +inf/-inf. Use more calibration windows or review gamma "
            "before plotting or scoring these intervals.",
            UserWarning,
            stacklevel=2,
        )
    return fcst_df