How to Perform Seasonal Decomposition of Time Series in Python

How to Perform Seasonal Decomposition of Time Series in Python

Seasonal decomposition helps you understand time series data by breaking it into parts. This process makes it easier to see patterns, like long-term changes and repeating cycles. We will study about seasonal decomposition of time series data using python in this article.

Key Components of Seasonal Decomposition

When you perform seasonal decomposition on a time series, the data is split into three main parts: Trend, Seasonality, and Residuals. Understanding these parts helps you analyze the patterns and behavior of the time series.

Trend

The trend shows the long-term direction of the data over time. It indicates if the data is mostly going up, down, or staying the same. This helps to see the overall path the data is taking.

Seasonality

Seasonality captures patterns that repeat at regular intervals, like daily, monthly, or yearly cycles. These patterns are tied to specific times and show the effect of recurring events.

Residual

Residuals, or noise, are the random changes in the data that don’t follow a pattern. They include unexpected fluctuations and help to spot any unusual or outlying points in the data.

Implementing Seasonal Decomposition in Python

In Python, you can use the statsmodels library to perform seasonal decomposition. Here’s how you can do it:

 

Import Libraries

Firstly, you must import the necessary libraries:

import pandas as pd
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose

Load and Prepare Your Data

Load your time series data into a pandas DataFrame. Ensure your data has a datetime index or column.

# Sample time series data
np.random.seed(0) 

# Define time range
dates = pd.date_range(start='2020-01-01', periods=120, freq='M') 

# Create trend component: Linear trend with a slope
trend = np.linspace(start=10, stop=100, num=len(dates))

# Create seasonal component: Sine wave for yearly seasonality
seasonal = 10 * np.sin(np.linspace(0, 2 * np.pi, len(dates)))

# Add random noise
noise = np.random.normal(loc=0, scale=5, size=len(dates))

# Combine components to form the time series
values = trend + seasonal + noise

# Create DataFrame
df = pd.DataFrame({'Date': dates, 'Value': values})
df.set_index('Date', inplace=True)

df.head()

Dataset

Perform Seasonal Decomposition

You can use the ‘seasonal_decompose’ function from the ‘statsmodels’ library to break down your time series data into three parts: trend, seasonality, and residuals.

# Perform seasonal decomposition
result = seasonal_decompose(df['Value'], model='additive')

# Extract components
trend = result.trend
seasonal = result.seasonal
residual = result.resid

Plot the Decomposed Components

Visualize the decomposed components to understand the trends, seasonality, and residuals.

# Plotting the decomposed components
plt.figure(figsize=(12, 8))

plt.subplot(4, 1, 1)
plt.plot(df['Value'], label='Original Data')
plt.legend(loc='upper left')
plt.title('Original Time Series')

plt.subplot(4, 1, 2)
plt.plot(trend, label='Trend', color='orange')
plt.legend(loc='upper left')
plt.title('Trend Component')

plt.subplot(4, 1, 3)
plt.plot(seasonal, label='Seasonal', color='green')
plt.legend(loc='upper left')
plt.title('Seasonal Component')

plt.subplot(4, 1, 4)
plt.plot(residual, label='Residual', color='red')
plt.legend(loc='upper left')
plt.title('Residual Component')

plt.tight_layout()
plt.show()

Plot

This code generates a figure with four subplots. Each shows a different component of the time series data:

  1. Original Time Series: The first subplot displays the entire original time series data. It shows the raw and unprocessed data over time.
  2. Trend Component: The second subplot shows the long-term movement or trend in the data. It highlights the overall direction (upward, downward, or stable) over time.
  3. Seasonal Component: Seasonality in time series data shows regular patterns that repeat over time. These patterns repeat at regular times, like every day, month, or year.
  4. Residual Component: The final subplot displays the residuals. They represent the random noise or variability left after removing the trend and seasonality from the original data.

Conclusion

Seasonal decomposition makes time series data easier to understand. It splits the data into trend, seasonality, and residuals. This helps you see patterns and make better forecasts.

Leave a Reply

Your email address will not be published. Required fields are marked *