40. Time series
A time series is data where the order of the rows is part of the information. Daily website visits, daily sales and sensor readings every 10 minutes are all time series. This module teaches the tools to clean them, to understand their structure and to forecast them. You compare a classical statistical model (SARIMA) with a machine learning model (gradient boosting on lag features) on the same holdout, and you score both honestly with time-series cross-validation.
What you will learn
Section titled “What you will learn”- Build a
DatetimeIndex, select by date strings, set a frequency withasfreqand fill missing days. - Resample data to a coarser frequency and choose
sumormeanfor each column. - Smooth a series with rolling statistics and split it into trend, seasonality and remainder with STL.
- Test stationarity with the ADF test, interpret its null hypothesis correctly, and difference a series.
- Read ACF and PACF plots and choose small ARIMA and SARIMA orders.
- Forecast with naive baselines, SARIMA and gradient boosting on leakage-free lag features, then score the forecasts with
TimeSeriesSplitand MAE, RMSE, MAPE, sMAPE and MASE.
Prerequisites
Section titled “Prerequisites”- 25. pandas advanced:
groupby,rolling,shiftand the.dtaccessor. - 26. Data cleaning: missing values,
interpolate()andffill(). - 29. Statistics and probability: hypothesis tests and p-values.
- 35. Regression: MAE, RMSE, MAPE and gradient boosting regressors.
- 37. Model evaluation and tuning: cross-validation.
- The course datasets: Get the data and the data dictionary.
Concepts
Section titled “Concepts”All code on this page runs top to bottom in one script. The first block loads the libraries and fixes the display width.
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
pd.set_option("display.width", 100)pd.set_option("display.max_columns", 12)pd.set_option("display.precision", 3)What makes time series data different
Section titled “What makes time series data different”A time series is a sequence of measurements in time order, usually taken at a fixed interval. data/web_traffic.csv holds one row per day: the number of website visits from 2022-01-01 to 2024-12-31.
Most of the data in earlier modules was a set of independent rows. You could shuffle the customers of a churn table and lose nothing. A time series is different in three ways:
- Neighbors are related. Today’s visits are close to yesterday’s visits. This dependence of a series on its own past is called autocorrelation. It is the signal that forecasting uses.
- Order matters. If you shuffle the rows, the patterns disappear. If you split the rows at random into a training set and a test set, the model sees days after the test days. That is data leakage: the model uses information that it would not have in real use.
- The future is the target. You usually want to forecast: to predict values that do not exist yet.
A series is often described as a sum of parts:
| Part | Meaning | Example in web_traffic.csv |
|---|---|---|
| Trend | the slow long-term direction | mean visits grow from about 3,500 a day in 2022 to about 5,500 in 2024 |
| Seasonality | a pattern that repeats with a fixed period | weekdays are busy, weekends are quiet: a 7-day period |
| Events | one-off shocks with a known cause | 7 marketing campaigns; the top day has 18,385 visits |
| Remainder | what is left: day-to-day noise | random ups and downs |
The seasonal period is the number of steps in one cycle: 7 for daily data with a weekly pattern, 24 for hourly data with a daily pattern, 12 for monthly data with a yearly pattern.
Three words describe every forecast:
- The forecast origin is the last time point you know. Here, the last day in the data.
- The forecast horizon is how far ahead you predict, for example 28 days.
- The holdout is the last part of the series that you hide from the model and use only to test it. It plays the role of the test set. Every choice of model, order or feature is made on earlier data (a validation window or a backtest); the holdout is scored once, at the end.
flowchart LR
H["History<br/>known values"] --> O["Forecast origin<br/>last known day"]
O --> F["Horizon<br/>28 days to predict"]
The datetime index
Section titled “The datetime index”pandas stores dates in the datetime64 dtype (module 24). When you make a date column the index of a DataFrame, pandas builds a DatetimeIndex. It unlocks the time-series tools of pandas:
- Partial string indexing:
df.loc["2024-12"]selects every row of December 2024, anddf.loc["2024-12-25":"2024-12-31"]selects a date range. Both ends are included. - Resampling with
resample(), shifting withshift()and rolling windows by time. - Plots with a real date axis.
Read the file with parse_dates and index_col:
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")print(type(traffic.index).__name__, traffic.index.dtype)print(traffic.loc["2024-12-29":, ["visits", "signups"]])DatetimeIndex datetime64[us] visits signupsdate2024-12-29 6200.0 942024-12-30 7283.0 1212024-12-31 7218.0 134A DatetimeIndex can carry a frequency: the fixed step between rows, such as one day. traffic.index.freq is None after read_csv, because pandas does not guess it. asfreq("D") sets a daily frequency. It also adds a row with NaN for every missing date, so gaps become visible. Example 1 uses it.
Frequencies and offset aliases
Section titled “Frequencies and offset aliases”An offset alias is the short text that names a frequency. pandas 3 removed several old aliases: "M", "H", "T", "Y" and "Q" now raise a ValueError. Use the new names.
| Alias | Meaning | Typical data |
|---|---|---|
"10min", "min" |
every 10 minutes, every minute | sensors, logs |
"h" |
hourly | energy use, server load |
"D" |
calendar day | visits, sales |
"B" |
business day (Monday to Friday) | stock prices |
"W" (same as "W-SUN") |
weeks that end on Sunday | weekly reports |
"W-MON" |
weeks that end on Monday | weeks that run Tuesday to Monday |
"MS", "ME" |
month start, month end | monthly revenue |
"QS", "QE" |
quarter start, quarter end | quarterly reports |
"YS", "YE" |
year start, year end | annual totals |
traffic["visits"].resample("M").sum()ValueError: Invalid frequency: M. Failed to parse with error message: ValueError("'M' is no longer supported for offsets. Please use 'ME' instead.")The error message names the fix: "ME". Older tutorials use "M"; they were written for pandas 1 or 2.
Resampling: change the frequency
Section titled “Resampling: change the frequency”Resampling changes the frequency of a series. Downsampling goes from a fine frequency to a coarse one: from 10-minute readings to hourly means, or from daily sales to monthly totals. Each new bin collects several old rows, so you must say how to combine them. Upsampling goes the other way, from coarse to fine. It creates empty rows that you must fill.
The right aggregation depends on what the column measures:
| The column is… | Examples | Downsample with |
|---|---|---|
| a flow: an amount per period | revenue, units, visits, signups | sum |
| a level: a state at a moment | temperature, humidity, price, bounce rate | mean (or min, max) |
| a stock: a running balance | inventory, account balance | last |
| a count of rows | number of readings per bin | count or size |
A sum over a bin with fewer days than the others is misleading. The first week of 2023 has only one day (2023-01-01 is a Sunday), so its weekly sum is small for a reason that has nothing to do with sales. Count the rows per bin and drop or flag partial bins.
The bins have edges and labels. "W" bins end on Sunday and carry the Sunday’s date as their label. "MS" bins carry the first day of the month, "ME" bins the last day. The values are the same; only the labels differ.
Missing dates and missing values
Section titled “Missing dates and missing values”A time series can have two kinds of holes:
- A missing date: the row does not exist.
asfreq("D")turns it into a row ofNaN. - A missing value: the row exists but a cell is
NaN.web_traffic.csvhas 5 blankvisitscells from tracking outages.
Most time-series tools need a regular index with no NaN. Choose the fill by the meaning of the gap:
| Situation | Fill | Why |
|---|---|---|
| a smooth series with a short outage | interpolate("time") |
draws a straight line between the neighbors, weighted by time |
| a state that holds until it changes (a price, a status) | ffill() |
the last known value is still valid |
| a count where a missing row means “nothing happened” | fillna(0) |
no orders that day is 0 orders |
| a long outage | interpolate(limit=3) and flag the rest |
a long straight line invents data |
Interpolation (module 26) uses the value after the gap. That is fine when you clean history. It is leakage at the end of the series: at the forecast origin there is no “after”, and a value filled from the future does not exist in real use.
Rolling statistics
Section titled “Rolling statistics”A rolling statistic is a statistic computed on a moving window of the last k rows (a trailing window, module 25). y.rolling(7).mean() gives, for each day, the mean of that day and the 6 days before it.
- A window as long as the seasonal period (7 days for a weekly pattern) averages out the seasonality. What remains shows the trend.
y.rolling(7).std()shows how much the series moves. It jumps during a marketing campaign.center=Trueputs the window around the day instead of behind it. It uses future days. Use it for plots and analysis, never for model features.
Decomposition: trend, seasonality and remainder
Section titled “Decomposition: trend, seasonality and remainder”Decomposition splits a series into a trend, a seasonal part and a remainder. There are two forms:
Use the additive form when the seasonal swing has a constant size, for example “Saturdays have about 700 fewer visits”. Use the multiplicative form when the swing grows with the level, for example “Saturdays have about 15% fewer visits”. The log of a multiplicative series is additive, because .
statsmodels has two tools:
| Tool | How it works | Strengths | Weaknesses |
|---|---|---|---|
seasonal_decompose |
a centered moving average for the trend, then the mean of each season position | simple, classical | NaN at both ends; one fixed seasonal pattern; outliers distort it |
STL |
STL (Seasonal-Trend decomposition using LOESS) fits local smooth curves; LOESS is local weighted regression: a small regression around each point, with more weight on close neighbors | no NaN at the ends; the pattern can change slowly; robust=True resists outliers |
additive only (log the series for multiplicative) |
STL gives a simple number for how strong the seasonality is, the strength of seasonality. Compare the variance of the remainder with the variance of the seasonal part plus the remainder:
near 0 means no seasonality. near 1 means a strong seasonal pattern. The strength of trend uses in the same way.
Stationarity
Section titled “Stationarity”A series is stationary when its statistical properties do not change over time: the mean, the variance and the autocorrelation stay the same in every part of the series. White noise (independent random values with mean 0) is stationary. A series with a trend is not: its mean in 2024 is higher than in 2022.
Stationarity matters for two reasons. ARMA models (below) assume it. And a model that learns the relationships of one period applies them to another, which only works when the relationships stay the same.
A series can fail to be stationary in several ways:
- a deterministic trend: the mean follows a fixed line or curve. Remove it by fitting the trend, or test with a trend term.
- a unit root: the series is a random walk, . Each shock moves the level for good, and the series wanders with no mean to return to. Remove it by differencing.
- seasonality, or a variance that grows with the level (a log helps).
The ADF test
Section titled “The ADF test”The augmented Dickey–Fuller (ADF) test checks for a unit root. It fits this regression on the differences:
If , yesterday’s level does not pull today’s change back: the series is a random walk. The extra lagged differences “augment” the test so that autocorrelation does not fool it.
Read the hypotheses carefully. They are the opposite of what many people expect:
| ADF | |
|---|---|
| H0 (null hypothesis) | the series has a unit root: it is not stationary |
| H1 (alternative) | the series is stationary (with regression="ct": stationary around a linear trend) |
| small p-value (below 0.05) | reject H0: evidence that the series is stationary |
| large p-value | you cannot reject H0: no evidence of stationarity. This does not prove a unit root. |
The regression argument says what the stationary alternative looks like: "c" around a constant mean (the default), "ct" around a constant plus a linear trend, "n" around zero. In statsmodels 0.15, pass result_object=True to get a result object with named fields (.statistic, .pvalue, .lags). Without it, adfuller warns that its return type will change.
Differencing
Section titled “Differencing”Differencing replaces each value by its change from an earlier value:
- the first difference removes a random-walk level or a linear trend. In pandas:
y.diff(). - the seasonal difference removes a fixed weekly pattern. In pandas:
y.diff(7). - the first difference of the log, , is close to the daily growth rate. For small changes, 0.05 means about +5%.
Each difference costs one row (or 7) at the start. To get back to the original scale, add the changes to a known starting value with cumsum(). Do not difference more than you need: over-differencing adds noise and shows up as a moving-average coefficient close to −1 in an ARIMA model.
Autocorrelation: ACF and PACF
Section titled “Autocorrelation: ACF and PACF”A lag is the same series moved back in time. Lag 1 of today is yesterday; lag 7 is the same weekday last week. In pandas, y.shift(1) is lag 1.
The autocorrelation function (ACF) gives the correlation between the series and its own lags: lag 1, lag 2, and so on. The partial autocorrelation function (PACF) gives the correlation at lag k after removing the part that the shorter lags 1 to k − 1 already explain. Both plots draw a shaded confidence band, and a bar outside the band is a significant correlation. The PACF band is about , flat at every lag. The ACF band of statsmodels uses Bartlett’s formula: it widens with the lag, because it allows for the correlation at the earlier lags.
How to read them:
| Pattern | Meaning |
|---|---|
| ACF decays very slowly from near 1 | a trend or a unit root: difference first |
| ACF spikes at lags 7, 14, 21 | weekly seasonality |
PACF cuts off after lag p, ACF decays |
an AR(p) process |
ACF cuts off after lag q, PACF decays |
an MA(q) process |
| no bar outside the band | white noise: nothing left to model |
Baselines: the forecasts to beat
Section titled “Baselines: the forecasts to beat”A baseline is a simple forecast that any model must beat. Two baselines are standard for time series:
- The naive forecast repeats the last known value: for every horizon .
- The seasonal naive forecast repeats the last full season: for the first season, where is the seasonal period. For daily data with , next Monday’s forecast is last Monday’s value.
Baselines are cheap and hard to beat on short horizons. If a complex model does not beat the seasonal naive forecast, it is not ready.
ARIMA and SARIMA
Section titled “ARIMA and SARIMA”ARIMA combines three ideas. Its order is written :
- AR(p), autoregressive: today is a weighted sum of the last values. AR(1) is .
- I(d), integrated: the model works on the series differenced times.
- MA(q), moving average: today depends on the last forecast errors. MA(1) is . Do not confuse it with a rolling mean.
SARIMA adds the same three parts at the seasonal lag, with order . With , a seasonal MA(1) term links today to the error of the same weekday last week, and means a seasonal difference . SARIMAX adds exogenous variables: outside inputs such as a marketing budget or a holiday flag.
In statsmodels, SARIMAX fits all of these:
from statsmodels.tsa.statespace.sarimax import SARIMAX
model = SARIMAX(y_train, order=(1, 1, 1), seasonal_order=(0, 1, 1, 7))result = model.fit(disp=False) # disp=False: no optimizer printoutforecast = result.get_forecast(steps=28)How to choose the orders:
- Choose and from the ADF test and the plots: difference until the series looks stationary, no more.
- Read , , and from the ACF and PACF of the differenced series. Keep them small (0, 1 or 2).
- Compare a few candidates by AIC (Akaike information criterion): a score that rewards a good fit and penalizes extra parameters. Lower is better. Compare AIC only between models fitted on the same data with the same differencing.
- Confirm on the holdout and in cross-validation.
Machine learning forecasting with lag features
Section titled “Machine learning forecasting with lag features”A regression model such as gradient boosting does not know about time. You turn the series into a normal table: one row per day, with lag features (past values such as y.shift(28)), rolling features (statistics of a past window such as y.shift(28).rolling(28).mean()) and calendar features (day of week, month). The target is the value of the day. Then any regressor can learn the mapping.
The shift is what keeps the table honest. y.rolling(7).mean() on day t includes day t itself, which is the target. y.shift(1).rolling(7).mean() uses days t − 7 to t − 1 only.
There are two ways to forecast several days ahead:
| Strategy | How | Pros | Cons |
|---|---|---|---|
| Direct | every lag is at least the horizon H (shift(28) and more for H = 28) |
one model, no loop, no error feedback | ignores the most recent H − 1 days |
| Recursive | a one-step model with shift(1); feed each prediction back as the next lag |
uses the latest values | errors pile up; a loop over the horizon |
Tree models have one more limit: they cannot extrapolate. Each tree splits the feature space into regions with a constant value, so a tree ensemble’s prediction is piecewise constant. Gradient boosting adds up many such trees (each fit to the errors of the ones before), but the sum is still flat beyond the range of the training features: a forecast for a level the model has not seen stays near the levels it has seen. A series with a strong trend needs help: model the log, a difference or a ratio to a recent level, or let a linear model handle the trend.
Time-series cross-validation
Section titled “Time-series cross-validation”Plain k-fold cross-validation uses later blocks of rows to train for earlier test blocks (and shuffles the rows, if you ask it to), so the model trains on days after the test days. For time series, use time-series cross-validation: every fold trains on the past and tests on the period right after it. scikit-learn’s TimeSeriesSplit does this with an expanding window: each fold adds the previous test period to the training data.
flowchart LR
subgraph F1["Fold 1"]
A1["train: days 1–100"] --> B1["test: 101–128"]
end
subgraph F2["Fold 2"]
A2["train: days 1–128"] --> B2["test: 129–156"]
end
subgraph F3["Fold 3"]
A3["train: days 1–156"] --> B3["test: 157–184"]
end
Useful arguments: n_splits (number of folds), test_size (set it to the forecast horizon), gap (rows to skip between train and test, when the latest data arrives late) and max_train_size (a sliding window of fixed length instead of an expanding one). Testing a model on several past origins like this is called backtesting.
Forecast metrics
Section titled “Forecast metrics”With forecast days, actual values and forecasts :
| Metric | Unit | Read it as | Watch out |
|---|---|---|---|
| MAE | the series unit | the typical error in visits | cannot compare series of different scale |
| RMSE | the series unit | like MAE, but large errors count more | one spike day dominates it |
| MAPE (mean absolute percentage error) | % | the typical error as a share of the actual value | undefined when ; punishes over-forecasts more |
| sMAPE (symmetric MAPE) | % (0 to 200) | MAPE with the mean of actual and forecast below the line | still unstable near 0 |
| MASE (mean absolute scaled error) | none | below 1: smaller errors than a one-season-ahead seasonal naive forecast inside the training data | needs the training series; multi-step forecasts often score above 1 |
The denominator of MASE is the MAE of the seasonal naive forecast inside the training data, with period . MASE works for any scale and for series with zeros, so it is the best single number to compare forecasts across series.
Worked examples
Section titled “Worked examples”Example 1 — Build a clean daily series
Section titled “Example 1 — Build a clean daily series”Goal: Turn data/web_traffic.csv into a daily visits series with a frequency and no gaps, ready for modeling. An analytics team does this before every dashboard or forecast.
Step 1 — Check the index
Section titled “Step 1 — Check the index”print(traffic.index.is_monotonic_increasing, traffic.index.is_unique)print(traffic.index.min().date(), "to", traffic.index.max().date())print(len(traffic), "rows")print("frequency:", traffic.index.freq)True True2022-01-01 to 2024-12-311096 rowsfrequency: NoneThe index is sorted and has no duplicate days. Always check both: resample and asfreq need a sorted index, and a duplicated date usually means a bad merge. The frequency is None because read_csv does not set one.
Step 2 — Look for missing dates
Section titled “Step 2 — Look for missing dates”all_days = pd.date_range(traffic.index.min(), traffic.index.max(), freq="D")missing_days = all_days.difference(traffic.index)print(len(all_days), "calendar days,", len(missing_days), "missing")traffic = traffic.asfreq("D")print("frequency:", traffic.index.freq)1096 calendar days, 0 missingfrequency: <Day>pd.date_range builds every calendar day between the first and the last date. difference() lists the days that the file lacks: none. asfreq("D") sets the daily frequency. If a date had been missing, asfreq would have added it as a row of NaN.
Step 3 — Find the missing values
Section titled “Step 3 — Find the missing values”visits = traffic["visits"]print(visits.dtype, visits.isna().sum(), "blank values")print(visits[visits.isna()].index.strftime("%Y-%m-%d").tolist())float64 5 blank values['2022-08-11', '2022-08-24', '2023-05-24', '2024-05-29', '2024-10-25']visits is float64 even though visits are whole numbers: an integer column with blanks loads as float. The 5 blanks are the tracking outages listed in the data dictionary. The other columns are complete on those days.
Step 4 — Compare two fills on one gap
Section titled “Step 4 — Compare two fills on one gap”fills = pd.DataFrame( { "raw": visits, "ffill": visits.ffill(), "interpolate": visits.interpolate("time"), })print(fills.loc["2022-08-09":"2022-08-13"]) raw ffill interpolatedate2022-08-09 4313.0 4313.0 4313.02022-08-10 4330.0 4330.0 4330.02022-08-11 NaN 4330.0 3956.02022-08-12 3582.0 3582.0 3582.02022-08-13 3043.0 3043.0 3043.0ffill() copies Wednesday’s 4,330 into Thursday. interpolate("time") draws a straight line from 4,330 to 3,582 and gives 3,956. Visits change smoothly from day to day, so interpolation suits them. The gaps are in the middle of the history, so the fill uses no data from after the forecast origin.
Step 5 — Select by date strings
Section titled “Step 5 — Select by date strings”y = visits.interpolate("time")for year in ["2022", "2023", "2024"]: print(year, f"{y.loc[year].mean():,.0f} visits a day")print(y.loc["2024-12-24":"2024-12-26"])2022 3,514 visits a day2023 4,058 visits a day2024 5,496 visits a daydate2024-12-24 6489.02024-12-25 5790.02024-12-26 6123.0Freq: D, Name: visits, dtype: float64y.loc["2023"] selects the whole year by a partial date string, and a date range includes both ends. The means confirm the trend: about 56% more visits a day in 2024 than in 2022. From now on, y is the clean daily series.
Common mistakes:
- Forgetting
parse_dates. The dates stay text, the index is not a DatetimeIndex, andy.loc["2023"]raises aKeyError. - Assuming the file has every day. Always compare with
pd.date_rangeor callasfreq; gaps in the dates are invisible in a plain table. - Filling with
bfill()(backward fill). It copies the next value back in time; at the end of a series, that is a value from the future.
Example 2 — Resample sensors and sales
Section titled “Example 2 — Resample sensors and sales”Goal: Downsample 10-minute sensor readings to hourly and daily values, and daily sales to weekly and monthly totals. Choose mean or sum for each, and spot partial bins.
Step 1 — Put each sensor in its own column
Section titled “Step 1 — Put each sensor in its own column”sensors = pd.read_csv("data/sensors.csv", parse_dates=["timestamp"])temp = sensors.pivot(index="timestamp", columns="sensor_id", values="temperature_c")print(temp.shape)print(temp.index.to_series().diff().value_counts())print(temp.head(3))(2016, 4)timestamp0 days 00:10:00 2015Name: count, dtype: int64sensor_id S1 S2 S3 S4timestamp2024-05-01 00:00:00 20.21 22.30 19.40 24.522024-05-01 00:10:00 20.22 22.44 19.46 24.632024-05-01 00:20:00 20.16 22.25 19.54 24.73The file is in long format: 4 rows per timestamp, one per sensor. pivot makes a wide table with one column per sensor and a DatetimeIndex. The value_counts of the steps between timestamps shows a single step, 10 minutes, so no timestamp is missing. The first row is NaT (not a time), because the first timestamp has no previous one.
Step 2 — Downsample to hourly means
Section titled “Step 2 — Downsample to hourly means”hourly = temp.resample("h").mean()print(hourly.shape)print(hourly.head(3).round(2))print("blank cells:", temp.isna().sum().sum(), "->", hourly.isna().sum().sum())(336, 4)sensor_id S1 S2 S3 S4timestamp2024-05-01 00:00:00 20.09 24.89 19.36 24.532024-05-01 01:00:00 19.84 21.67 19.11 24.202024-05-01 02:00:00 19.26 21.46 19.26 23.92blank cells: 22 -> 0Each hourly bin averages 6 readings. Temperature is a level, so mean is the right aggregation; a sum of temperatures has no meaning. The 22 blank readings disappear because mean skips NaN and every hour still has other readings.
Step 3 — Summarize each day of one sensor
Section titled “Step 3 — Summarize each day of one sensor”s3_daily = temp["S3"].resample("D").agg(["min", "mean", "max"])print(s3_daily.head(3).round(2))print(s3_daily.tail(2).round(2)) min mean maxtimestamp2024-05-01 18.56 21.29 33.512024-05-02 18.67 21.60 32.982024-05-03 19.14 21.84 24.15 min mean maxtimestamp2024-05-13 22.97 25.34 27.802024-05-14 23.04 25.85 39.29agg computes several statistics per bin. The daily mean of S3 rises by more than 4 °C over two weeks: that is the calibration drift that the data dictionary describes. A daily resample hides the daily cycle and shows the drift.
Step 4 — Aggregate sales lines to days
Section titled “Step 4 — Aggregate sales lines to days”sales = pd.read_csv("data/sales.csv", parse_dates=["order_date"])daily = ( sales.groupby("order_date") .agg(revenue=("revenue", "sum"), units=("quantity", "sum")) .asfreq("D"))print(daily.shape, "missing days:", daily["revenue"].isna().sum())print(daily.head(3))(731, 2) missing days: 0 revenue unitsorder_date2023-01-01 4767.04 312023-01-02 1593.88 192023-01-03 1811.84 26sales.csv has one row per order line, not per day. groupby with named aggregation (module 25) sums the lines of each day. asfreq("D") checks that no day is missing: every day of 2023 and 2024 has orders.
Step 5 — Resample to weeks and find partial bins
Section titled “Step 5 — Resample to weeks and find partial bins”weekly = daily["revenue"].resample("W").agg(["sum", "mean", "count"])print(weekly.head(3).round(0))print(weekly.tail(2).round(0)) sum mean countorder_date2023-01-01 4767.0 4767.0 12023-01-08 21439.0 3063.0 72023-01-15 28965.0 4138.0 7 sum mean countorder_date2024-12-29 50581.0 7226.0 72025-01-05 22695.0 11348.0 2The first bin, labeled 2023-01-01, holds one day: 2023-01-01 is a Sunday, and "W" weeks end on Sunday. The last bin holds 2 days. Their sums are small for no business reason. The mean column is still fair. Keep full weeks with weekly[weekly["count"] == 7].
Step 6 — Resample to months
Section titled “Step 6 — Resample to months”monthly = daily["revenue"].resample("MS").sum()print(monthly.head(3).round(0))print("best month:", monthly.idxmax().date(), f"{monthly.max():,.0f}")order_date2023-01-01 107330.02023-02-01 77405.02023-03-01 106543.0Freq: MS, Name: revenue, dtype: float64best month: 2024-12-01 302,912Revenue is a flow, so months use sum. "MS" labels each month by its first day; "ME" would give the same numbers labeled 2023-01-31, 2023-02-28 and so on. December 2024 is the best month, as expected from the yearly peak.
Common mistakes:
- Summing a level: a “total temperature” or a “total bounce rate” means nothing. Use
mean. - Averaging a flow when the business asks for totals. Monthly revenue is a sum, not the mean daily revenue.
- Comparing a partial first or last bin with full bins. Count the rows per bin.
- Resampling a long table with several sensors mixed in one column. Pivot first, or select a numeric column:
sensors.groupby("sensor_id").resample("h", on="timestamp")["temperature_c"].mean().
Example 3 — Smooth and decompose web traffic
Section titled “Example 3 — Smooth and decompose web traffic”Goal: Show the trend under the weekly noise with rolling means, then split the visits into trend, weekly seasonality and remainder with STL. A product team uses this to tell real growth from weekday effects.
Step 1 — Compute trailing rolling statistics
Section titled “Step 1 — Compute trailing rolling statistics”rolling = pd.DataFrame( { "visits": y, "mean_7": y.rolling(7).mean(), "std_7": y.rolling(7).std(), })print(rolling.loc["2024-04-05":"2024-04-11"].round(0)) visits mean_7 std_7date2024-04-05 4556.0 4926.0 482.02024-04-06 4065.0 4874.0 557.02024-04-07 4605.0 4871.0 559.02024-04-08 18385.0 6763.0 5154.02024-04-09 15901.0 8222.0 6148.02024-04-10 10673.0 8977.0 6066.02024-04-11 9342.0 9647.0 5761.0The campaign of 2024-04-08 quadruples the visits for a day, and they decay over the next days. The 7-day mean rises more slowly, because it averages the spike with 6 normal days. The 7-day standard deviation jumps from about 500 to over 5,000: a rolling standard deviation is a simple event detector.
Step 2 — Plot the series with two rolling means
Section titled “Step 2 — Plot the series with two rolling means”fig, ax = plt.subplots(figsize=(10, 4))ax.plot(y.index, y, color="0.75", linewidth=0.6, label="daily visits")ax.plot(y.index, y.rolling(7).mean(), label="7-day mean")ax.plot(y.index, y.rolling(28).mean(), label="28-day mean", linewidth=2)ax.set(title="Daily website visits, 2022–2024", ylabel="visits")ax.legend()plt.show()
The raw line is a band of weekly ups and downs with seven campaign spikes. The 7-day mean removes the weekly pattern because each window holds exactly one of each weekday. The 28-day mean shows the growth and the yearly November–December peak.
Step 3 — Decompose with STL
Section titled “Step 3 — Decompose with STL”from statsmodels.tsa.seasonal import STL
stl = STL(y, period=7, robust=True).fit()parts = pd.DataFrame({"trend": stl.trend, "seasonal": stl.seasonal, "resid": stl.resid})print(parts.loc["2024-12-01":"2024-12-04"].round(1))print("parts add up:", np.allclose(parts.sum(axis=1), y)) trend seasonal residdate2024-12-01 7574.8 -871.8 145.02024-12-02 7588.9 454.5 -541.52024-12-03 7585.8 885.9 52.32024-12-04 7568.0 639.4 50.6parts add up: Trueperiod=7 tells STL that the pattern repeats every 7 days. robust=True gives less weight to the campaign spikes, so most of each spike goes to the remainder; the trend still bends a little at the larger campaigns. The three parts add up exactly to the series: STL is additive.
Step 4 — Plot the decomposition
Section titled “Step 4 — Plot the decomposition”fig = stl.plot()fig.set_size_inches(10, 7)plt.show()
stl.plot() draws four panels: the data, the trend, the seasonal part and the remainder. The seasonal band widens over the three years: the weekday effect grows with the level. That is a sign of multiplicative seasonality, which a log transform turns into additive.
Step 5 — Measure the weekday effect and the strength of each part
Section titled “Step 5 — Measure the weekday effect and the strength of each part”day_names = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]weekday_effect = stl.seasonal.groupby(y.index.day_of_week).mean()weekday_effect.index = day_namesprint(weekday_effect.round(0))strength_seasonal = max(0, 1 - stl.resid.var() / (stl.seasonal + stl.resid).var())strength_trend = max(0, 1 - stl.resid.var() / (stl.trend + stl.resid).var())print(f"seasonal strength {strength_seasonal:.2f}, trend strength {strength_trend:.2f}")Mon 260.0Tue 376.0Wed 282.0Thu 108.0Fri -185.0Sat -559.0Sun -286.0Name: season, dtype: float64seasonal strength 0.18, trend strength 0.57Tuesday is about 380 visits above the trend and Saturday about 560 below it: the weekday peak and weekend dip of the data dictionary. The seasonal strength is only 0.18. The weekly pattern is real, but it is small next to the remainder, which holds the day-to-day noise and the campaign spikes. The trend strength of 0.57 is higher: most of the slow movement of the series is growth.
Common mistakes:
- Using
center=Truerolling means as model features. They average future days. - Choosing the wrong
period. For daily data with a weekly cycle it is 7, not 365 and not 52. - Calling
seasonal_decomposeorSTLon a series withNaN. Fill the gaps first; both need a complete regular series.
Example 4 — Test stationarity and read the ACF and PACF
Section titled “Example 4 — Test stationarity and read the ACF and PACF”Goal: Decide whether the visits need differencing before an ARIMA model, and read the lags that matter. This step proposes the d, D, p and q of Example 5. It uses only the data that the models of Example 5 are fitted on.
Step 1 — Lock the holdout and run a first ADF test
Section titled “Step 1 — Lock the holdout and run a first ADF test”from statsmodels.tsa.stattools import adfuller
horizon = 28train, test = y.iloc[:-horizon], y.iloc[-horizon:] # test = the locked holdouty_fit, y_valid = train.iloc[:-horizon], train.iloc[-horizon:]
def adf_report(series: pd.Series, name: str, regression: str = "c") -> None: """Run the ADF test and print one line with the decision at the 5% level.""" res = adfuller(series.dropna(), regression=regression, result_object=True) verdict = "stationary" if res.pvalue < 0.05 else "no evidence of stationarity" print(f"{name:<22} stat={res.statistic:7.2f} p={res.pvalue:.2g} lags={res.lags:2d}" f" -> {verdict}")
adf_report(y_fit, "level, constant")level, constant stat= -2.99 p=0.036 lags=21 -> stationaryBefore any test, the last 28 days (test) are locked away, and the 28 days before them (y_valid) are kept to check forecasts. Every identification step uses y_fit only. On this data the p-value is borderline: just below 0.05. The data dictionary reports p = 0.114 for the full three years. ADF p-values move with the sample, so a value near 0.05 is weak evidence either way. lags is the number of lagged differences that the test chose by AIC.
Step 2 — Test with a trend and test the differences
Section titled “Step 2 — Test with a trend and test the differences”adf_report(y_fit, "level, constant+trend", regression="ct")adf_report(y_fit.diff(), "first difference")adf_report(np.log(y_fit).diff(), "log first difference")level, constant+trend stat= -5.85 p=4.4e-06 lags=22 -> stationaryfirst difference stat= -10.76 p=2.6e-19 lags=20 -> stationarylog first difference stat= -9.55 p=2.7e-16 lags=22 -> stationaryRead the three lines carefully, because they do not say the same thing:
- With a linear trend in the test, the unit root is rejected very clearly. That is evidence that the visits are trend-stationary: stationary around a deterministic trend. The natural model then has
d = 0and a trend term. - The first difference is stationary, but that does not decide anything. Differencing makes both a random walk and a series with a linear trend stationary.
- So the data point to a deterministic trend, and
d = 1would remove more than needed. It may still forecast well: one difference adapts to a level that drifts, and it needs no trend line that could overshoot.
Example 5 fits both routes, and Example 7 lets a backtest choose. AIC cannot make this choice, because models with a different d are fitted on different series.
Step 3 — Plot the ACF and PACF of the level
Section titled “Step 3 — Plot the ACF and PACF of the level”from statsmodels.graphics.tsaplots import plot_acf, plot_pacffrom statsmodels.tsa.stattools import acf
fig, axes = plt.subplots(2, 1, figsize=(10, 6))plot_acf(y_fit, lags=28, ax=axes[0], title="ACF of daily visits (fit data)")plot_pacf(y_fit, lags=28, ax=axes[1], title="PACF of daily visits (fit data)")fig.tight_layout()plt.show()print("ACF at lags 1, 7, 14:", acf(y_fit, nlags=14)[[1, 7, 14]].round(3))
ACF at lags 1, 7, 14: [0.771 0.44 0.41 ]The ACF stays high at every lag, and it rises again at lags 7, 14, 21 and 28. High everywhere means trend; the bumps every 7 lags mean weekly seasonality. The PACF has one big bar at lag 1: most of the memory is “today is close to yesterday”. The ACF band widens with the lag and the PACF band stays flat (see Autocorrelation).
Step 4 — Read the ACF of the differenced series
Section titled “Step 4 — Read the ACF of the differenced series”both_diffs = np.log(y_fit).diff().diff(7).dropna()values = acf(both_diffs, nlags=14)print("ACF after a first and a weekly difference:")print({lag: round(float(values[lag]), 2) for lag in [1, 2, 6, 7, 8, 14]})ACF after a first and a weekly difference:{1: -0.07, 2: -0.09, 6: 0.03, 7: -0.53, 8: 0.04, 14: 0.03}After one regular and one weekly difference of the log, the ACF has one large negative spike at lag 7 (−0.53) and only small values elsewhere. A single negative spike at the seasonal lag is the signature of a seasonal MA(1) term. The small values at lags 1 and 2 leave room for, at most, a small non-seasonal term. A first candidate is SARIMA ; Example 5 compares it with a model that adds an AR term.
Common mistakes:
- Reading a small ADF p-value as “not stationary”. It is the reverse: H0 is the unit root, so a small p-value is evidence for stationarity.
- Treating a large p-value as proof of a unit root. The test only failed to find evidence. Short or noisy series give large p-values often.
- Reading p and q from the ACF of a trending series. The slow decay hides everything else. Difference first.
- Running the tests on the full series, holdout included. The holdout must not influence any choice, not even the differencing order.
- Reading “the first difference is stationary” as proof of a unit root. A trend-stationary series gives the same result.
Example 5 — Fit baselines and SARIMA on a validation window
Section titled “Example 5 — Fit baselines and SARIMA on a validation window”Goal: A capacity planner needs the expected visits for the next 28 days. The last 28 days of 2024 are the locked holdout. Fit the naive, seasonal naive and SARIMA models on the history before a 28-day validation window, choose the SARIMA orders on that history, and check the forecasts on the validation window.
Step 1 — Look at the three parts
Section titled “Step 1 — Look at the three parts”for name, part in [("fit", y_fit), ("valid", y_valid), ("holdout", test)]: start, end = part.index[0].date(), part.index[-1].date() print(f"{name:<8} {start} to {end} {len(part):5d} days")fit 2022-01-01 to 2024-11-05 1040 daysvalid 2024-11-06 to 2024-12-03 28 daysholdout 2024-12-04 to 2024-12-31 28 daysExample 4 made the split by position, never at random. The holdout (test) stays locked until the end of Example 7: no model or feature choice may look at it. The validation window is the 28 days right before it, so it mimics the real forecast as closely as possible.
Step 2 — Compute the two baselines
Section titled “Step 2 — Compute the two baselines”def mae(actual, forecast) -> float: return float(np.mean(np.abs(np.asarray(actual) - np.asarray(forecast))))
def seasonal_naive_forecast(history: pd.Series, steps: int, m: int = 7) -> np.ndarray: """Repeat the last full season of `history` for `steps` steps.""" return np.resize(history.iloc[-m:].to_numpy(), steps)
naive_valid = np.repeat(y_fit.iloc[-1], horizon)snaive_valid = seasonal_naive_forecast(y_fit, horizon)print(f"naive MAE {mae(y_valid, naive_valid):7.1f}")print(f"seasonal naive MAE {mae(y_valid, snaive_valid):7.1f}")naive MAE 607.6seasonal naive MAE 1053.7The naive forecast repeats the visits of 2024-11-05, a busy Tuesday, for 28 days. The seasonal naive forecast repeats the last week; np.resize repeats an array until it has the requested length. It keeps the weekly shape, yet the naive forecast wins here: the visits climb during November, and a high flat line happens to sit close to them. The seasonal naive forecast repeats a quieter week.
Step 3 — Choose the SARIMA orders by AIC
Section titled “Step 3 — Choose the SARIMA orders by AIC”from statsmodels.tsa.statespace.sarimax import SARIMAX
candidates = [((0, 1, 1), (0, 1, 1, 7)), ((1, 1, 1), (0, 1, 1, 7))]for order, seasonal_order in candidates: res = SARIMAX(np.log(y_fit), order=order, seasonal_order=seasonal_order).fit( disp=False, maxiter=200 ) print(order, seasonal_order, "AIC", round(res.aic, 1), "converged", res.mle_retvals["converged"])(0, 1, 1) (0, 1, 1, 7) AIC -1627.1 converged True(1, 1, 1) (0, 1, 1, 7) AIC -1729.7 converged TrueThe first candidate is the one that the ACF of Example 4 suggested. The second adds an AR(1) term. Both work on the log, with one regular and one weekly difference, so their AIC values are comparable. The AR term lowers the AIC by about 100: a much better fit for one extra parameter. Both fits converged, with no warning.
Step 4 — Fit the chosen model and read its parameters
Section titled “Step 4 — Fit the chosen model and read its parameters”sarima_res = SARIMAX(np.log(y_fit), order=(1, 1, 1), seasonal_order=(0, 1, 1, 7)).fit( disp=False, maxiter=200)print(sarima_res.params.round(3))ar.L1 0.742ma.L1 -0.982ma.S.L7 -1.000sigma2 0.010dtype: float64ar.L1 is the day-to-day memory. ma.L1 is close to −1 and ma.S.L7 sits at −1, the edge of its allowed range. These are the over-differencing signatures, and they agree with Example 4: the regular difference removes a trend that the ADF test called deterministic, and the weekly difference removes a weekday pattern that is almost fixed. A seasonal MA of −1 after a weekly difference acts like a fixed weekday pattern. The model is a pragmatic forecasting choice, not the “true” structure. The fit converged with no warning. sigma2 is the variance of the one-step errors on the log scale.
Step 5 — Fit the trend-stationary alternative
Section titled “Step 5 — Fit the trend-stationary alternative”trend_res = SARIMAX( np.log(y_fit), order=(1, 0, 0), seasonal_order=(0, 1, 1, 7), trend="c").fit(disp=False, maxiter=200)print("converged:", trend_res.mle_retvals["converged"])print(trend_res.params.round(4).to_dict())converged: True{'intercept': 0.0009, 'ar.L1': 0.7707, 'ma.S.L7': -0.9982, 'sigma2': 0.0104}This model follows the ADF evidence: no regular difference (d = 0). After a weekly difference, a linear trend becomes a constant, so trend="c" models the trend: intercept is the weekly growth on the log scale, divided by (1 − ar.L1). ar.L1 near 0.77 is ordinary day-to-day memory, far from 1. Its AIC is not comparable with the d = 1 models. Example 7 compares both routes in a backtest.
Step 6 — Forecast the validation window with a prediction interval
Section titled “Step 6 — Forecast the validation window with a prediction interval”fc = sarima_res.get_forecast(steps=horizon)sarima_valid = np.exp(fc.predicted_mean)band = np.exp(fc.conf_int(alpha=0.05))table = pd.DataFrame( {"actual": y_valid, "sarima": sarima_valid, "lower": band.iloc[:, 0], "upper": band.iloc[:, 1]})print(table.head(7).round(0))inside = ((y_valid >= table["lower"]) & (y_valid <= table["upper"])).mean()print(f"SARIMA MAE {mae(y_valid, sarima_valid):.1f}")print(f"actuals inside the 95% band: {inside:.0%}")trend_valid = np.exp(trend_res.forecast(horizon))print(f"trend-stationary SARIMA MAE {mae(y_valid, trend_valid):.1f}") actual sarima lower upper2024-11-06 6424.0 6577.0 5379.0 8042.02024-11-07 6147.0 6220.0 4831.0 8007.02024-11-08 6620.0 5692.0 4309.0 7518.02024-11-09 5936.0 5063.0 3778.0 6784.02024-11-10 6314.0 5444.0 4028.0 7357.02024-11-11 6822.0 6427.0 4731.0 8730.02024-11-12 6814.0 6538.0 4797.0 8911.0SARIMA MAE 1156.0actuals inside the 95% band: 100%trend-stationary SARIMA MAE 1465.9get_forecast returns the forecast and its uncertainty as a prediction interval: a range that should contain the actual value with a given probability, here 95%. np.exp turns the log forecasts back into visits. (The back-transformed value is the median forecast, slightly below the mean; for MAE this does not matter.) On this window SARIMA does not beat either baseline: the visits climb toward the yearly peak, and a model with a weekly period cannot know that. The band covers every day here; one window cannot show whether it is too wide. The trend-stationary model does worse on this window: its fitted trend line does not know about the November climb either.
Step 7 — Plot the validation forecasts
Section titled “Step 7 — Plot the validation forecasts”fig, ax = plt.subplots(figsize=(10, 4))ax.plot(y_fit.loc["2024-09-25":], color="0.4", label="fit data")ax.plot(y_valid, color="black", linewidth=2, label="actual (validation)")ax.plot(y_valid.index, snaive_valid, linestyle="--", label="seasonal naive")ax.plot(sarima_valid, label="SARIMA")ax.fill_between( y_valid.index, table["lower"], table["upper"], alpha=0.2, label="95% band")ax.set(title="28-day forecasts on the validation window", ylabel="visits")ax.legend(loc="upper left")plt.show()
Both forecasts keep the weekly shape but stay at the level of early November, while the actual visits climb. The shaded band widens with the horizon, and the busiest days of the window are near its upper edge. One window of 28 days is one draw; Example 7 tests the models on five windows.
Common mistakes:
- Forgetting to transform back. The forecasts of a model on
np.log(y_fit)are logs; usenp.exp. - Ignoring a
ConvergenceWarning. The parameters are then not the best fit. Fix it before you trust the forecast. - Choosing the orders by trying dozens of models on the holdout. You then fit the holdout itself, and its score is no longer an honest estimate. Choose with AIC, a validation window or cross-validation, and use the holdout once.
Example 6 — Forecast with gradient boosting on lag features
Section titled “Example 6 — Forecast with gradient boosting on lag features”Goal: Build a leakage-free feature table from the visits and train a LightGBM gradient boosting model that forecasts the same validation window. Compare it with the classical models of Example 5.
Step 1 — Build lag, rolling and calendar features
Section titled “Step 1 — Build lag, rolling and calendar features”def make_features(log_series: pd.Series, horizon: int = 28) -> pd.DataFrame: """Direct-strategy features: every value is at least `horizon` days old.""" X = pd.DataFrame(index=log_series.index) for lag in [horizon, horizon + 7, horizon + 14]: X[f"lag_{lag}"] = log_series.shift(lag) X["roll_mean_28"] = log_series.shift(horizon).rolling(28).mean() X["day_of_week"] = log_series.index.day_of_week X["month"] = log_series.index.month return X
log_y = np.log(y) # features use only shifted values, so the full index is safefeatures = make_features(log_y, horizon)print(features.loc["2024-11-06":"2024-11-08"].round(3)) lag_28 lag_35 lag_42 roll_mean_28 day_of_week monthdate2024-11-06 8.807 8.809 8.729 8.759 2 112024-11-07 8.753 8.670 8.753 8.767 3 112024-11-08 8.704 8.590 8.618 8.774 4 11Every lag is at least 28 days old, so the model can forecast all 28 days of the horizon at once: the direct strategy. Lags 28, 35 and 42 fall on the same weekday as the target. The features are built on the log for the same reason as SARIMA, and because trees cannot extrapolate: the log makes the growth smaller.
Step 2 — Prove that no feature sees the future
Section titled “Step 2 — Prove that no feature sees the future”day = y_valid.index[-1]assert features.loc[day, "lag_28"] == log_y.loc[day - pd.Timedelta(days=28)]newest_input = day - pd.Timedelta(days=28)print("last validation day:", day.date())print("newest value it uses:", newest_input.date())print("newest value is not after the origin:", newest_input <= y_fit.index[-1])last validation day: 2024-12-03newest value it uses: 2024-11-05newest value is not after the origin: TrueThe last validation day uses no value newer than 2024-11-05, the forecast origin. The assert checks the shift on real numbers. A leakage check like this is worth one line in every forecasting pipeline.
Step 3 — Train and forecast
Section titled “Step 3 — Train and forecast”from lightgbm import LGBMRegressor
fit_rows = features.loc[y_fit.index].dropna()lgbm = LGBMRegressor( n_estimators=200, learning_rate=0.05, n_jobs=1, random_state=42, verbose=-1)lgbm.fit(fit_rows, log_y.loc[fit_rows.index])lgbm_valid = np.exp(lgbm.predict(features.loc[y_valid.index]))print(len(fit_rows), "training rows")print(f"gradient boosting MAE {mae(y_valid, lgbm_valid):.1f}")985 training rowsgradient boosting MAE 1086.8dropna() removes the first 55 days (a 28-day shift plus 27 more days for the 28-day rolling mean), where the lags and the rolling mean do not exist yet. LightGBM (module 36) needs no scaling. verbose=-1 silences its log lines. n_jobs=1 uses one CPU thread, which keeps the run fast and reproducible on a small table.
Step 4 — Compare the models on the validation window
Section titled “Step 4 — Compare the models on the validation window”valid_mae = pd.Series( { "naive": mae(y_valid, naive_valid), "seasonal naive": mae(y_valid, snaive_valid), "SARIMA": mae(y_valid, sarima_valid), "gradient boosting": mae(y_valid, lgbm_valid), })print(valid_mae.round(1).sort_values())naive 607.6seasonal naive 1053.7gradient boosting 1086.8SARIMA 1156.0dtype: float64On this window the naive forecast wins, and gradient boosting is slightly better than SARIMA. Does that make the naive forecast the best model? No: one window of 28 days with an unusual climb decides this ranking. Do not choose a model on one window.
Step 5 — Plot the two models
Section titled “Step 5 — Plot the two models”fig, ax = plt.subplots(figsize=(10, 4))ax.plot(y_valid, color="black", linewidth=2, label="actual")ax.plot(sarima_valid, label=f"SARIMA (MAE {valid_mae['SARIMA']:.0f})")ax.plot(y_valid.index, lgbm_valid, label=f"gradient boosting (MAE {valid_mae['gradient boosting']:.0f})")ax.set(title="Validation window: classical vs machine learning", ylabel="visits")ax.legend()fig.autofmt_xdate()plt.show()
Both models learned the weekly shape, and both miss the climb toward the yearly peak. SARIMA starts from the most recent level. The direct gradient boosting model sees only values from 28 days or more before each target, plus the month, so its level lags behind too.
Common mistakes:
- Building rolling features without
shift.log_series.rolling(28).mean()includes the target day; the model looks perfect in training and fails in production. - Using
shift(1)features with a 28-day horizon and no recursion. On day 2 of the forecast, the lag-1 value is a future value that you do not have. - Training a tree model on a trending raw series. Its forecasts flatten near the top of the training range.
Example 7 — Backtest with TimeSeriesSplit, then score the holdout once
Section titled “Example 7 — Backtest with TimeSeriesSplit, then score the holdout once”Goal: Score the two baselines, the two SARIMA routes of Example 5 and gradient boosting on five past 28-day windows with TimeSeriesSplit, choose a model by the mean score, and only then report MAE, RMSE, MAPE, sMAPE and MASE on the locked holdout. This is how a forecasting team chooses and reports a model.
Step 1 — Write the metric functions
Section titled “Step 1 — Write the metric functions”def rmse(actual, forecast) -> float: errors = np.asarray(actual) - np.asarray(forecast) return float(np.sqrt(np.mean(errors**2)))
def mape(actual, forecast) -> float: actual, forecast = np.asarray(actual), np.asarray(forecast) return float(100 * np.mean(np.abs((actual - forecast) / actual)))
def smape(actual, forecast) -> float: actual, forecast = np.asarray(actual), np.asarray(forecast) denominator = np.abs(actual) + np.abs(forecast) return float(100 * np.mean(2 * np.abs(actual - forecast) / denominator))
def mase(actual, forecast, history, m: int = 7) -> float: history = np.asarray(history) scale = np.mean(np.abs(history[m:] - history[:-m])) # in-sample seasonal naive MAE return mae(actual, forecast) / scale
print(round(mape([100, 200], [110, 180]), 2), round(smape([100, 200], [110, 180]), 2))print(round(mase(y_valid, snaive_valid, y_fit), 3))print(round(mase(y_valid, sarima_valid, y_fit), 3))10.0 10.031.8422.02Each function is one line of its formula. Check the small case by hand: both errors are 10% of the actual value, so MAPE is 10. sMAPE divides by the mean of actual and forecast, so it gives a slightly different value. MASE divides the MAE by the in-sample seasonal naive MAE. On the validation window both forecasts score above 1: they are worse than the seasonal naive forecast is on an average week of the fit data.
Step 2 — Create the folds
Section titled “Step 2 — Create the folds”from sklearn.model_selection import TimeSeriesSplit
tscv = TimeSeriesSplit(n_splits=5, test_size=horizon)folds = list(tscv.split(train))for k, (train_idx, test_idx) in enumerate(folds, start=1): first, last = train.index[test_idx[0]].date(), train.index[test_idx[-1]].date() print(f"fold {k}: train {len(train_idx):4d} days | test {first} to {last}")fold 1: train 928 days | test 2024-07-17 to 2024-08-13fold 2: train 956 days | test 2024-08-14 to 2024-09-10fold 3: train 984 days | test 2024-09-11 to 2024-10-08fold 4: train 1012 days | test 2024-10-09 to 2024-11-05fold 5: train 1040 days | test 2024-11-06 to 2024-12-03The folds use only train; the holdout stays locked. Each fold trains on everything before its test window, and each training set is 28 days longer than the one before: an expanding window. test_size=horizon makes every test window as long as the real forecast. Fold 5 is the validation window of Examples 5 and 6.
Step 3 — Draw the folds
Section titled “Step 3 — Draw the folds”fig, ax = plt.subplots(figsize=(10, 3))for k, (train_idx, test_idx) in enumerate(folds, start=1): ax.plot(train.index[train_idx], [k] * len(train_idx), color="tab:blue", linewidth=6) ax.plot(train.index[test_idx], [k] * len(test_idx), color="tab:orange", linewidth=6)ax.plot(test.index, [6] * len(test), color="tab:red", linewidth=6)ax.set_yticks(range(1, 7), [f"fold {k}" for k in range(1, 6)] + ["holdout"])ax.invert_yaxis()ax.set(title="Expanding-window backtest: train (blue), test (orange), holdout (red)")plt.show()
Every training bar starts on the first day and ends right before its test block. No test block lies before any of its training days. This is the property that plain KFold breaks.
Step 4 — Run the backtest
Section titled “Step 4 — Run the backtest”def fit_and_forecast(history: pd.Series, target_index: pd.DatetimeIndex) -> dict: """Fit the five models on `history` and forecast the days in `target_index`.""" steps = len(target_index) log_history = np.log(history) sarima = SARIMAX(log_history, order=(1, 1, 1), seasonal_order=(0, 1, 1, 7)) sarima_fc = np.exp(sarima.fit(disp=False, maxiter=200).forecast(steps)) trend_model = SARIMAX( log_history, order=(1, 0, 0), seasonal_order=(0, 1, 1, 7), trend="c" ) trend_fc = np.exp(trend_model.fit(disp=False, maxiter=200).forecast(steps)) rows = features.loc[history.index].dropna() model = LGBMRegressor( n_estimators=200, learning_rate=0.05, n_jobs=1, random_state=42, verbose=-1 ) model.fit(rows, log_y.loc[rows.index]) return { "naive": np.repeat(history.iloc[-1], steps), "seasonal naive": seasonal_naive_forecast(history, steps), "SARIMA": sarima_fc.to_numpy(), "SARIMA trend": trend_fc.to_numpy(), "gradient boosting": np.exp(model.predict(features.loc[target_index])), }
results = []for k, (train_idx, test_idx) in enumerate(folds, start=1): fold_train, fold_test = train.iloc[train_idx], train.iloc[test_idx] for name, fc in fit_and_forecast(fold_train, fold_test.index).items(): results.append({"fold": k, "model": name, "MAE": mae(fold_test, fc), "MASE": mase(fold_test, fc, fold_train)})backtest = pd.DataFrame(results)print(backtest.pivot(index="fold", columns="model", values="MAE").round(0))model SARIMA SARIMA trend gradient boosting naive seasonal naivefold1 256.0 249.0 275.0 506.0 406.02 213.0 214.0 271.0 487.0 315.03 1514.0 1494.0 1538.0 1623.0 1549.04 323.0 377.0 332.0 637.0 343.05 1156.0 1466.0 1087.0 608.0 1054.0fit_and_forecast holds the whole workflow, so every fold runs exactly the same code: fit on the past, forecast 28 days, score. Fold 3 holds the campaign of 2024-09-16, and every model misses it: no feature tells the models that a campaign is coming. The two SARIMA routes are close in folds 1 to 3, and the d = 1 model is clearly better in folds 4 and 5. The naive forecast wins only fold 5, the validation window of Examples 5 and 6.
Step 5 — Choose a model on the backtest
Section titled “Step 5 — Choose a model on the backtest”summary = backtest.groupby("model")[["MAE", "MASE"]].mean().sort_values("MAE")print("Backtest, mean of 5 folds:")print(summary.round(2))print("chosen model:", summary.index[0])Backtest, mean of 5 folds: MAE MASEmodelSARIMA 692.32 1.26gradient boosting 700.41 1.27seasonal naive 733.31 1.33SARIMA trend 760.06 1.37naive 771.93 1.41chosen model: SARIMASARIMA (d = 1) has the lowest mean MAE and MASE over the five folds, so it is the chosen model, with gradient boosting a close second. The trend-stationary model, which follows the ADF evidence, ranks fourth. A correct description of the history is not always the best forecaster: its fitted trend line reacts slowly when the level shifts, while one difference adapts at once. The gaps are small because the campaign fold adds a large error to every model’s mean. Every MASE is above 1: a 28-day forecast is harder than the one-week-ahead seasonal naive forecast that scales MASE. This choice uses only data before the holdout.
Step 6 — Score the holdout once
Section titled “Step 6 — Score the holdout once”holdout_fc = fit_and_forecast(train, test.index)final = pd.DataFrame( { name: { "MAE": mae(test, fc), "RMSE": rmse(test, fc), "MAPE %": mape(test, fc), "sMAPE %": smape(test, fc), "MASE": mase(test, fc, train), } for name, fc in holdout_fc.items() }).Tprint(f"Holdout, {test.index[0].date()} to {test.index[-1].date()}:")print(final.round(2).sort_values("MAE"))Holdout, 2024-12-04 to 2024-12-31: MAE RMSE MAPE % sMAPE % MASESARIMA 430.74 546.18 6.38 6.34 0.76gradient boosting 510.94 620.40 7.38 7.50 0.90SARIMA trend 820.73 922.09 11.86 12.77 1.44seasonal naive 837.64 1000.71 13.12 12.01 1.47naive 1750.14 1925.24 27.62 23.49 3.07fit_and_forecast refits every model on all of train (fit and validation days) and forecasts the 28 holdout days. This is the first and only time the holdout is used. The chosen SARIMA model is also the best on the holdout: off by about 6% a day (MAPE 6.38), and with a MASE of 0.76, about a quarter less error than the in-sample seasonal naive forecast. Gradient boosting is second on every metric, the trend-stationary SARIMA third, and SARIMA and gradient boosting beat both baselines on all five metrics. This is the classical vs machine learning comparison, on the same holdout, made once.
Common mistakes:
- Using
KFold(shuffle=True)orcross_val_scorewith the default splitter on a time series. Every fold leaks the future. - Computing features inside each fold with
center=Trueorbfill(). The backtest then looks better than real use. - Looking at the holdout, changing the model and looking again. After the first look, the holdout is a validation set and you need a new holdout.
- Reporting only MAPE. It explodes on days with values near 0 and favors forecasts that are too low. Report MAE or MASE next to it.
Pitfalls
Section titled “Pitfalls”| Mistake | Symptom | Fix |
|---|---|---|
| Dates read as text | y.loc["2024"] raises KeyError; resample raises TypeError |
parse_dates=["date"], index_col="date" |
Old offset alias "M", "H" or "T" |
ValueError: Invalid frequency: M |
Use "ME", "h" or "min" |
| Missing dates not checked | Lags of “7 rows” are not 7 days | asfreq("D") before you compute lags |
sum on a partial week or month |
A fake drop at the start or end | Count rows per bin and drop partial bins |
bfill() or interpolation at the end of the series |
Backtests look better than production | Fill only inside the history; never across the origin |
rolling(...) features without shift |
Near-perfect training score, poor forecasts | y.shift(h).rolling(k).mean() with h ≥ horizon |
Random train_test_split on a time series |
Optimistic scores | Split by position; use TimeSeriesSplit |
| Small ADF p-value read as “non-stationary” | Needless differencing | H0 is a unit root: a small p-value means stationary |
| Over-differencing | MA coefficient near −1, wider intervals | Use the smallest d that makes the series stationary |
Ignoring ConvergenceWarning |
Unstable or wrong parameters | Simpler model, log scale or maxiter=200; check mle_retvals |
| Tree model on a trending raw series | Forecasts flatten near the top of the training range | Model the log, a difference or a ratio |
| MAPE on series with zeros | inf or huge values |
Use MAE, MASE or sMAPE |
| Choosing the model on the holdout | The holdout score is too optimistic | Choose with a backtest; use the holdout once |
Where this is used beyond data science
Section titled “Where this is used beyond data science”- Site reliability and DevOps: monitoring tools resample server metrics to 1-minute means, compare them with a rolling baseline and alert when the rolling standard deviation jumps.
- Finance and accounting: month-end (
"ME") and quarter-end ("QE") resampling turns a transaction log into a ledger; log returns are first differences of log prices. - IoT and automation: a home-automation script downsamples a thermostat to hourly means and forward-fills the last known setpoint.
- Capacity planning: web teams forecast traffic with seasonal naive and SARIMA models to size servers before a holiday peak.
Summary
Section titled “Summary”- A time series is ordered data; neighbors are correlated. Never shuffle it, and never let a feature use a value from after the forecast origin.
- Build a
DatetimeIndexwithparse_datesandindex_col, check it withpd.date_range, set the frequency withasfreqand fill gaps by their meaning. - Downsample flows with
sumand levels withmean; watch for partial bins. pandas 3 uses"ME","h"and"min". - Rolling means with the seasonal period remove the seasonality. STL splits a series into trend, seasonality and remainder.
- The ADF null hypothesis is a unit root. A small p-value is evidence of stationarity. Differencing removes a unit root or a trend.
- The ACF and PACF show the memory of the series and suggest small ARIMA orders.
- Always compute the naive and seasonal naive baselines. SARIMA models the log, the differences and the weekly pattern. Gradient boosting needs lag features built with
shift, and lags of at least the horizon for the direct strategy. - Choose a model with
TimeSeriesSplitbacktests. Report MAE or MASE, with MAPE or sMAPE for a percentage view.
Self-check questions
Section titled “Self-check questions”Q1. Why is a random train/test split wrong for a time series?
Answer
The rows are ordered and correlated. A random split puts days after the test days into the training set, so the model learns from the future. The score is too optimistic. Split by position instead: the last part of the series is the test set.
Q2. You resample daily revenue and daily bounce_rate to months. Which aggregation do you use for each, and why?
Answer
sum for revenue, because it is a flow: the monthly revenue is the total of the daily amounts. mean for the bounce rate, because it is a level (a rate): the sum of 30 rates has no meaning.
Q3. web_traffic.csv loads with index.freq equal to None. What does asfreq("D") do?
Answer
It sets a daily frequency on the index and adds a row of NaN for every calendar day that is missing from the file. For web_traffic.csv no row is added, because every day exists; only the 5 blank visits cells are NaN.
Q4. An ADF test on a series gives p = 0.002. What do you conclude?
Answer
Reject H0 at the 5% level. H0 of the ADF test is a unit root (non-stationary), so the small p-value is evidence that the series is stationary (around a constant with regression="c", or around a trend with "ct").
Q5. Why does y.rolling(7).mean() leak information when you use it as a feature to predict y, and what is the fix?
Answer
The window on day t includes day t itself, which is the target. Shift first: y.shift(1).rolling(7).mean() uses days t − 7 to t − 1. For a direct forecast with horizon H, shift by at least H.
Q6. The ACF of daily data has bars at lags 7, 14 and 21 that are larger than their neighbors. What does it tell you, and how do you use it in SARIMA?
Answer
The series has weekly seasonality: each day is correlated with the same weekday in earlier weeks. Use a seasonal period s = 7 in seasonal_order, and consider a seasonal difference (D = 1) or a seasonal AR or MA term.
Q7. What does the seasonal naive forecast predict for next Saturday, with daily data and ? Why is it a useful baseline?
Answer
It predicts last Saturday’s value. It costs nothing, keeps the weekly shape and is often hard to beat on short horizons. A model that does not beat it is not worth its complexity. MASE uses it as its scale.
Q8. A gradient boosting forecast of a growing series flattens out near the top of the training range. Why, and what can you do?
Answer
Tree predictions are piecewise constant: each leaf holds a fixed value, and a boosted sum of trees stays flat beyond the range of the training features. So the forecast cannot follow the growth past the levels it has seen. Model a transformed target that does not grow: the log (it shrinks the growth), the difference from a recent value, or the ratio to a recent level. Or let a linear model or SARIMA handle the trend.
Q9. What does TimeSeriesSplit(n_splits=5, test_size=28) produce?
Answer
Five folds. The test sets are five consecutive 28-day blocks at the end of the data. Each training set holds every row before its test block, so it grows by 28 rows from fold to fold (an expanding window). No training row comes after a test row.
Q10. A forecast has MASE = 1.3. Is it good?
Answer
Not by itself. MASE = 1.3 means the forecast’s MAE is 30% larger than the MAE of a one-season-ahead seasonal naive forecast inside the training data. For a long horizon that bar is high. Compare it with the MASE of the seasonal naive forecast on the same window: if the model is not clearly lower, the baseline is as good.
Q11. Why can MAPE not be used for daily units of a product that sells 0 units on some days?
Answer
MAPE divides each error by the actual value. On a day with 0 units, the division gives infinity (or a huge number). Use MAE, MASE or sMAPE.
Track your progress
Section titled “Track your progress”Next steps
Section titled “Next steps”- Exercises: 27 exercises on indexes, resampling, decomposition, stationarity, features, models, backtests and metrics.
- Mini-project: forecast 28 days of daily units sold, classical vs machine learning.
- Cheat sheet: every pandas, statsmodels and scikit-learn call of this module on one page.
- Next module: 41. NLP fundamentals turns text into features with bag of words, TF-IDF and embeddings.