The one-line mental model
A time series is an ordered sequence where past values correlate with future ones β so before forecasting you decompose trend and seasonality, make the series stationary if it is not, and read ACF/PACF to learn how much history the model should actually use.
You will be able to:
- Load a dated series onto a regular frequency and handle gaps
- Decompose into trend, seasonal, and residual components
- Run ADF and KPSS tests and transform a series until it is stationary
- Interpret ACF and PACF cutoffs to choose model orders
Prerequisites
- !Pandas datetime indexing
- !Mean, variance, and autocorrelation intuition
- !Plotting with Matplotlib
What You'll Learn
- 1Explain why random-forest style shuffling breaks time order
- 2Choose additive versus multiplicative decomposition from the data
- 3Apply differencing and log transforms to remove trend and variance growth
- 4Translate ACF/PACF patterns into candidate ARIMA orders
What makes temporal data different
Cross-sectional data lets you shuffle rows freely; time series do not. Tomorrow's sales depend on yesterday's promotions, today's inventory, and last year's seasonality. That serial dependence breaks two assumptions at once: i.i.d. sampling and the idea that a random 80/20 split measures generalization. A model evaluated on randomly interleaved dates has already seen the future β a problem called look-ahead leakage that inflates offline metrics and then collapses in production.
The practical consequences show up everywhere in the workflow. Cross-validation must walk forward in time (expanding or rolling origin), error metrics must respect the horizon, and every feature must be computable at the moment of prediction. Before any of that, though, you need to understand the shape of the signal: is there a trend, a repeating cycle, growing variance, and how much of the movement is just noise?
Loading onto a regular frequency
Real-world series arrive with gaps β missed days, partial weeks, timezone confusion. Models like ARIMA assume a fixed interval, so the first job is to parse dates, sort, set a DatetimeIndex, and reindex onto a complete calendar.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv("data/daily_sales.csv", parse_dates=["date"])
df = df.sort_values("date").drop_duplicates("date")
ts = df.set_index("date")["revenue"]
ts = ts.asfreq("D") # declare daily frequency
gaps = ts.isna().sum()
print(f"Calendar length: {len(ts)}, gaps: {gaps} "
f"({100 * gaps / len(ts):.1f}%)")
ts = ts.interpolate(method="time") # gap-aware interpolation
print(f"Range: {ts.index.min().date()} β {ts.index.max().date()}")
fig, ax = plt.subplots(figsize=(12, 4))
ts.plot(ax=ax, linewidth=0.8)
ax.axhline(ts.mean(), color="gray", linestyle="--", linewidth=1)
ax.set_title("Daily revenue on a complete calendar")
plt.tight_layout()
plt.show()
interpolate(method="time") weights by the actual time distance between points, which is safer than a plain mean fill when gaps vary in length. For series with structural missingness (holidays, closures), consider modeling those dates explicitly rather than interpolating across them.
Decomposition: trend, season, residual
Classical decomposition splits a series into three parts. Additive decomposition assumes the seasonal swing is constant in absolute terms; multiplicative assumes it scales with the level β think holiday retail spikes that grow as the business grows.
A quick eyeball test: if the amplitude of the seasonal wave widens as the level rises, go multiplicative (or take logs and go additive). STL is a more robust modern alternative that handles changing seasonal patterns over long histories.
from statsmodels.tsa.seasonal import seasonal_decompose, STL
fig, axes = plt.subplots(2, 1, figsize=(12, 8))
additive = seasonal_decompose(ts, model="additive", period=7)
additive.plot(axes=axes[0], legend=True)
axes[0].set_title("Additive decomposition (weekly period)")
stl = STL(ts, period=7, robust=True).fit()
stl.plot(axes=axes[1], legend=True)
axes[1].set_title("STL decomposition (robust to outliers)")
plt.tight_layout()
plt.show()
seasonal_amp = stl.seasonal.max() - stl.seasonal.min()
print(f"Seasonal amplitude: {seasonal_amp:.1f}, "
f"residual std: {stl.resid.std():.1f}")
Compare the residual standard deviation against the raw series standard deviation. If the residual is barely smaller, the decomposition found almost nothing and a seasonal model will not help much either.
Stationarity: why ARIMA demands it
ARIMA models assume the statistical properties β mean, variance, autocorrelation structure β are stable over time. A trending series violates that: the mean drifts, and a model fit on early history misreads the later level. Stationarity is what lets a single set of parameters describe the whole series.
Two tests check it from opposite directions. The Augmented Dickey-Fuller test has a null hypothesis of a unit root (non-stationary); you reject it when the p-value is small. The KPSS test flips the hypotheses β its null is stationarity β so ideally both tests agree. Disagreement usually means a trend-stationary series that needs a deterministic trend term rather than differencing.
from statsmodels.tsa.stattools import adfuller, kpss
def stationarity_report(series, name="series"):
s = series.dropna()
adf = adfuller(s, autolag="AIC")
kps = kpss(s, regression="ct", nlags="auto")
print(f"[{name}] ADF stat={adf[0]:.3f} p={adf[1]:.4f} β "
f"{'stationary' if adf[1] < 0.05 else 'non-stationary'}")
print(f"[{name}] KPSS stat={kps[0]:.3f} p={kps[1]:.4f} β "
f"{'stationary' if kps[1] > 0.05 else 'non-stationary'}")
stationarity_report(ts, "raw")
stationarity_report(ts.diff().dropna(), "first difference")
stationarity_report(ts.diff(7).dropna(), "seasonal difference lag 7")
Transforming until the series behaves
Three tools cover most cases: first differences to kill a linear trend, seasonal differences (often lag 7 or 12) to remove repeating structure, and log or Box-Cox transforms to stabilize a variance that grows with the level. Order matters β logs before differencing, because differencing a log produces approximate percentage changes, which are naturally scale-free.
from scipy.stats import boxcox
log_ts = np.log(ts)
log_diff = log_ts.diff().dropna()
seasonal_diff = log_ts.diff(7).dropna()
combined = log_ts.diff().diff(7).dropna()
stationarity_report(log_diff, "log + 1st diff")
stationarity_report(seasonal_diff, "log + seasonal diff")
stationarity_report(combined, "log + 1st + seasonal diff")
# Box-Cox finds a power transform that best normalizes variance
positive = ts[ts > 0]
transformed, lam = boxcox(positive.values)
print(f"Box-Cox lambda: {lam:.3f} "
f"(lambdaβ0 β log, lambdaβ0.5 β sqrt)")
fig, axes = plt.subplots(1, 3, figsize=(14, 4))
ts.plot(ax=axes[0], title="Raw")
log_diff.plot(ax=axes[1], title="Log + first difference")
combined.plot(ax=axes[2], title="Log + first + seasonal difference")
plt.tight_layout()
plt.show()
Stop transforming once the stationarity tests agree and the rolling mean and standard deviation look flat β over-differencing invents negative autocorrelation and makes forecasts jitter.
Reading ACF and PACF
The autocorrelation function measures correlation between y_t and y_{t-k}; the partial autocorrelation isolates the direct link at lag k after removing intermediate lags. Together they are a quick model-selection tool: an ACF that decays slowly signals non-stationarity; a sharp ACF cutoff after lag q suggests an MA(q); a sharp PACF cutoff after lag p suggests an AR(p).
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.stattools import acf, pacf
fig, axes = plt.subplots(2, 2, figsize=(12, 8))
plot_acf(ts.dropna(), lags=28, ax=axes[0, 0])
axes[0, 0].set_title("ACF β raw (expect slow decay)")
plot_pacf(ts.dropna(), lags=28, ax=axes[0, 1], method="ywm")
axes[0, 1].set_title("PACF β raw")
plot_acf(combined, lags=28, ax=axes[1, 0])
axes[1, 0].set_title("ACF β transformed")
plot_pacf(combined, lags=28, ax=axes[1, 1], method="ywm")
axes[1, 1].set_title("PACF β transformed")
plt.tight_layout()
plt.show()
vals = acf(combined, nlags=14, fft=True)
band = 1.96 / np.sqrt(len(combined))
significant = [k for k in range(1, len(vals)) if abs(vals[k]) > band]
print(f"Significant ACF lags: {significant}")
print(f"95% significance band: Β±{band:.3f}")
Use the plots as guidance, not gospel β seasonality, structural breaks, and heavy tails all distort the classic patterns, and modern selection criteria (AIC, BIC, cross-validated forecast error) are safer tiebreakers when the plots are ambiguous.
A quick forecasting sanity check
To prove the diagnostics were worth it, fit a naive seasonal baseline and a minimal AR model, then compare walk-forward errors. If the fancy model cannot beat "same as last week," the stationarity and autocorrelation work you just did points at a series that needs external regressors or a different problem framing, not a bigger ARIMA.
The seasonal-naive baseline deserves special attention because it is the bar every forecasting model must clear. For daily retail data it is literally "last Monday's value"; for monthly data it is "same month last year." It requires no fitting, no stationarity, and no stationarity tests β which is exactly why it is such an unforgiving benchmark. A model that cannot beat it is, by definition, adding noise where a copy-paste would have done better. Use it as a gate, not a formality: if your sophisticated pipeline does not clear it, stop tuning and revisit the problem assumptions before reaching for a different algorithm family.
from sklearn.metrics import mean_absolute_error
split = int(len(ts) * 0.8)
train, test = ts.iloc[:split], ts.iloc[split:]
naive_seasonal = train.iloc[-len(test):].values.copy()
# repeat last full week pattern
pattern = train.values[-7:]
naive_seasonal = np.tile(pattern, len(test) // 7 + 1)[:len(test)]
import warnings
from statsmodels.tsa.arima.model import ARIMA
warnings.filterwarnings("ignore")
arima = ARIMA(train, order=(2, 1, 1)).fit()
arima_fc = arima.forecast(steps=len(test))
print(f"Seasonal naive MAE: {mean_absolute_error(test, naive_seasonal):.2f}")
print(f"ARIMA(2,1,1) MAE: {mean_absolute_error(test, arima_fc):.2f}")
Beating a seasonal-naive baseline is the minimum bar for claiming a forecasting model is useful at all.