liveBook · Manning

Seasonal_decompose

As explained in Outlier Detection in Python

seasonal_decompose is a statsmodels function that decomposes a time series into trend, seasonal, and residual components.

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

How Outlier Detection in Python covers it

How deep it goes
Explains returned components, LOESS trend estimation, period selection, and interpretation, but does not derive the decomposition mathematically.
Examples
Uses synthetic sine-wave data with an upward trend, noise, a 365-day period, and regular ten-second spikes.
What it assumes
Assumes a time series with a known or chosen seasonal period and awareness that special events can distort comparisons.
What you can do after
Diagnose/debug with it by plotting components and inspecting residuals for unexplained patterns or extreme values.
How it connects
Connects time-series decomposition with trend, seasonality, residuals, outliers, smoothing, and special events.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Outlier Detection in Python. The section links point to the parts of the book it draws on.