Time-Series Forecasting in ML: Trend, Seasonality, Lag Features & Walk-Forward CV
How to turn sequential timestamps into tabular ML features (lags, rolling means, cyclical dates), avoid future leakage, and validate with Walk-Forward splits
Time-Series Forecasting predicts future values (sales, traffic, energy load) from chronologically ordered history by decomposing Trend + Seasonality and engineering Lag & Rolling features for GBDT or statistical models (ARIMA).
Standard random train/test splits leak future days into the past — giving fake 98% offline accuracy that collapses immediately when predicting tomorrow.
Demand forecasting, cloud capacity planning, and dynamic pricing are among the highest-ROI ML systems in retail, logistics, and fintech.
Forgetting .shift(1) before .rolling(7).mean() leaks today's target y_t right into today's feature — the #1 bug in time-series pipelines!
Global LightGBM models trained across thousands of products with lag + calendar + promo features consistently outperform per-series ARIMA.
Guaranteed question: 'Why is random K-Fold illegal for time-series, and how do you engineer features for a 7-day-ahead forecast without leakage?'
Why do we encode hour_of_day (0–23) using sin(2π·h/24) and cos(2π·h/24) for Linear/Neural models instead of a raw integer 0–23?
- Decompose any time series into Trend, Seasonality, and Residual Noise.
- Engineer leak-free Lag features (
y_{t-1}, y_{t-7}), shifted Rolling statistics, and Cyclical sin/cos calendar features. - Validate strictly with Expanding-Window or Sliding-Window Walk-Forward Cross-Validation.
- Always benchmark against the Seasonal Naive baseline (
ŷ_t = y_{t-7}) before claiming ML adds value.
Turning a time series into tabular ML is super clean once you obey one iron law: every feature for timestamp may ONLY look at timestamps strictly before your forecast horizon (shift(horizon)), and validation MUST march forward in time (Walk-Forward CV).
1. The 3 Essential Time-Series Feature Families
- Lags:
y.shift(1),y.shift(7),y.shift(28)(always your forecast horizon!). - Shifted Rolling Windows:
y.shift(1).rolling(7).mean()and.std()— notice the mandatory.shift(1)BEFORE.rolling()! - Calendar & Exogenous Signals:
day_of_week,is_holiday,sin/cos(month), plus known future events like scheduled promotions.
2. ARIMA vs. Global GBDT (LightGBM)
- ARIMA / Exponential Smoothing: Great for a single short, clean, univariate series with strong linear autocorrelation.
- Global LightGBM / CatBoost: Trains ONE model across 10,000 SKUs simultaneously, naturally absorbing promotions, prices, holidays, and cross-product patterns!
The exact honest questions almost every beginner wonders — answered in plain English without hiding behind jargon.
Decision trees only output averages of training-set leaf values, so they cannot predict higher than the max historical value! Fix: forecast differenced targets (), detrend first with Linear Regression, or use linear-tree hybrids.
Watch the Walk-Forward Expanding Window Advance Strictly Forward in Time
Compare Random K-Fold (future leakage!) vs. Expanding Walk-Forward CV across Months 1–12
.shift() before computing rolling windows, benchmark against Seasonal Naive, evaluate with Walk-Forward CV, and detrend/difference when using tree models on strong trends.import numpy as np
# Leak-Free Lag + Shifted Rolling Mean + Walk-Forward Expanding Evaluation
sales = np.array([100, 110, 105, 115, 120, 125, 130, 135, 142, 148], dtype=float)
# Build features for t >= 3 using ONLY past observations (t-1, t-2, t-3)
rows = []
for t in range(3, len(sales)):
lag1 = sales[t - 1]
roll3 = sales[t - 3:t].mean() # strictly excludes sales[t]!
rows.append((t, lag1, roll3, sales[t]))
# Compare Seasonal/Persistence Naive (y_hat = y_{t-1}) vs. Rolling Mean
naive_mae = float(np.mean([abs(y - lag1) for _, lag1, _, y in rows]))
roll_mae = float(np.mean([abs(y - r3) for _, _, r3, y in rows]))
print(f"Leak-free features built for {len(rows)} steps | Naive MAE={naive_mae:.2f} | Roll3 MAE={roll_mae:.2f}")
df['y'].rolling(7).mean() without .shift(1) first.y_t inside the feature — instant target leakage!