Sub topic 1
What makes time series data different
A time series is a sequence of measurements of the same quantity, taken in time order. Examples are daily sales, hourly electricity load, and weekly web traffic. Later chapters turn a series into a table and fit gradient boosting to it. This chapter covers the properties that decide how that table must be built and checked.
Prerequisites
You should be comfortable with the following:
- Python and pandas:
Series,DataFrame,DatetimeIndex,shiftandrolling. - Basic supervised learning: train/test split, regression, overfitting.
- scikit-learn's
fit/predictinterface. - The basic idea of a decision tree.
No time series theory is assumed.
Why ordinary tabular assumptions break
Standard regression assumes rows are independent and identically distributed (i.i.d.). Each row is a separate draw from one fixed process, and the order of rows carries no information. Time series data breaks both assumptions.
| Property | Typical tabular data | Time series data |
|---|---|---|
| Row order | Irrelevant | Carries the signal |
| Neighbouring rows | Independent | Correlated |
| Distribution | Fixed | Often drifts (trend, level shifts) |
| Valid train/test split | Random | Chronological |
| Available inputs at prediction time | All columns | Only what is known before the target time |
The last two rows cause most mistakes. A random split puts rows from after the test point into training. The model then learns from the future and its score is optimistic. The chapters on leakage and validation return to this. Here the aim is to see the structure that makes it a problem.
Components of a series
A series is usually described as a mix of four components.
- Trend is a slow, long-run change in level, such as sales growing 5% a year.
- Seasonality is a pattern that repeats at a fixed period, such as higher weekend traffic or a December sales peak. The period is known in advance.
- Autocorrelation is the correlation of a series with a shifted copy of itself. Today's value is related to yesterday's value and to the value one week ago.
- Noise is the part left over that no feature can explain.
Seasonality differs from a cycle. A cycle, such as a business cycle, rises and falls without a fixed period. Calendar features capture seasonality well. They do not capture cycles.
A synthetic series to experiment with
The code below builds a daily series with a known trend, a weekly pattern and random noise. Because you know what went in, you can check that the diagnostics find it.
import numpy as np
import pandas as pd
rng = np.random.default_rng(0)
idx = pd.date_range("2024-01-01", periods=365, freq="D")
t = np.arange(len(idx))
dow = idx.dayofweek.to_numpy()
trend = 50 + 0.05 * t
weekly = 8 * np.sin(2 * np.pi * dow / 7)
noise = rng.normal(0, 2, len(idx))
s = pd.Series(trend + weekly + noise, index=idx, name="sales")
print(s.head())
print(s.index.freq)The last line prints <Day>. The index knows its frequency, so pandas can compute "one step later" reliably.
Frequency and missing timestamps
Frequency is the spacing between observations: daily, hourly, every 15 minutes. Lag features rely on it. s.shift(7) moves values by seven rows, not seven days. If a day is missing, seven rows back is no longer one week back, and the model silently learns a wrong relationship.
Check regularity before building any features:
gappy = s.drop(s.index[[10, 11, 100]])
print(gappy.index.freq) # None: pandas can no longer assume regular spacing
regular = gappy.asfreq("D") # re-insert the missing days as NaN
print(regular.isna().sum()) # 3asfreq restores the full grid and marks the gaps as NaN. You then choose how to fill them. Forward-filling suits a level that persists, such as a price. A zero suits counts where a missing row means nothing happened. Leaving NaN is also valid, because gradient boosting implementations such as HistGradientBoostingRegressor accept missing values in features. Whichever you choose, make the gap explicit rather than letting rows shift.
Measuring autocorrelation
The autocorrelation at lag k is the correlation between the series and itself shifted by k steps. pandas provides it as Series.autocorr.
for k in (1, 3, 7, 14):
print(k, round(s.autocorr(lag=k), 3))Lag 7 and lag 14 should come out clearly higher than lag 3. That pattern is the weekly seasonality, and it tells you which lags are worth turning into features. The trend adds a second effect. Any series that drifts upward looks correlated with its recent past, so all low lags score high. To see the seasonal structure without the trend, remove the trend first:
detrended = s - s.rolling(7, center=True).mean()
for k in (1, 3, 7, 14):
print(k, round(detrended.autocorr(lag=k), 3))The centred rolling mean uses values from both sides of each point. That is acceptable for analysis, but it would be look-ahead bias inside a forecasting feature. Keep this kind of smoothing for exploration only.
Stationarity, informally
A series is stationary if its mean, variance and autocorrelation do not change over time. The synthetic series above is not stationary, because its mean rises. Many classical models, such as ARIMA, require stationarity, so practitioners difference the series or remove the trend.
Gradient boosting does not require it, but non-stationarity still matters. A tree predicts by averaging training targets in a leaf. It cannot output a value outside the range it saw in training. If the series trends upward, forecasts flatten near the highest training values. The chapter on trend and extrapolation covers the fixes, such as predicting differences or ratios instead of raw levels.
Practical checks before modelling
Run these checks on every new series:
- Plot it, with a zoomed view of one seasonal period.
- Confirm the index is sorted, unique and regular, and note the frequency.
- Identify the likely seasonal periods from domain knowledge (7 for daily data with weekly effects, 24 for hourly data with daily effects).
- Look at autocorrelation at those periods and at lag 1.
- Look for level shifts, outliers and structural breaks such as a price change or a new store. A model trained across a break may learn a pattern that no longer holds.
Exercise
A daily series has one missing date in the middle. Why can s.shift(7) produce a wrong "same weekday last week" feature, and what should you do first?
Show answer
shift(7) moves values by seven rows, not seven calendar days. After the gap, seven rows back is eight days back for some rows, so the feature pairs the wrong dates. Re-index to a regular grid first with s.asfreq("D"), then decide how to treat the resulting NaN (fill it or leave it for the model).
Exercise
On a series with a strong upward trend, autocorr is high at every small lag. Why is that misleading for choosing lag features, and how can you see the seasonal structure instead?
Show answer
The trend makes values near each other in time similar regardless of any repeating pattern, so every lag looks informative. Removing the trend, for example by subtracting a rolling mean or taking first differences, leaves the seasonal and short-term structure. Peaks at the seasonal period then stand out.
Exercise
Why does a random train/test split give an over-optimistic score for a forecasting model?
Show answer
Test rows are surrounded in time by training rows, including rows from after the test point. Because neighbouring values are autocorrelated, the model can effectively interpolate between known neighbours. A real forecast never has future values, so the score does not reflect real use. Chronological splits avoid this.