Chapter 39 of 42 · ~18 min read & lab+65 XP
Chapter 39 · Machine Learning

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

What Is It?

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).

Why Is It Required?

Standard random train/test splits leak future days into the past — giving fake 98% offline accuracy that collapses immediately when predicting tomorrow.

Everyday Analogy: Predicting tomorrow's weather by looking at yesterday's temperature, the 7-day moving average, and the month of the year — never peeking at next Tuesday's newspaper!
Why ML Engineers & Data Scientists Actually Need This

Demand forecasting, cloud capacity planning, and dynamic pricing are among the highest-ROI ML systems in retail, logistics, and fintech.

ML / AI Engineer

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!

Data Scientist

Global LightGBM models trained across thousands of products with lag + calendar + promo features consistently outperform per-series ARIMA.

Interview & Debug Edge

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?'

Step 0 · Test Your Gut Before Any Math!

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?

What You Will Master in This Chapter
  • 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.
Plain-English Symbol Decoder · Click Any Symbol Before We Begin
1 / 2
yt−ky_{t-k}Say aloud:“Lag-k feature”
Plain-English Meaning
The observed value k time steps earlier (e.g., same day last week = y_{t-7}).
Everyday Example
For a 7-day-ahead forecast, the freshest legal lag is y_{t-7}!
Story-First Intuition, Visual Diagrams & Interactive Walkthroughs

Turning a time series into tabular ML is super clean once you obey one iron law: every feature for timestamp tt 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

  1. Lags: y.shift(1), y.shift(7), y.shift(28) (always ≥\ge your forecast horizon!).
  2. Shifted Rolling Windows: y.shift(1).rolling(7).mean() and .std() — notice the mandatory .shift(1) BEFORE .rolling()!
  3. 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!
“Wait, I'm Confused...” · Teacher Office Hours Q&A

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 (Δyt=yt−yt−1\Delta y_t = y_t - y_{t-1}), detrend first with Linear Regression, or use linear-tree hybrids.

Interactive Visual Lab
Lab Challenge: Step through Walk-Forward expanding validation windows without leaking future timestamps.
Interactive Animation • Temporal Validation Discipline

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

M1
M2
M3
M4
M5
M6
M7
M8
M9
M10
M11
M12
0%
Expanding Fold #1/4
Split #1: Train M1–M4 → Validate strictly in the future on M5–M6!
Intuition Takeaway: Always .shift() before computing rolling windows, benchmark against Seasonal Naive, evaluate with Walk-Forward CV, and detrend/difference when using tree models on strong trends.
Production NumPy & PyTorch Code Patterns
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}")
Common ML Interview Traps & Numerical Pitfalls
Trap #1: Using df['y'].rolling(7).mean() without .shift(1) first.
Best Practice: Unshifted rolling windows include today's target y_t inside the feature — instant target leakage!
Chapter Mastery Check (+65 XP)
Score: 0 / 1
1Why do Decision Trees and XGBoost struggle to forecast a time series with a strong continuous upward trend?

Apply What You Learned — Solve Matching Coding Problems