Sub topic 15
Adding External Regressors and Known-Future Covariates
Lag and rolling features describe the series' own past. Many forecasts improve when you also give the model outside information such as promotions, prices, holidays or weather. This chapter assumes you can build the lag, rolling and calendar features from earlier chapters and that you understand target leakage. It also assumes you know the recursive strategy for multi-step forecasts. The central question is which covariate values you will actually have on the day you forecast.
Three kinds of covariates
An external regressor (also called an exogenous variable) is any column that is not the target. What matters is when its values become known.
| Kind | Example | Known for future dates at forecast time? | How to use it |
|---|---|---|---|
| Known-future | Promotion calendar, holidays, planned price, day of week | Yes | Align to the target date, with no shift |
| Observed-only | Actual temperature, competitor price, web traffic | No | Lag it by at least the forecast horizon |
| Static | Store region, product category | Yes, it never changes | Add as a constant column (see the global models chapter) |
Calendar features are the simplest known-future covariates. Anything you can state with certainty about a future date belongs in the same group. A forecast of weather is a different case, covered below.
The availability rule
Leakage in covariates works like leakage in lags. For each feature, ask what the model will see when it predicts date t from a forecast origin o, where o < t. A feature is valid only if its value for t is known at o.
A common mistake is to join actual weather for day t into the training table. The backtest then looks excellent because the model sees weather that nobody has at forecast time. In production you only have a weather forecast, which is noisier than the actuals.
Building the features
The example below builds a synthetic daily series with a weekend effect, a promotion effect and a temperature effect. It extends make_features with two covariates. promo is known-future, so it is aligned to the target row. temp_lag_7 is observed-only, so it is shifted by the 7-day horizon we plan to forecast.
import numpy as np
import pandas as pd
from sklearn.ensemble import HistGradientBoostingRegressor
from sklearn.metrics import mean_absolute_error
HORIZON = 7
rng = np.random.default_rng(0)
idx = pd.date_range('2023-01-01', periods=400, freq='D')
promo = pd.Series((rng.random(len(idx)) < 0.1).astype(int), index=idx)
temp = pd.Series(15 + 10 * np.sin(2 * np.pi * idx.dayofyear / 365)
+ rng.normal(0, 2, len(idx)), index=idx)
y = pd.Series(100 + np.where(idx.dayofweek >= 5, 5, 0) + 30 * promo
+ 0.8 * temp + rng.normal(0, 3, len(idx)), index=idx)
def make_features(y, promo, temp):
df = pd.DataFrame({'y': y})
for lag in (1, 7, 14):
df[f'lag_{lag}'] = y.shift(lag)
df['roll_mean_7'] = y.shift(1).rolling(7).mean()
df['dayofweek'] = y.index.dayofweek
df['promo'] = promo # known-future: same date as target
df[f'temp_lag_{HORIZON}'] = temp.shift(HORIZON) # observed-only: lagged
return df.dropna()
data = make_features(y, promo, temp)
all_cols = [c for c in data.columns if c != 'y']
base_cols = [c for c in all_cols if c not in ('promo', f'temp_lag_{HORIZON}')]
train = data.loc[:idx[-HORIZON - 1]]
test = data.loc[idx[-HORIZON]:]
for name, cols in [('without covariates', base_cols), ('with covariates', all_cols)]:
m = HistGradientBoostingRegressor(max_iter=300, learning_rate=0.05, random_state=0)
m.fit(train[cols], train['y'])
print(name, mean_absolute_error(test['y'], m.predict(test[cols])))Both models are scored on the same chronological test rows. A covariate only helps if the error drops against that comparison, so always keep the version without covariates.
Known-future features can look forward
Because a known-future value exists for any future date, you can shift it in either direction. promo.shift(-1) means "a promotion starts tomorrow", which can capture customers holding back their purchases. promo.shift(1) captures a post-promotion dip. A negative shift would be leakage for y or for an observed-only series. For a schedule that is fixed in advance, it is legitimate.
Why observed-only covariates need a lag of at least the horizon
With the recursive strategy, step 7 of a forecast is made from origin o, so the newest observed value you have is from o. A feature temp_lag_1 would need the temperature for t-1, which does not exist yet for steps 2 through 7. A shift of HORIZON days makes every step valid. The direct strategy has a related option. You train one model per horizon h and use temp.shift(h). Short horizons then get fresher information.
Forecasting with future covariates
The recursive forecaster from the multi-step chapter needs one more input. At each step it reads the known-future values for that date from a table you supply. Keep the row definitions identical to training.
def recursive_forecast_exog(model, history, temp, future_promo, feature_cols):
# history: target Series with freq set; temp: observed up to the origin
values = history.copy()
freq = values.index.freq
preds = []
for _ in range(len(future_promo)):
ts = values.index[-1] + freq
recent = values.iloc[-7:]
row = {
'lag_1': values.iloc[-1],
'lag_7': values.iloc[-7],
'lag_14': values.iloc[-14],
'roll_mean_7': recent.mean(),
'dayofweek': ts.dayofweek,
'promo': future_promo.loc[ts], # KeyError if the plan is missing
f'temp_lag_{HORIZON}': temp.loc[ts - pd.Timedelta(days=HORIZON)],
}
X = pd.DataFrame([row], columns=feature_cols)
yhat = float(model.predict(X)[0])
values.loc[ts] = yhat
preds.append(yhat)
return preds
origin = idx[-HORIZON - 1]
model = HistGradientBoostingRegressor(max_iter=300, learning_rate=0.05, random_state=0)
model.fit(train[all_cols], train['y'])
preds = recursive_forecast_exog(
model, y.loc[:origin], temp.loc[:origin],
promo.loc[idx[-HORIZON]:], all_cols)
print(mean_absolute_error(y.loc[idx[-HORIZON]:], preds))Note that temp is cut at origin. If the function runs without a KeyError, you know it used no temperature value later than the origin. Passing a shorter future_promo shortens the horizon automatically.
Practical gotchas
- Train and serve skew. If you train on actual weather but serve a weather forecast, errors in the forecast pass straight into your predictions. Better options are to train on archived forecasts as they were issued, or to add noise to the actuals during training.
- Point-in-time correctness. Prices, stock levels and revisions get overwritten. Join the value that was current at the origin, not the latest value in the table.
- Missing future plans. Decide ahead of time what happens when a promotion calendar is incomplete. Silent fill with
0hides the error. Fail loudly, as theKeyErrorabove does. - Extrapolation. Trees cannot go beyond the target range seen in training. A price covariate outside its training range is clamped to the nearest split. This is the same limit described in the trend chapter.
- Encoding. Gradient boosting needs no scaling. Binary and integer flags work as they are. Add an interaction like
promotimesdayofweekonly if the validation score shows it helps, since trees already model interactions. - Validate with walk-forward splits. A covariate that helps in one chronological split may not help in others. Check it across the folds from the validation chapter, with the same
gap.
Exercise
You forecast daily demand 3 days ahead with the direct strategy. Your table has ad_spend (the budget is fixed two weeks in advance) and competitor_price (scraped each morning). Which shift would you apply to each column for the horizon-3 model, and why?
Show answer
Use ad_spend for the target date unshifted, since the budget is known in the future (you can also add leads or lags such as shift(-1)). Use competitor_price.shift(3) or larger for the horizon-3 model, because the price for the target date is only observed after the forecast is needed. The newest price available at the origin belongs to the origin day, which is 3 days before the target.
Exercise
A teammate joins daily actual rainfall to the training table with no shift, and the backtest MAE drops by 40%. What is wrong, and how do you test the covariate fairly?
Show answer
Rainfall for the target date is unknown at forecast time, so the feature leaks future information. Replace it with a lagged value of at least the horizon, or with the weather forecast that was issued at the origin. Then rerun walk-forward validation and compare against the model without the covariate.