Sub topic 1
What makes time series data different
Prerequisites
This chapter assumes you know Python and pandas basics, including DataFrame, Series and DatetimeIndex. You should also know the train/test split and how regression models overfit. No forecasting background is needed.
Why order matters
A time series is a sequence of values recorded at successive points in time, such as daily sales or hourly temperature. In ordinary tabular data, rows are treated as independent draws, so you can shuffle them without losing information. In a time series, the order carries the information. Today's value depends on yesterday's, and the model must only learn from the past to predict the future.
Four properties describe most series.
- Trend is a slow, long-term rise or fall in the level of the series.
- Seasonality is a pattern that repeats at a fixed period, such as higher sales every weekend (period 7 for daily data).
- Autocorrelation is the correlation of a series with a shifted copy of itself. High autocorrelation at lag 1 means that today's value is a good guide to tomorrow's.
- Frequency is the regular spacing between observations, such as daily (
'D') or hourly ('h').
Looking at the properties in code
The code below builds a synthetic daily series with a trend and a weekly cycle. It then measures autocorrelation at several lags.
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")
trend = np.linspace(100, 130, len(idx))
weekly = 10 * np.sin(2 * np.pi * idx.dayofweek / 7)
noise = rng.normal(0, 2, len(idx))
s = pd.Series(trend + weekly + noise, index=idx)
print("frequency:", s.index.freq)
for lag in (1, 3, 7, 14):
print(f"autocorrelation at lag {lag}:", round(s.autocorr(lag=lag), 3))Lags 7 and 14 should show higher autocorrelation than lag 3, because of the weekly cycle. Lag 1 is also high, mostly because the trend moves slowly.
Regular frequency
Lag features such as "the value 7 steps ago" only make sense if every step is the same length. Missing dates silently break this, because shift(7) moves 7 rows, not 7 days. Check and repair the index before you build features.
s = s.asfreq("D") # insert missing dates as NaN
print(s.isna().sum()) # count the gaps you need to fill or handleConsequences for modeling
These properties change how you work, and the later chapters build on each one.
| Property | Consequence |
|---|---|
| Order matters | Never split randomly. Train on the past and test on the future. |
| Autocorrelation | Past values are useful features, so we will build lag features. |
| Seasonality | Calendar features and seasonal baselines capture repeating patterns. |
| Trend | Tree models cannot extrapolate beyond the values they saw in training. |
| Regular frequency | Lags and windows are only meaningful on an evenly spaced index. |
Exercise
A daily series has three missing days in the middle of March. You call s.shift(7) without fixing the index. What goes wrong, and how do you fix it?
Show answer
shift(7) moves 7 rows, not 7 days. After the gap, each row gets the value from a date more than 7 days earlier, so the lag is misaligned. Call s.asfreq("D") first to insert the missing dates as NaN, then fill or handle them before building lag features.
Exercise
Why is randomly shuffling rows into train and test sets a problem for time series?
Show answer
Shuffling places future rows in the training set and past rows in the test set. The model then learns from information that would not be available at forecast time, so the score looks better than real performance.