19  Feature-Based Machine Learning for Time Series

Part V. Forecasting at Scale and Machine Learning Methods
Chapter goal: convert time-series forecasting into supervised learning without losing the time-order structure. We build lag, rolling-window, calendar, Fourier, and exogenous features; compare recursive, direct, and multi-output forecasting; and design leakage-aware validation for machine-learning models.

19.1 Learning objectives

After studying this chapter, you should be able to:

  1. explain how a time series can be transformed into a supervised-learning data set;
  2. construct lag features, rolling-window features, calendar features, Fourier features, and exogenous covariates;
  3. distinguish features that are available at forecast time from features that leak future information;
  4. compare recursive, direct, and multi-output strategies for multi-step forecasting;
  5. write the mathematical risk minimization problem behind feature-based forecasting;
  6. use time-aware train/test splits and rolling-origin validation;
  7. fit linear models, regularized models, random forests, and gradient boosting models to lagged features;
  8. interpret feature importance cautiously in dependent data;
  9. diagnose residual autocorrelation and forecast errors after fitting a machine-learning model;
  10. use AI assistants to accelerate feature engineering while independently checking causality, validation, and leakage.

19.2 17.1 Why feature-based machine learning?

Classical time-series models build dependence directly into the model. For example, an AR(\(p\)) model assumes

\[ Y_t=\phi_1Y_{t-1}+\cdots+\phi_pY_{t-p}+W_t. \]

A feature-based machine-learning model keeps the same basic idea—future values depend on past information—but replaces the linear formula by a flexible function:

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

Here \(X_t\) is a vector of features constructed from information available at time \(t\). Typical components of \(X_t\) include

\[ X_t= \big( Y_t,Y_{t-1},\ldots,Y_{t-p+1}, \operatorname{rollmean}_w(t), \operatorname{rollstd}_w(t), \text{calendar}(t), \text{Fourier}(t), Z_t \big), \]

where \(Z_t\) represents known exogenous variables.

This approach is common in applied forecasting because it can combine several strengths:

  • classical time-series information through lags;
  • trend and seasonality through calendar and Fourier features;
  • nonlinear interactions through tree ensembles or neural networks;
  • business or scientific information through external covariates;
  • scalable training across many related series.
NoteThe supervised-learning translation

Feature-based forecasting does not mean that time order disappears. The rows of the supervised-learning table are still ordered, the features must be computed using past information only, and validation must mimic real forecasting.

19.3 17.2 Mathematical setup: forecasting with information sets

Let \((\Omega,\mathcal F,\mathbb P)\) be a probability space and let

\[ \mathcal F_t=\sigma(Y_s,Z_s: s\le t) \]

be the information available at time \(t\). A valid feature vector \(X_t\) for forecasting from origin \(t\) must be \(\mathcal F_t\)-measurable. This means \(X_t\) may use observed history up to time \(t\), but not future values \(Y_{t+1},Y_{t+2},\ldots\).

For horizon \(h\ge 1\), the ideal squared-error forecast is the conditional expectation

\[ m_h^*(X_t)=\mathbb E[Y_{t+h}\mid X_t]. \]

A machine-learning forecaster chooses a function class \(\mathcal G\) and estimates

\[ \widehat f_h \in \arg\min_{g\in\mathcal G} \frac{1}{|\mathcal T_{\text{train}}|} \sum_{t\in\mathcal T_{\text{train}}} \ell(Y_{t+h},g(X_t)), \]

where \(\ell\) might be squared loss, absolute loss, quantile loss, or another task-specific loss.

For squared loss,

\[ \ell(y,\widehat y)=(y-\widehat y)^2. \]

For absolute loss,

\[ \ell(y,\widehat y)=|y-\widehat y|. \]

For quantile level \(\tau\in(0,1)\), the pinball loss is

\[ \ell_\tau(y,q) =(\tau-\mathbf 1\{y<q\})(y-q). \]

19.4 Forecasting as empirical risk minimization

A feature-based forecasting model estimates a conditional functional of \(Y_{t+h}\) given \(X_t\). Under squared loss the target is the conditional mean; under absolute loss it is a conditional median; under pinball loss it is a conditional quantile.

19.5 17.3 From a time series to a supervised-learning table

Suppose we observe \(y_1,\ldots,y_T\). With \(p\) lags and one-step forecasting, we create rows

\[ \begin{array}{c|cccc|c} \text{origin} & y_t & y_{t-1} & \cdots & y_{t-p+1} & y_{t+1} \\ \hline t=p & y_p & y_{p-1} & \cdots & y_1 & y_{p+1} \\ t=p+1 & y_{p+1} & y_p & \cdots & y_2 & y_{p+2} \\ \vdots & \vdots & \vdots & & \vdots & \vdots \end{array} \]

The first columns are features. The last column is the label.

For horizon \(h\), the label becomes \(y_{t+h}\):

\[ \text{label at origin }t = y_{t+h}. \]

The index \(t\) is called the forecast origin. At origin \(t\), the model is allowed to use information up to \(t\) and must predict \(t+h\).

19.5.1 Design matrix notation

Let

\[ X= \begin{bmatrix} X_{t_1}^\top\\ X_{t_2}^\top\\ \vdots\\ X_{t_n}^\top \end{bmatrix}, \qquad \mathbf y_h= \begin{bmatrix} Y_{t_1+h}\\ Y_{t_2+h}\\ \vdots\\ Y_{t_n+h} \end{bmatrix}. \]

A linear machine-learning forecaster has the form

\[ \widehat {\mathbf y}_h=X\widehat\beta_h. \]

Ridge regression estimates

\[ \widehat\beta_h = \arg\min_\beta \left\{ \|\mathbf y_h-X\beta\|_2^2+\lambda\|\beta\|_2^2 \right\}. \]

Tree-based models replace the linear map \(X\beta\) by a piecewise constant or boosted nonlinear function.

19.6 17.4 Feature types

19.6.1 Lag features

Lag features are the most direct analogue of autoregression:

\[ \operatorname{lag}_j(t)=Y_{t-j+1},\qquad j=1,\ldots,p. \]

Some authors define \(\operatorname{lag}_j(t)=Y_{t-j}\). The convention is not important as long as the forecast origin is clear. In this chapter, when forecasting \(Y_{t+h}\) from origin \(t\), the feature \(Y_t\) is available.

Lag features can capture short-term momentum, mean reversion, and recurring patterns. For seasonal data, useful lag choices often include

\[ 1,2,\ldots,p,\quad s,\quad 2s,\quad s\pm 1, \]

where \(s\) is a seasonal period.

19.6.2 Rolling-window features

Rolling means and rolling standard deviations summarize recent history:

\[ \operatorname{rollmean}_w(t)=\frac{1}{w}\sum_{j=0}^{w-1}Y_{t-j}, \]

\[ \operatorname{rollvar}_w(t)=\frac{1}{w-1}\sum_{j=0}^{w-1} \left(Y_{t-j}-\operatorname{rollmean}_w(t)\right)^2. \]

Other rolling features include rolling minima, maxima, quantiles, slopes, exponentially weighted means, and counts of threshold exceedances.

WarningCentered windows leak future information

A centered rolling mean such as \[ \frac{1}{2w+1}\sum_{j=-w}^{w}Y_{t+j} \] uses values \(Y_{t+1},\ldots,Y_{t+w}\). It is useful for offline smoothing, but invalid as a forecasting feature at origin \(t\).

19.6.3 Calendar features

Calendar features encode systematic changes by time of day, day of week, month, quarter, semester, or holiday period. For daily data, common features include

\[ \text{day_of_week},\quad \text{week_of_year},\quad \text{month},\quad \text{is_weekend},\quad \text{is_holiday}. \]

Calendar variables are known in advance, so they are usually safe forecasting features.

19.6.4 Fourier features

For seasonal period \(s\), Fourier features use

\[ \sin\left(\frac{2\pi kt}{s}\right), \qquad \cos\left(\frac{2\pi kt}{s}\right), \qquad k=1,\ldots,K. \]

They provide smooth seasonal curves and connect feature-based ML to the frequency-domain ideas from earlier chapters.

19.6.5 Exogenous variables

An exogenous variable \(Z_t\) can improve forecasts if it is predictive and available at forecast time. For horizon \(h\), there are two common cases:

  1. Known future covariates: calendar variables, scheduled promotions, planned prices, academic calendars, holidays.
  2. Unknown future covariates: weather, demand drivers, economic indicators, sensor readings.

If future \(Z_{t+h}\) is unknown, the model must either use only \(Z_t,Z_{t-1},\ldots\) or forecast \(Z_{t+h}\) separately.

19.7 17.5 Direct, recursive, and multi-output ML forecasting

Feature-based models can forecast multiple steps ahead in several ways.

19.7.1 Recursive strategy

Train a one-step model

\[ \widehat Y_{t+1\mid t}=\widehat f_1(X_t). \]

Then recursively feed predictions back into the feature vector:

\[ \widehat Y_{t+2\mid t} =\widehat f_1(\widehat X_{t+1}), \]

where \(\widehat X_{t+1}\) contains \(\widehat Y_{t+1\mid t}\) in place of the unknown future value.

Recursive forecasting is efficient but can accumulate errors.

19.7.2 Direct strategy

Train a separate model for each horizon:

\[ \widehat Y_{t+h\mid t}=\widehat f_h(X_t), \qquad h=1,\ldots,H. \]

This avoids recursive feedback but requires \(H\) models.

19.7.3 Multi-output strategy

Train one model with vector output:

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

This is common in neural networks and can also be used with multi-output wrappers around standard regressors.

TipPractical rule

Use recursive forecasting for simple short-horizon baselines, direct forecasting when horizons have different structure, and multi-output forecasting when the whole future path matters jointly.

19.8 17.6 Leakage-aware validation

Random train/test splitting is usually invalid for time series because it trains on future observations and tests on earlier observations. A valid split preserves time order:

\[ \{1,\ldots,T_{\text{train}}\} \quad\text{then}\quad \{T_{\text{train}}+1,\ldots,T\}. \]

For more reliable evaluation, use rolling-origin validation. Let \(\mathcal O\) be a set of forecast origins. For each origin \(o\in\mathcal O\):

  1. train only on observations up to \(o\);
  2. forecast \(Y_{o+1},\ldots,Y_{o+H}\);
  3. compute errors;
  4. aggregate errors by horizon and model.

The backtest error for model \(m\) at horizon \(h\) is

\[ e_{o,h}^{(m)}=Y_{o+h}-\widehat Y_{o+h\mid o}^{(m)}. \]

Horizon-specific MAE is

\[ \operatorname{MAE}_h^{(m)} =\frac{1}{|\mathcal O_h|} \sum_{o\in\mathcal O_h}|e_{o,h}^{(m)}|. \]

This is the same evaluation philosophy as the forecasting-evaluation chapter, now applied to feature-based ML models.

19.9 17.7 Interactive demonstration: supervised table construction

The interactive below shows how a time series becomes a supervised-learning table. Move the sliders to change the number of lag features, the rolling-window width, the forecast horizon, and the selected forecast origin. The first plot marks the lags used at the selected origin and the target value. The second plot shows a heatmap of the supervised-learning rows.

19.10 17.8 Python example: constructing lagged features

The following code constructs a synthetic daily series and converts it to a supervised-learning data frame.

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

rng = np.random.default_rng(7339)
n = 520
idx = pd.date_range("2024-01-01", periods=n, freq="D")
t = np.arange(n)

ar = np.zeros(n)
noise = rng.normal(0, 1.0, size=n)
for i in range(1, n):
    ar[i] = 0.65 * ar[i - 1] + noise[i]

y = (
    80
    + 0.03 * t
    + 8 * np.sin(2 * np.pi * t / 7)
    + 3 * np.cos(2 * np.pi * t / 30)
    + 2.0 * ar
    + rng.normal(0, 2.0, size=n)
)

series = pd.DataFrame({"ds": idx, "y": y})
series.plot(x="ds", y="y", figsize=(9, 3), legend=False)
plt.xlabel("date")
plt.ylabel("value")
plt.title("Synthetic series with trend, seasonality, and dependence")
plt.show()

Synthetic daily time series used for feature-based forecasting.
Code
def make_lagged_features(df, y_col="y", max_lag=14, rolling_windows=(7, 28), horizon=1):
    out = df.copy()
    y = out[y_col]

    # Lag features available at forecast origin t.
    for lag in range(1, max_lag + 1):
        out[f"lag_{lag}"] = y.shift(lag - 1)

    # Rolling features using past and current values only.
    for w in rolling_windows:
        out[f"roll_mean_{w}"] = y.rolling(w, min_periods=w).mean()
        out[f"roll_std_{w}"] = y.rolling(w, min_periods=w).std()

    # Calendar and Fourier features known in advance.
    day_index = np.arange(len(out))
    out["day_of_week"] = out["ds"].dt.dayofweek
    out["is_weekend"] = (out["day_of_week"] >= 5).astype(int)
    for k in range(1, 4):
        out[f"sin_week_{k}"] = np.sin(2 * np.pi * k * day_index / 7)
        out[f"cos_week_{k}"] = np.cos(2 * np.pi * k * day_index / 7)

    # Label: value h steps after the forecast origin.
    out[f"target_h{horizon}"] = y.shift(-horizon)
    out = out.dropna().reset_index(drop=True)
    return out

supervised = make_lagged_features(series, max_lag=14, rolling_windows=(7, 28), horizon=7)
feature_cols = [c for c in supervised.columns if c.startswith(("lag_", "roll_", "sin_", "cos_"))] + ["is_weekend"]
target_col = "target_h7"

supervised[["ds", "y"] + feature_cols[:8] + [target_col]].head()
ds y lag_1 lag_2 lag_3 lag_4 lag_5 lag_6 lag_7 lag_8 target_h7
0 2024-01-28 79.305896 79.305896 72.866968 79.418827 81.036452 87.500677 80.944791 77.436235 73.933338 76.811646
1 2024-01-29 81.869961 81.869961 79.305896 72.866968 79.418827 81.036452 87.500677 80.944791 77.436235 91.851188
2 2024-01-30 94.554564 94.554564 81.869961 79.305896 72.866968 79.418827 81.036452 87.500677 80.944791 91.924750
3 2024-01-31 90.656623 90.656623 94.554564 81.869961 79.305896 72.866968 79.418827 81.036452 87.500677 90.311178
4 2024-02-01 86.608821 86.608821 90.656623 94.554564 81.869961 79.305896 72.866968 79.418827 81.036452 87.005967

First rows of a supervised-learning table with lag, rolling, and Fourier features.

The row indexed by date \(t\) contains features computed from \(Y_t,Y_{t-1},\ldots\) and a label \(Y_{t+7}\). This is a direct seven-day-ahead forecasting table.

19.11 17.9 Linear and nonlinear ML forecasters

Feature-based ML can be used with many supervised-learning algorithms.

19.11.1 Linear regression

A linear model estimates

\[ \widehat Y_{t+h\mid t}=\beta_0+\beta^\top X_t. \]

It is interpretable and often strong when the feature design captures the main structure.

19.11.2 Ridge and lasso

Ridge regression stabilizes estimates when many lag and Fourier features are correlated:

\[ \widehat\beta_{\text{ridge}} =\arg\min_\beta \sum_t (Y_{t+h}-\beta_0-\beta^\top X_t)^2 +\lambda\sum_j\beta_j^2. \]

Lasso uses an \(\ell^1\) penalty:

\[ \widehat\beta_{\text{lasso}} =\arg\min_\beta \sum_t (Y_{t+h}-\beta_0-\beta^\top X_t)^2 +\lambda\sum_j|\beta_j|. \]

Ridge shrinks coefficients smoothly. Lasso can set coefficients exactly to zero.

19.11.3 Random forests

A random forest averages many decision trees:

\[ \widehat f(x)=\frac{1}{B}\sum_{b=1}^B T_b(x). \]

Trees can discover nonlinear threshold effects and interactions, but they do not extrapolate trend naturally unless trend is encoded through features.

19.11.4 Gradient boosting

Gradient boosting builds an additive model of trees:

\[ \widehat f_M(x)=\sum_{m=0}^M\nu T_m(x), \]

where each new tree approximately fits the current residuals or negative gradient. Boosting often performs well on tabular time-series features.

WarningTree models and extrapolation

Tree models interpolate within feature ranges. If a future trend moves beyond the range of the training data, a tree model may flatten unless time, trend, or external driver features make extrapolation possible.

19.12 17.10 Python example: chronological split and model comparison

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

feature_cols = [c for c in supervised.columns if c.startswith(("lag_", "roll_", "sin_", "cos_"))]
feature_cols += ["day_of_week", "is_weekend"]
target_col = "target_h7"

split_date = supervised["ds"].quantile(0.80)
train = supervised[supervised["ds"] <= split_date].copy()
test = supervised[supervised["ds"] > split_date].copy()

numeric_features = [c for c in feature_cols if c != "day_of_week"]
categorical_features = ["day_of_week"]

preprocess_linear = ColumnTransformer(
    transformers=[
        ("num", StandardScaler(), numeric_features),
        ("cat", OneHotEncoder(handle_unknown="ignore"), categorical_features),
    ],
    remainder="drop",
)

preprocess_tree = ColumnTransformer(
    transformers=[
        ("num", "passthrough", numeric_features),
        ("cat", OneHotEncoder(handle_unknown="ignore"), categorical_features),
    ],
    remainder="drop",
)

models = {
    "ridge": Pipeline([
        ("prep", preprocess_linear),
        ("model", Ridge(alpha=10.0)),
    ]),
    "random_forest": Pipeline([
        ("prep", preprocess_tree),
        ("model", RandomForestRegressor(
            n_estimators=120,
            min_samples_leaf=5,
            random_state=7339,
        )),
    ]),
    "gradient_boosting": Pipeline([
        ("prep", preprocess_tree),
        ("model", GradientBoostingRegressor(
            n_estimators=120,
            learning_rate=0.04,
            max_depth=3,
            random_state=7339,
        )),
    ]),
}

results = []
predictions = pd.DataFrame({"ds": test["ds"], "actual": test[target_col]})

for name, model in models.items():
    model.fit(train[feature_cols], train[target_col])
    yhat = model.predict(test[feature_cols])
    predictions[name] = yhat
    results.append({
        "model": name,
        "MAE": mean_absolute_error(test[target_col], yhat),
        "RMSE": np.sqrt(mean_squared_error(test[target_col], yhat)),
    })

pd.DataFrame(results).sort_values("MAE")
model MAE RMSE
0 ridge 3.619053 4.643866
2 gradient_boosting 4.096294 5.187475
1 random_forest 4.127917 5.229897

Seven-day-ahead forecasts from feature-based machine-learning models.

Code
plt.figure(figsize=(10, 4))
plt.plot(predictions["ds"], predictions["actual"], label="actual", linewidth=2)
for name in models:
    plt.plot(predictions["ds"], predictions[name], label=name, alpha=0.85)
plt.xlabel("date")
plt.ylabel("seven-day-ahead target")
plt.title("Feature-based ML forecasts on chronological test period")
plt.legend()
plt.tight_layout()
plt.show()

Chronological test-period forecasts from feature-based ML models.

19.13 17.11 Recursive forecasting with a one-step model

Recursive forecasting trains a one-step model and repeatedly updates the lag vector using predicted values. The following example illustrates the idea with ridge regression. Recursive code is more delicate than direct code because future feature rows do not already exist.

Code
from sklearn.pipeline import make_pipeline

max_lag = 14
one_step = make_lagged_features(series, max_lag=max_lag, rolling_windows=(), horizon=1)
lag_cols = [f"lag_{j}" for j in range(1, max_lag + 1)]

train_end = int(len(series) * 0.80)
train_one = one_step[one_step.index < train_end].copy()

ridge_lag = make_pipeline(StandardScaler(), Ridge(alpha=5.0))
ridge_lag.fit(train_one[lag_cols], train_one["target_h1"])

history = list(series.loc[:train_end - 1, "y"].values)
H = 40
recursive_forecast = []

for step in range(H):
    x_row = pd.DataFrame([history[-1: -max_lag-1: -1]], columns=lag_cols)
    y_next = ridge_lag.predict(x_row)[0]
    recursive_forecast.append(y_next)
    history.append(y_next)

future_dates = series.loc[train_end: train_end + H - 1, "ds"].values
actual_future = series.loc[train_end: train_end + H - 1, "y"].values

plt.figure(figsize=(9, 3.5))
plt.plot(series.loc[train_end-80:train_end-1, "ds"], series.loc[train_end-80:train_end-1, "y"], label="history")
plt.plot(future_dates, actual_future, label="actual future")
plt.plot(future_dates, recursive_forecast, label="recursive ridge forecast")
plt.xlabel("date")
plt.ylabel("value")
plt.title("Recursive forecasting with predicted lags")
plt.legend()
plt.tight_layout()
plt.show()

Recursive one-step forecasts using a lag-only ridge model.
ImportantRecursive forecasting changes the input distribution

During training, lag features contain observed values. During recursive prediction, some lag features contain model predictions. This train/predict mismatch is one reason recursive forecasts can degrade at longer horizons.

19.14 17.12 Direct multi-horizon forecasting

A direct strategy trains one model per horizon. For \(H=14\), we train

\[ \widehat f_1,\widehat f_2,\ldots,\widehat f_{14}. \]

Each model uses the same origin-time features but a different target.

Code
H = 14
base = series.copy()

# Origin-time features with no horizon-specific target yet.
features_base = make_lagged_features(base, max_lag=14, rolling_windows=(7, 28), horizon=1)
feature_cols_direct = [c for c in features_base.columns if c.startswith(("lag_", "roll_", "sin_", "cos_"))]
feature_cols_direct += ["day_of_week", "is_weekend"]

# Add targets for all horizons.
for h in range(1, H + 1):
    features_base[f"target_h{h}"] = series["y"].shift(-h).reindex(features_base.index).values
features_base = features_base.dropna().reset_index(drop=True)

origin_date = features_base["ds"].iloc[int(0.80 * len(features_base))]
train_direct = features_base[features_base["ds"] < origin_date]
origin_row = features_base[features_base["ds"] == origin_date].iloc[[0]]

direct_forecast = []
for h in range(1, H + 1):
    model = Pipeline([
        ("prep", preprocess_tree),
        ("model", GradientBoostingRegressor(
            n_estimators=80,
            learning_rate=0.05,
            max_depth=3,
            random_state=7339 + h,
        )),
    ])
    model.fit(train_direct[feature_cols], train_direct[f"target_h{h}"])
    direct_forecast.append(model.predict(origin_row[feature_cols])[0])

origin_idx = series.index[series["ds"] == origin_date][0]
actual_path = series.loc[origin_idx + 1: origin_idx + H, "y"].values
future_dates = series.loc[origin_idx + 1: origin_idx + H, "ds"].values

plt.figure(figsize=(8, 3.5))
plt.plot(series.loc[origin_idx-80:origin_idx, "ds"], series.loc[origin_idx-80:origin_idx, "y"], label="history")
plt.plot(future_dates, actual_path, marker="o", label="actual")
plt.plot(future_dates, direct_forecast, marker="o", label="direct ML forecast")
plt.xlabel("date")
plt.ylabel("value")
plt.title("Direct multi-horizon forecast")
plt.legend()
plt.tight_layout()
plt.show()

Direct forecasts from separate horizon-specific models.

19.15 17.13 Rolling-origin validation for ML feature models

The following backtest trains a model repeatedly at different forecast origins. This is slower than a single chronological split, but it gives a more realistic estimate of forecasting performance.

Code
def make_features_for_horizon(df, horizon, max_lag=14):
    tab = make_lagged_features(df, max_lag=max_lag, rolling_windows=(7, 28), horizon=horizon)
    fcols = [c for c in tab.columns if c.startswith(("lag_", "roll_", "sin_", "cos_"))]
    fcols += ["day_of_week", "is_weekend"]
    return tab, fcols, f"target_h{horizon}"

origins = pd.date_range(series["ds"].iloc[280], series["ds"].iloc[420], freq="35D")
H_eval = 5
records = []

for h in range(1, H_eval + 1):
    tab, fcols, target = make_features_for_horizon(series, horizon=h, max_lag=14)
    for origin in origins:
        train_h = tab[tab["ds"] <= origin]
        test_h = tab[tab["ds"] == origin]
        if len(train_h) < 80 or len(test_h) == 0:
            continue
        model = Pipeline([
            ("prep", preprocess_tree),
            ("model", GradientBoostingRegressor(
                n_estimators=50,
                learning_rate=0.05,
                max_depth=3,
                random_state=1000 + h,
            )),
        ])
        model.fit(train_h[fcols], train_h[target])
        yhat = model.predict(test_h[fcols])[0]
        actual = test_h[target].iloc[0]
        records.append({"origin": origin, "horizon": h, "error": actual - yhat})

bt = pd.DataFrame(records)
horizon_summary = (
    bt.assign(abs_error=lambda d: d["error"].abs())
      .groupby("horizon", as_index=False)["abs_error"]
      .mean()
      .rename(columns={"abs_error": "MAE"})
)

plt.figure(figsize=(7, 3.5))
plt.plot(horizon_summary["horizon"], horizon_summary["MAE"], marker="o")
plt.xlabel("forecast horizon")
plt.ylabel("MAE")
plt.title("Rolling-origin MAE by horizon")
plt.tight_layout()
plt.show()

horizon_summary

Horizon-wise MAE from rolling-origin validation.
horizon MAE
0 1 3.777906
1 2 3.233628
2 3 2.806294
3 4 1.596699
4 5 2.547511

19.16 17.14 Feature importance and interpretation

Feature importance can help explain a model, but it must be interpreted carefully.

For a fitted random forest or gradient boosting model, impurity-based importance often favors continuous variables and correlated groups. Permutation importance is usually more meaningful: it measures the increase in error after randomly permuting a feature.

For time-series features, correlated lag variables are common. If \(Y_t,Y_{t-1},\ldots,Y_{t-7}\) are highly correlated, importance may be distributed across them in unstable ways.

A more stable strategy is to group features:

  • short lags: \(Y_t,Y_{t-1},\ldots,Y_{t-6}\);
  • seasonal lags: \(Y_{t-7},Y_{t-14},\ldots\);
  • rolling features;
  • Fourier/calendar features;
  • exogenous variables.

Then ask whether removing an entire group changes validation performance.

Code
from sklearn.inspection import permutation_importance

rf = models["random_forest"]
rf.fit(train[feature_cols], train[target_col])
perm = permutation_importance(
    rf,
    test[feature_cols],
    test[target_col],
    n_repeats=5,
    random_state=7339,
    scoring="neg_mean_absolute_error",
)

importance = (
    pd.DataFrame({"feature": feature_cols, "importance": perm.importances_mean})
    .sort_values("importance", ascending=False)
    .head(15)
)

plt.figure(figsize=(7, 4))
plt.barh(importance["feature"][::-1], importance["importance"][::-1])
plt.xlabel("increase in MAE after permutation")
plt.title("Permutation importance, top features")
plt.tight_layout()
plt.show()

importance

Permutation importance on the chronological test set.
feature importance
18 sin_week_1 1.522503
0 lag_1 0.328023
4 lag_5 0.091041
17 roll_std_28 0.054667
21 cos_week_2 0.050378
5 lag_6 0.020947
8 lag_9 0.014119
14 roll_mean_7 0.013196
6 lag_7 0.012949
3 lag_4 0.008140
2 lag_3 0.008133
23 cos_week_3 0.004149
13 lag_14 0.003751
10 lag_11 0.003486
20 sin_week_2 0.001594

19.17 17.15 Diagnostics after machine learning

A flexible ML model can fit nonlinear patterns, but it can still leave time-dependent errors. Let

\[ e_{t,h}=Y_{t+h}-\widehat Y_{t+h\mid t}. \]

Useful diagnostics include:

  1. time plot of forecast errors;
  2. ACF of forecast errors;
  3. error versus fitted value;
  4. error by horizon;
  5. error by calendar group;
  6. comparison with naive and seasonal naive baselines;
  7. performance during regime changes or shock periods.

If the forecast errors have strong autocorrelation, the feature set or model may be missing temporal information. If errors vary systematically by day of week, the seasonal features may be insufficient. If errors grow sharply with horizon, the multi-step strategy may need revision.

Code
from statsmodels.graphics.tsaplots import plot_acf

best_name = pd.DataFrame(results).sort_values("MAE").iloc[0]["model"]
errors = predictions["actual"] - predictions[best_name]

fig, ax = plt.subplots(figsize=(9, 3))
ax.plot(predictions["ds"], errors)
ax.axhline(0, linewidth=1)
ax.set_xlabel("date")
ax.set_ylabel("forecast error")
ax.set_title(f"Test errors for {best_name}")
plt.tight_layout()
plt.show()

plot_acf(errors, lags=30)
plt.title(f"ACF of test errors for {best_name}")
plt.show()

Test forecast errors and their sample autocorrelation.

19.18 17.16 Relationship with ARIMA, SARIMA, Prophet, and deep learning

Feature-based ML is not separate from earlier methods. It reuses many of their ideas.

19.18.1 Connection with AR models

An AR(\(p\)) model is a linear feature-based model with lag features:

\[ X_t=(Y_t,Y_{t-1},\ldots,Y_{t-p+1}), \qquad f(X_t)=\beta^\top X_t. \]

19.18.2 Connection with SARIMA

Seasonal lags and seasonal differences inspire features such as

\[ Y_{t-s},\quad Y_{t-2s},\quad Y_t-Y_{t-s}. \]

19.18.3 Connection with Prophet-type models

Prophet-like models use calendar, changepoint, holiday, and Fourier features in an additive regression structure. Feature-based ML keeps those features but allows nonlinear functions and interactions.

19.18.4 Connection with neural networks

A windowed neural network also uses features derived from a recent time window. The difference is that neural models learn internal representations, while feature-based ML often uses explicit handcrafted features.

19.19 17.17 AI-assisted modeling activity

19.20 AI-assisted feature engineering prompt

Ask an AI assistant:

I have a daily time series with trend, weekly seasonality, possible holidays, and autocorrelated errors. I want to forecast 1 to 14 days ahead using feature-based machine learning. Propose lag, rolling, Fourier, calendar, and exogenous features. For each feature, state whether it is available at forecast origin \(t\) and identify any leakage risk.

Then verify every proposed feature manually. Delete any feature that uses future information.

19.21 AI-assisted validation prompt

Ask:

Design a rolling-origin backtest for this forecast task. Include forecast origins, horizons, metrics, baseline models, and how to aggregate errors by horizon.

Then check whether the proposed split ever trains on data after the forecast origin. If it does, revise it.

19.22 AI-assisted diagnostic prompt

Ask:

Given residual plots, ACF of forecast errors, and horizon-wise MAE, list possible model failures and propose feature changes. Separate mathematical issues from implementation issues.

Use the answer as a hypothesis list, not as proof.

19.23 17.18 Common mistakes

  1. Random train/test split. This trains on future data and overstates performance.
  2. Centered rolling features. These use future values and leak information.
  3. Using unknown future covariates. Weather, prices, or economic variables may not be known at forecast time.
  4. Forgetting baselines. A complicated ML model should beat naive and seasonal naive forecasts.
  5. Tuning on the test set. Hyperparameters must be chosen using validation folds before final testing.
  6. Confusing residuals with backtest errors. A fitted residual is not the same as a genuine forecast error.
  7. Ignoring horizon-specific behavior. A model can be strong at horizon 1 and weak at horizon 14.
  8. Overinterpreting feature importance. Correlated lag features can make individual importance unstable.
  9. Not matching strategy to deployment. A direct model is not evaluated the same way as a recursive model.
  10. Assuming ML handles nonstationarity automatically. Feature design and validation still matter.

19.24 17.19 Mini project: ML forecasting pipeline

Choose a daily, weekly, hourly, or monthly time series. Build a feature-based forecasting pipeline.

Your report should include:

  1. problem statement and forecast horizon;
  2. time plot and EDA summary;
  3. baseline forecasts;
  4. feature table description;
  5. at least two ML models;
  6. rolling-origin validation;
  7. horizon-wise error plot;
  8. residual or forecast-error diagnostics;
  9. feature-importance or feature-ablation analysis;
  10. final recommendation and limitations.

Suggested data sets include energy demand, transit ridership, retail demand, weather measurements, finance, website traffic, or synthetic data with known structure.

19.25 17.20 Exercises

  1. Lag table. For observations \(y_1,\ldots,y_{10}\), construct the supervised table for \(p=3\) lags and horizon \(h=2\). Which rows are lost at the beginning and end?
  2. Leakage detection. Decide whether each feature is valid at forecast origin \(t\): \(Y_t\), \(Y_{t-7}\), \(Y_{t+1}\), day of week at \(t+7\), weather observed at \(t+7\), scheduled holiday indicator at \(t+7\), centered rolling mean from \(t-3\) to \(t+3\).
  3. Ridge model. Suppose \(X\in\mathbb R^{n\times p}\) and target vector \(y\in\mathbb R^n\). Derive the ridge estimator for a fixed horizon \(h\).
  4. Recursive versus direct. Give a mathematical explanation for why recursive forecast errors can accumulate.
  5. Fourier features. Write the first three sine/cosine pairs for weekly seasonality in daily data.
  6. Rolling-origin design. Design a rolling-origin validation scheme for a monthly series with five years of data and a six-month forecast horizon.
  7. Baseline comparison. Implement naive and seasonal naive forecasts and compare them with a random forest using lag features.
  8. Feature ablation. Remove rolling features, seasonal features, and lag features one group at a time. Which group matters most?
  9. Diagnostics. Simulate a series with a weekly seasonal pattern. Fit an ML model without day-of-week features. What pattern remains in the errors?
  10. AI critique. Ask an AI assistant to design a feature set. Identify at least three suggestions that require leakage checks.

19.26 17.21 Chapter checklist

Before moving on, make sure you can:

19.27 17.22 Companion Python lab

Open the companion notebook: chapter-17-feature-based-machine-learning-lab.ipynb.

The lab asks you to build a leakage-aware ML forecasting pipeline with lag, rolling, Fourier, and calendar features; compare linear and tree-based models; and write a short diagnostic report.