Sub topic 12
Forecasting several steps ahead: recursive vs direct
This chapter assumes you can already build lag and rolling features, fit a HistGradientBoostingRegressor, and validate chronologically. It covers what to do when you need forecasts for more than one future step.
Why one step is easy and many steps are not
A model trained on lag_1 learns "tomorrow looks like today plus adjustments". To predict tomorrow you need today's value, and you have it. To predict three days from now, the model still expects lag_1, which is the value two days from now. That value hasn't happened yet.
There are two standard ways around this:
- Recursive: use one one-step model. Feed each prediction back in as if it were an observation.
- Direct: train a separate model for each horizon
h. Each model only uses information available at the forecast origin.
The recursive strategy
You already have the building blocks. The recursive_forecast function from the earlier code example does the following at each step:
- It builds one feature row from the last values in
values. Those values are real observations plus earlier predictions. - It predicts, appends the prediction to the series, and moves on.
You call it like this:
history = series.asfreq('D')
preds = recursive_forecast(model, history, horizon=14, feature_cols=feature_cols)The function reads values.index.freq, so asfreq (or any other way of setting a frequency) is required. The row it builds must match make_features exactly: same columns, same window definitions, same exclusion of the current value from the rolling window.
What goes wrong
- Errors compound. Step 5 uses inputs that already contain the errors of steps 1 to 4, and the model never saw such inputs in training.
- Train/predict mismatch. The model was fit on true lags. At prediction time its lags are model outputs, which are usually smoother than reality. A rolling standard deviation computed over predictions will be too small, so a feature the model relies on drifts away from its training distribution.
- Damping. Tree models tend to pull predictions toward typical values, and feeding those back amplifies the pull. Long recursive forecasts often flatten into a weekly average.
- Cost is cheap, though. One model, one fit, and any horizon works without retraining.
The direct strategy
For horizon h, build a table where each row is a forecast origin t. The features use only data up to t, and the target is y[t+h]. In pandas the target is s.shift(-h). Calendar features should describe the target date, because that is the day being predicted.
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
def origin_features(s: pd.Series, h: int) -> pd.DataFrame:
# Every column uses data at or before the origin t. Daily data assumed.
X = pd.DataFrame(index=s.index)
X['y_t'] = s
X['y_t_minus_6'] = s.shift(6)
X['y_t_minus_13'] = s.shift(13)
X['roll_mean_7'] = s.rolling(7).mean()
X['roll_std_7'] = s.rolling(7).std()
X['target_dow'] = (s.index + pd.Timedelta(days=h)).dayofweek
return X
def fit_direct(s: pd.Series, horizon: int) -> dict:
models = {}
for h in range(1, horizon + 1):
X = origin_features(s, h)
y = s.shift(-h)
ok = X.notna().all(axis=1) & y.notna()
m = HistGradientBoostingRegressor(
max_iter=300, learning_rate=0.05, random_state=0)
m.fit(X[ok], y[ok])
models[h] = m
return models
def direct_forecast(models: dict, s: pd.Series) -> list:
return [float(m.predict(origin_features(s, h).iloc[[-1]])[0])
for h, m in models.items()]
rng = np.random.default_rng(0)
idx = pd.date_range('2024-01-01', periods=400, freq='D')
demo = pd.Series(
100 + 10 * np.sin(2 * np.pi * np.arange(400) / 7) + rng.normal(0, 2, 400),
index=idx)
models = fit_direct(demo, horizon=7)
print(direct_forecast(models, demo))Each model sees real inputs at both training and prediction time, so nothing is fed back and nothing compounds. The price is that you train and store H models. Training rows also shrink slightly as h grows, because the last h origins have no target.
The lag names change meaning here. They are measured from the origin, not from the target. For the target at t+h, y_t is lag h. That makes a seasonal lag of 7 only usable when h ≤ 7, and h = 7 makes y_t the seasonal-naive value. The naming makes this visible.
Comparing the two
| Aspect | Recursive | Direct |
|---|---|---|
| Models to train | 1 | 1 per horizon |
| Inputs at prediction time | Observed values mixed with predictions | Observed values only |
| Error behaviour | Compounds with step count | Independent per horizon |
| Consistency across horizons | Forecast path is smooth and coherent | Each horizon can disagree with its neighbours |
| Horizon flexibility | Any length without retraining | Fixed set of horizons |
| Unknown future covariates | Must be forecast too | Used only at the origin |
Direct forecasts can look jagged. Forecasts for day 3 and day 4 come from different models and may not line up. Smoothing or a shared model with horizon as a feature can help, but both add complexity.
Variations worth knowing
- Lags at least as long as the horizon. If you need 7-day forecasts and use only features with lag ≥ 7 (
lag_7,lag_14, rolling means of the shifted series), a single model forecasts every step with no feedback. Accuracy suffers because you discard the freshest information, but you get one model and no error compounding. - One model with a horizon column. Stack the tables for all
h, addhas a feature, and train once. This shares data across horizons. A tree must learn to split onh, which works but may need more iterations. - Hybrid. Use direct models for the first few steps, where fresh lags matter most, and a recursive or long-lag model afterwards.
Evaluating by horizon
A single overall MAE hides the pattern. Error grows with horizon, and the strategies cross over at different points. Run walk-forward validation (see the validation chapter), and for every origin, score each horizon h separately. Then compare against the seasonal-naive forecast at the same h.
Keep these rules:
- Fit on data up to the origin only. Refit direct models per fold, since their targets reach
hsteps past the origin. - Use a
gapinTimeSeriesSplitof at least the maximum horizon. A training target att+hotherwise overlaps the validation period. - For recursive evaluation, start each validation origin from the true history. Do not let predictions from the previous origin leak into the next one.
Choosing between them
Start with recursive if you need arbitrary horizons, have limited training budget, or have a short horizon where compounding is small. Switch to direct when you see predictions flattening, when the horizon is long compared to the seasonal period, or when per-horizon accuracy matters more than a smooth path. Measure both per horizon against seasonal naive before deciding. A strategy that doesn't beat seasonal naive at some horizon shouldn't be used there.
Exercise
You forecast daily sales 14 days ahead with a recursive model whose features include rollstd7. The forecasts become nearly flat after day 5, and the walk-forward error at long horizons is worse than seasonal naive. Name two reasons related to the recursive strategy, and one change you would try.
Show answer
First, predictions are smoother than real data, so rollstd7 computed over fed-back predictions shrinks and moves outside the range seen in training. Second, errors and the tree model's pull toward typical values compound over steps, which flattens the path. Changes to try: train direct models per horizon, or restrict features to lags of at least 14 so one model needs no feedback. A hybrid that uses direct models for the first few days also works.
Exercise
In the direct table for horizon h = 3, why is target_dow computed from s.index + 3 days rather than s.index.dayofweek?
Show answer
Each row's target is the value three days after the origin, so the calendar feature must describe the target date. Using the origin's day of week would give the model the wrong weekday for the day it is predicting. This is a known-future feature, so using it does not leak anything.