Seasonal decomposition in Python
Splitting a series into trend, season and what is left.
import numpy as np
import pandas as pd
from statsmodels.tsa.seasonal import STL, seasonal_decompose
index = pd.date_range("2026-01-01", periods=180, freq="D")
rng = np.random.default_rng(13)
season = 8 * np.sin(2 * np.pi * np.arange(180) / 30)
series = pd.Series(90 + np.arange(180) * 0.05 + season
+ rng.normal(0, 1.5, 180), index=index)
classic = seasonal_decompose(series, period=30)
print(round(float(classic.trend.dropna().iloc[0]), 2))
print(round(float(classic.seasonal.abs().max()), 2))
stl = STL(series, period=30).fit()
print(round(float(stl.resid.std()), 3), round(float(stl.trend.iloc[-1]), 2))
How it works
seasonal_decomposeneeds the period.STLis the more robust, loess-based version.- The residual is what a model still has to explain.
Keywords and builtins used here
asfloatprintround
The run, in numbers
- Lines
- 16
- Characters to type
- 609
- Tokens
- 210
- Three-star pace
- 115 tpm
At the three-star pace of 115 tokens a minute, this run takes about 110 seconds.
Step 3 of 6 in Time series, step 15 of 19 in Statistics with statsmodels.