Learning path: Data and Features in Production · Step 2 of 8
Time Series Basics: Lags, Rolling Windows and Walk-Forward Backtesting
Forecast tomorrow's maximum temperature in Sydney from past temperatures only: fill the calendar with asfreq, build lag and rolling features with shift, beat the same-as-today guess, and backtest over five walk-forward folds.
What you will learn
- Make one row mean one day with asfreq, so shift never skips a gap
- Turn one temperature column into a supervised table with shift and a rolling window that stops at yesterday
- Score a naive baseline and a linear model with MAE, and spot a leaky window
- Walk forward through time with TimeSeriesSplit and read the error of every fold
Before you start
- Time Splits and Group Splits
- Linear Regression in scikit-learn
- Regression Metrics: MAE, RMSE and R-squared
Somebody asks you: what will the maximum temperature be in Sydney tomorrow? The simplest possible answer is "the same as today". Here are the last seven days in our Sydney data, a fairly calm winter week:
| Date | 19 Jun | 20 Jun | 21 Jun | 22 Jun | 23 Jun | 24 Jun | 25 Jun |
|---|---|---|---|---|---|---|---|
| MaxTemp | 18.3 | 20.0 | 19.6 | 19.2 | 17.7 | 19.3 | 19.3 |
Guess "same as today" and you miss by 1.7, then 0.4, and on the last day by a perfect zero. No model and no training. But any forecast we build has to beat this guess, or there's no point building it.
In this lesson we forecast tomorrow's MaxTemp in Sydney, using nothing but the temperatures before it, and check honestly whether the forecast is any good. The rule for the whole lesson: a column you could not have known that morning doesn't belong in the table.
The project
A small package called tempcast, one data file (the Sydney rows of weatherAUS.csv) and one short file per step. Each file runs with python -m tempcast.<name>. Every score below is mean absolute error (MAE) in degrees Celsius: the average size of a miss. If MAE is new, see Regression Metrics.
Step 1: the calendar has holes
import pandas as pd
def load_daily(path="data/sydney.csv"):
df = pd.read_csv(path, parse_dates=["Date"])
y = df.set_index("Date")["MaxTemp"].sort_index()
return y.asfreq("D") # a missing date becomes a blank row
rows in the file 3337
calendar days 3433
missing dates 96
blank MaxTemp 2
jumps in the file 9
longest jump 32 days
3,337 rows, but 3,433 calendar days, so 96 dates are simply missing. Why does that matter? shift works by rows, not days. In the file, 30 November 2012 is followed straight by 1 January 2013. Without a fix, the row for 1 January would call a day 32 days old "yesterday".
asfreq("D") gives one row for every calendar day, and the missing dates become blank rows. The row after a gap then has a blank lag, and we drop it. We don't fill it in, because that would be inventing weather.
Step 2: one shift turns a column into a table
A model can't read one long column of temperatures. It needs rows of features and a label. shift builds them:
FEATURES = ["lag_1", "lag_2", "lag_7", "roll_7", "roll_30"]
def make_features(y):
t = pd.DataFrame({"y": y}) # y: the day we predict
t["lag_1"] = y.shift(1)
t["lag_2"] = y.shift(2)
t["lag_7"] = y.shift(7)
t["roll_7"] = y.shift(1).rolling(7).mean()
t["roll_30"] = y.shift(1).rolling(30).mean()
return t.dropna() # complete rows only
usable rows 3009
y lag_1 lag_2 lag_7 roll_7 roll_30
Date
2017-06-23 17.7 19.2 19.6 17.3 18.79 18.94
2017-06-24 19.3 17.7 19.2 19.1 18.84 18.77
2017-06-25 19.3 19.3 17.7 18.0 18.87 18.70
y.shift(1) slides every value down one row, so each day sits beside the day before it. Read the last row: y is the answer for 25 June, and lag_1 is what we knew the evening before. lag_2 and lag_7 go two days and a week back.
A rolling window stops at yesterday
Lags give single days. A rolling window gives the recent trend in one number. The important part is the shift(1) in front: it puts the end of the window at yesterday.
roll_7 averages 18 to 24 June (18.87). Leave out shift(1) and the window slides one day right, onto the answer itself (19.06).rolling only counts full windows, so after a gap a row waits 30 days for roll_30. That's why 3,335 temperatures become 3,009 usable rows.
Step 3: two guesses with no model
import numpy as np
def same_as_today(test):
return test["lag_1"]
def calendar_average(train, test, days=0):
"""Mean of training days within `days` of this date."""
seen = train.index.dayofyear.to_numpy()
y = train["y"].to_numpy()
out = []
for d in test.index.dayofyear:
gap = np.abs(seen - d)
near = np.minimum(gap, 366 - gap) <= days
out.append(y[near].mean() if near.any() else y.mean())
return np.array(out)
"Same as today" just returns lag_1. The second guess is the calendar: average the same day of the year across the training years. For 26 June 2016 there are seven past years, averaging 18.4. What happened that day? 15.3, and "same as today" (15.1) was much closer. One day proves nothing, so we score the last 365 rows:
train 2644 rows, test 365 rows
test 2016-06-26 to 2017-06-25
same as today 2.55
same date average 2.33
On this one test year, the calendar wins. Hold that thought.
Step 4: a plain linear model
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error
t = make_features(load_daily())
train, test = t.iloc[:-365], t.iloc[-365:] # the last year tests
model = LinearRegression().fit(train[FEATURES], train["y"])
pred = model.predict(test[FEATURES])
print(f"model MAE {mean_absolute_error(test['y'], pred):.2f}")
for name, c in zip(FEATURES, model.coef_):
print(f"{name:8} {c:+.2f}")
model MAE 2.12
lag_1 +0.37
lag_2 -0.06
lag_7 +0.01
roll_7 +0.27
roll_30 +0.35
2.12 against 2.55 for "same as today". Look at what it learned. "Same as today" is the same kind of formula, with 1.0 on lag_1 and zero on everything else. The model trusts today about a third, and gives the rest to the recent weeks. There's no seed: a linear fit gives the same answer every time.
Step 5: one missing shift, and a score too good
Now break it on purpose, because this bug is very common. Same rows, but leave out the shift in both windows:
def leaky_features(y):
t = make_features(y) # the same rows
t["roll_7"] = y.rolling(7).mean() # the bug
t["roll_30"] = y.rolling(30).mean() # the bug
return t
with shift, 5 columns 2.12
no shift, 5 columns 1.91
with shift, lags 1 to 6 2.17
no shift, lags 1 to 6 0.00
The day we're predicting is now inside its own feature. The error drops from 2.12 to 1.91, and that's the dangerous part: it doesn't look broken, it looks like a nice improvement.
Push it with lags 1 to 6 plus the buggy window, and the error is 0.00. It's just algebra: seven times roll_7, minus those six lags, gives back the answer. In production that value doesn't exist yet, so the great score disappears.
If a score jumps after you add a column, check that column first.
Step 6: walk forward, again and again
So far we tested on one year, and that year said the calendar beats "same as today". One odd year can fool us. A walk-forward backtest trains on everything up to a point, tests on what comes next, then moves forward and does it again:
from sklearn.metrics import mean_absolute_error as mae
from sklearn.model_selection import TimeSeriesSplit
def backtest(t, n_splits=5, test_size=365, cols=FEATURES):
folds = TimeSeriesSplit(n_splits=n_splits, test_size=test_size)
rows = []
for k, (a, b) in enumerate(folds.split(t), 1):
train, test = t.iloc[a], t.iloc[b]
model = LinearRegression().fit(train[cols], train["y"])
y = test["y"]
rows.append({
"fold": k, "train": len(train),
"first": test.index[0].date(),
"last": test.index[-1].date(),
"today": mae(y, same_as_today(test)),
"date": mae(y, calendar_average(train, test)),
"near": mae(y, calendar_average(train, test, days=15)),
"model": mae(y, model.predict(test[cols])),
})
return pd.DataFrame(rows)
fold train first last today date near model
1 1184 2011-12-01 2012-11-29 2.38 2.63 2.26 2.04
2 1549 2012-11-30 2014-03-28 2.55 2.68 2.45 2.17
3 1914 2014-03-29 2015-06-26 2.18 2.50 2.26 1.94
4 2279 2015-06-27 2016-06-25 2.49 2.64 2.40 2.15
5 2644 2016-06-26 2017-06-25 2.55 2.33 2.14 2.12
mean today 2.43 date 2.55 near 2.30 model 2.08
model beats today in 5 of 5 folds
by 0.35 degrees, 14.2%
Fold 2 covers more calendar time than the others, because its 365 rows have to step over the holes in the data.
Does it really beat "same as today"?
- The calendar was a one-year fluke. The same-date average beat "same as today" in only one fold out of five (the last year, the one we tested first).
- "Same as today" isn't unbeatable. Average 15 days either side of the date (
near) and the calendar gets to 2.30, winning four folds of five. - The model wins five of five, by 0.35 degrees on average, which is 14.2%.
- The rolling windows do most of the work. With
lag_1alone, the model only gets to 2.35. - Keep it honest. The model was closer on 57% of the 1,825 test days, so "same as today" still wins the rest. Its worst single miss is still 14.2 degrees, against 18.8.
- It holds on other fold setups. From three folds to ten, the model won every fold there too.
So it's a real gain, and a small one: about a third of a degree, in every fold.
Common mistakes
- Shifting a series with missing dates. Use
asfreq("D")first, orshift(1)can reach back a month. - Filling the gaps. A filled lag is invented weather. Drop the incomplete rows.
rollingwithoutshift(1). The window then includes the day you are predicting.- No baseline. Without "same as today", 2.12 means nothing.
- Judging on one test period. One year made the calendar look good. Five folds said otherwise.
Quick recap
| Step | Code | Sydney result |
|---|---|---|
| One row per day | y.asfreq("D") | 3,337 rows become 3,433 days |
| Features from the past | shift(1), shift(1).rolling(7).mean() | 3,009 usable rows |
| Baseline | same as today | MAE 2.43 over 5 folds |
| Model | LinearRegression | MAE 2.08, wins 5 of 5 |
| Leaky window | rolling without shift | 2.12 falls to a fake 1.91 |
Try it yourself
In backtest.py, set n_splits=9 and test_size=180, and run it again. Does the model still beat "same as today" in every fold?
The project and the dataset are in the StudyEasy AI Community, free to join.
Built this? Share your solution in the StudyEasy AI Community.
Join free on Skool →Time Splits and Group Splits: Make the Split Match How the Model Is Used
Next →Feature Engineering Patterns, Each One Tested: Date Parts, Differences, Windows and Target Encoding
StudyEasy AI Community
Learn AI engineering, share what you build, and connect with other learners.
Free resources: lesson files, notebooks and code
Ask questions and join engineering discussions
Meet real people learning and building with AI
Machine Learning Engineer: From First Model to ML Engineer
Learn machine learning in Python, then ship it: data analysis, regression, classification, tuning, deployment and MLOps.View on Udemy ↗: Machine Learning Engineer: From First Model to ML Engineer (opens in a new tab)Related articles
Python Virtual Environments: One Project, One Toolbox
Why every Python project gets its own virtual environment: two projects that need different versions of requests, python -m venv .venv, activation, pip install and the PyCharm setting that activates it for you.
Git and GitHub Fundamentals: Commits, Branches, Push and Pull
The Git you use every day, on a tiny hello-ml project: commits as save points, the staging area, a branch merged with a fast-forward, then push, clone, pull and pull requests with a teammate.
Testing a FastAPI App with pytest: Three Small Tests
A tiny FastAPI app with a Hello World route and a name route that refuses numbers, three pytest tests that check it, and what happens when the validation is deleted by mistake.
Config and Logging Instead of Hard-Coded Values in ML Training
Take the hard-coded values out of a car price training script: one config.toml read with tomllib, logging with levels and a run id on every line, and secrets read from the environment. Same RMSE, 2195, before and after.