Skip to content

Online Adaptive Conformal Inference (ACI) & Regime-Shift Tracking

flowchart TD
    A1["1. Initialize Nominal Coverage & Step Size<br/>target_coverage (1 - alpha) · gamma (aci_gamma) · normalized=True"] --> A2["2. Observe Delayed h-Step Feedback<br/>err_{t,h} = 1{y_t not in [L_{t|t-h}, U_{t|t-h}]} · horizon_delay"]
    A2 --> A3["3. Update Effective Miscoverage Rate Online<br/>alpha_{t+1,h} = clip(alpha_{t,h} + gamma * (alpha - err_{t,h}), 0.005, 0.50)"]
    A3 --> A4["4. Recalibrate Intervals & Flag Regime Drift<br/>compute_aci_df · update_aci_online · ks_drift_stat · plot_aci"]

aci

Online Adaptive Conformal Inference (ACI & Volatility-Normalized ACI) — pure.

Standard split/out-of-fold conformal prediction intervals assume exchangeability between historical backtest folds and future periods. Under mid-series volatility shocks, price regime shifts, or structural breaks, static conformal intervals can suffer severe miscoverage.

This module implements: 1. Gibbs & Candès (2021) Online Quantile Adaptation ("aci"): $$\alpha_{t+1} = \text{clip}(\alpha_t + \gamma (\alpha_{\text{target}} - \text{err}t), \; \epsilon,\; 1 - \epsilon)$$ where $\text{err}_t = \mathbb{I}{y_t \notin [\hat{L}_t, \hat{U}_t]}$. 2. Scale-Normalized / Volatility-Weighted ACI ("aci_normalized"): Couples online $\alpha_t$ adaptation with an Exponentially Weighted Moving Average (EWMA) local residual volatility multiplier $s} = \hat{\sigma{i,t} / \hat{\sigma}$ so prediction intervals expand immediately during volatility bursts and contract smoothly when stability returns. 3. Leak-Free Multi-Step Horizon Feedback Delay ($h$-Step Lag): For an $h$-step-ahead forecast at index $t$, online state updates $(\alpha_t, s_{i,t})$ depend strictly on realized errors at indices $\tau \le t - h$ (i.e., available at forecast origin $t - h + 1$), guaranteeing zero lookahead leakage across multi-step horizons.

AciCalibrationState dataclass

AciCalibrationState(
    method,
    target_alpha,
    gamma,
    terminal_alpha,
    empirical_coverage_split,
    empirical_coverage_aci,
    mean_width_split,
    mean_width_aci,
    volatility_scale,
    drift_detected,
    alpha_trajectory,
    err_trajectory,
    q80_per_step,
    q80_flat,
    quantile_offsets_per_step,
    quantile_offsets_flat,
)

Summary of online ACI state and empirical coverage across an OOF or streaming trajectory.

n_steps property

n_steps

Number of online trajectory steps processed.

calibrate_aci_from_oof

calibrate_aci_from_oof(
    oof,
    *,
    method="aci",
    gamma=0.05,
    target_coverage=0.8,
    quantiles=DEFAULT_QUANTILES,
    residual_column="yhat_raw",
)

Learn an online ACI-adjusted Calibration and AciCalibrationState from an OOF frame.

Source code in src/scale_forecasting/aci.py
def calibrate_aci_from_oof(
    oof: pd.DataFrame,
    *,
    method: CalibrationMethod = "aci",
    gamma: float = 0.05,
    target_coverage: float = 0.80,
    quantiles: Sequence[float] = DEFAULT_QUANTILES,
    residual_column: str = "yhat_raw",
) -> tuple[Calibration | None, AciCalibrationState | None]:
    """Learn an online ACI-adjusted `Calibration` and `AciCalibrationState` from an OOF frame."""
    if oof is None or oof.empty:
        return None, None
    needed = {"y_true", residual_column}
    if not needed.issubset(oof.columns):
        return None, None

    y_true = pd.to_numeric(oof["y_true"], errors="coerce").to_numpy(dtype=float)
    y_raw = pd.to_numeric(oof[residual_column], errors="coerce").to_numpy(dtype=float)
    resid = y_true - y_raw
    ok = np.isfinite(resid)
    if int(np.count_nonzero(ok)) < MIN_RESIDUALS_TOTAL:
        return None, None

    # Run online ACI across OOF to obtain terminal alpha_T and volatility scale
    oof_for_aci = oof.copy()
    if "yhat" not in oof_for_aci.columns:
        oof_for_aci["yhat"] = oof_for_aci[residual_column]
    _, aci_state = _run_single_series_aci(
        oof_for_aci,
        gamma=gamma,
        target_coverage=target_coverage,
        normalized=(method == "aci_normalized"),
        horizon_delay=True,
        ts_id_col="ts_id" if "ts_id" in oof_for_aci.columns else "fold_id",
        date_col="ds" if "ds" in oof_for_aci.columns else "cutoff_date",
    )

    # Compute effective scale multiplier from terminal_alpha and volatility_scale
    z_ratio = _normal_quantile_ratio(aci_state.terminal_alpha, aci_state.target_alpha)
    scale_mult = float(np.clip(z_ratio * aci_state.volatility_scale, 0.35, 15.0))

    q_seq = tuple(sorted({round(float(q), 6) for q in quantiles} | {0.1, 0.5, 0.9}))
    ordered_all = np.sort(resid[ok])
    base_pooled = StepCalibration(
        quantiles={float(q): empirical_quantile(ordered_all, float(q)) for q in q_seq},
        mean=float(np.mean(resid[ok])),
        n=int(ordered_all.size),
    )
    scaled_pooled = _scale_step_calibration(base_pooled, scale_mult, q_seq)

    steps_raw = (
        pd.to_numeric(oof["horizon_step"], errors="coerce").to_numpy(dtype=float)
        if "horizon_step" in oof.columns
        else None
    )
    src_prefix = "aci-normalized" if method == "aci_normalized" else "aci"

    if steps_raw is None or not bool(np.any(ok & np.isfinite(steps_raw))):
        cal = Calibration(by_step={}, pooled=scaled_pooled, source=f"{src_prefix}-flat")
        return cal, aci_state

    have_steps = ok & np.isfinite(steps_raw)
    valid_resid = resid[have_steps]
    valid_steps = steps_raw[have_steps].astype(int)
    unique_steps = np.unique(valid_steps)
    grouped: dict[int, np.ndarray] = {int(s): valid_resid[valid_steps == s] for s in unique_steps}
    steps = [int(s) for s in unique_steps]
    by_step: dict[int, StepCalibration] = {}
    for step in steps:
        sample = window_residuals(grouped, step, steps)
        if sample.size:
            ord_s = np.sort(sample)
            base_s = StepCalibration(
                quantiles={float(q): empirical_quantile(ord_s, float(q)) for q in q_seq},
                mean=float(np.mean(sample)),
                n=int(ord_s.size),
            )
            by_step[step] = _scale_step_calibration(base_s, scale_mult, q_seq)

    distinct = {(*sorted(s.quantiles.items()), s.mean) for s in by_step.values()}
    if not by_step or len(distinct) == 1:
        cal = Calibration(by_step={}, pooled=scaled_pooled, source=f"{src_prefix}-flat")
    else:
        cal = Calibration(by_step=by_step, pooled=scaled_pooled, source=f"{src_prefix}-per-step")
    return cal, aci_state

compute_aci_df

compute_aci_df(
    oof_or_actuals_df,
    predictions_df=None,
    *,
    gamma=0.05,
    target_coverage=0.8,
    normalized=True,
    method=None,
    horizon_delay=True,
    ts_id_col="ts_id",
    date_col="ds",
)

Compute online Adaptive Conformal Inference (ACI) trajectories and coverage diagnostics.

Accepts either: - An out-of-fold DataFrame containing y_true and yhat (or yhat_raw), or - Newly arrived actuals oof_or_actuals_df (with y or y_true) paired with predictions_df (with yhat).

Source code in src/scale_forecasting/aci.py
def compute_aci_df(
    oof_or_actuals_df: pd.DataFrame,
    predictions_df: pd.DataFrame | None = None,
    *,
    gamma: float = 0.05,
    target_coverage: float = 0.80,
    normalized: bool = True,
    method: CalibrationMethod | None = None,
    horizon_delay: bool = True,
    ts_id_col: str = "ts_id",
    date_col: str = "ds",
) -> pd.DataFrame:
    """Compute online Adaptive Conformal Inference (`ACI`) trajectories and coverage diagnostics.

    Accepts either:
    - An out-of-fold DataFrame containing ``y_true`` and ``yhat`` (or ``yhat_raw``), or
    - Newly arrived actuals ``oof_or_actuals_df`` (with ``y`` or ``y_true``) paired with
      ``predictions_df`` (with ``yhat``).
    """
    use_normalized = (method == "aci_normalized") if method is not None else bool(normalized)

    columns = [
        "ts_id",
        "model_type",
        "ds",
        "step_idx",
        "fold_id",
        "horizon_step",
        "y_true",
        "yhat",
        "abs_error",
        "volatility_scale",
        "local_scale",
        "alpha_t",
        "err_t",
        "static_lower",
        "static_upper",
        "aci_lower",
        "aci_upper",
        "lower_split",
        "upper_split",
        "lower_aci",
        "upper_aci",
        "static_covered",
        "aci_covered",
        "covered_split",
        "covered_aci",
        "static_coverage",
        "aci_coverage",
        "rolling_coverage_split",
        "rolling_coverage_aci",
        "target_coverage",
        "static_width",
        "aci_width",
        "interval_width_ratio",
        "drift_detected",
    ]
    if oof_or_actuals_df is None or oof_or_actuals_df.empty:
        return pd.DataFrame(columns=columns)

    df = oof_or_actuals_df.copy()
    dcol = (
        date_col
        if date_col in df.columns
        else ("forecast_date" if "forecast_date" in df.columns else "ds")
    )

    # If predictions_df is provided separately, join actuals + predictions
    if predictions_df is not None and not predictions_df.empty and "yhat" not in df.columns:
        p_df = predictions_df.copy()
        p_dcol = (
            dcol
            if dcol in p_df.columns
            else ("forecast_date" if "forecast_date" in p_df.columns else "ds")
        )
        if p_dcol != dcol and p_dcol in p_df.columns:
            p_df = p_df.rename(columns={p_dcol: dcol})
        join_cols = [c for c in (ts_id_col, dcol) if c in df.columns and c in p_df.columns]
        if join_cols:
            df = pd.merge(df, p_df, on=join_cols, how="inner", suffixes=("_actual", ""))
            if "y_true" not in df.columns and "y" in df.columns:
                df["y_true"] = df["y"]

    if "y_true" not in df.columns and "y" in df.columns:
        df["y_true"] = df["y"]
    if "yhat" not in df.columns and "yhat_raw" in df.columns:
        df["yhat"] = df["yhat_raw"]

    if "y_true" not in df.columns or "yhat" not in df.columns:
        return pd.DataFrame(columns=columns)

    group_cols = [c for c in (ts_id_col, "model_type") if c in df.columns]
    parts: list[pd.DataFrame] = []
    states: dict[str, AciCalibrationState] = {}

    if group_cols:
        for g_key, grp in df.groupby(group_cols, sort=False):
            part_df, st = _run_single_series_aci(
                grp,
                gamma=gamma,
                target_coverage=target_coverage,
                normalized=use_normalized,
                horizon_delay=horizon_delay,
                ts_id_col=ts_id_col,
                date_col=dcol,
            )
            if not part_df.empty:
                parts.append(part_df)
                key_str = (
                    "|".join(str(x) for x in g_key) if isinstance(g_key, tuple) else str(g_key)
                )
                states[key_str] = st
    else:
        part_df, st = _run_single_series_aci(
            df,
            gamma=gamma,
            target_coverage=target_coverage,
            normalized=use_normalized,
            horizon_delay=horizon_delay,
            ts_id_col=ts_id_col,
            date_col=dcol,
        )
        if not part_df.empty:
            parts.append(part_df)
            states["series_0"] = st

    if not parts:
        return pd.DataFrame(columns=columns)

    res_df = pd.concat(parts, ignore_index=True)
    res_df.attrs["aci_states"] = states
    return res_df

plot_aci

plot_aci(aci_df_in, *, ts_id=None, ax=None)

Plot static conformal vs. online ACI intervals, rolling coverage, and drift events.

Source code in src/scale_forecasting/aci.py
def plot_aci(
    aci_df_in: pd.DataFrame,
    *,
    ts_id: str | None = None,
    ax: Any | None = None,
) -> Any:
    """Plot static conformal vs. online ACI intervals, rolling coverage, and drift events."""
    import matplotlib.pyplot as plt

    if ax is None:
        _, ax = plt.subplots(figsize=(9, 4.5))

    if aci_df_in is None or aci_df_in.empty:
        ax.set_title("Online Adaptive Conformal Inference (Empty)")
        return ax

    df = aci_df_in
    if "aci_lower" not in df.columns:
        df = compute_aci_df(df)

    if ts_id is not None and "ts_id" in df.columns:
        df = df[df["ts_id"].astype(str) == str(ts_id)]
    elif "ts_id" in df.columns and df["ts_id"].nunique() > 1:
        first_id = df["ts_id"].iloc[0]
        df = df[df["ts_id"] == first_id]

    if df.empty:
        ax.set_title("Online Adaptive Conformal Inference (No Matching Series)")
        return ax

    x = np.arange(len(df))
    y_true = df["y_true"].to_numpy(dtype=float)
    yhat = df["yhat"].to_numpy(dtype=float)
    s_lo = df["static_lower"].to_numpy(dtype=float)
    s_hi = df["static_upper"].to_numpy(dtype=float)
    a_lo = df["aci_lower"].to_numpy(dtype=float)
    a_hi = df["aci_upper"].to_numpy(dtype=float)

    ax.plot(x, y_true, "k.", markersize=4, label="Actual (y_true)")
    ax.plot(x, yhat, "b-", linewidth=1.3, label="Forecast (yhat)")
    ax.fill_between(x, s_lo, s_hi, color="gray", alpha=0.25, label="Static Conformal Band")
    ax.fill_between(x, a_lo, a_hi, color="tab:orange", alpha=0.25, label="Online ACI Band")

    s_cov = float(df["static_covered"].mean()) if "static_covered" in df.columns else float("nan")
    a_cov = float(df["aci_covered"].mean()) if "aci_covered" in df.columns else float("nan")
    tid_label = str(df["ts_id"].iloc[0]) if "ts_id" in df.columns else "series"
    ax.set_title(
        f"Online ACI vs. Static Conformal — {tid_label} "
        f"(Static Cov={s_cov:.1%}, ACI Cov={a_cov:.1%})"
    )
    ax.set_xlabel("Step Index")
    ax.set_ylabel("Value")
    ax.legend(loc="best")
    return ax