Sub topic 5
Building lag features
This chapter assumes you know pandas basics (Series, DataFrame, DatetimeIndex), scikit-learn's fit/predict interface, and how a regression table of features and a target works. It builds on the idea that a forecast can be framed as supervised regression.
What a lag feature is
A lag feature is the value of the series some number of steps earlier. At row t, lag_k holds y[t-k]. The model then predicts y[t] from values it would already know at prediction time.
In pandas, Series.shift(k) moves values down by k positions. The first k rows become NaN because no earlier value exists.
import pandas as pd
s = pd.Series(
[10, 12, 11, 15, 14],
index=pd.date_range("2026-01-01", periods=5, freq="D"),
)
df = pd.DataFrame({"y": s, "lag_1": s.shift(1), "lag_2": s.shift(2)})
print(df)The output shows lag_1 on 2026-01-03 equal to 12, which is the value from 2026-01-02. Each row now holds the target and the history that precedes it.
Choosing which lags to build
Pick lags that match the structure of the series.
- Short lags (1, 2, 3): capture momentum and recent level.
- Seasonal lags (7 for daily data with a weekly cycle): capture the same point in the previous cycle.
- Multiples of the season (14, 21): give the model a more stable view of the seasonal pattern.
Autocorrelation plots help you choose. Spikes at lag 7 and 14 suggest weekly structure. Avoid adding every lag from 1 to 60. Many near-duplicate columns add noise and slow training without adding information.
Building them in a function
The function below builds lag features for a series with a regular frequency. It also adds rolling and calendar columns, which later chapters explain.
import pandas as pd
def make_features(s: pd.Series) -> pd.DataFrame:
# s must have a DatetimeIndex with a regular frequency
df = pd.DataFrame({'y': s})
for lag in (1, 7, 14):
df[f'lag_{lag}'] = s.shift(lag)
past = s.shift(1) # exclude the current value from the window
df['roll_mean_7'] = past.rolling(7).mean()
df['roll_std_7'] = past.rolling(7).std()
df['dayofweek'] = s.index.dayofweek
return df.dropna()The final dropna() removes the first 14 rows, because lag_14 is missing there. You lose as many rows as your largest lag, so a longer lag costs more training data.
Common errors
- Irregular timestamps.
shift(k)moves by rows, not by time. If days are missing,lag_7no longer means one week. Calls.asfreq('D')first and decide how to fill the gaps. - Shifting in the wrong direction.
shift(-1)brings in a future value. That leaks the answer into the features. Always use positive shifts for features. - Shifting across series. With several series in one DataFrame, use
groupby(...).shift(k)so one series' history does not bleed into the next. - Forgetting lag availability at forecast time. A
lag_1feature is not known when forecasting 5 days ahead. Multi-step strategies handle this, and a later chapter covers them.
Exercise
A daily series has missing rows for several weekends. You call s.shift(7) to build a weekly lag. Why can the result be wrong, and what should you do first?
Show answer
shift moves by row position, not by calendar time. With missing days, seven rows back is no longer seven days back. First convert the series to a regular frequency with s.asfreq('D'), then handle the resulting NaN values (for example by filling or by leaving them for the model), and only then call shift(7).