Sub topic 5
Building lag features
This chapter shows how to turn past values of a series into model inputs. It assumes you know pandas (Series, DatetimeIndex, shift), the scikit-learn fit/predict interface, and the supervised table from the previous chapters, where each row is one time step and the target is y.
What a lag feature is
A lag feature is the value of the series some number of steps before the row's own timestamp. lag_1 on 8 March holds the value from 7 March. lag_7 on a daily series holds the value from the same weekday one week earlier.
A gradient boosting model sees each row on its own and has no memory. Lag features put the recent past into the row, so the model can learn rules such as "tomorrow looks like last week's same day, adjusted by yesterday's level".
Creating lags with shift
Series.shift(k) moves values down by k positions, so each row receives the value from k rows earlier. The first k rows become NaN because no earlier value exists.
import numpy as np
import pandas as pd
idx = pd.date_range('2024-01-01', periods=60, freq='D')
rng = np.random.default_rng(0)
s = pd.Series(
100 + 10 * np.sin(2 * np.pi * np.arange(60) / 7) + rng.normal(0, 2, 60),
index=idx,
name='y',
)
df = pd.DataFrame({'y': s})
for lag in (1, 7, 14):
df[f'lag_{lag}'] = s.shift(lag)
print(df.iloc[[0, 1, 7, 14]])In the printout, row 0 has NaN in every lag column. Row 1 has lag_1 only. Row 7 has lag_1 and lag_7. Row 14 has all three. Rows with missing lags are normally dropped before fitting, which is why the longest lag decides how much early data you lose.
The shift counts rows, not time
shift(k) counts rows. It assumes each row is exactly one step after the previous one. If dates are missing, shift(1) silently pulls a value from further back than one day.
s_gap = s.drop(s.index[10:13]) # remove 11, 12 and 13 January
print(s_gap.shift(1).loc['2024-01-14']) # value from 10 January, not 13 January
print(s.loc['2024-01-10']) # same numberThe model would be trained on a feature that means "one day ago" in some rows and "four days ago" in others. Regularize the index first:
s_reg = s_gap.asfreq('D') # inserts the missing dates as NaN
print(s_reg.isna().sum()) # 3After asfreq, the lag for 14 January is NaN instead of wrong. Decide explicitly what to do with the gaps: drop those rows, or fill the series with a justified rule such as interpolation for sensor data or zero for "no sales". Do not fill by default, because a filled value looks like real data to the model.
Choosing which lags to build
More lags are not automatically better. Each extra lag adds a column, removes k rows from the start, and gives the model another chance to fit noise. Use three sources of evidence:
- Short lags (1, 2, 3) capture momentum and the current level.
- Seasonal lags capture repeating patterns. Use 7 and 14 for daily data with a weekly cycle, 12 for monthly data with a yearly cycle, and 24 and 168 for hourly data with daily and weekly cycles.
- The autocorrelation of the series shows which lags carry signal.
Autocorrelation is the correlation between the series and a shifted copy of itself. A quick check with pandas:
for k in range(1, 15):
print(k, round(s.autocorr(lag=k), 2))On this synthetic series, lags 7 and 14 show high positive values because the weekly cycle repeats. Lags near 3 or 4 are strongly negative because they fall on the opposite half of the cycle. Strong negative correlation is also useful to a tree model. Treat the numbers as a guide for choosing candidates and check the final choice with validation, since autocorrelation only measures linear relationships.
Features derived from lags
Raw lags give the level. Differences and ratios between lags give the change, which the model would otherwise need several splits to approximate.
df['diff_1_7'] = df['lag_1'] - df['lag_7'] # change versus a week ago
df['ratio_1_7'] = df['lag_1'] / df['lag_7'] # relative changeBoth columns use only lagged values, so they carry no information from time t. Ratios fail when the denominator can be zero, so guard against that for count data with many zero days.
Common errors
| Error | What happens | Fix |
|---|---|---|
| Calling `shift` on an irregular index | A lag means different time spans in different rows | Call `asfreq` first and handle the `NaN` rows |
| Using `shift(-k)` | The row receives a future value, which is leakage | Use only positive shifts for features |
| Shifting the whole DataFrame, including `y` | The target moves along with the features and the model learns nothing real | Shift the feature columns and keep `y` aligned to its own timestamp |
| Building lags on multiple series stacked in one table | The first rows of one series receive the last values of the previous series | Apply `groupby(id).shift(k)` |
| Computing lags after the train/test split | The first test rows lose their lags | Build lags on the full series, then split by time |
| Using a lag shorter than the forecast horizon | The feature is unavailable at prediction time | Keep the lag at least as long as the horizon, or use a recursive strategy |
The last row of the table matters most in practice. If you must forecast 7 days ahead and you train with lag_1, then on forecast day 1 you know yesterday's value, but on day 7 you do not. A later chapter on multi-step strategies covers the options. For now, remember that a lag is only usable if it would be known when you make the forecast.
Splitting after building lags
Building lags on the full series before splitting is safe, because each lag looks only backward. The first test row correctly receives its lag from the end of the training period, which matches what happens in production. The following code builds the table and splits it by time:
data = df[['y', 'lag_1', 'lag_7', 'lag_14']].dropna()
cut = int(len(data) * 0.8)
train, test = data.iloc[:cut], data.iloc[cut:]
print(train.index[-1], test.index[0])Check that the last training date is earlier than the first test date. Never shuffle this table.
Lags in production
At prediction time, the feature row for the next step must be built from the same definitions used in training. Keep one function that builds features and call it in both places. If training uses shift(7) and the serving code uses "the value from 6 days ago" because of an off-by-one error, the model receives inputs it was never trained on, and nothing raises an error. Compare the serving feature values against the training table for a known date as a basic test.
Exercise
A daily series has no entry for 3 March. You compute lag_1 = s.shift(1) and train on all rows. What is wrong with the row for 4 March, and what two steps fix it?
Show answer
The row for 4 March receives the value from 2 March, which is two days earlier, but the column is named lag_1, so the feature means different things in different rows. First call s.asfreq('D') so 3 March exists as NaN, then compute the lags and either drop the rows with missing lags or fill 3 March with a justified rule before computing them.
Exercise
You need to forecast 14 days ahead in one step, without feeding predictions back in. Which of lag_1, lag_7, lag_14 and lag_21 can you use as features, and why?
Show answer
Only lag_14 and lag_21. When you forecast 14 days ahead, the values from the last 13 days are not yet known at forecast time, so lag_1 and lag_7 would be unavailable. A lag is usable only if it is at least as long as the horizon.