A time series is a sequence of values in time order. Order matters: the past can explain the future, never the reverse. This page covers the pandas date tools, decomposition, the statsmodels tests and models, lag features for machine learning, time-aware validation and forecast metrics. The examples use the daily visits in data/web_traffic.csv and the 10-minute readings in data/sensors.csv. The blocks share one session:
pd.set_option( "display.width" , 100 )
pd.set_option( "display.max_columns" , 12 )
pd.set_option( "display.precision" , 3 )
traffic = pd.read_csv( "data/web_traffic.csv" , parse_dates = [ "date" ], index_col = "date" )
traffic = traffic.asfreq( "D" ) # a fixed daily frequency; missing days become NaN rows
y = traffic[ "visits" ].interpolate( "time" ) # fill the 5 blank days
sensors = pd.read_csv( "data/sensors.csv" , parse_dates = [ "timestamp" ])
print (y.index.freqstr, len (y), int (traffic[ "visits" ].isna().sum()), len (sensors))
I want to…
Use…
Notes
parse dates while reading
pd.read_csv(path, parse_dates=["date"], index_col="date")
a DatetimeIndex
parse a text column
pd.to_datetime(s, format="%Y-%m-%d")
explicit format is faster and safer
calendar parts of a column
s.dt.year, s.dt.month, s.dt.day_of_week, s.dt.hour
Monday = 0
calendar parts of an index
idx.month, idx.day_of_week, idx.day_name()
no .dt
round timestamps
s.dt.floor("h"), s.dt.normalize()
normalize = midnight
attach and convert a time zone
s.dt.tz_localize("UTC").dt.tz_convert("Europe/Berlin")
select a month or a year
df.loc["2024-02"], df.loc["2023"]
sorted index needed
select a date range
df.loc["2024-12-01":"2024-12-07"]
both ends included
fix the frequency, expose gaps
df.asfreq("D")
missing dates become NaN
all dates in a range
pd.date_range("2024-01-01", periods=7, freq="D")
find missing dates
full_range.difference(df.index)
downsample a flow (counts, money)
df.resample("W").sum()
downsample a level (temperature, rate)
df.resample("h").mean()
resample several series in a long table
df.groupby("id").resample("h", on="ts")[cols].mean()
or pivot first
fill a short gap
s.interpolate("time", limit=3)
smooth series
carry the last state forward
s.ffill()
prices, settings
a value k steps back
s.shift(k)
rows, not days
change from k steps back
s.diff(k), s.pct_change(k)
a trailing mean as a feature
s.shift(1).rolling(7).mean()
no leak
an exponentially weighted mean
s.ewm(span=7).mean()
recent values weigh more
trend + seasonal + remainder
STL(y, period=7, robust=True).fit()
statsmodels
test for a unit root
adfuller(y, result_object=True).pvalue
H0: not stationary
test for stationarity
kpss(y, regression="c", result_object=True)
H0: stationary
autocorrelation values
acf(y, nlags=28, result_object=True), pacf(y, nlags=28)
alpha=0.05 adds bands
ACF and PACF plots
plot_acf(y, lags=28, ax=ax), plot_pacf(...)
statsmodels.graphics.tsaplots
fit seasonal ARIMA
SARIMAX(y, order=(p, d, q), seasonal_order=(P, D, Q, s))
.fit(disp=False, maxiter=200)
check the fit converged
res.mle_retvals["converged"]
a forecast with an interval
res.get_forecast(h).summary_frame(alpha=0.05)
a known future input
SARIMAX(y, exog=X), then res.forecast(h, exog=X_future)
a time-aware CV splitter
TimeSeriesSplit(n_splits=5, test_size=h, gap=0)
never shuffle
a baseline to beat
seasonal naive: np.resize(train.iloc[-m:], h)
a scale-free error
MASE: MAE ÷ in-sample seasonal naive MAE
stamps = pd.Series(pd.to_datetime([ "2024-03-08 14:35" , "2024-03-10 09:05" ],
format = "%Y-%m- %d %H:%M" ))
"day" : stamps.dt.day_name(),
"dow" : stamps.dt.day_of_week, # Monday = 0
"floor_h" : stamps.dt.floor( "h" ),
"berlin" : stamps.dt.tz_localize( "UTC" ).dt.tz_convert( "Europe/Berlin" ),
print (stamps.diff().iloc[ 1 ], (stamps.iloc[ 1 ] - pd.Timedelta( days = 28 )).date())
print (y.loc[ "2024-12-30" :].to_string()) # both ends included
day dow hour floor_h berlin
0 Friday 4 14 2024-03-08 14:00:00 2024-03-08 15:35:00+01:00
1 Sunday 6 9 2024-03-10 09:00:00 2024-03-10 10:05:00+01:00
1 days 18:30:00 2024-02-11
Offset alias
Meaning
Removed in pandas 3
"s", "min", "10min"
seconds, minutes
"S", "T"
"h"
hours
"H"
"D", "B"
calendar days, business days
"W" (= "W-SUN"), "W-MON"
weeks ending Sunday / Monday
"MS", "ME"
month start, month end
"M"
"QS", "QE"
quarter start, quarter end
"Q"
"YS", "YE"
year start, year end
"Y", "A"
Tool
Does
idx.is_monotonic_increasing, idx.is_unique
sorted and unique dates?
df.sort_index()
sort before slicing by date
s.shift(1, freq="D")
moves the index, not the values
pd.Timedelta(days=7), pd.DateOffset(months=1)
fixed length / calendar-aware steps
s.dt.day_of_week
not dt.weekday or dt.dayofweek (deprecated in pandas 3.1)
weekly = traffic.resample( "W" ).agg({ "visits" : "sum" , "bounce_rate" : "mean" })
n_days = traffic[ "visits" ].resample( "W" ).size()
print (n_days.iloc[[ 0 , - 1 ]].to_string()) # partial bins at both ends
temp = sensors.pivot( index = "timestamp" , columns = "sensor_id" , values = "temperature_c" )
print (temp.resample( "D" ).agg([ "min" , "max" ]).iloc[: 2 , : 4 ]) # level: min / max
feat = pd.DataFrame({ "y" : y, "ma7" : y.rolling( 7 ).mean(),
"ma7_lagged" : y.shift( 1 ).rolling( 7 ).mean(),
"ewm7" : y.ewm( span = 7 , adjust = False ).mean()})
print (feat.iloc[ 6 : 8 ].round( 1 ))
2024-05-01 19.13 24.96 21.29 38.03
2024-05-02 18.98 36.03 21.35 44.89
2022-01-07 3155.0 3324.1 NaN 3289.5
2022-01-08 2912.0 3351.9 3324.1 3195.1
Column type
Examples
Downsample
Upsample
flow
sales, visits, spend
sum
split the value over the new periods
level
temperature, price, rate
mean, median, min, max
ffill or interpolate
stock
inventory, balance
last
ffill
Window
Code
Note
trailing mean
s.rolling(7).mean()
includes the current row
feature-safe trailing mean
s.shift(1).rolling(7).mean()
only the past
centered mean
s.rolling(7, center=True).mean()
plots only: uses the future
time-based window
s.rolling("7D").mean()
irregular timestamps
allow short windows
s.rolling(7, min_periods=1)
no leading NaN
running total or mean
s.expanding().mean(), s.cumsum()
exponential weights
s.ewm(span=7).mean(), ewm(halflife="3D", times=idx)
per group
df.groupby("id")["x"].transform(lambda g: g.shift(1).rolling(7).mean())
no leak across groups
from statsmodels.tsa.seasonal import STL
stl = STL(np.log(y), period = 7 , robust = True ).fit() # log: multiplicative effects
weekday = np.exp(stl.seasonal.groupby(y.index.day_of_week).mean())
print (weekday.round( 3 ).to_dict()) # factor per weekday, Monday = 0
strength = 1 - stl.resid.var() / (stl.seasonal + stl.resid).var()
print ( f "weekly strength {max ( 0 , strength) :.2f } " )
{0: 1.067, 1: 1.095, 2: 1.067, 3: 1.028, 4: 0.96, 5: 0.868, 6: 0.937}
Tool
Use
STL(y, period=7, robust=True)
robust to outliers; any period; .trend, .seasonal, .resid
STL(np.log(y), period=7)
multiplicative seasonality through the log
seasonal_decompose(y, period=7, model="multiplicative")
classical; NaN at both ends
MSTL(y, periods=(7, 365))
several seasonal periods
stl.plot(), then plt.show()
data, trend, seasonal and remainder panels
Seasonal strength F S = max ( 0 , 1 − Var ( R ) / Var ( S + R ) ) F_S = \max(0, 1 - \text{Var}(R) / \text{Var}(S + R)) F S = max ( 0 , 1 − Var ( R ) / Var ( S + R )) : near 1 is strong.
A stationary series has a constant mean and variance and a correlation that depends only on the lag. ARIMA needs one; differencing (diff) often gives one.
from statsmodels.tsa.stattools import adfuller, kpss
for name, s, reg in [( "level, c" , y, "c" ), ( "level, ct" , y, "ct" ),
( "diff, c" , y.diff().dropna(), "c" )]:
res = adfuller(s, regression = reg, result_object = True ) # named fields
print ( f "ADF { name :<10 } stat= { res.statistic :7.2f } p= { res.pvalue :.2g } " )
res = kpss(y.loc[ "2024" ], regression = "ct" , nlags = "auto" , result_object = True )
print ( f "KPSS 2024, ct stat= { res.statistic :.3f } p= { res.pvalue :.3f } " ,
res.critical_values[ "5%" ])
ADF level, c stat= -2.51 p=0.11
ADF level, ct stat= -5.29 p=5.8e-05
ADF diff, c stat= -10.89 p=1.2e-19
KPSS 2024, ct stat=0.204 p=0.014 0.146
Test
H0
p below 0.05 means
regression
adfuller
unit root (not stationary)
stationary
"c" constant, "ct" trend, "n" none
kpss
stationary
not stationary
"c" level, "ct" trend
ADF (H0: unit root)
KPSS (H0: stationary)
Read as
rejects
does not reject
stationary
does not reject
rejects
unit root: difference
rejects with "ct" only
does not reject with "ct"
trend-stationary: detrend or add a trend
rejects
rejects
the tests disagree: a break, a near unit root or a short window; difference or model the trend, then check the residuals
does not reject
does not reject
too little data to tell
Here the tests disagree. ADF with "ct" rejects a unit root, but KPSS with "ct" on 2024 rejects trend stationarity (0.204 is above the 5% critical value 0.146). This is common on a short window. Difference or model the trend, then check the residuals.
kpss p-values come from a table between 0.01 and 0.1. Outside it, kpss warns InterpolationWarning and the p-value is only a bound. Compare statistic with critical_values instead.
from statsmodels.tsa.stattools import acf, pacf
ac = acf(d, nlags = 14 , alpha = 0.05 , result_object = True ) # named fields
r, ci = ac.acf, ac.confint # ci is centered on r
pr, pci = pacf(d, nlags = 14 , alpha = 0.05 )
print ( "ACF " , r[lags].round( 3 ), "band" , (ci[lags, 1 ] - r[lags]).round( 3 ))
print ( "PACF" , pr[lags].round( 3 ), "band" , (pci[lags, 1 ] - pr[lags]).round( 3 ))
ACF [-0.012 0.178 0.213] band [0.059 0.065 0.069]
PACF [-0.012 0.034 0.068] band [0.059 0.059 0.059]
The ACF band uses Bartlett’s formula: it widens with the lag, because it allows for the correlation at earlier lags. The PACF band is flat at about ± 1.96 / n \pm 1.96/\sqrt{n} ± 1.96/ n . The plots draw the bands around 0; a bar outside the band is significant.
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 lag p, ACF decays
AR(p)
ACF cuts off after lag q, PACF decays
MA(q)
negative spike at lag s after a seasonal difference
seasonal MA(1): Q = 1
all bars inside the band
white noise: nothing left to model
from statsmodels.tsa.statespace.sarimax import SARIMAX
train, test = y.iloc[: - h], y.iloc[ - h:] # split by position, never shuffle
model = SARIMAX(np.log(train), order = ( 1 , 1 , 1 ), seasonal_order = ( 0 , 1 , 1 , 7 ))
res = model.fit( disp = False , maxiter = 200 ) # the default maxiter=50 may not converge
print (res.mle_retvals[ "converged" ], round (res.aic, 1 ))
print (res.params.round( 3 ).to_dict())
frame = np.exp(res.get_forecast(h).summary_frame( alpha = 0.05 )) # "mean" is now a median
print (frame[[ "mean" , "mean_ci_lower" , "mean_ci_upper" ]].iloc[: 2 ].round( 0 ))
sarima_fc = frame[ "mean" ].to_numpy()
{'ar.L1': 0.742, 'ma.L1': -0.979, 'ma.S.L7': -0.994, 'sigma2': 0.01}
visits mean mean_ci_lower mean_ci_upper
2024-12-04 7900.0 6468.0 9651.0
2024-12-05 7344.0 5710.0 9447.0
Both MA terms are near −1, which the Gotchas below list as a sign of over-differencing. Here the differences remove a trend and a weekly pattern that are almost fixed. The forecast still beats the baselines (see the metrics below), but estimates at the edge of −1 are unstable, and the intervals are less reliable. A usual alternative is day-of-week dummies as exog with d=1, D=0. After np.exp, the mean column of a log model is the median forecast, not the mean.
Template with a known future input (exogenous variable):
res = SARIMAX(y_train, exog = X_train, order = ( 1 , 1 , 1 ), seasonal_order = ( 0 , 1 , 1 , 7 ),
trend = "n" ).fit( disp = False , maxiter = 200 )
if not res.mle_retvals[ "converged" ]: # simplify the model, log y or raise maxiter
raise RuntimeError ( "SARIMAX did not converge" )
fc = res.get_forecast( steps = h, exog = X_future) # X_future must be known in advance
print (fc.summary_frame( alpha = 0.05 ))
print (res.summary()) # coefficients, Ljung-Box and other residual tests
Part
Meaning
Choose with
d
non-seasonal differences
ADF / KPSS; usually 0 or 1
D, s
seasonal differences at period s
STL strength, ACF at s
p, P
AR lags
PACF cut-off
q, Q
MA lags
ACF cut-off
trend="c"
drift (with d = 0: a constant)
comparing models
lowest res.aic
same d and D only
residual check
res.plot_diagnostics(), acorr_ljungbox(res.resid, lags=[14])
s = pd.Series([ 10.0 , 12.0 , 14.0 , 13.0 , 15.0 , 17.0 ],
index = pd.date_range( "2024-01-01" , periods = 6 , freq = "D" ))
"lag_1" : s.shift( 1 ), # yesterday
"mean_3" : s.shift( 1 ).rolling( 3 ).mean(), # last 3 days, today excluded
"dow" : s.index.day_of_week, # known in advance
print (lagged.dropna().shape) # rows with a full history
2024-01-01 10.0 NaN NaN NaN 0
2024-01-02 12.0 10.0 NaN NaN 1
2024-01-03 14.0 12.0 10.0 NaN 2
2024-01-04 13.0 14.0 12.0 12.0 3
2024-01-05 15.0 13.0 14.0 13.0 4
2024-01-06 17.0 15.0 13.0 14.0 5
Rule
Why
every lag ≥ the forecast horizon (direct strategy)
at forecast time, lags under h are not known yet
shift before rolling, expanding, ewm
the window must end before the target row
calendar, holidays, planned promotions
known in advance: safe
weather, competitor prices
future values unknown: use lags or forecasts
per series: groupby("id")[col].shift(k)
a plain shift crosses into the previous series
trees cannot extrapolate a trend
model np.log(y), diff or a ratio to a recent level
asfreq before shift
shift(7) is 7 rows; equal to 7 days only on a regular index
from sklearn.model_selection import TimeSeriesSplit
tss = TimeSeriesSplit( n_splits = 3 , test_size = 2 , gap = 1 ) # gap: skipped rows
for fold, (tr, te) in enumerate (tss.split(np.arange( 12 )), start = 1 ):
print (fold, "train" , tr.min(), "to" , tr.max(), "| test" , te.tolist())
1 train 0 to 4 | test [6, 7]
2 train 0 to 6 | test [8, 9]
3 train 0 to 8 | test [10, 11]
Argument
Effect
n_splits
number of folds; train always ends before test
test_size
length of each test window: set it to the horizon
gap
rows dropped between train and test: data delay, or lags shorter than h
max_train_size
cap the train length: a sliding instead of an expanding window
cross_val_score(model, X, y, cv=tss)
works with any scikit-learn model
The rows must be in time order. One row per time step; for several series in one table, split on the unique dates.
from sklearn.metrics import (
mean_absolute_percentage_error,
def mase (actual, forecast, history, m = 7 ):
hist = np.asarray(history)
scale = np.mean(np.abs(hist[m:] - hist[: - m])) # in-sample seasonal naive MAE
return mean_absolute_error(actual, forecast) / scale
"naive" : np.repeat(train.iloc[ - 1 ], h), # last value
"seasonal naive" : np.resize(train.iloc[ - 7 :].to_numpy(), h), # last week
"mean" : np.repeat(train.iloc[ - h:].mean(), h), # last 4 weeks
name: { "MAE" : mean_absolute_error(test, fc),
"RMSE" : root_mean_squared_error(test, fc),
"MAPE %" : 100 * mean_absolute_percentage_error(test, fc),
"MASE" : mase(test, fc, train)}
for name, fc in forecasts.items()
naive 1750.14 1925.24 27.62 3.07
seasonal naive 837.64 1000.71 13.12 1.47
mean 731.52 850.87 11.36 1.28
SARIMA 430.74 546.18 6.38 0.76
Metric
Formula
Use
MAE
1 n ∑ ∣ y − y ^ ∣ \frac{1}{n}\sum \lvert y - \hat y \rvert n 1 ∑ ∣ y − y ^ ∣
the data’s unit; robust
RMSE
1 n ∑ ( y − y ^ ) 2 \sqrt{\frac{1}{n}\sum (y - \hat y)^2} n 1 ∑ ( y − y ^ ) 2
big errors weigh more
MAPE
100 n ∑ ∣ ( y − y ^ ) / y ∣ \frac{100}{n}\sum \lvert (y - \hat y)/y \rvert n 100 ∑ ∣( y − y ^ ) / y ∣
breaks at 0; scikit-learn returns a fraction
sMAPE
100 n ∑ 2 ∣ y − y ^ ∣ ∣ y ∣ + ∣ y ^ ∣ \frac{100}{n}\sum \frac{2\lvert y - \hat y \rvert}{\lvert y \rvert + \lvert \hat y \rvert} n 100 ∑ ∣ y ∣ + ∣ y ^ ∣ 2 ∣ y − y ^ ∣
0 to 200
MASE
MAE ÷ in-sample seasonal naive MAE
scale-free; below 1 beats the naive
interval coverage
((lo <= y) & (y <= hi)).mean()
should be near the nominal 95%
Baseline
Forecast
When it is hard to beat
naive
the last value
random walks, prices
seasonal naive
the same day last season
strong seasonality
mean / drift
a recent mean, or a line through the first and last points
stable or trending series
Report every model next to a baseline. A model that does not beat the seasonal naive is not ready.
Trap
Symptom
Fix
no parse_dates
y.loc["2024"] raises KeyError; the index holds strings
parse_dates= or pd.to_datetime
old offset aliases
ValueError for "M", "H", "T", "Q", "Y" in pandas 3
"ME"/"MS", "h", "min", "QE", "YE"
dt.weekday, dt.dayofweek
Pandas4Warning
dt.day_of_week
index.inferred_freq
Pandas4Warning
asfreq("D") sets the frequency; read index.freqstr
partial "W" bins
the first and last weekly sums are too small
count rows per bin with .size(); drop partial bins
shift(7) on an irregular index
lags of the wrong date
asfreq first, or shift(7, freq="D")
rolling(7).mean() as a feature
leakage: the window includes the target
shift(1).rolling(7).mean()
bfill() or interpolation at the end
values from the future
ffill() at the forecast origin
ADF without result_object=True
FutureWarning (statsmodels 0.15)
adfuller(y, result_object=True)
KPSS without result_object=True
FutureWarning
kpss(y, result_object=True)
acf(..., alpha=0.05) without result_object=True
FutureWarning about a plain tuple
acf(..., result_object=True); read .acf, .confint
reading the ADF p-value backwards
“p < 0.05, so it has a trend”
ADF H0 is non-stationary: a small p supports stationarity
SARIMAX with the default maxiter=50
ConvergenceWarning
fit(maxiter=200), check mle_retvals["converged"]
MA coefficient near −1
over-differencing, or an almost fixed trend or season
drop one difference, use trend="c", or model the season with exog dummies
model on np.log(y)
forecasts in log units
np.exp the forecast and the interval
exog= at fit only
forecast raises: exog needed
pass future exog that is known in advance
KFold(shuffle=True) or train_test_split
optimistic scores: the future leaks into training
TimeSeriesSplit or a split by position
tuning on the holdout
the final score is optimistic
backtest with TimeSeriesSplit; look at the holdout once
MAPE with zeros
inf or huge values
MAE or MASE