Of course! Here is a comprehensive guide and Python code to reveal seasonality in a time series, specifically designed to handle non-stationary data.
Understanding Seasonality and Non-Stationarity
- Seasonality: A repeating, predictable pattern in a time series that occurs at regular intervals. For example, retail sales are often higher in the fourth quarter (holiday season) every year. This interval is known as the seasonal period (e.g., 12 for monthly data with yearly seasonality).
- Non-Stationary Series: A time series whose statistical properties (like mean and variance) change over time. A common cause of non-stationarity is a trend (a long-term increase or decrease in the data).
The challenge is that a strong trend can mask or distort the underlying seasonality. Therefore, we need methods that can separate these components.
Key Methods to Reveal Seasonality
We will use a combination of visual and statistical methods. Using multiple techniques provides a more robust conclusion.
- Visual Inspection (Time Series Plot): The simplest first step. Sometimes seasonality is obvious.
- Seasonal Decomposition: The most powerful method. It breaks down the time series into three components:
- Trend: The long-term direction of the series.
- Seasonal: The repeating, periodic patterns.
- Residual: The random noise or remainder left over after removing the trend and seasonal components.
- Seasonal Subseries Plot: This plot groups the data by season (e.g., by month) and plots the data for each season side-by-side. This makes it very easy to see if a consistent pattern emerges across the years.
- Boxplots by Season: These show the distribution of values for each seasonal period (e.g., for every January, every February, etc.). A repeating pattern in the medians and spreads across the boxes is a strong indicator of seasonality.
- Autocorrelation Function (ACF) Plot: The ACF plot shows the correlation of the series with its own lagged values. For seasonal data, we will see significant spikes at lags corresponding to the seasonal period (e.g., at lags 12, 24, 36 for monthly data).
Python Implementation
This code is structured into a reusable function that performs all the analyses. We'll first generate a sample non-stationary time series with clear seasonality to demonstrate the techniques.
1. Setup and Imports
First, ensure you have the necessary libraries installed:
pip install pandas numpy matplotlib seaborn statsmodels
2. The Code
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.graphics.tsaplots import plot_acf
# Set some default styles for our plots
plt.style.use('seaborn-v0_8-whitegrid')
sns.set_context('notebook')
def generate_sample_series(start_date='2018-01-01', periods=60, freq='M'):
"""
Generates a sample non-stationary time series with a clear trend and seasonality.
"""
# Create a date range
dates = pd.date_range(start=start_date, periods=periods, freq=freq)
# 1. Trend component (linear upward trend)
trend = np.linspace(0, 20, periods)
# 2. Seasonal component (sine wave for yearly seasonality)
# The period is 12 for monthly frequency
seasonal_period = 12
seasonal = 10 * np.sin(2 * np.pi * np.arange(periods) / seasonal_period)
# 3. Residual component (random noise)
noise = np.random.normal(0, 2, periods)
# Combine the components: Y = Trend + Seasonal + Noise
# This creates an additive model
data = 50 + trend + seasonal + noise
# Create a pandas Series with a DatetimeIndex
series = pd.Series(data, index=dates, name='Sales')
print("--- Sample Time Series Generated ---")
print("This series has a linear trend, yearly seasonality, and random noise.\n")
return series
def analyze_seasonality(series, seasonal_period):
"""
Analyzes and visualizes seasonality in a time series using multiple methods.
Args:
series (pd.Series): The time series to analyze. Must have a DatetimeIndex.
seasonal_period (int): The number of periods in a season (e.g., 12 for monthly,
4 for quarterly).
"""
if not isinstance(series.index, pd.DatetimeIndex):
raise ValueError("Input series must have a DatetimeIndex.")
print(f"--- Starting Seasonality Analysis (Period = {seasonal_period}) ---\n")
# --- Method 1: Basic Time Series Plot ---
print("--- 1. Visual Inspection: Time Series Plot ---")
plt.figure(figsize=(12, 6))
series.plot()
plt.title('Time Series Plot')
plt.xlabel('Date')
plt.ylabel('Value')
plt.show()
print("Interpretation: Look for repeating patterns. A clear trend might obscure the seasonality.\n")
# --- Method 2: Seasonal Decomposition ---
# The `seasonal_decompose` function separates the series into trend, seasonal, and residual components.
# For non-stationary series, this is the most effective way to view seasonality.
# We use 'additive' model if seasonal fluctuations are constant size,
# and 'multiplicative' if they are proportional to the trend. Let's assume additive.
print("--- 2. Statistical Method: Seasonal Decomposition ---")
decomposition = seasonal_decompose(series, model='additive', period=seasonal_period)
fig = decomposition.plot()
fig.set_size_inches(12, 8)
fig.suptitle('Seasonal Decomposition', y=0.95)
plt.show()
print("Interpretation: The 'Seasonal' component plot is the key. If it shows a regular, repeating pattern, seasonality is present.\n")
# --- Method 3: Seasonal Subseries Plot ---
print("--- 3. Visual Inspection: Seasonal Subseries Plot ---")
df = pd.DataFrame({'value': series})
df['year'] = series.index.year
# Determine the seasonal grouping (e.g., month, quarter)
if seasonal_period == 12:
df['season'] = series.index.month
season_label = 'Month'
elif seasonal_period == 4:
df['season'] = series.index.quarter
season_label = 'Quarter'
else:
# For other periods, we just use a generic number
df['season'] = (series.index.to_period('D').day_of_year - 1) % seasonal_period + 1
season_label = 'Seasonal Period'
plt.figure(figsize=(12, 6))
sns.lineplot(data=df, x='season', y='value', hue='year', palette='viridis', marker='o')
plt.title('Seasonal Subseries Plot')
plt.xlabel(season_label)
plt.ylabel('Value')
plt.legend(title='Year', bbox_to_anchor=(1.05, 1), loc='upper left')
plt.tight_layout()
plt.show()
print("Interpretation: Each line represents a year. If the lines follow a similar pattern, it confirms seasonality.\n")
# --- Method 4: Boxplots by Seasonal Period ---
print("--- 4. Visual Inspection: Boxplots by Season ---")
plt.figure(figsize=(12, 6))
sns.boxplot(data=df, x='season', y='value', palette='pastel')
plt.title(f'Distribution of Values by {season_label}')
plt.xlabel(season_label)
plt.ylabel('Value')
plt.show()
print(f"Interpretation: Look for a repeating pattern in the medians (the line inside the boxes) across the {season_label}s. A clear up-and-down pattern indicates seasonality.\n")
# --- Method 5: Autocorrelation Function (ACF) Plot ---
print("--- 5. Statistical Method: Autocorrelation (ACF) Plot ---")
plt.figure(figsize=(12, 6))
plot_acf(series, lags=seasonal_period * 2) # Show at least two full seasonal cycles
plt.title('Autocorrelation Function (ACF)')
plt.xlabel('Lag')
plt.ylabel('Correlation')
plt.show()
print(f"Interpretation: Strong seasonality results in significant spikes at lags corresponding to the seasonal period. Look for high peaks at lags {seasonal_period}, {seasonal_period*2}, etc. The blue shaded area is the confidence interval; spikes outside this area are statistically significant.\n")
if __name__ == '__main__':
# Generate a sample series with monthly data (seasonal period = 12)
# The series will have 60 data points (5 years of monthly data)
my_series = generate_sample_series(start_date='2019-01-01', periods=60, freq='M')
# Analyze the series for seasonality
# We know the seasonal period is 12 because the data is monthly and seasonality is yearly.
analyze_seasonality(my_series, seasonal_period=12)
How to Interpret the Output
When you run the code, it will generate a series of plots. Here's what to look for in each one using the sample data as an example:
- Time Series Plot: You will see a clear upward trend. The seasonal ups and downs are visible but might be hard to isolate from the trend just by looking.
- Seasonal Decomposition: This is the most revealing plot.
Observed: The original data.
Trend: A smooth line showing the upward trend.
Seasonal: This is the critical part. You will see a perfectly repeating sine wave. This is the isolated seasonal pattern. This confirms strong seasonality.
Resid: The random noise. It should look like random static with no clear pattern.
- Seasonal Subseries Plot: You will see five lines (one for each year). All five lines will follow the same general shape (dipping in the middle of the year and peaking at the beginning/end), confirming the seasonal pattern is consistent year after year.
- Boxplots by Season: You'll see 12 boxplots, one for each month. The median line in the boxes will form a repeating "U" or "V" shape, showing that certain months are consistently higher or lower than others.
- ACF Plot: You will see a tall, significant spike at lag 12, and another one at lag 24. This is a very strong statistical sign that the data repeats its pattern every 12 periods (i.e., yearly seasonality).
By using all these methods together, you can confidently identify and characterize the seasonality in your time series, even when a strong trend is present.