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

Do Oil Stocks Hedge Inflation? Rolling Beta Analysis in Python

What’s the question?

The conventional wisdom is that oil stocks are natural inflation hedges — when consumer prices rise, energy companies benefit from higher commodity prices, and their stock returns should compensate for the erosion of purchasing power. If true, the regression beta of oil stock returns against CPI changes should be positive and statistically significant. This article tests whether that claim holds across three major integrated oil companies over 8 years of data.

The approach

Pull monthly CPI (CPIAUCSL) from FRED and monthly returns for XOM, CVX, COP from xfinlink. Run OLS regression of stock returns on CPI month-over-month changes. Compute rolling 24-month betas to test stability.

import xfinlink as xfl
import pandas as pd
import numpy as np
from fredapi import Fred
from scipy import stats

xfl.api_key = "YOUR_API_KEY"  # free at https://xfinlink.com/signup
fred = Fred(api_key=os.environ["FRED_API_KEY"])

# Monthly CPI
cpi = fred.get_series("CPIAUCSL", observation_start="2018-01-01")
cpi_mom = cpi.pct_change().dropna().rename("cpi_change")
cpi_mom.index = cpi_mom.index.to_period("M")

# Monthly stock returns
tickers = ["XOM", "CVX", "COP"]
df = xfl.prices(tickers, start="2018-01-01", fields=["close"])
df["date"] = pd.to_datetime(df["date"])
monthly = df.groupby(["ticker", df["date"].dt.to_period("M")])["close"].last()
returns = monthly.groupby("ticker").pct_change().dropna().rename("ret")
returns = returns.reset_index()

# OLS regression per ticker
for t in tickers:
    tr = returns[returns["ticker"] == t].set_index("date")["ret"]
    merged = pd.concat([tr, cpi_mom], axis=1).dropna()
    slope, intercept, r, p, se = stats.linregress(merged["cpi_change"], merged["ret"])
    # Rolling 24-month beta significance
    rolling_p = merged.rolling(24).apply(
        lambda w: stats.linregress(w.iloc[:, 0], w.iloc[:, 1]).pvalue, raw=False
    )
    sig_pct = (rolling_p["ret"] < 0.10).mean() * 100
    print(f"{t}: full_beta={slope:+.2f} (p={p:.3f}, R²={r**2:.3f}) | sig at 10%: {sig_pct:.0f}%")

Full script with formatting and visualisation: oil-inflation-hedge-beta-python.py

Output:

Rolling 24-month inflation beta for XOM CVX COP with significance shading
XOM: full_beta=+4.40 (p=0.156, R²=0.021) | rolling median=+2.75, sig at 10%: 14%
CVX: full_beta=+1.91 (p=0.532, R²=0.004) | rolling median=+0.65, sig at 10%: 5%
COP: full_beta=+2.90 (p=0.453, R²=0.006) | rolling median=+0.41, sig at 10%: 5%

Conclusion: inflation betas are UNSTABLE

What this tells us

All three betas are positive — the direction is correct. But none are statistically significant at conventional levels (p = 0.16, 0.53, 0.45). R² values are near zero (0.4-2.1%), meaning CPI changes explain almost none of the variation in oil stock returns. The rolling analysis reveals the real problem: XOM’s beta is significant at the 10% level in only 14% of rolling windows. CVX and COP are significant in only 5%. The inflation hedge property is not just weak — it is unreliable. It appears and disappears depending on the estimation window.

So what?

Oil stocks may provide an indirect hedge against inflation over very long horizons (decades), but they are not reliable hedges at the portfolio-construction timescale (1-3 years). The monthly R² of 2% means 98% of oil stock return variation comes from factors other than consumer prices — supply shocks, OPEC decisions, geopolitical risk, and general equity market movements. Investors seeking explicit inflation protection should consider TIPS, commodities futures, or inflation swaps rather than relying on oil equity exposure.

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