ADF Test in Time Series Python: What It Is and How to Use
ADF test (Augmented Dickey-Fuller test) in Python is a statistical test used to check if a time series is stationary, meaning its properties do not change over time. It helps decide if differencing or other transformations are needed before modeling time series data.How It Works
The ADF test checks if a time series has a unit root, which means it shows trends or patterns that change over time. Imagine watching the temperature every day: if it keeps rising or falling, it is not stationary. The ADF test tries to find out if such trends exist.
It does this by fitting a simple model that predicts the current value based on past values and checks if the series tends to return to a constant mean or drifts away. If it returns, the series is stationary; if it drifts, it is not.
Think of it like checking if a ball in a bowl settles at the bottom (stationary) or keeps rolling away (non-stationary).
Example
This example shows how to run the ADF test on a sample time series using Python's statsmodels library and interpret the results.
import numpy as np import pandas as pd from statsmodels.tsa.stattools import adfuller # Create a non-stationary time series (random walk) np.random.seed(0) random_walk = np.cumsum(np.random.normal(size=100)) time_series = pd.Series(random_walk) # Run ADF test result = adfuller(time_series) print(f"ADF Statistic: {result[0]:.4f}") print(f"p-value: {result[1]:.4f}") print("Critical Values:") for key, value in result[4].items(): print(f" {key}: {value:.4f}")
When to Use
Use the ADF test when you want to check if your time series data is stationary before applying models like ARIMA or other forecasting methods. Stationarity is important because many models assume the data's behavior does not change over time.
For example, if you analyze sales data that grows over time, the ADF test can tell you if you need to remove trends or seasonality first. It is commonly used in finance, weather forecasting, and any field involving time-based data.
Key Points
- The ADF test checks if a time series is stationary by testing for a unit root.
- A low p-value (usually below 0.05) means the series is stationary.
- It helps decide if data needs transformation before modeling.
- Implemented in Python via
statsmodels.tsa.stattools.adfuller.