Loading...
Loading...
Decompose time series into trend, seasonal, and residual components. Compare additive and multiplicative models with interactive visualization.
import pandas as pd
import numpy as np
from statsmodels.tsa.seasonal import seasonal_decompose, STL
import matplotlib.pyplot as plt
# Data
data = pd.Series([200, 220, 250, 280, 210, 230, 260, 290, 220, 240, 270, 300, 230, 250, 280, 310, 240, 260, 290, 320])
# Classical Decomposition
result = seasonal_decompose(data, model='additive', period=4)
print("Trend (first 10):", result.trend.dropna().values[:10].round(2))
print("Seasonal pattern:", result.seasonal.values[:4].round(4))
print("Residual std:", result.resid.dropna().std().round(4))
# Plot decomposition
fig = result.plot()
fig.set_size_inches(12, 8)
plt.suptitle('Additive Seasonal Decomposition (period=4)')
plt.tight_layout()
plt.show()
# STL Decomposition (more robust)
stl = STL(data, period=4, robust=True).fit()
fig_stl = stl.plot()
fig_stl.set_size_inches(12, 8)
plt.suptitle('STL Decomposition (period=4)')
plt.tight_layout()
plt.show()
# Strength of components
trend_strength = max(0, 1 - stl.resid.var() / (stl.trend.var() + stl.resid.var()))
season_strength = max(0, 1 - stl.resid.var() / (stl.seasonal.var() + stl.resid.var()))
print(f"\nTrend strength: {trend_strength:.4f}")
print(f"Seasonal strength: {season_strength:.4f}")Seasonal decomposition breaks a time series into three components: Trend (long-term direction), Seasonal (repeating patterns), and Residual (random noise). This helps understand what drives the data and improves forecasting.
Additive: when seasonal fluctuations are constant regardless of level (Y = T + S + R). Multiplicative: when seasonal swings grow proportionally with the series level (Y = T × S × R). If the seasonal amplitude increases over time, use multiplicative.
STL (Seasonal and Trend decomposition using LOESS) is a more robust method than classical decomposition. It uses local regression (LOESS) to estimate trend and seasonal components, handling outliers better and allowing the seasonal pattern to change over time.
The period depends on your data frequency: monthly data with yearly seasonality → period=12, quarterly → period=4, daily with weekly patterns → period=7, hourly with daily patterns → period=24. Use ACF plots to confirm the period.
Residuals should ideally be random noise (white noise) - no patterns or autocorrelation. If residuals show patterns, the decomposition has missed some systematic component, or you may need a different model or period.