seasonal_decompose separates a time series into trend, seasonal pattern, and residual components. Subtracting trend and seasonality leaves residuals for assessing whether observations are otherwise unusual. section 17.2.3
The function requires a period, such as 365 days. statsmodels estimates the trend with LOESS and returns components that can be analyzed or plotted; residuals are usually the main focus, although trend or seasonal anomalies can also matter. section 17.2.3
Interpret the decomposition cautiously:
- Treat regular cycles as expected structure rather than anomalies; a missing expected spike can itself be anomalous. section 17.2.3
- Consider holidays, maintenance, blackouts, discounts, and other special events before labeling residuals as outliers. section 17.2.3
Listing 17.4 Using statsmodels for time-series decomposition
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
np.random.seed(0)
n_points = 2000
dates = np.array('2005-01-01', dtype=np.datetime64) + np.arange(n_points)
data = 12*np.sin(4 * np.pi * np.arange(n_points)/365) + \
50.0*np.array(range(n_points))/n_points + \
np.random.normal(12, 2, n_points)
df = pd.DataFrame({'Values': data}, index=dates)
result = seasonal_decompose(df, model='additive', period=365)
result.plot()
plt.show()
A concise Python implementation constructs synthetic seasonal data, applies an additive decomposition with a 365-point period, and plots the results. section 17.2.3
