Skip to content

40. Time series — Cheat sheet

The essentials of module 40 on one page. Every runnable block on this page is checked against its output.

I want to… Use… Example
read dates as a DatetimeIndex parse_dates + index_col pd.read_csv(path, parse_dates=["date"], index_col="date")
select a month or a year partial string indexing df.loc["2024-02"], df.loc["2023"]
select a date range (both ends included) .loc with a slice df.loc["2024-12-01":"2024-12-07"]
set a frequency and expose missing dates asfreq df.asfreq("D")
list every calendar day pd.date_range pd.date_range("2024-01-01", "2024-12-31", freq="D")
add missing days with a value reindex s.reindex(days, fill_value=0)
downsample a flow resample(...).sum() daily.resample("MS").sum()
downsample a level resample(...).mean() temp.resample("h").mean()
count rows per bin resample(...).size() daily.resample("W").size()
fill a short gap in a smooth series interpolate("time") s.interpolate("time", limit=3)
carry the last known state ffill() price.ffill()
lag a series shift(k) y.shift(7)
change since last week diff(k) y.diff(7)
trailing rolling mean (no leak) shift then rolling y.shift(1).rolling(7).mean()
decompose trend and seasonality STL STL(y, period=7, robust=True).fit()
test for a unit root adfuller adfuller(y, regression="c", result_object=True).pvalue
plot autocorrelation plot_acf, plot_pacf plot_acf(y, lags=28, ax=ax)
fit SARIMA SARIMAX SARIMAX(np.log(y), order=(1, 1, 1), seasonal_order=(0, 1, 1, 7)).fit(disp=False, maxiter=200)
forecast with an interval get_forecast res.get_forecast(28).conf_int(alpha=0.05)
add a known future input exog= SARIMAX(y, exog=spend, ...); res.forecast(28, exog=future_spend)
forecast with gradient boosting lag features + LGBMRegressor LGBMRegressor(n_jobs=1, verbose=-1, random_state=42)
cross-validate without leakage TimeSeriesSplit TimeSeriesSplit(n_splits=5, test_size=28)
score a forecast across scales MASE MAE divided by the in-sample seasonal naive MAE
import numpy as np
import pandas as pd
pd.set_option("display.width", 100)
pd.set_option("display.precision", 3)
traffic = pd.read_csv("data/web_traffic.csv", parse_dates=["date"], index_col="date")
traffic = traffic.asfreq("D") # daily frequency; missing dates would become NaN rows
y = traffic["visits"].interpolate("time") # fill the 5 blank days
print(y.index.freqstr, len(y), y.isna().sum())
print(y.loc["2024-12-30":])
Output
D 1096 0
date
2024-12-30 7283.0
2024-12-31 7218.0
Freq: D, Name: visits, dtype: float64
Alias Meaning Removed alias (pandas 3 raises ValueError)
"min", "10min" minutes "T"
"h" hours "H"
"D", "B" calendar days, business days
"W" = "W-SUN", "W-MON" weeks ending Sunday or Monday
"MS", "ME" month start, month end "M"
"QS", "QE" quarter start, quarter end "Q"
"YS", "YE" year start, year end "Y", "A"
Index tool Does
idx.is_monotonic_increasing, idx.is_unique check sorted and unique dates
idx.day_of_week (Monday = 0), idx.month, idx.day_of_year, idx.hour calendar features
idx.day_name() "Monday" …
pd.Timedelta(days=28) date arithmetic: day - pd.Timedelta(days=28)
s.shift(7, freq="D") move the index, not the values
weekly = traffic.resample("W").agg(
{"visits": "sum", "signups": "sum", "bounce_rate": "mean", "marketing_spend": "sum"}
)
days = traffic["visits"].resample("W").size()
print(days.iloc[[0, 1, -1]].to_string()) # partial first and last bins
print(weekly[days == 7].head(2))
Output
date
2022-01-02 2
2022-01-09 7
2025-01-05 2
visits signups bounce_rate marketing_spend
date
2022-01-09 23640.0 361 0.428 2921.97
2022-01-16 23872.0 358 0.434 2986.88
Column type Examples Downsample with Upsample with
flow (amount per period) revenue, units, visits, spend sum split: value ÷ number of new periods
level (state, rate) temperature, price, bounce rate mean, median, min, max ffill or interpolate
stock (running balance) inventory last ffill
  • Long table with several series: df.pivot(index="timestamp", columns="sensor_id", values="temperature_c").resample("h").mean(), or df.groupby("sensor_id").resample("h", on="timestamp")["temperature_c"].mean() (select numeric columns: mean fails on the text column status).
  • Labels: "W" uses the Sunday that ends the week, "MS" the first day, "ME" the last day.
  • resample(...).agg(["min", "mean", "max"]) gives several statistics per bin.
Situation Code
find missing dates pd.date_range(s.index.min(), s.index.max(), freq="D").difference(s.index)
find missing values s[s.isna()].index
smooth series, short gap s.interpolate("time", limit=3)
state that holds s.ffill()
count with absent rows s.reindex(all_days, fill_value=0)
never at the forecast origin bfill() and interpolation use later values
from statsmodels.tsa.seasonal import STL
stl = STL(y, period=7, robust=True).fit() # trend + seasonal + resid == y
effect = stl.seasonal.groupby(y.index.day_of_week).mean().round(0)
f_s = max(0, 1 - stl.resid.var() / (stl.seasonal + stl.resid).var())
print(effect.to_dict())
print(f"seasonal strength {f_s:.2f}")
print(y.rolling(7).std().idxmax().date()) # a rolling std finds the biggest shock
Output
{0: 260.0, 1: 376.0, 2: 282.0, 3: 108.0, 4: -185.0, 5: -559.0, 6: -286.0}
seasonal strength 0.18
2024-04-09
Call Use
y.rolling(7).mean() smooth out a weekly pattern (trailing)
y.rolling(7, center=True).mean() plots only: uses future days
y.rolling(7).std() volatility, event detection
y.expanding().mean() running mean since the start
seasonal_decompose(y, period=7, model="multiplicative") classical; factors around 1; NaN at both ends
STL(np.log(y), period=7) multiplicative seasonality through the log
stl.plot() four panels: data, trend, seasonal, remainder
from statsmodels.tsa.stattools import acf, adfuller
for name, series, reg in [("level, c", y, "c"), ("level, ct", y, "ct"),
("diff, c", y.diff().dropna(), "c")]:
res = adfuller(series, regression=reg, result_object=True)
print(f"{name:<10} p={res.pvalue:.2g} lags={res.lags}")
print(acf(y, nlags=7)[[1, 7]].round(3))
Output
level, c p=0.11 lags=21
level, ct p=5.8e-05 lags=22
diff, c p=1.2e-19 lags=20
[0.808 0.538]
ADF Meaning
H0 unit root: not stationary
p below 0.05 reject H0: evidence of stationarity
p above 0.05 no evidence of stationarity (not proof of a unit root)
regression="c" / "ct" / "n" stationary around a constant / a linear trend / zero
result_object=True named fields .statistic, .pvalue, .lags, .critical_values; no FutureWarning in statsmodels 0.15
KPSS (kpss(y, result_object=True)) the reverse test: H0 is stationary. It warns InterpolationWarning when the statistic is outside its p-value table; the reported p-value is then only a bound
ACF / PACF pattern Read as
ACF decays very slowly from near 1 trend or unit root: difference
ACF spikes at 7, 14, 21 weekly seasonality (s = 7)
PACF cuts off after p, ACF decays AR(p)
ACF cuts off after q, PACF decays MA(q)
one negative spike at lag s after differencing seasonal MA(1)
band PACF: about ±1.96/√n, flat; ACF (statsmodels default): Bartlett’s formula, widens with the lag

Plot: fig, axes = plt.subplots(2, 1), plot_acf(y, lags=28, ax=axes[0]), plot_pacf(y, lags=28, ax=axes[1]), plt.show() (from statsmodels.graphics.tsaplots).

from statsmodels.tsa.statespace.sarimax import SARIMAX
train, test = y.iloc[:-28], y.iloc[-28:] # by position, never shuffled
snaive = np.resize(train.iloc[-7:].to_numpy(), 28) # seasonal naive
res = SARIMAX(np.log(train), order=(1, 1, 1), seasonal_order=(0, 1, 1, 7)).fit(
disp=False, maxiter=200
)
fc = np.exp(res.get_forecast(28).predicted_mean) # back from the log scale
print(res.mle_retvals["converged"], round(res.aic, 1))
print(res.params.round(3).to_dict())
Output
True -1788.8
{'ar.L1': 0.742, 'ma.L1': -0.979, 'ma.S.L7': -0.994, 'sigma2': 0.01}
Model Forecast for T + h Code
naive last value np.repeat(train.iloc[-1], h)
seasonal naive same position last season np.resize(train.iloc[-m:].to_numpy(), h)
seasonal mean mean of the last k seasons train.iloc[-m*k:].to_numpy().reshape(k, m).mean(axis=0)
ARIMA(p, d, q) AR on p lags, d differences, MA on q errors SARIMAX(y, order=(p, d, q))
SARIMA plus (P, D, Q, s) at the seasonal lag seasonal_order=(0, 1, 1, 7)
SARIMAX plus known inputs exog=X_past, then forecast(h, exog=X_future)
with drift constant on the differenced series trend="c"
SARIMAX result Gives
res.params, res.aic coefficients, AIC (lower is better; compare same d, D)
res.mle_retvals["converged"] True when the optimizer finished
res.forecast(h) point forecasts
res.get_forecast(h).conf_int(alpha=0.05) 95% prediction interval
from lightgbm import LGBMRegressor
log_y = np.log(y)
X = pd.DataFrame({f"lag_{k}": log_y.shift(k) for k in [28, 35, 42]}) # lags >= horizon
X["roll_mean_28"] = log_y.shift(28).rolling(28).mean()
X["day_of_week"] = y.index.day_of_week
X["month"] = y.index.month
rows = X.loc[train.index].dropna()
model = LGBMRegressor(n_estimators=200, learning_rate=0.05, n_jobs=1,
random_state=42, verbose=-1).fit(rows, log_y.loc[rows.index])
lgbm_fc = np.exp(model.predict(X.loc[test.index]))
print(len(rows), X.loc[test.index].notna().all().all())
Output
1013 True
Strategy Features Loop
direct every lag ≥ horizon none: predict the whole horizon at once
recursive lags from 1; feed predictions back one prediction per step
direct, one model per step lags ≥ h for step h H models
  • Trees cannot extrapolate: model np.log(y), a difference or a ratio to a recent level.
  • HistGradientBoostingRegressor works the same way. On small tables under heavy CPU load, LightGBM with n_jobs=1 avoids thread overhead.
from sklearn.model_selection import TimeSeriesSplit
def mase(actual, forecast, history, m=7):
h = np.asarray(history)
scale = np.mean(np.abs(h[m:] - h[:-m])) # in-sample seasonal naive MAE
return np.mean(np.abs(np.asarray(actual) - np.asarray(forecast))) / scale
splitter = TimeSeriesSplit(n_splits=3, test_size=28)
for k, (tr, te) in enumerate(splitter.split(train), start=1):
print(k, len(tr), train.index[te[0]].date(), train.index[te[-1]].date())
print(round(mase(test, snaive, train), 2), round(mase(test, fc, train), 2),
round(mase(test, lgbm_fc, train), 2))
Output
1 984 2024-09-11 2024-10-08
2 1012 2024-10-09 2024-11-05
3 1040 2024-11-06 2024-12-03
1.47 0.76 0.9
TimeSeriesSplit argument Effect
n_splits number of folds
test_size length of each test window: set it to the horizon
gap rows skipped between train and test (data delay)
max_train_size cap the training length: a sliding window
Metric Formula Note
MAE 1n∑∣y−y^∣\frac{1}{n}\sum \lvert y - \hat y \rvert same unit as the data
RMSE 1n∑(y−y^)2\sqrt{\frac{1}{n}\sum (y - \hat y)^2} large errors weigh more
MAPE 100n∑∣(y−y^)/y∣\frac{100}{n}\sum \lvert (y - \hat y) / y \rvert breaks at 0; sklearn returns a fraction
sMAPE 100n∑2∣y−y^∣∣y∣+∣y^∣\frac{100}{n}\sum \frac{2 \lvert y - \hat y \rvert}{\lvert y \rvert + \lvert \hat y \rvert} 0 to 200
MASE MAE ÷ in-sample seasonal naive MAE scale-free; works with zeros
  • parse_dates is missing: the index holds strings and y.loc["2024"] raises KeyError.
  • pandas 3 rejects "M", "H", "T", "Q", "Y": use "ME"/"MS", "h", "min", "QE", "YE".
  • "W" bins at the start and end of the data can hold fewer than 7 days; their sums are too small.
  • shift(7) means 7 rows, not 7 days, unless the index has a regular frequency: call asfreq first.
  • y.rolling(7).mean() includes today: shift it before you use it as a feature.
  • bfill() and interpolation near the end of the series use future values.
  • The ADF null hypothesis is “not stationary”. A small p-value is good news for stationarity.
  • adfuller without result_object=True raises a FutureWarning in statsmodels 0.15.
  • A ConvergenceWarning is a real problem: simplify the model, log the data or raise maxiter, then check mle_retvals.
  • A moving-average coefficient near −1 means over-differencing or a fixed seasonal pattern.
  • Forecasts of a model on np.log(y) must go back through np.exp.
  • With exog, you must supply future values to forecast. Use only inputs that are known in advance.
  • KFold(shuffle=True) on a time series leaks the future. Use TimeSeriesSplit.
  • Choose models with a backtest; look at the holdout once.