28  End-to-End Forecasting Pipeline

Part VII. Responsible AI, Projects, and Deployment
Chapter goal: build a complete, reproducible forecasting workflow from raw ordered data to a forecast report. We connect mathematical information sets, preprocessing, feature construction, baseline modeling, validation, uncertainty, monitoring, and AI-assisted quality control.

28.1 Learning objectives

After studying this chapter, you should be able to:

  1. define the forecasting target, forecast origin, horizon, and information set for an applied problem;
  2. design a leakage-safe preprocessing and feature-engineering pipeline;
  3. construct baseline, statistical, and machine-learning forecasting models in a reproducible workflow;
  4. use chronological validation and rolling-origin evaluation to compare candidate models;
  5. evaluate point forecasts, intervals, and residual behavior;
  6. package forecasts into a report that records assumptions, diagnostics, and model limitations;
  7. identify the difference between validation performance and deployment performance;
  8. use AI assistance as a workflow critic while verifying every suggestion with code, mathematics, or diagnostics.

28.2 26.1 Why an end-to-end pipeline matters

A forecasting model is only one part of a forecasting system. In practice, students and analysts often spend most of their time on the surrounding decisions:

\[ \text{raw data} \rightarrow \text{cleaning} \rightarrow \text{target definition} \rightarrow \text{features} \rightarrow \text{model fitting} \rightarrow \text{validation} \rightarrow \text{forecast report} \rightarrow \text{monitoring}. \]

A mathematically strong model can fail if any step is invalid. A random train–test split can make a weak model look excellent. A rolling mean can accidentally use the target value being predicted. A model can beat ARIMA on one validation split but fail under a different forecast horizon. An interval forecast can look impressive but miss the true value too often.

The purpose of this chapter is to make the whole workflow explicit. We treat forecasting as an operation performed at a forecast origin. At time \(t\), the analyst has an information set \(\mathcal F_t\). A valid \(h\)-step-ahead forecast must satisfy

\[ \widehat Y_{t+h|t}=g_h(\mathcal F_t). \]

This condition is the organizing principle for the entire pipeline.

WarningForecasting is not ordinary supervised learning

In ordinary supervised learning, the row order may be irrelevant. In forecasting, the row order is part of the mathematical problem. The feature vector for \(Y_{t+h}\) must be constructed only from information available at time \(t\).

28.3 26.2 The forecasting contract

Before fitting any model, write a forecasting contract. A forecasting contract is a precise statement of the statistical problem.

A minimal contract includes:

  • target variable \(Y_t\);
  • time index \(t\) and observation frequency;
  • forecast origin \(t_0\);
  • horizon set \(\mathcal H=\{1,\ldots,H\}\);
  • information set \(\mathcal F_{t_0}\);
  • update schedule;
  • loss function;
  • forecast output: point forecast, interval forecast, quantile forecast, probability event forecast, or scenario forecast.

For example, for daily demand forecasting, the contract may be:

\[ \widehat Y_{t+h|t}=g_h\left(Y_t,Y_{t-1},\ldots; C_t,C_{t+1},\ldots,C_{t+h}; X_t,X_{t-1},\ldots\right), \]

where \(C_s\) are calendar variables known in advance and \(X_s\) are exogenous covariates. If a covariate \(X_{t+h}\) is not known at the forecast origin, then it cannot be used unless a separate forecast for \(X_{t+h}\) is included.

A common mistake is to form a feature matrix first and then ask whether it predicts well. A better workflow is to first define \(\mathcal F_t\), then build the feature matrix from \(\mathcal F_t\).

28.4 26.3 Mathematical structure of a forecasting pipeline

Let the observed series be \(Y_1,\ldots,Y_n\). Let \(\tau\) denote a forecast origin and let \(h\) be a forecast horizon. A valid forecasting pipeline has the form

\[ \widehat Y_{\tau+h|\tau} = T_\tau^{-1}\left( f_{\widehat\theta_\tau,h}\left(\Phi_{\tau,h}(\mathcal F_\tau)\right) \right), \]

where:

  • \(T_\tau\) is a transformation fitted using training data available at \(\tau\);
  • \(\Phi_{\tau,h}\) is the feature map constructed from \(\mathcal F_\tau\);
  • \(f_{\widehat\theta_\tau,h}\) is the fitted forecasting model;
  • \(T_\tau^{-1}\) maps the forecast back to the original scale.

The subscript \(\tau\) is important. It reminds us that transformations, scalers, imputers, and model parameters must be fitted using only the training information available at the forecast origin.

For a chronological split with training set \(\{1,\ldots,m\}\) and test set \(\{m+1,\ldots,n\}\), a leakage-safe preprocessing estimator must satisfy

\[ \widehat T_m = \operatorname{FitTransform}(Y_1,\ldots,Y_m), \]

not

\[ \widehat T_n = \operatorname{FitTransform}(Y_1,\ldots,Y_n). \]

The second expression uses future test information and can make validation performance overly optimistic.

28.5 26.4 Target design and horizon design

The same data set can produce different forecasting problems. For horizon \(h\), one may define a direct model

\[ Y_{t+h}=f_h(X_t)+\varepsilon_{t+h}, \]

where \(X_t\) is a feature vector built from \(\mathcal F_t\). The model \(f_h\) is trained separately for each horizon.

A recursive model first trains a one-step model

\[ Y_{t+1}=f_1(X_t)+\varepsilon_{t+1}, \]

then feeds predicted values back into the future feature vectors. Recursive forecasting is simple but may accumulate error.

A multi-output model predicts an entire path:

\[ (Y_{t+1},\ldots,Y_{t+H}) = F(X_t)+\varepsilon_{t,1:H}. \]

Each design is valid, but each answers a different operational question. The validation procedure must match the forecast use case.

NoteForecast origin discipline

When evaluating a forecast for \(Y_{t+h}\), ask: At what time was this forecast made? Then check whether every feature would have been known at that time.

28.6 26.5 Preprocessing without leakage

Typical preprocessing steps include missing-value handling, outlier treatment, variance-stabilizing transformations, scaling, and calendar alignment. For time series, preprocessing must be fitted chronologically.

Suppose \(S(\cdot)\) is a scaling transformation. A valid split-specific scaler is

\[ \widehat\mu_{\text{train}} = \frac{1}{m}\sum_{t=1}^m Y_t, \qquad \widehat\sigma_{\text{train}}^2 = \frac{1}{m-1}\sum_{t=1}^m (Y_t-\widehat\mu_{\text{train}})^2. \]

Then the scaled test value is

\[ Z_t = \frac{Y_t-\widehat\mu_{\text{train}}}{\widehat\sigma_{\text{train}}}, \qquad t>m. \]

Invalid scaling would compute the mean and standard deviation using all \(n\) observations.

The same rule applies to imputation. If a missing value at time \(t\) is filled using a centered moving average,

\[ \frac{Y_{t-1}+Y_{t+1}}{2}, \]

then the imputation uses future data. This may be acceptable for retrospective smoothing, but it is invalid for real-time forecasting unless \(Y_{t+1}\) would already be known.

28.7 26.6 Feature engineering as an information map

Feature engineering should be viewed as a map

\[ \Phi_{\tau,h}:\mathcal F_\tau \to \mathbb R^p. \]

For one-step-ahead daily forecasting, valid features may include

\[ Y_\tau, \quad Y_{\tau-1}, \quad Y_{\tau-6}, \quad \frac{1}{7}\sum_{j=0}^6 Y_{\tau-j}, \quad \sin\left(\frac{2\pi d_\tau}{7}\right), \quad \cos\left(\frac{2\pi d_\tau}{7}\right). \]

For forecasting \(Y_t\) using a row indexed by \(t\), the same features are often written as

\[ Y_{t-1}, \quad Y_{t-7}, \quad \frac{1}{7}\sum_{j=1}^7 Y_{t-j}, \quad \sin\left(\frac{2\pi d_t}{7}\right), \quad \cos\left(\frac{2\pi d_t}{7}\right). \]

Notice that the rolling mean starts at \(Y_{t-1}\), not \(Y_t\).

WarningRolling-feature leakage

For predicting \(Y_t\), the feature \[ \frac{1}{7}\sum_{j=0}^6 Y_{t-j} \] is invalid because it includes \(Y_t\), the target being predicted. Use \[ \frac{1}{7}\sum_{j=1}^7 Y_{t-j} \] instead.

28.8 26.7 Baselines are part of the pipeline

A forecasting system should include baselines before advanced models. Baselines are not optional; they define what “useful” means.

Common baselines include:

\[ \widehat Y_{t+1|t}^{\text{naive}} = Y_t, \]

\[ \widehat Y_{t+h|t}^{\text{seasonal naive}} = Y_{t+h-s}, \]

where \(s\) is the seasonal period, and

\[ \widehat Y_{t+1|t}^{\text{mean}}=\frac{1}{m}\sum_{j=1}^m Y_j. \]

If a neural network, transformer, or automated forecasting method cannot beat a simple seasonal naive baseline under a fair validation design, the advanced method is not yet justified.

28.9 26.8 Model fitting as a reproducible object

A fitted forecasting pipeline should be reproducible. This means recording:

  • data version;
  • target definition;
  • feature definitions;
  • train/validation/test splits;
  • model class;
  • hyperparameters;
  • random seeds;
  • metrics;
  • diagnostic plots;
  • final forecast origin;
  • final forecast output.

Mathematically, model selection can be written as empirical risk minimization over candidate pipelines \(\mathcal P_1,\ldots,\mathcal P_M\):

\[ \widehat m = \arg\min_{m\in\{1,\ldots,M\}} \frac{1}{K}\sum_{k=1}^K L\left(Y_{\tau_k+h},\widehat Y_{\tau_k+h|\tau_k}^{(m)}\right), \]

where \(\tau_1,\ldots,\tau_K\) are rolling forecast origins. The selected model depends on the chosen loss \(L\), horizon \(h\), and validation origins.

28.10 26.9 Validation design

Time-aware validation should imitate the future use of the model. In rolling-origin validation, we choose forecast origins

\[ \tau_1<\tau_2<\cdots<\tau_K, \]

fit the model using data up to each \(\tau_k\), and evaluate forecasts after \(\tau_k\).

For one-step-ahead validation,

\[ e_k = Y_{\tau_k+1}-\widehat Y_{\tau_k+1|\tau_k}. \]

For multi-step validation,

\[ e_{k,h}=Y_{\tau_k+h}-\widehat Y_{\tau_k+h|\tau_k}, \qquad h=1,\ldots,H. \]

Horizon-wise error summaries are important:

\[ \operatorname{MAE}(h)=\frac{1}{K}\sum_{k=1}^K |e_{k,h}|, \]

\[ \operatorname{RMSE}(h)=\left(\frac{1}{K}\sum_{k=1}^K e_{k,h}^2\right)^{1/2}. \]

A model may be excellent at horizon \(h=1\) and poor at horizon \(h=14\).

28.11 26.10 Interactive module: validation versus deployment

This interactive module shows how a model can look good during validation when it uses an invalid future feature. Toggle the leakage option and compare the apparent validation error with the deployment-safe error.

Interactive Module 26.1: Forecasting Pipeline Simulator

The model is fitted on a synthetic daily series. When leakage is enabled, the validation forecast is allowed to use a future target value. The deployment-safe line shows what happens when that future value is unavailable.

<label>Trend strength
  <input id="ch26_pipe_trend" type="range" min="0" max="0.08" step="0.005" value="0.03">
  <span id="ch26_pipe_trend_value">0.03</span>
</label>
<label>Weekly seasonality
  <input id="ch26_pipe_season" type="range" min="0" max="6" step="0.25" value="3.00">
  <span id="ch26_pipe_season_value">3.00</span>
</label>
<label>Noise level
  <input id="ch26_pipe_noise" type="range" min="0" max="4" step="0.25" value="1.50">
  <span id="ch26_pipe_noise_value">1.50</span>
</label>
<label>Training fraction
  <input id="ch26_pipe_train" type="range" min="0.50" max="0.85" step="0.05" value="0.70">
  <span id="ch26_pipe_train_value">0.70</span>
</label>
<label>Model class
  <select id="ch26_pipe_model">
    <option value="seasonal">seasonal naive</option>
    <option value="laglinear" selected>lag linear model</option>
    <option value="calendar">calendar ridge model</option>
  </select>
</label>
<label class="checkbox-label">
  <input id="ch26_pipe_leakage" type="checkbox">
  include invalid future feature
</label>

28.12 26.11 Residual diagnostics and forecast intervals

After choosing a model, inspect the residuals. For one-step forecasts, residuals are

\[ \widehat e_t=Y_t-\widehat Y_{t|t-1}. \]

A useful model should leave residuals that are difficult to predict from the past. We do not require perfect Gaussian white noise for every machine-learning model, but we should look for:

  • residual autocorrelation;
  • horizon-specific bias;
  • changing residual variance;
  • outliers and structural breaks;
  • poor interval coverage;
  • systematic errors during holidays or special regimes.

A simple residual-based interval is

\[ \widehat Y_{t+h|t} \pm z_{1-\alpha/2}\widehat\sigma_h, \]

where \(\widehat\sigma_h\) is estimated from validation residuals at horizon \(h\). A more robust alternative is to use empirical residual quantiles:

\[ \left[ \widehat Y_{t+h|t}+\widehat q_{\alpha/2,h}, \widehat Y_{t+h|t}+\widehat q_{1-\alpha/2,h} \right]. \]

For machine-learning pipelines, conformal prediction can be added after validation residuals are obtained. The key point is that interval construction must use a calibration set that occurs after training and before final testing or deployment.

28.13 26.12 Deployment and monitoring

Forecasting does not end when the model is fitted. After deployment, the data-generating process may change. Let \(e_t\) be a deployed forecast error. A rolling monitoring statistic may be

\[ M_t = \frac{1}{w}\sum_{j=0}^{w-1}|e_{t-j}|. \]

If \(M_t\) exceeds a threshold based on validation performance, the system should alert the analyst.

For example, if \(\widehat m_{\text{val}}\) and \(\widehat s_{\text{val}}\) are the mean and standard deviation of validation absolute errors, a simple alert rule is

\[ M_t > \widehat m_{\text{val}} + c\widehat s_{\text{val}}. \]

This rule is not a theorem guaranteeing failure. It is a practical monitoring device that tells the analyst when the production environment no longer resembles validation.

Interactive Module 26.2: Deployment Monitoring Dashboard

A deployed model is monitored using rolling absolute error. Increase the drift size or make the monitoring threshold stricter to see when alerts occur.

<label>Drift time
  <input id="ch26_mon_drift_time" type="range" min="80" max="180" step="5" value="130">
  <span id="ch26_mon_drift_time_value">130</span>
</label>
<label>Drift size
  <input id="ch26_mon_drift_size" type="range" min="0" max="8" step="0.5" value="3.0">
  <span id="ch26_mon_drift_size_value">3.0</span>
</label>
<label>Rolling window
  <input id="ch26_mon_window" type="range" min="7" max="35" step="7" value="14">
  <span id="ch26_mon_window_value">14</span>
</label>
<label>Threshold multiplier
  <input id="ch26_mon_threshold" type="range" min="0.5" max="4" step="0.25" value="2.0">
  <span id="ch26_mon_threshold_value">2.0</span>
</label>

28.14 26.13 Python example: a reproducible daily-demand pipeline

The following example builds a small but complete forecasting pipeline. The goal is not to find the most sophisticated model. The goal is to make each decision explicit and reproducible.

Code
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

rng = np.random.default_rng(7339)

n = 420
dates = pd.date_range("2025-01-01", periods=n, freq="D")
t = np.arange(n)

weekly = 8 * np.sin(2 * np.pi * t / 7)
slow = 0.035 * t
promo = np.zeros(n)
promo[[80, 81, 180, 181, 300, 301]] = 18
noise = rng.normal(0, 3.0, size=n)
y = 60 + slow + weekly + promo + noise

df = pd.DataFrame({"ds": dates, "y": y, "promo_known": promo > 0})

fig, ax = plt.subplots(figsize=(9, 3.6))
ax.plot(df["ds"], df["y"], linewidth=1)
ax.set_title("Synthetic daily demand")
ax.set_xlabel("date")
ax.set_ylabel("demand")
plt.show()

Synthetic daily demand with trend, weekly seasonality, and occasional shocks.

The variable promo_known is treated as a known calendar-like event. In a real project, a promotion indicator is valid only if the promotion schedule is known at the forecast origin.

28.15 26.14 Feature construction with explicit timing

The feature table must use past target values only.

Code
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import Ridge
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.pipeline import Pipeline
from sklearn.metrics import mean_absolute_error, mean_squared_error


def make_features(data, lags=(1, 7, 14), rolling_windows=(7, 14)):
    """Create leakage-safe one-step-ahead features for predicting y_t.

    Every target-derived feature for row t uses only y_{t-1}, y_{t-2}, ... .
    """
    out = pd.DataFrame(index=data.index)
    y = data["y"]

    for lag in lags:
        out[f"lag_{lag}"] = y.shift(lag)

    for window in rolling_windows:
        out[f"roll_mean_{window}"] = y.shift(1).rolling(window).mean()
        out[f"roll_std_{window}"] = y.shift(1).rolling(window).std()

    day = data["ds"].dt.dayofweek.to_numpy()
    out["dow_sin"] = np.sin(2 * np.pi * day / 7)
    out["dow_cos"] = np.cos(2 * np.pi * day / 7)
    out["trend"] = np.arange(len(data))
    out["promo_known"] = data["promo_known"].astype(float)
    out["target"] = y
    out["ds"] = data["ds"]

    return out.dropna().reset_index(drop=True)

feature_df = make_features(df)
feature_cols = [c for c in feature_df.columns if c not in ["target", "ds"]]

feature_df.head()
lag_1 lag_7 lag_14 roll_mean_7 roll_std_7 roll_mean_14 roll_std_14 dow_sin dow_cos trend promo_known target ds
0 52.486262 57.317373 61.993909 60.320347 5.578485 60.084311 6.204204 0.974928 -0.222521 14 0.0 59.907672 2025-01-15
1 59.907672 66.391572 64.693202 60.690390 5.430023 59.935294 6.179817 0.433884 -0.900969 15 0.0 64.921686 2025-01-16
2 64.921686 66.125463 68.841626 60.480406 5.196195 59.951614 6.193635 -0.433884 -0.900969 16 0.0 66.696564 2025-01-17
3 66.696564 65.472355 65.610715 60.561992 5.302986 59.798395 5.979631 -0.974928 -0.222521 17 0.0 65.268535 2025-01-18
4 65.268535 57.054627 54.062290 60.532875 5.272000 59.773954 5.954693 -0.781831 0.623490 18 0.0 56.411896 2025-01-19

A useful habit is to test the feature timing directly.

Code
# For a selected row, verify that roll_mean_7 equals the mean of the previous seven y-values.
row = 25
original_position = row + 14  # because dropna removes the first 14 rows
manual = df.loc[original_position-7:original_position-1, "y"].mean()
computed = feature_df.loc[row, "roll_mean_7"]

print("manual previous-7 mean:", round(manual, 4))
print("computed feature:", round(computed, 4))
assert np.isclose(manual, computed)
manual previous-7 mean: 62.8895
computed feature: 62.8895

28.16 26.15 Chronological holdout and baselines

We first create a chronological split and evaluate simple baselines.

Code
split = int(0.75 * len(feature_df))
train = feature_df.iloc[:split].copy()
test = feature_df.iloc[split:].copy()

y_train = train["target"].to_numpy()
y_test = test["target"].to_numpy()

baseline_preds = pd.DataFrame({
    "ds": test["ds"],
    "actual": y_test,
    "naive_lag_1": test["lag_1"],
    "seasonal_naive_lag_7": test["lag_7"],
    "rolling_mean_7": test["roll_mean_7"],
})


def rmse(y_true, y_pred):
    return mean_squared_error(y_true, y_pred) ** 0.5

baseline_summary = []
for col in ["naive_lag_1", "seasonal_naive_lag_7", "rolling_mean_7"]:
    baseline_summary.append({
        "model": col,
        "MAE": mean_absolute_error(y_test, baseline_preds[col]),
        "RMSE": rmse(y_test, baseline_preds[col]),
    })

pd.DataFrame(baseline_summary).sort_values("MAE")
model MAE RMSE
1 seasonal_naive_lag_7 3.259153 4.056401
0 naive_lag_1 5.391515 6.321787
2 rolling_mean_7 5.559941 6.449090

28.17 26.16 Candidate models inside preprocessing pipelines

Scaling must be fitted on training data only. scikit-learn pipelines help enforce this rule.

Code
X_train = train[feature_cols]
X_test = test[feature_cols]

models = {
    "ridge": Pipeline([
        ("scaler", StandardScaler()),
        ("model", Ridge(alpha=5.0))
    ]),
    "gradient_boosting": GradientBoostingRegressor(
        n_estimators=60,
        learning_rate=0.05,
        max_depth=2,
        random_state=7339,
    ),
}

model_summary = []
predictions = baseline_preds[["ds", "actual"]].copy()

for name, model in models.items():
    model.fit(X_train, y_train)
    pred = model.predict(X_test)
    predictions[name] = pred
    model_summary.append({
        "model": name,
        "MAE": mean_absolute_error(y_test, pred),
        "RMSE": rmse(y_test, pred),
    })

all_results = pd.concat([
    pd.DataFrame(baseline_summary),
    pd.DataFrame(model_summary)
], ignore_index=True).sort_values("MAE")

all_results
model MAE RMSE
3 ridge 2.125771 2.727825
1 seasonal_naive_lag_7 3.259153 4.056401
4 gradient_boosting 3.305782 4.089745
0 naive_lag_1 5.391515 6.321787
2 rolling_mean_7 5.559941 6.449090
Code
fig, ax = plt.subplots(figsize=(9, 3.8))
ax.plot(predictions["ds"], predictions["actual"], label="actual", linewidth=1.5)
ax.plot(predictions["ds"], baseline_preds["seasonal_naive_lag_7"], label="seasonal naive", alpha=0.8)
ax.plot(predictions["ds"], predictions["ridge"], label="ridge", alpha=0.8)
ax.plot(predictions["ds"], predictions["gradient_boosting"], label="gradient boosting", alpha=0.8)
ax.set_title("Holdout forecasts")
ax.set_xlabel("date")
ax.set_ylabel("demand")
ax.legend()
plt.show()

Chronological test-set forecasts from baselines and machine-learning models.

28.18 26.17 Rolling-origin validation

A single holdout split can be misleading. We next run rolling one-step-ahead validation. Each split trains on all earlier rows and predicts the next row.

Code
def rolling_one_step_scores(feature_data, feature_cols, model_factory, min_train=180, step=7):
    records = []
    for end in range(min_train, len(feature_data) - 1, step):
        train_part = feature_data.iloc[:end]
        test_row = feature_data.iloc[[end]]

        X_tr = train_part[feature_cols]
        y_tr = train_part["target"].to_numpy()
        X_te = test_row[feature_cols]
        y_te = test_row["target"].to_numpy()

        model = model_factory()
        model.fit(X_tr, y_tr)
        pred = float(model.predict(X_te)[0])

        records.append({
            "ds": test_row["ds"].iloc[0],
            "actual": float(y_te[0]),
            "prediction": pred,
            "error": float(y_te[0] - pred),
        })
    return pd.DataFrame(records)

ridge_factory = lambda: Pipeline([
    ("scaler", StandardScaler()),
    ("model", Ridge(alpha=5.0))
])

gb_factory = lambda: GradientBoostingRegressor(
    n_estimators=60,
    learning_rate=0.05,
    max_depth=2,
    random_state=7339,
)

ridge_roll = rolling_one_step_scores(feature_df, feature_cols, ridge_factory)
gb_roll = rolling_one_step_scores(feature_df, feature_cols, gb_factory)

rolling_summary = pd.DataFrame([
    {"model": "ridge rolling", "MAE": mean_absolute_error(ridge_roll["actual"], ridge_roll["prediction"]), "RMSE": rmse(ridge_roll["actual"], ridge_roll["prediction"])},
    {"model": "gradient boosting rolling", "MAE": mean_absolute_error(gb_roll["actual"], gb_roll["prediction"]), "RMSE": rmse(gb_roll["actual"], gb_roll["prediction"])},
])

rolling_summary
model MAE RMSE
0 ridge rolling 2.527239 3.151755
1 gradient boosting rolling 2.942416 3.588993
Code
fig, ax = plt.subplots(figsize=(9, 3.5))
ax.axhline(0, linewidth=1)
ax.plot(ridge_roll["ds"], ridge_roll["error"], marker="o", markersize=3, label="ridge error")
ax.plot(gb_roll["ds"], gb_roll["error"], marker="o", markersize=3, label="gradient boosting error")
ax.set_title("Rolling-origin one-step forecast errors")
ax.set_xlabel("date")
ax.set_ylabel("error")
ax.legend()
plt.show()

Rolling one-step-ahead forecast errors.

28.19 26.18 Residual-based interval construction

We can construct a simple validation-residual interval. This is not the only approach, but it is transparent.

Code
# Fit the selected model on the chronological training set.
selected = Pipeline([
    ("scaler", StandardScaler()),
    ("model", Ridge(alpha=5.0))
])
selected.fit(X_train, y_train)
point_pred = selected.predict(X_test)

# Use rolling-origin residual quantiles as empirical error offsets.
residuals = ridge_roll["error"].to_numpy()
lo_offset, hi_offset = np.quantile(residuals, [0.05, 0.95])

interval_df = pd.DataFrame({
    "ds": test["ds"],
    "actual": y_test,
    "forecast": point_pred,
    "lower_90": point_pred + lo_offset,
    "upper_90": point_pred + hi_offset,
})

coverage = np.mean((interval_df["actual"] >= interval_df["lower_90"]) & (interval_df["actual"] <= interval_df["upper_90"]))
print("Empirical 90% interval coverage on holdout:", round(coverage, 3))
interval_df.head()
Empirical 90% interval coverage on holdout: 0.912
ds actual forecast lower_90 upper_90
304 2025-11-15 72.215943 74.524246 68.666280 78.673867
305 2025-11-16 65.376446 67.945236 62.087271 72.094857
306 2025-11-17 61.087872 64.236849 58.378883 68.386469
307 2025-11-18 64.692912 65.150766 59.292800 69.300386
308 2025-11-19 77.285982 71.310223 65.452257 75.459843
Code
fig, ax = plt.subplots(figsize=(9, 3.8))
ax.plot(interval_df["ds"], interval_df["actual"], label="actual", linewidth=1.3)
ax.plot(interval_df["ds"], interval_df["forecast"], label="forecast", linewidth=1.3)
ax.fill_between(
    interval_df["ds"],
    interval_df["lower_90"].to_numpy(),
    interval_df["upper_90"].to_numpy(),
    alpha=0.2,
    label="90% residual interval",
)
ax.set_title("Forecast report object: point forecast and interval")
ax.set_xlabel("date")
ax.set_ylabel("demand")
ax.legend()
plt.show()

Point forecasts with a residual-quantile interval.

28.20 26.19 Final forecast report object

A final forecast should be saved as a table with enough metadata to be interpreted later.

Code
forecast_origin = train["ds"].max()
report = interval_df.copy()
report["forecast_origin"] = forecast_origin
report["model"] = "ridge_lag_calendar_pipeline"
report["target"] = "daily demand"
report["horizon_days_after_origin"] = (report["ds"] - forecast_origin).dt.days

report[["forecast_origin", "ds", "horizon_days_after_origin", "model", "forecast", "lower_90", "upper_90"]].head()
forecast_origin ds horizon_days_after_origin model forecast lower_90 upper_90
304 2025-11-14 2025-11-15 1 ridge_lag_calendar_pipeline 74.524246 68.666280 78.673867
305 2025-11-14 2025-11-16 2 ridge_lag_calendar_pipeline 67.945236 62.087271 72.094857
306 2025-11-14 2025-11-17 3 ridge_lag_calendar_pipeline 64.236849 58.378883 68.386469
307 2025-11-14 2025-11-18 4 ridge_lag_calendar_pipeline 65.150766 59.292800 69.300386
308 2025-11-14 2025-11-19 5 ridge_lag_calendar_pipeline 71.310223 65.452257 75.459843

The report object should be accompanied by a model card or modeling log. A concise model card includes the forecast contract, training period, validation design, model class, feature list, metrics, interval coverage, known limitations, and monitoring plan.

28.21 26.20 AI-assisted pipeline review

28.22 AI-assisted modeling prompt

Use this prompt after your first complete pipeline is working.

I am building a time-series forecasting pipeline. The target is [target]. The frequency is [frequency]. The forecast horizon is [horizon]. The information available at the forecast origin is [information set]. My preprocessing steps are [steps]. My features are [features]. My validation design is [design]. My baselines are [baselines]. My candidate models are [models]. My metrics are [metrics]. My residual diagnostics are [diagnostics]. Please act as a skeptical reviewer. Identify possible leakage, horizon mismatch, weak baselines, invalid transformations, nonstationarity, calibration problems, and unsupported conclusions. For every concern, give a concrete verification step.

The strongest AI prompt does not ask for approval. It asks for failure modes and checks.

28.23 26.21 Common mistakes

  1. Building features before defining the forecast origin. This often creates accidental future information.
  2. Using random splits. Random splits break the time order and often overstate performance.
  3. Scaling before splitting. Test-set information enters the training pipeline.
  4. Comparing advanced models without baselines. A complex model should beat naive and seasonal-naive methods.
  5. Ignoring the horizon. A model that predicts tomorrow may not predict next month.
  6. Using actual future lags in multi-step forecasting. Recursive forecasts must use predicted values after the forecast origin.
  7. Reporting only one metric. Use multiple metrics and horizon-wise summaries.
  8. Skipping monitoring. A deployed forecast can degrade when the data-generating process changes.

28.24 26.22 Exercises

  1. Define a forecasting contract for weekly electricity demand with horizon \(H=4\) weeks. State the information set \(\mathcal F_t\).
  2. For predicting \(Y_t\), decide whether each feature is valid: \(Y_{t-1}\), \(Y_{t+1}\), a centered seven-day rolling mean, a lagged seven-day rolling mean, day of week, and next week’s temperature forecast.
  3. Implement a leakage-safe feature table with lags \(1,2,7,14\) and rolling means of lengths \(7\) and \(28\).
  4. Compare naive, seasonal naive, ridge regression, and gradient boosting using chronological validation.
  5. Construct a residual-quantile interval and evaluate its empirical coverage.
  6. Write a model card for your forecasting pipeline.
  7. Modify the Python example so that it predicts seven days ahead. Explain how your validation design changes.
  8. Create a synthetic distribution shift and design a monitoring statistic that detects it.

28.25 26.23 Mini project

Choose a real or simulated time series. Build an end-to-end forecasting pipeline with the following deliverables:

  • a forecasting contract;
  • a leakage-safe feature table;
  • at least two baselines;
  • at least two candidate models;
  • chronological or rolling-origin validation;
  • point forecast metrics;
  • an interval or uncertainty estimate;
  • residual or error diagnostics;
  • a final forecast report table;
  • a short AI-assisted critique and your verification of the critique.

28.26 26.24 Chapter checklist

Before moving to the final project studio, make sure you can answer yes to each question.

  • Did I define the forecast origin and horizon?
  • Did I define the information set \(\mathcal F_t\)?
  • Are all target-derived features lagged correctly?
  • Were preprocessing steps fitted only on training data?
  • Did I compare against naive and seasonal-naive baselines?
  • Does my validation design match the deployment use case?
  • Did I inspect residuals or forecast errors?
  • Did I evaluate uncertainty or interval coverage?
  • Did I create a forecast report object?
  • Did I document assumptions, limitations, and monitoring rules?