# Feature-Based Machine Learning for Time Series
::: {.hero}
**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.
:::
## 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.
## 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.
::: {.callout-note}
## The 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.
:::
## 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).
$$
::: {.theorem-box}
## 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.
:::
## 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$.
### 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.
## 17.4 Feature types
### 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.
### 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.
::: {.callout-warning}
## Centered 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$.
:::
### 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.
### 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.
### 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.
## 17.5 Direct, recursive, and multi-output ML forecasting
Feature-based models can forecast multiple steps ahead in several ways.
### 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.
### 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.
### 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.
::: {.callout-tip}
## Practical 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.
:::
## 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.
## 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.
<div class="interactive-card">
<div class="controls-grid">
<label>Number of lags: <span id="ch17_lags_value">5</span>
<input id="ch17_lags" type="range" min="1" max="14" step="1" value="5">
</label>
<label>Rolling window: <span id="ch17_window_value">7</span>
<input id="ch17_window" type="range" min="2" max="28" step="1" value="7">
</label>
<label>Forecast horizon: <span id="ch17_horizon_value">3</span>
<input id="ch17_horizon" type="range" min="1" max="14" step="1" value="3">
</label>
<label>Forecast origin: <span id="ch17_origin_value">80</span>
<input id="ch17_origin" type="range" min="40" max="130" step="1" value="80">
</label>
</div>
<div id="ch17_feature_series_plot" style="height:430px;"></div>
<div id="ch17_feature_matrix_plot" style="height:430px;"></div>
<div id="ch17_feature_explanation" class="small-note"></div>
</div>
<script>
(function() {
function rng(seed) {
let s = seed % 2147483647;
return function() {
s = s * 16807 % 2147483647;
return (s - 1) / 2147483646;
};
}
function normal(rand) {
const u1 = Math.max(rand(), 1e-12);
const u2 = rand();
return Math.sqrt(-2 * Math.log(u1)) * Math.cos(2 * Math.PI * u2);
}
function rollingMean(y, t, w) {
let total = 0;
let count = 0;
for (let j = 0; j < w; j++) {
const idx = t - j;
if (idx >= 0) {
total += y[idx];
count += 1;
}
}
return total / Math.max(count, 1);
}
function standardizeColumns(matrix) {
const rows = matrix.length;
const cols = matrix[0].length;
const out = Array.from({length: rows}, () => Array(cols).fill(0));
for (let c = 0; c < cols; c++) {
const values = matrix.map(row => row[c]);
const mean = values.reduce((a,b) => a+b, 0) / rows;
const sd = Math.sqrt(values.reduce((a,b) => a + (b-mean)*(b-mean), 0) / Math.max(rows-1, 1)) || 1;
for (let r = 0; r < rows; r++) out[r][c] = (matrix[r][c] - mean) / sd;
}
return out;
}
function compute() {
const p = +document.getElementById('ch17_lags').value;
const w = +document.getElementById('ch17_window').value;
const h = +document.getElementById('ch17_horizon').value;
const origin = +document.getElementById('ch17_origin').value;
document.getElementById('ch17_lags_value').innerText = p;
document.getElementById('ch17_window_value').innerText = w;
document.getElementById('ch17_horizon_value').innerText = h;
document.getElementById('ch17_origin_value').innerText = origin;
const n = 160;
const rand = rng(733917);
const t = Array.from({length:n}, (_,i) => i);
const y = [];
let ar = 0;
for (let i = 0; i < n; i++) {
ar = 0.65 * ar + normal(rand);
y.push(40 + 0.08*i + 6*Math.sin(2*Math.PI*i/7) + 2.5*Math.cos(2*Math.PI*i/30) + 2.2*ar);
}
const lagXs = [];
const lagYs = [];
for (let j = 0; j < p; j++) {
const idx = origin - j;
lagXs.push(idx);
lagYs.push(y[idx]);
}
const targetIndex = origin + h;
const traces1 = [
{x:t, y:y, mode:'lines', name:'series'},
{x:lagXs, y:lagYs, mode:'markers', name:'lag features', marker:{size:11}},
{x:[targetIndex], y:[y[targetIndex]], mode:'markers', name:'target y(t+h)', marker:{size:14, symbol:'star'}},
{x:[origin], y:[y[origin]], mode:'markers', name:'forecast origin', marker:{size:13, symbol:'diamond'}}
];
const shapes = [
{type:'line', x0:origin, x1:origin, yref:'paper', y0:0, y1:1, line:{width:2, dash:'dot'}},
{type:'line', x0:targetIndex, x1:targetIndex, yref:'paper', y0:0, y1:1, line:{width:2, dash:'dash'}}
];
Plotly.newPlot('ch17_feature_series_plot', traces1, {
title:'Forecast origin, lag features, and target value',
xaxis:{title:'time index'},
yaxis:{title:'series value'},
shapes: shapes,
margin:{t:55, l:55, r:20, b:45}
}, window.TSInteractives ? window.TSInteractives.plotlyConfig : {responsive:true, displayModeBar:true});
const start = Math.max(p + w - 1, 30);
const rows = [];
const rowLabels = [];
for (let row = 0; row < 24; row++) {
const tt = start + row;
const features = [];
for (let j = 0; j < p; j++) features.push(y[tt - j]);
features.push(rollingMean(y, tt, w));
features.push(Math.sin(2*Math.PI*tt/7));
features.push(Math.cos(2*Math.PI*tt/7));
features.push(y[tt + h]);
rows.push(features);
rowLabels.push('origin ' + tt);
}
const z = standardizeColumns(rows);
const colLabels = [];
for (let j = 1; j <= p; j++) colLabels.push('lag_' + j);
colLabels.push('roll_mean_' + w);
colLabels.push('sin_week');
colLabels.push('cos_week');
colLabels.push('target_h' + h);
Plotly.newPlot('ch17_feature_matrix_plot', [{
z: z,
x: colLabels,
y: rowLabels,
type:'heatmap',
colorbar:{title:'standardized value'}
}], {
title:'Supervised-learning table: features and target',
xaxis:{title:'columns'},
yaxis:{title:'rows'},
margin:{t:55, l:95, r:30, b:95}
}, window.TSInteractives ? window.TSInteractives.plotlyConfig : {responsive:true, displayModeBar:true});
document.getElementById('ch17_feature_explanation').innerHTML =
`<strong>Selected row:</strong> At origin t=${origin}, the model may use ` +
`${p} lag values y_t,...,y_{t-${p-1}}, the past rolling mean of width ${w}, and known seasonal features. ` +
`It predicts y_{t+${h}}, located at time ${targetIndex}. ` +
`No value after origin ${origin} is allowed as a feature.`;
}
['ch17_lags','ch17_window','ch17_horizon','ch17_origin'].forEach(id => {
document.getElementById(id).addEventListener('input', compute);
});
compute();
})();
</script>
## 17.8 Python example: constructing lagged features
The following code constructs a synthetic daily series and converts it to a supervised-learning data frame.
```{python}
#| label: ch17-simulate-lagged-data
#| fig-cap: "Synthetic daily time series used for feature-based forecasting."
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()
```
```{python}
#| label: ch17-lag-feature-function
#| fig-cap: "First rows of a supervised-learning table with lag, rolling, and Fourier features."
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()
```
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.
## 17.9 Linear and nonlinear ML forecasters
Feature-based ML can be used with many supervised-learning algorithms.
### 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.
### 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.
### 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.
### 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.
::: {.callout-warning}
## Tree 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.
:::
## 17.10 Python example: chronological split and model comparison
```{python}
#| label: ch17-ml-model-comparison
#| fig-cap: "Seven-day-ahead forecasts from feature-based machine-learning models."
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")
```
```{python}
#| label: ch17-ml-forecast-plot
#| fig-cap: "Chronological test-period forecasts from feature-based ML models."
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()
```
## 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.
```{python}
#| label: ch17-recursive-ridge
#| fig-cap: "Recursive one-step forecasts using a lag-only ridge model."
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()
```
::: {.callout-important}
## Recursive 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.
:::
## 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.
```{python}
#| label: ch17-direct-multihorizon
#| fig-cap: "Direct forecasts from separate horizon-specific models."
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()
```
## 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.
```{python}
#| label: ch17-rolling-origin-ml
#| fig-cap: "Horizon-wise MAE from rolling-origin validation."
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
```
## 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.
```{python}
#| label: ch17-permutation-importance
#| fig-cap: "Permutation importance on the chronological test set."
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
```
## 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.
```{python}
#| label: ch17-error-diagnostics
#| fig-cap: "Test forecast errors and their sample autocorrelation."
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()
```
## 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.
### 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.
$$
### 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}.
$$
### 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.
### 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.
## 17.17 AI-assisted modeling activity
::: {.callout-ai}
## 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.
:::
::: {.callout-ai}
## 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.
:::
::: {.callout-ai}
## 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.
:::
## 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.
## 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.
## 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.
## 17.21 Chapter checklist
Before moving on, make sure you can:
- [ ] define a forecast origin and horizon;
- [ ] construct a lagged supervised-learning table;
- [ ] distinguish valid origin-time features from leakage features;
- [ ] use calendar and Fourier features for seasonality;
- [ ] explain recursive, direct, and multi-output forecasting;
- [ ] implement a chronological train/test split;
- [ ] implement rolling-origin validation;
- [ ] compare ML models with naive and seasonal naive baselines;
- [ ] diagnose forecast errors using plots and ACF;
- [ ] use AI suggestions only after checking assumptions and time order.
## 17.22 Companion Python lab
Open the companion notebook: [`chapter-17-feature-based-machine-learning-lab.ipynb`](../labs/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.