Finding multi-seasonality patterns in a large number of potentially non-stationary time series programmatically requires a robust approach, as visual inspection is out of the question.
The most common and effective techniques involve:
- Differencing/Detrending: To achieve stationarity (or closer to it), which helps in identifying periodic patterns more clearly.
- Autocorrelation Function (ACF): Peaks in the ACF indicate potential seasonal lags.
- Spectral Analysis (Fourier Transform / Periodogram): This method directly analyzes the frequency components of the time series, allowing you to identify dominant periodicities. It's often more robust for discovering multiple, potentially subtle, seasonalities than just looking at ACF peaks.
Given your constraints ("too many time series", "non-stationary"), spectral analysis is generally preferred as it's less sensitive to noise and can highlight multiple periods more clearly.
Here's a Python code structure that combines these ideas:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import periodogram, find_peaks
from statsmodels.tsa.stattools import acf
import warnings
# Suppress potential warnings from statmodels or scipy for very short/flat series
warnings.filterwarnings("ignore", category=RuntimeWarning)
warnings.filterwarnings("ignore", category=UserWarning)
def _preprocess_series(series: pd.Series, diff_order: int = 1, apply_log_transform: bool = False) -> pd.Series:
"""
Applies differencing and/or log transform to a time series to help with stationarity.
"""
s = series.copy().dropna()
if s.empty:
return pd.Series([], dtype=float)
if apply_log_transform:
if (s <= 0).any():
print(f"Warning: Skipping log transform for series (contains non-positive values).")
return pd.Series([], dtype=float) # Indicate failure for log transform
s = np.log(s)
for _ in range(diff_order):
s = s.diff().dropna()
if s.empty or s.std() == 0:
return pd.Series([], dtype=float) # Series became flat or too short after differencing
return s
def _detect_seasonality_spectral(
series: pd.Series,
top_n_peaks: int = 3,
min_period: float = 2.0, # Minimum period to consider (e.g., 2 samples)
max_period_ratio: float = 0.5, # Max period as a ratio of series length (e.g., 0.5 * len(series))
peak_prominence_threshold: float = 0.1, # Relative prominence threshold for peaks
peak_distance_ratio: float = 0.05, # Minimum distance between peaks as ratio of max_period_len
round_periods: bool = True
) -> list:
"""
Detects seasonality using spectral analysis (Periodogram).
Returns a list of detected periods.
"""
if series.empty or series.std() == 0:
return []
# Compute the periodogram
# fs is the sampling frequency, 1.0 implies 1 sample per unit time
frequencies, powers = periodogram(series, fs=1.0)
# Convert frequencies to periods (period = 1 / frequency)
# Exclude DC component (freq=0) and Nyquist frequency (freq=0.5)
non_zero_freq_indices = np.where(frequencies > 0)[0]
if len(non_zero_freq_indices) == 0:
return []
frequencies = frequencies[non_zero_freq_indices]
powers = powers[non_zero_freq_indices]
periods = 1.0 / frequencies
# Filter periods based on min_period and max_period_ratio
max_period_len = len(series) * max_period_ratio
valid_indices = np.where((periods >= min_period) & (periods <= max_period_len))[0]
if len(valid_indices) == 0:
return []
periods = periods[valid_indices]
powers = powers[valid_indices]
if len(periods) == 0:
return []
# Normalize powers for prominence threshold
normalized_powers = powers / np.max(powers) if np.max(powers) > 0 else powers
# Find peaks in the power spectrum
# prominence helps filter out minor fluctuations
# distance ensures peaks are not too close (e.g., a seasonality and its harmonic)
min_peak_distance = max(1, int(peak_distance_ratio * len(periods))) # Ensure at least 1
peak_indices, _ = find_peaks(
normalized_powers,
height=peak_prominence_threshold, # Minimum height of peak
distance=min_peak_distance # Minimum horizontal distance between peaks
)
detected_periods = []
if len(peak_indices) > 0:
# Sort by power in descending order and select top_n_peaks
sorted_peak_indices = peak_indices[np.argsort(powers[peak_indices])[::-1]]
for i in sorted_peak_indices[:top_n_peaks]:
p = periods[i]
if round_periods:
p = round(p)
detected_periods.append(p)
# Remove duplicates and sort
detected_periods = sorted(list(set(detected_periods)))
return detected_periods
def _detect_seasonality_acf(
series: pd.Series,
max_lag: int,
peak_threshold_acf: float = 0.2, # Minimum correlation value for a peak
top_n_lags: int = 3,
min_period: float = 2.0, # Minimum period to consider (e.g., 2 samples)
round_periods: bool = True
) -> list:
"""
Detects seasonality using Autocorrelation Function (ACF).
Returns a list of detected periods (lags).
"""
if series.empty or series.std() == 0:
return []
# Ensure max_lag is appropriate for series length
max_lag = min(max_lag, len(series) // 2 - 1) # Rule of thumb: max_lag <= N/2
if max_lag <= 0:
return []
try:
# Compute ACF
# adjusted=True accounts for bias due to finite series length
acf_values = acf(series, nlags=max_lag, adjusted=True)
except ValueError as e:
# This can happen for series with no variance or too short
# print(f"ACF computation failed: {e}")
return []
# Lags start from 0, so we ignore lag 0 (correlation with self)
lags = np.arange(1, len(acf_values))
acf_values = acf_values[1:]
if len(lags) == 0:
return []
# Find peaks in ACF values
# A peak must be above a certain correlation threshold and positive
peak_indices, _ = find_peaks(acf_values, height=peak_threshold_acf)
detected_lags = []
if len(peak_indices) > 0:
# Sort by ACF value in descending order and select top_n_lags
sorted_peak_indices = peak_indices[np.argsort(acf_values[peak_indices])[::-1]]
for i in sorted_peak_indices[:top_n_lags]:
p = lags[i]
if p >= min_period:
if round_periods:
p = round(p)
detected_lags.append(p)
# Remove duplicates and sort
detected_lags = sorted(list(set(detected_lags)))
return detected_lags
def find_multi_seasonality_patterns(
time_series_dict: dict[str, pd.Series],
method: str = 'spectral', # 'spectral' or 'acf'
diff_order: int = 1, # Order of differencing (0 for no diff, 1 for first diff)
apply_log_transform: bool = False, # Apply log transform before differencing
min_series_length: int = 20, # Minimum length of series to analyze
**kwargs
) -> dict[str, list]:
"""
Analyzes multiple time series to find multi-seasonality patterns.
Args:
time_series_dict (dict[str, pd.Series]): A dictionary where keys are series names
and values are pandas Series (time series data).
method (str): The detection method to use: 'spectral' (Periodogram) or 'acf' (Autocorrelation).
diff_order (int): Order of differencing to apply for stationarity.
0: No differencing.
1: First-order differencing (removes linear trend).
2: Second-order differencing.
apply_log_transform (bool): Whether to apply a log transform before differencing.
Useful for stabilizing variance if it increases with the mean.
Requires all values to be positive.
min_series_length (int): Minimum length a series must have to be analyzed.
**kwargs: Additional parameters passed to the chosen detection method:
For 'spectral': top_n_peaks, min_period, max_period_ratio,
peak_prominence_threshold, peak_distance_ratio, round_periods
For 'acf': max_lag, peak_threshold_acf, top_n_lags, min_period, round_periods
Returns:
dict[str, list]: A dictionary where keys are series names and values are
lists of detected seasonal periods.
"""
results = {}
print(f"Starting multi-seasonality analysis using {method} method...")
for name, series in time_series_dict.items():
print(f"\nAnalyzing series: {name}")
if not isinstance(series, pd.Series):
print(f" Skipping (not a pandas Series).")
results[name] = []
continue
if len(series.dropna()) < min_series_length:
print(f" Skipping (length {len(series.dropna())} < min_series_length {min_series_length}).")
results[name] = []
continue
# Preprocess the series
processed_series = _preprocess_series(series, diff_order, apply_log_transform)
if processed_series.empty:
print(f" Skipping (pre-processing resulted in empty or flat series).")
results[name] = []
continue
if processed_series.std() == 0:
print(f" Skipping (pre-processed series is flat).")
results[name] = []
continue
detected_seasonalities = []
if method == 'spectral':
detected_seasonalities = _detect_seasonality_spectral(processed_series, **kwargs)
elif method == 'acf':
# ACF max_lag typically is half the series length
max_lag_acf = kwargs.get('max_lag', min(len(processed_series) // 2 - 1, 100))
if 'max_lag' not in kwargs: kwargs['max_lag'] = max_lag_acf
detected_seasonalities = _detect_seasonality_acf(processed_series, **kwargs)
else:
raise ValueError(f"Unknown method: {method}. Choose 'spectral' or 'acf'.")
results[name] = detected_seasonalities
print(f" Detected seasonalities: {detected_seasonalities}")
return results
# --- Example Usage ---
if __name__ == "__main__":
# 1. Generate Synthetic Data
# Series 1: Daily data with weekly and monthly seasonality, and a trend
np.random.seed(42)
n_days_1 = 365 * 2
time_index_1 = pd.to_datetime(pd.date_range(start='2020-01-01', periods=n_days_1, freq='D'))
trend_1 = np.linspace(0, 50, n_days_1)
weekly_seasonality_1 = 10 * np.sin(np.arange(n_days_1) * (2 * np.pi / 7))
monthly_seasonality_1 = 7 * np.sin(np.arange(n_days_1) * (2 * np.pi / 30.4))
noise_1 = np.random.normal(0, 2, n_days_1)
series_1 = pd.Series(trend_1 + weekly_seasonality_1 + monthly_seasonality_1 + noise_1, index=time_index_1)
# Series 2: Hourly data with daily and weekly seasonality, and increasing variance
n_hours_2 = 24 * 30 * 3 # 3 months of hourly data
time_index_2 = pd.to_datetime(pd.date_range(start='2021-01-01', periods=n_hours_2, freq='H'))
daily_seasonality_2 = 5 * np.sin(np.arange(n_hours_2) * (2 * np.pi / 24))
weekly_seasonality_2 = 3 * np.sin(np.arange(n_hours_2) * (2 * np.pi / (24 * 7)))
noise_2 = np.random.normal(0, 1 + np.arange(n_hours_2) / n_hours_2 * 5, n_hours_2) # Increasing noise
series_2 = pd.Series(100 + daily_seasonality_2 + weekly_seasonality_2 + noise_2, index=time_index_2)
# Series 3: Flat series (should detect nothing)
series_3 = pd.Series(np.ones(100) * 50)
# Series 4: Short series (should be skipped)
series_4 = pd.Series(np.random.rand(15))
# Series 5: With Yearly seasonality
n_days_5 = 365 * 5 # 5 years
time_index_5 = pd.to_datetime(pd.date_range(start='2010-01-01', periods=n_days_5, freq='D'))
trend_5 = np.linspace(10, 60, n_days_5)
yearly_seasonality_5 = 15 * np.sin(np.arange(n_days_5) * (2 * np.pi / 365.25))
noise_5 = np.random.normal(0, 3, n_days_5)
series_5 = pd.Series(trend_5 + yearly_seasonality_5 + noise_5, index=time_index_5)
all_time_series = {
"Series_Daily_Weekly_Monthly": series_1,
"Series_Hourly_Daily_Weekly_Volatile": series_2,
"Series_Flat": series_3,
"Series_Short": series_4,
"Series_Daily_Yearly": series_5
}
print("--- Running Spectral Analysis ---")
spectral_results = find_multi_seasonality_patterns(
all_time_series,
method='spectral',
diff_order=1, # Apply first differencing
apply_log_transform=False, # Series 2 might benefit, but general case might not need
min_series_length=50, # Min length to analyze
top_n_peaks=5, # Look for top 5 dominant seasonalities
min_period=6.0, # Don't consider periods smaller than 6 (e.g., half-day, or very fast fluctuations)
max_period_ratio=0.7, # Max period can be 70% of series length (to avoid trivial results)
peak_prominence_threshold=0.1, # Relative prominence, tune this
peak_distance_ratio=0.03, # Ensures distinct peaks, tune this
round_periods=True
)
print("\nSpectral Analysis Results:")
for name, periods in spectral_results.items():
print(f"{name}: {periods}")
print("\n--- Running ACF Analysis ---")
acf_results = find_multi_seasonality_patterns(
all_time_series,
method='acf',
diff_order=1, # Apply first differencing
apply_log_transform=False,
min_series_length=50,
max_lag=100, # Max lag to check for ACF
peak_threshold_acf=0.2, # Minimum correlation value for a peak
top_n_lags=5, # Look for top 5 lags
min_period=6.0,
round_periods=True
)
print("\nACF Analysis Results:")
for name, periods in acf_results.items():
print(f"{name}: {periods}")
# Optional: Plotting for one series to visually inspect the periodogram/ACF
# Note: For large number of series, this is for debugging/tuning parameters
series_to_plot = all_time_series["Series_Daily_Weekly_Monthly"]
processed_series_plot = _preprocess_series(series_to_plot, diff_order=1)
if not processed_series_plot.empty:
plt.figure(figsize=(15, 6))
# Plot Periodogram
plt.subplot(1, 2, 1)
frequencies, powers = periodogram(processed_series_plot, fs=1.0)
non_zero_freq_indices = np.where(frequencies > 0)[0]
frequencies_plot = frequencies[non_zero_freq_indices]
powers_plot = powers[non_zero_freq_indices]
periods_plot = 1.0 / frequencies_plot
plt.plot(periods_plot, powers_plot)
plt.title(f'Periodogram for Daily_Weekly_Monthly (Processed, diff_order=1)')
plt.xlabel('Period (samples)')
plt.ylabel('Power')
plt.xscale('log') # Log scale for periods helps visualize
plt.grid(True)
# Add detected periods as vertical lines
for p in spectral_results["Series_Daily_Weekly_Monthly"]:
plt.axvline(x=p, color='r', linestyle='--', alpha=0.7, label=f'Detected: {p}')
plt.xlim(1, len(processed_series_plot) / 2) # Limit x-axis to reasonable periods
# Plot ACF
plt.subplot(1, 2, 2)
try:
max_lag_plot = min(len(processed_series_plot) // 2 - 1, 100)
acf_vals = acf(processed_series_plot, nlags=max_lag_plot, adjusted=True)
plt.bar(range(len(acf_vals)), acf_vals)
plt.title(f'ACF for Daily_Weekly_Monthly (Processed, diff_order=1)')
plt.xlabel('Lag (samples)')
plt.ylabel('Autocorrelation')
plt.grid(True)
# Add detected lags as vertical lines
for p in acf_results["Series_Daily_Weekly_Monthly"]:
plt.axvline(x=p, color='r', linestyle='--', alpha=0.7, label=f'Detected: {p}')
except ValueError:
plt.text(0.5, 0.5, 'ACF could not be computed', horizontalalignment='center', verticalalignment='center', transform=plt.gca().transAxes)
plt.tight_layout()
plt.show()
series_to_plot_yearly = all_time_series["Series_Daily_Yearly"]
processed_series_yearly_plot = _preprocess_series(series_to_plot_yearly, diff_order=1)
if not processed_series_yearly_plot.empty:
plt.figure(figsize=(15, 6))
# Plot Periodogram
plt.subplot(1, 2, 1)
frequencies, powers = periodogram(processed_series_yearly_plot, fs=1.0)
non_zero_freq_indices = np.where(frequencies > 0)[0]
frequencies_plot = frequencies[non_zero_freq_indices]
powers_plot = powers[non_zero_freq_indices]
periods_plot = 1.0 / frequencies_plot
plt.plot(periods_plot, powers_plot)
plt.title(f'Periodogram for Daily_Yearly (Processed, diff_order=1)')
plt.xlabel('Period (samples)')
plt.ylabel('Power')
plt.xscale('log') # Log scale for periods helps visualize
plt.grid(True)
# Add detected periods as vertical lines
for p in spectral_results["Series_Daily_Yearly"]:
plt.axvline(x=p, color='r', linestyle='--', alpha=0.7, label=f'Detected: {p}')
plt.xlim(1, len(processed_series_yearly_plot) / 2) # Limit x-axis to reasonable periods
# Plot ACF
plt.subplot(1, 2, 2)
try:
max_lag_plot = min(len(processed_series_yearly_plot) // 2 - 1, 400) # Increased max_lag for yearly
acf_vals = acf(processed_series_yearly_plot, nlags=max_lag_plot, adjusted=True)
plt.bar(range(len(acf_vals)), acf_vals)
plt.title(f'ACF for Daily_Yearly (Processed, diff_order=1)')
plt.xlabel('Lag (samples)')
plt.ylabel('Autocorrelation')
plt.grid(True)
# Add detected lags as vertical lines
for p in acf_results["Series_Daily_Yearly"]:
plt.axvline(x=p, color='r', linestyle='--', alpha=0.7, label=f'Detected: {p}')
except ValueError:
plt.text(0.5, 0.5, 'ACF could not be computed', horizontalalignment='center', verticalalignment='center', transform=plt.gca().transAxes)
plt.tight_layout()
plt.show()
Explanation and Key Concepts:
-
_preprocess_series Function:
dropna(): Essential. Missing values can severely distort statistical calculations.
apply_log_transform: If your time series exhibits increasing variance with increasing mean (common in sales, web traffic), a log transform can stabilize the variance, making seasonal patterns more consistent across the series. It requires all values to be positive.
diff_order:
- Non-stationary time series often have a trend (mean changes over time) or varying variance.
- Differencing (
series.diff()) is a common technique to make a series stationary. A first difference (diff_order=1) removes a linear trend. A second difference (diff_order=2) removes a quadratic trend. For many applications, diff_order=1 is a good starting point.
- Seasonal differencing (e.g.,
series.diff(7) for weekly seasonality in daily data) can also be applied, but for detecting unknown seasonalities, it's usually better to apply standard differencing first, and then let the spectral/ACF analysis find the periods in the stationary residuals.
- Empty/Flat Series Handling: Returns an empty
pd.Series to signal that the series is no longer viable for analysis.
-
_detect_seasonality_spectral Function (Recommended for Multi-Seasonality):
scipy.signal.periodogram: This function computes the Power Spectral Density (PSD) of the time series. Peaks in the PSD indicate dominant frequencies.
fs=1.0: This means a sampling frequency of 1 sample per unit time. So, if your data is daily, fs=1.0 means 1 sample per day.
- Frequencies to Periods: The
periodogram returns frequencies (cycles per sample). We convert these to periods (samples per cycle) using period = 1 / frequency.
- Filtering Periods:
min_period: Ignores very short, often noisy, periods.
max_period_ratio: Ignores periods that are too long relative to the series length. Periods longer than half the series length are often unreliable or represent very slow trends rather than distinct seasonalities.
scipy.signal.find_peaks: Identifies significant peaks in the power spectrum.
How to Tune Parameters:
The effectiveness of these methods heavily depends on parameter tuning:
diff_order: Start with 1. If residuals still look non-stationary after differencing, try 2.
apply_log_transform: Use if variance increases with the mean.
top_n_peaks / top_n_lags: How many seasonalities are you looking for per series?
min_period: What's the smallest meaningful period in your data (e.g., 2 for hourly, 7 for daily)?
max_period_ratio: How long can a seasonality be relative to your series length? Too long (e.g., >0.7) can lead to unreliable results.
peak_prominence_threshold (spectral): This is crucial. Start with 0.1 or 0.05 and adjust. Higher values detect fewer, but stronger, seasonalities. Lower values detect more, potentially including noise.
peak_distance_ratio (spectral): Helps avoid picking up multiple nearby frequencies that relate to the same underlying seasonality.
peak_threshold_acf (ACF): Similar to prominence, this sets the minimum correlation value to consider a peak.
For a very large number of time series, you might run this with default parameters first, then visually inspect a sample of series where the results seem questionable to fine-tune.
This comprehensive approach should give you a good starting point for automatically identifying multi-seasonality patterns across many time series.