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$:
When engineering rolling features for predicting time $t$, always call .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:
4# Plot Autocorrelation Function (ACF) up to 30 lags
5fig, ax = plt.subplots(figsize=(10,4))
6plot_acf(df['sales'].dropna(), lags=30, ax=ax)
7plt.title("Autocorrelation Function (ACF)")
8plt.show()
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$).
1from statsmodels.tsa.stattools import adfuller
2
3defcheck_stationarity(series):
4 result = adfuller(series.dropna())
5 adf_statistic = result[0]
6 p_value = result[1]
7print(f"ADF Statistic: {adf_statistic:.4f}")
8print(f"p-value: {p_value:.4f}")
9
10if p_value <0.05:
11print(">> Reject H0: Series IS STATIONARY (Ready for modeling)")
12else:
13print(">> Fail to reject H0: Series is NON-STATIONARY (Differencing needed)")
14
15check_stationarity(df['sales'])
5. Achieving Stationarity: Differencing (.diff())
If a series is non-stationary, apply first-order differencing ($Delta Y_t = Y_t - Y_{t-1}$):
1# 1st order differencing to remove trend
2df['sales_diff']= df['sales'].diff(1)
3check_stationarity(df['sales_diff'])
Interactive Quiz• Knowledge Check
Practice Quiz
Question 1
In time series feature engineering, what error occurs if you compute df['sales'].rolling(7).mean() without shifting by 1 period before forecasting $t$?
Question 2
In the Augmented Dickey-Fuller (ADF) test, what does a $p$-value of 0.012 indicate?
Question 3
Which Pandas method creates a lag feature representing the value from 7 periods ago?
Question 4
What does a significant positive spike at lag 12 in a monthly sales ACF plot signify?
Question 5
How does first-order differencing ($Delta Y_t = Y_t - Y_{t-1}$) help stabilize a non-stationary series?
Next Lesson
Exponential Smoothing & Moving Average Baseline Models
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Test your understanding of this lesson with 5 questions. Each question has one correct answer.
12-Month Data Analysis Mastery Program
Master Full-Stack Data Analytics (Excel, SQL, Python, Power BI & Tableau)
Combine 15 complete courses, 150 chapters, 541 topics, live SQL/Power BI/Tableau dashboards, and Scikit-Learn capstones at MSK Institute Shikohabad or Live Online.