Sub topic 9
Building Lag Features for a Forecasting Model
A lag feature is a past value of a series, placed on the same row as the value you want to predict. Most tabular forecasting models, such as linear regression, gradient-boosted trees and random forests, have no sense of time. They see one row at a time. Lag features give each row a short memory by copying earlier observations into extra columns.
This chapter assumes you already know shift() with positive and negative periods, how NaN appears at the edges, and groupby(). It also assumes you know what a DatetimeIndex is and how asfreq() restores missing timestamps. Here you combine those pieces into a repeatable feature-building routine. The next chapter looks at lookahead leakage in more depth, so this chapter only covers the rules that keep a lag feature safe.
The goal: one row, one prediction
Suppose you want to predict sales on day t. The model may only use information that would exist at the moment you make the prediction. That moment is the forecast origin. The number of days between the origin and the day you predict is the forecast horizon, written h.
For a one-day-ahead forecast, h = 1. Yesterday's sales are known when you forecast today, so a lag of 1 is allowed. For a seven-day-ahead forecast, h = 7. At the origin you do not yet know the last six days, so the smallest allowed lag is 7.
The rule: every feature built from the target must use a lag of at least h.
A dataset with two stores
The examples use daily sales for two stores over four weeks. Weekends get a small bump so there is a weekly pattern to find. The data is generated with a fixed seed so you can rerun it.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
dates = pd.date_range("2024-01-01", periods=28, freq="D")
stores = ["A", "B"]
df = pd.DataFrame(
[(store, d) for store in stores for d in dates],
columns=["store", "date"],
)
base = {"A": 100, "B": 300}
df["sales"] = (
df["store"].map(base)
+ 10 * (df["date"].dt.dayofweek >= 5)
+ rng.integers(-5, 6, size=len(df))
)
df = df.sort_values(["store", "date"]).reset_index(drop=True)
print(df.head())Notice the layout. This is a long table with one row per store per day. The dates repeat for each store, so the date column is not unique. A plain df["sales"].shift(1) would therefore be wrong here, because the first row of store B would receive the last value of store A. The previous chapter's rule applies: group first, then shift.
Adding several lags at once
A lag column is one groupby().shift() call. Wrap it in a function so the same code serves any column and any list of lags.
def add_lags(frame, column, lags, group="store"):
out = frame.copy()
grouped = out.groupby(group)[column]
for k in lags:
out[f"{column}_lag{k}"] = grouped.shift(k)
return out
features = add_lags(df, "sales", [1, 2, 7])
print(features[features["store"] == "A"].head(9))Each store loses its first k values in the lag-k column. Rows 0 to 6 of each store have NaN in sales_lag7, and rows 0 and 1 have NaN in sales_lag2. These rows are the warm-up period. The model has no history for them, so they cannot be used as training examples with that feature set.
Choosing which lags to include
Pick lags from what you know about the data, not from a long default list.
- Lag 1 and lag 2 capture short-term momentum.
- Lag 7 captures a weekly cycle in daily data. Lag 14 and lag 28 extend that idea.
- Lag 365 captures a yearly cycle, but it costs a year of warm-up rows per group.
Every extra lag removes more rows from the start of each group and adds a column that is strongly correlated with its neighbors. A short list such as [1, 2, 7, 14] is a reasonable first set. Check whether longer lags actually improve your validation error before keeping them.
Features you know in advance
Lag features are not the only inputs. Some columns are known for any future date, such as the day of the week, the month, or a planned promotion. These need no shifting, because they do not depend on the unknown future.
features["dayofweek"] = features["date"].dt.dayofweek
features["month"] = features["date"].dt.monthMixing the two kinds is the usual pattern. Lags carry what the series did recently, and calendar columns carry what is scheduled to happen.
Respecting the forecast horizon
To forecast h days ahead, start your lags at h. A small helper makes the rule explicit and prevents accidental use of too-recent values.
def add_lags_for_horizon(frame, column, horizon, n_lags, group="store"):
lags = range(horizon, horizon + n_lags)
return add_lags(frame, column, lags, group=group)
h3 = add_lags_for_horizon(df, "sales", horizon=3, n_lags=3)
print([c for c in h3.columns if "lag" in c])This prints ['sales_lag3', 'sales_lag4', 'sales_lag5']. There is no sales_lag1 or sales_lag2, because the model would not have those values at the forecast origin.
There is an equivalent formulation. Instead of shifting the features backward, you can shift the target forward with a negative period, groupby("store")["sales"].shift(-h), and keep the features unshifted. Both give the same pairs of feature and target. Shifting features is safer in practice, because the target column keeps its real meaning (sales on that date) and the model's inputs are visibly marked as lagged by their column names.
Gaps break the meaning of a lag
shift(k) moves by k rows. A lag is only a lag of k days if every day has exactly one row. If a date is missing, shift(1) silently reaches back two days at that point. The fix is to regularize before shifting. With groups, build the full grid of store and date pairs and reindex onto it.
full = pd.MultiIndex.from_product([stores, dates], names=["store", "date"])
gappy = df.drop(index=[3]) # removes store A on 2024-01-04
regular = (
gappy.set_index(["store", "date"])
.reindex(full)
.reset_index()
)
print(regular["sales"].isna().sum())This prints 1. The missing day is back as an explicit row with NaN sales. The next step is to lag it:
regular = add_lags(regular, "sales", [1, 7])
print(regular[regular["store"] == "A"].iloc[2:7])Now the lag for 2024-01-05 is NaN, because the real previous day is unknown. The lag for 2024-01-04 itself is still correct, since 2024-01-03 exists. The missing value affects exactly the rows it should: the missing day, plus any row that lags back onto it.
You then decide how to treat this NaN. Options include dropping the affected rows, filling with interpolation, or leaving the NaN for a model that supports it.
Dropping warm-up rows and splitting by time
After lagging, remove rows that lack the features you need. Then split the data by date. A random split would put later rows in the training set and earlier rows in the test set, which lets the model learn from the future.
model_df = features.dropna().copy()
cutoff = pd.Timestamp("2024-01-22")
train = model_df[model_df["date"] < cutoff]
test = model_df[model_df["date"] >= cutoff]
feature_cols = ["sales_lag1", "sales_lag2", "sales_lag7", "dayofweek"]
X_train, y_train = train[feature_cols], train["sales"]
X_test, y_test = test[feature_cols], test["sales"]
print(len(train), len(test))Every training date is earlier than every test date. For the sales_lag7 feature, the test rows still use real past sales as lags, including values that fall before the cutoff. That is fine. At the cutoff, those earlier days were already known.
X_train and y_train can go to any estimator. Before you fit one, compute a baseline so you know what the model has to beat. The seasonal naive forecast says "the same weekday last week" and needs only the lag-7 column.
baseline_mae = (y_test - test["sales_lag7"]).abs().mean()
print(round(baseline_mae, 2))If a model with ten features cannot beat this one-line baseline, the extra features are not helping.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Store B's first row has a value in its lag column | Shifted without grouping | Use `groupby(group)[col].shift(k)` |
| Lag looks correct but is wrong around holidays | Missing dates made `shift` count rows | Reindex to a full date grid first |
| Great validation score, poor live performance | A lag shorter than the horizon, or a random split | Start lags at `h`; split by date |
| Wrong results after merging or concatenating | Rows not sorted by group and date | Sort before every shift |
| Model drops most of the training data | Too many long lags with `dropna()` | Use fewer lags, or a model that accepts `NaN` |
| Lag columns misaligned after `groupby` | Result assigned to a frame with a different index | Assign to the same frame the group came from |
Practical checks before you train
Run these quick checks every time you build lag features.
- Check that the frame is sorted by group and date, and that
(group, date)pairs are unique. - Check that each group has one row per expected date. Compare
groupby("store").size()with the number of dates. - Pick one row by hand. Confirm that its
sales_lag7equals thesalesvalue from exactly seven days earlier in the same store. - Confirm that the smallest lag is at least the forecast horizon.
- Confirm that every test date is later than every training date.
The third check catches most alignment bugs in a few seconds. Do it with loc on a real date instead of trusting the code.
Exercise
You need to forecast daily sales 3 days ahead for each store. A colleague builds the features with add_lags(df, "sales", [1, 2, 3, 7]) and trains on them. What is wrong, and how do you correct it?
Show answer
Lags 1 and 2 use values from the 1 and 2 days before the predicted day. With a 3-day horizon, those days are not yet known at the forecast origin, so the model would see information it will not have in production. The validation score would look better than real performance. Use only lags of at least 3, for example add_lags(df, "sales", [3, 4, 5, 7]), or add_lags_for_horizon(df, "sales", horizon=3, n_lags=3) plus lag 7.
Exercise
A store has no row for 2024-02-10. You call df.groupby("store")["sales"].shift(1) without reindexing. Which dates get a wrong lag, and what does each one receive? How do you fix the pipeline?
Show answer
The row for 2024-02-11 gets the value from 2024-02-09, which is two days back, not one. Every other date is correct. Reindex each store onto a full daily grid, for example with pd.MultiIndex.from_product and reindex, so the missing day appears as NaN. After that, 2024-02-11 correctly gets NaN for lag 1, and you decide whether to drop, fill, or keep that row.