Skip to main content

Lesson 7 of 9

Temporal EDA: Seasonality, Autocorrelation & Stationarity

Time-series and sequential data violate the fundamental Independent and Identically Distributed (i.i.d.) assumption of classical machine learning. In temporal datasets, past values predict future values (autocorrelation), seasonal cycles recur across diurnal and weekly intervals, and statistical properties change over time (non-stationarity). Diagnosing trend, seasonality, and stationarity via ADF unit-root tests is essential before building predictive pipelines.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Stationarity Testing, ACF/PACF & Seasonal Decomposition

Stationarity Testing, ACF/PACF & Seasonal Decomposition
import numpy as np
import pandas as pd
from statsmodels.tsa.stattools import adfuller, acf

# Generate a synthetic daily retail demand series with trend and 7-day seasonality
np.random.seed(42)
n_days = 365
dates = pd.date_range('2026-01-01', periods=n_days, freq='D')

trend = np.linspace(100, 300, n_days) # Upward non-stationary drift
day_of_week_pattern = np.array([20, 15, 10, 15, 30, 50, 40]) # Weekend spikes
seasonality = np.tile(day_of_week_pattern, int(np.ceil(n_days / 7)))[:n_days]
noise = np.random.normal(0, 10, n_days)

y_ts = pd.Series(trend + seasonality + noise, index=dates)

# 1. STATIONARITY DIAGNOSTICS: AUGMENTED DICKEY-FULLER (ADF) TEST
# H0: Series possesses a unit root (is non-stationary)
adf_stat, p_val, lags, nobs, crit_vals, _ = adfuller(y_ts)
print("=== AUGMENTED DICKEY-FULLER (ADF) TEST (RAW SERIES) ===")
print(f"ADF Statistic: {adf_stat:.4f} | p-value: {p_val:.4f}")
print(f"Result: {'Non-Stationary (Contains trend/unit root)' if p_val > 0.05 else 'Stationary'}")

# 2. FIRST-ORDER DIFFERENCING TO INDUCE STATIONARITY
y_diff = y_ts.diff().dropna()
adf_stat_diff, p_val_diff, _, _, _, _ = adfuller(y_diff)
print("\n=== ADF TEST AFTER 1ST-ORDER DIFFERENCING ===")
print(f"Differenced ADF Statistic: {adf_stat_diff:.4f} | p-value: {p_val_diff:.4e}")
print(f"Result: {'Stationary' if p_val_diff < 0.05 else 'Non-Stationary'}")

# 3. AUTOCORRELATION FUNCTION (ACF) TO REVEAL SEASONAL LAGS
autocorrs = acf(y_ts, nlags=14)
print("\nAutocorrelation at Key Lags:")
print(f"  Lag 1 (Yesterday)    : {autocorrs[1]:.4f}")
print(f"  Lag 7 (Same weekday) : {autocorrs[7]:.4f} (Strong weekly seasonality confirmed!)")

Pro Tip: Cyclical Sin/Cos Encoding for Periodic Features

Never encode calendar features like `hour_of_day` (0-23) or `month` (1-12) as raw integers. In integer encoding, hour 23 and hour 0 appear 23 units apart despite being adjacent. Transform into trigonometric cyclical components: `sin_h = sin(2*pi*hour/24)` and `cos_h = cos(2*pi*hour/24)` to preserve temporal continuity.

Diagram
Loading diagram…

MlTimeSeriesEDA Visual Representation

Hands-On Challenge: Build a Rolling Trend Decomposer

Implement classical additive time-series decomposition from scratch in Pandas: Compute a 7-day rolling centered mean to isolate the Trend component, subtract the trend to isolate the Detrended series, average by day-of-week to find Seasonality, and subtract both to isolate the Residual noise.

Quick Quiz & Key Concept Checks

Common Pitfall: Random Train-Test Shuffling on Time-Series Data

Applying `train_test_split(shuffle=True)` to time-series data allows future records to leak into the training partition. The model memorizes future trajectories, yielding deceptive test performance that fails completely in real-time deployment. Always use `TimeSeriesSplit`.

Topics in This Module

0/9 done