Skip to main content

Lesson 4 of 9

Time-Series Feature Engineering: Lagged Variables, Rolling Windows & EWMA

When applying supervised machine learning (GBDTs, Random Forests) to sequential or time-series data, temporal patterns must be explicitly converted into tabular features. Feature engineering strategies include: Lagged Variables (y_{t-1}, y_{t-7} capturing past state), Rolling Aggregations (7-day mean, rolling volatility), Exponentially Weighted Moving Averages (EWMA; giving exponentially decaying weight to recency), and Calendar Cyclical Indicators.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Constructing Production Time-Series Feature Windows

Constructing Production Time-Series Feature Windows
import pandas as pd
import numpy as np

# Synthetic daily retail product demand time series
np.random.seed(42)
n_days = 365
dates = pd.date_range('2026-01-01', periods=n_days, freq='D')
base_demand = np.linspace(100, 250, n_days)
weekly_seasonality = np.sin(2 * np.pi * dates.dayofweek / 7.0) * 30
noise = np.random.normal(0, 10, n_days)

df_ts = pd.DataFrame({'date': dates, 'demand': base_demand + weekly_seasonality + noise}).set_index('date')

# 1. LAGGED PREDICTOR VARIABLES (Shifted strictly into the past)
df_ts['lag_1'] = df_ts['demand'].shift(1) # Yesterday's demand
df_ts['lag_7'] = df_ts['demand'].shift(7) # Same weekday last week
df_ts['lag_14'] = df_ts['demand'].shift(14)

# 2. ROLLING WINDOW STATISTICS (Must use closed='left' to prevent current-day leakage!)
# closed='left' calculates rolling statistics using strictly past days [t-7, t-1]
df_ts['rolling_mean_7d'] = df_ts['demand'].shift(1).rolling(window=7).mean()
df_ts['rolling_std_7d'] = df_ts['demand'].shift(1).rolling(window=7).std()

# 3. EXPONENTIALLY WEIGHTED MOVING AVERAGE (EWMA)
# Smooths noise while prioritizing recent demand shocks: y_t = alpha * x_t + (1 - alpha) * y_{t-1}
df_ts['ewma_7d'] = df_ts['demand'].shift(1).ewm(span=7).mean()

# 4. MOMENTUM RATIOS
df_ts['demand_momentum_ratio'] = df_ts['lag_1'] / np.maximum(df_ts['rolling_mean_7d'], 1.0)

# Drop initial rows containing NaN from lag shift
df_ml = df_ts.dropna()

print("=== TIME-SERIES FEATURE STORE READY FOR GBDT ===")
print(df_ml[['demand', 'lag_1', 'lag_7', 'rolling_mean_7d', 'ewma_7d', 'demand_momentum_ratio']].head(4).to_string())

Pro Tip: The `shift(1)` Rule for Rolling Windows

Never calculate rolling statistics on the raw target column directly: `df['demand'].rolling(7).mean()` includes the current day's target `y_t` in the feature, causing instant target leakage! Always shift the series first: `df['demand'].shift(1).rolling(7).mean()`.

Diagram
Loading diagramโ€ฆ

MlTimeSeriesForecasting Visual Representation

Hands-On Challenge: Build Multi-Horizon Lags

Write a function `generate_multi_horizon_features(df, target_col, horizons=[1, 3, 7, 14, 30])` that automatically generates lagged values, rolling means, and rolling standard deviations across all specified horizons.

Quick Quiz & Key Concept Checks

Common Pitfall: Multi-Step Forecasting Leakage

If you need to forecast 7 days into the future, you cannot use `lag_1` (yesterday) as a feature, because at prediction time on Day 0, Day 6's value is not yet known. Ensure lag horizons match your operational forecast lead time.

Topics in This Module

0/9 done