To reveal seasonality in a time series, especially when the series may be non-stationary, we can use a combination of techniques such as decomposition, differencing, and spectral analysis. Below is a Python code that uses the statsmodels and pandas libraries to detect seasonality in a time series.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.tsa.stattools import adfuller
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
# Example time series data (replace this with your own data)
np.random.seed(42)
date_range = pd.date_range(start='2020-01-01', periods=100, freq='D')
data = pd.Series(np.random.randn(100).cumsum() + 5 * np.sin(np.arange(0, 100) * 0.1), index=date_range)
# Check for stationarity using Augmented Dickey-Fuller test
def check_stationarity(series):
result = adfuller(series)
print(f'ADF Statistic: {result[0]}')
print(f'p-value: {result[1]}')
for key, value in result[4].items():
print(f'Critical Value ({key}): {value}')
if result[1] <= 0.05:
print("Reject H0: Series is stationary")
else:
print("Fail to reject H0: Series is non-stationary")
check_stationarity(data)
# If non-stationary, apply differencing
if adfuller(data)[1] > 0.05:
data_diff = data.diff().dropna()
check_stationarity(data_diff)
data_to_decompose = data_diff
else:
data_to_decompose = data
# Seasonal decomposition
decomposition = seasonal_decompose(data_to_decompose, model='additive', period=7) # Adjust period based on your data
trend = decomposition.trend
seasonal = decomposition.seasonal
residual = decomposition.resid
# Plot the decomposition
plt.figure(figsize=(12, 8))
plt.subplot(411)
plt.plot(data, label='Original')
plt.legend(loc='best')
plt.subplot(412)
plt.plot(trend, label='Trend')
plt.legend(loc='best')
plt.subplot(413)
plt.plot(seasonal, label='Seasonal')
plt.legend(loc='best')
plt.subplot(414)
plt.plot(residual, label='Residual')
plt.legend(loc='best')
plt.tight_layout()
plt.show()
# ACF and PACF plots to identify seasonality
plt.figure(figsize=(12, 4))
plot_acf(residual.dropna(), ax=plt.subplot(121), lags=30)
plot_pacf(residual.dropna(), ax=plt.subplot(122), lags=30)
plt.show()
Explanation:
- Stationarity Check: The Augmented Dickey-Fuller (ADF) test is used to check if the series is stationary. If the series is non-stationary, differencing is applied.
- Seasonal Decomposition: The
seasonal_decompose function from statsmodels is used to decompose the series into trend, seasonal, and residual components.
- ACF and PACF Plots: Autocorrelation (ACF) and Partial Autocorrelation (PACF) plots are used to identify any remaining seasonality in the residuals.
Notes:
- Adjust the
period parameter in seasonal_decompose based on the expected seasonality in your data (e.g., 7 for daily data with weekly seasonality, 12 for monthly data with yearly seasonality).
- If the series is non-stationary, differencing is applied before decomposition to make the series stationary.
This code provides a comprehensive approach to detecting seasonality in time series data, even when the series is non-stationary.