BLOG

Behind the numbers.

Code examples, market analysis, and data quality deep-dives.

Is AI Capex Paying Back Fast Enough? Revenue Hurdle Forecasting in Python
Could Shorter AI Asset Lives Hit Earnings? Depreciation Stress Test in Python
How Much AI Capex Risk Can a Portfolio Remove? Constrained Optimization in Python
Is the AI Capex Trade Crowded? Rolling Volatility and Sector Rotation in Python
Did the AI Boom Come From Existing S&P 500 Members? Point-in-Time Momentum Test in Python
Is AI Revenue Circular? Customer-Vendor Capex Loop Analysis in Python
Is the AI Trade Connected to Private Credit? Rolling Correlation Network in Python
Is Apollo More Balance-Sheet Sensitive Than Peers? Leverage Screen in Python
Are AI Earnings Supported by Cash Flow? Accrual and Capex Screen in Python
Can Defensive Stocks Hedge AI Drawdowns? Basket Regime Test in Python
How Fast Does the Market Price In Fed Decisions? FOMC Event Study in Python
How Much Are Options Sellers Overpaid? The Variance Risk Premium in Python
Which Companies Have the Worst Earnings Quality? Sloan Accrual Screen with Geographic Revenue Data in Python
Does the Oil-to-Gold Ratio Signal Recessions? XLE/GLD Backtest in Python
Is AI Spending Crowding Out Free Cash Flow? Capex Sustainability Across the Mag 7 in Python
Does a Long Energy / Short Bonds Portfolio Capture Inflation Surprises? Factor Construction in Python
Can a Hidden Markov Model Detect Oil Market Regimes? HMM Analysis in Python
Do Grain Prices Predict Food Inflation? Granger Causality Test in Python
Does the Corporate Credit Spread Predict Stock Market Crashes? BAA-AAA Spread Analysis in Python
Do Oil Stocks Hedge Inflation? Rolling Beta Analysis in Python
Which Stocks Are Most Rate-Sensitive? Equity Duration via Bond Beta in Python
Which Companies Have the Highest Accrual Ratios? Earnings Quality Screening in Python
Is Alpha Persistent or Decaying? Rolling Sharpe Ratio Analysis in Python
Are Markets Trending or Mean-Reverting? Hurst Exponent Analysis in Python
Is Consumer Discretionary vs Staples a Leading Indicator? XLY/XLP Ratio Analysis in Python
Does Heavy Capex Predict Future Stock Returns? Capital Expenditure Analysis in Python
How to Estimate Cost of Equity Using CAPM in Python
Is Volatility Predictable? Testing for Volatility Clustering in Python
Which Industrials Are Overleveraged? Net Debt to EBITDA Screening in Python
GM Before and After Bankruptcy: Why Entity Resolution Matters for Financial Data
What Is Adjusted Beta? Merrill Lynch Beta Shrinkage in Python
How Good Is a Stock Pick? Information Ratio and Tracking Error in Python
Do Stock Returns Follow a Normal Distribution? Testing for Fat Tails in Python
Which Large Caps Have the Highest Free Cash Flow Yield? FCF Screening in Python
Which Sectors Won Over 5 Years? Sector Rotation Analysis in Python
How to Forecast Stock Volatility with GARCH Models in Python
Are Stock Prices Mean-Reverting? Augmented Dickey-Fuller Test in Python
How to Calculate CAPM Alpha and Beta with Regression in Python
How to Compare Sector Sharpe Ratios and Sortino Ratios in Python
DELL: Why Stitching Historical Price Data Together Is Wrong
How to Analyze Drawdown and Recovery for Bank Stocks in Python
How to Screen SaaS Stocks by Revenue Growth and Cash Flow in Python
How to Screen REITs by Dividend Yield and Valuation in Python
How Correlated Are the Magnificent 7? Intra-Group Correlation in Python
AAPL vs XOM: Do Individual Stocks Have Seasonal Patterns?
How to Rank Large-Cap Stocks by Momentum in Python
How to Build a Multi-Endpoint Financial Dashboard in Python
How to Compare Volatility Across Energy Stocks in Python
How to Screen Healthcare Stocks by Valuation in Python
How to Build a Sector Correlation Matrix for Portfolio Diversification in Python
How to Find Oversold and Overbought Stocks Using Z-Scores in Python
How to Measure Earnings Quality: Cash Flow vs Net Income in Python
How to Build a Multi-Factor Stock Screen in Python (Value + Momentum + Quality)
How to Build a Simple DCF Model for Any Stock in Python
How to Screen Tech Stocks by Revenue Growth in Python
How to Screen Stocks by Balance Sheet Health in Python
Is "Sell in May" Real? SPY Monthly Seasonality Over 10 Years
How to Compare Sector Performance YTD Using Python
How to Track S&P 500 Additions and Removals Over Time in Python
How to Screen Dividend Stocks by Yield and Quality in Python
How to Calculate Max Drawdown and Recovery Time for Any Stock in Python
How to Compare Profitability Across Mega-Cap Tech Stocks in Python
Why Ticker Symbols Are Unreliable: The Recycling Problem Every Quant Should Know
How to Calculate and Compare Stock Volatility in Python
How to Screen Blue-Chip Stocks by P/E Ratio in Python
How to Track Companies Through Ticker Changes, Bankruptcies, and Renames in Python
S&P 500 Turnover: How Much the Index Has Changed Since 2010
How to Calculate Stock Beta and Correlation in Python
← All articles

Are Stock Prices Mean-Reverting? Augmented Dickey-Fuller Test in Python

What’s the question?

Mean reversion is the idea that asset prices tend to return to a long-run average over time. A stock that has fallen significantly will eventually recover. A stock that has risen sharply will eventually pull back. Many trading strategies depend on this assumption — pairs trading, Bollinger Band signals, and RSI-based entries all rely on prices reverting to some equilibrium.

The problem is that this assumption may not be correct. If stock prices follow a random walk — where each day’s movement is independent and the series has no tendency to return to any particular level — then mean reversion strategies are attempting to exploit a pattern that does not exist.

The Augmented Dickey-Fuller (ADF) test provides a statistical answer. It tests whether a time series contains a unit root. A unit root indicates that the series is non-stationary: it wanders freely without a fixed mean to return to. If the test rejects the unit root hypothesis (p-value below 0.05), the series is stationary — it fluctuates around a stable average, and mean reversion has a mathematical basis.

The approach

We test 6 stocks across different sectors: AAPL and MSFT (technology), XOM (energy), JNJ (healthcare), NVDA (semiconductors), and PG (consumer staples). Sector diversity is important because mean reversion, if it exists, may appear in defensive sectors but not in high-growth ones.

For each stock, we run the ADF test on two series: raw closing prices and daily returns. This distinction is central. Prices and returns have fundamentally different statistical properties, and confusing the two is one of the most common errors in quantitative strategy design.

import xfinlink as xfl
import pandas as pd
import numpy as np
from statsmodels.tsa.stattools import adfuller

xfl.set_api_key("your_key")  # free at https://xfinlink.com/signup

tickers = ["AAPL", "MSFT", "XOM", "JNJ", "NVDA", "PG"]
df = xfl.prices(tickers, period="1y", fields=["close", "return_daily"])

for ticker in tickers:
    t = df[df["ticker"] == ticker].sort_values("date")
    adf_price = adfuller(t["close"].dropna(), autolag="AIC")
    adf_return = adfuller(t["return_daily"].dropna(), autolag="AIC")
    price_result = "STATIONARY" if adf_price[1] < 0.05 else "UNIT ROOT"
    return_result = "STATIONARY" if adf_return[1] < 0.05 else "UNIT ROOT"
    print(f"{ticker}: price_p={adf_price[1]:.4f} ({price_result}) return_p={adf_return[1]:.4f} ({return_result})")

Output:

=== Augmented Dickey-Fuller Test: Are Stock Prices Mean-Reverting? ===

Ticker   Price ADF   Price p        Result  |  Return ADF  Return p        Result
-------------------------------------------------------------------------------------
AAPL        -0.557    0.8803     UNIT ROOT  |     -14.469    0.0000    STATIONARY
MSFT        -0.753    0.8325     UNIT ROOT  |     -15.126    0.0000    STATIONARY
XOM         -0.491    0.8937     UNIT ROOT  |     -12.008    0.0000    STATIONARY
JNJ         -1.327    0.6168     UNIT ROOT  |     -15.172    0.0000    STATIONARY
NVDA        -1.424    0.5708     UNIT ROOT  |      -9.588    0.0000    STATIONARY
PG          -1.694    0.4340     UNIT ROOT  |     -15.093    0.0000    STATIONARY

Prices stationary:  0/6 (expect 0 — prices follow random walks)
Returns stationary: 6/6 (expect all — returns are i.i.d.)

What this tells us

The results are consistent across every sector. All 6 price series contain unit roots. P-values range from 0.43 (PG) to 0.89 (XOM), none approaching the 0.05 rejection threshold. Stock prices do not mean-revert.

This holds even for PG — Procter & Gamble, the most stable and defensive stock in the sample. If any equity were to exhibit mean-reverting prices, a low-volatility consumer staple would be the most likely candidate. Its p-value of 0.43 confirms that the random walk property is not a function of volatility or sector. It is structural. Markets incorporate available information into prices continuously, so future price movements are driven by new information, which is by definition unpredictable. There is no fixed level for prices to return to.

Daily returns present the opposite result. Every p-value is 0.0000 — strongly stationary. Returns fluctuate around a stable mean near zero. This follows directly from the mathematical relationship between prices and returns. If prices are integrated of order 1 (a random walk), then returns — the first difference of prices — are integrated of order 0 (stationary). Differencing removes the unit root.

This duality is foundational in quantitative finance. Portfolio theory, the Capital Asset Pricing Model, factor models, and options pricing all assume stationary returns, not stationary prices. The ADF test provides empirical verification of this assumption.

So what?

A strategy that buys when price falls below a moving average and sells when it crosses above is implicitly assuming prices are stationary. The evidence above indicates they are not. The strategy may produce occasional gains, but it lacks statistical support.

Mean reversion strategies can be effective, but not on raw prices. The key is to construct derived series that are stationary: the spread between two correlated stocks in a pairs trade, the ratio of a stock’s price to its sector ETF, or the z-score of price relative to a rolling mean. These constructed series can exhibit stationarity, and the ADF test is the standard method for confirming this before committing capital.

Built with xfinlink — free financial data API for Python. pip install xfinlink
← All articles