Lag Features, Autocorrelation & Stationarity Checks
Lag Features, Autocorrelation & Stationarity Checks
Machine learning algorithms (such as XGBoost, Random Forest, or Ridge Regression) do not naturally understand chronological sequence order. To enable supervised learning models to forecast future timestamps, data analysts engineer lag features and rolling statistics, while validating stationarity using statistical tests like the Augmented Dickey-Fuller (ADF) test.
1. Creating Lag Features with .shift()
A lag feature takes the value of a metric at time $t-k$ and maps it to the current row at time $t$:
.shift(1) before .rolling(). Otherwise, the target observation at time $t$ will leak into the rolling feature!2. Autocorrelation & The ACF Plot
Autocorrelation measures the correlation of a time series with its own past lagged values:
- If lag 7 exhibits a tall vertical bar breaching the blue confidence band, the data has strong weekly autocorrelation.
3. What is Stationarity and Why Does it Matter?
A time series is stationary if its statistical properties (mean, variance, and covariance) do not change over time:
- Non-Stationary: Series with an upward trend or changing volatility. Models trained on non-stationary data fail to generalize because past distributions differ from future distributions.
- Stationary: Series oscillating around a constant mean with constant variance.
4. Testing Stationarity: Augmented Dickey-Fuller (ADF) Test
The ADF hypothesis test evaluates whether a unit root is present:
- $H_0$ (Null Hypothesis): Series is Non-Stationary (has unit root).
- $H_1$ (Alternative Hypothesis): Series is Stationary ($p$-value $< 0.05$).
5. Achieving Stationarity: Differencing (.diff())
If a series is non-stationary, apply first-order differencing ($Delta Y_t = Y_t - Y_{t-1}$):
Multiple Choice Questions
df['sales'].rolling(7).mean() without shifting by 1 period before forecasting $t$?Exponential Smoothing & Moving Average Baseline Models
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Trend, Seasonality & Residual Decomposition | Exponential Smoothing & Moving Average Baseline Models |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.