BLOG

Behind the numbers.

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

Are Consumer Staples Margins Shrinking Under Inflation? Gross Margin Trend Analysis in Python
Do Weak Jobs Reports Predict Market Drawdowns? NFP Surprise Event Study in Python
Is the Rotation From Tech to Industrials Backed by Earnings? Relative EPS Growth Analysis in Python
Is the Semiconductor Rally Broadening Beyond NVIDIA? Return Dispersion Analysis in Python
Which Stocks Benefit Most When Oil Prices Fall? Oil Beta Screening in Python
Do Bond Returns Predict Stock Returns? Granger Causality Test in Python
Which Stocks Actually Drive Portfolio Returns? Shapley Value Attribution in Python
Does "Sell in May" Still Work? Calendar Anomaly Backtest in Python
How to Build Complete Price History Through Ticker Changes? Entity Resolution in Python
Are KO and PEP Cointegrated? Pairs Trading Signal Construction in Python
Which Commodities Have the Strongest Momentum? Rotation Backtest in Python
Which Commodity ETFs Have the Worst Tail Risk? Expected Shortfall in Python
Are Gold Miners Leveraged Gold Bets? Rolling Beta Analysis in Python
Does the Base-Metals-to-Gold Ratio Lead Cyclical Stocks? Signal Test in Python
Can Risk Parity Tame Commodity Volatility? Portfolio Optimization in Python
Are Power Stocks Becoming an AI Infrastructure Trade? Momentum Screening in Python
Which AI Chip Stocks Have Margin Momentum? Profitability Trend Analysis in Python
Which AI Stocks Are Cheapest Relative to Growth? Growth-Adjusted Valuation in Python
Does AI Stock Leadership Persist? Momentum Backtest in Python
Which AI Stocks Have the Cleanest Balance Sheets? Net Cash Screening in Python
Can Risk Parity Reduce Mega-Cap Drawdowns? Portfolio Optimization in Python
Which Growth Stocks Are Self-Funding? Cash-Flow Quality Screening in Python
Which Sectors Struggle When the Dollar Rallies? Sector Rotation Analysis in Python
Do Cheap Stocks Hold Up When Bonds Sell Off? Valuation Rotation in Python
Does the Nasdaq 100 Have Better Growth Quality Than the Dow? Index Constituent Analysis in Python
Do Healthcare Cash-Flow Margins Predict Returns? Signal Evaluation in Python
Which Dividend Stocks Survive a Cash-Flow Stress Test? Dividend Screening in Python
Does Heavy Insider Selling Predict Weak Returns? Insider Flow Test in Python
Can Quality Screens Reduce Small-Cap Balance-Sheet Risk? Russell 2000 Test in Python
Which Retailers Have Positive Operating Leverage? Margin Screening in Python
Is MSTR a Leveraged Bitcoin Proxy? Rolling Beta Analysis in Python
Is Micron's Memory Cycle Recovering? Inventory and Margin Forecasting in Python
Which Sectors Work When Bonds Rally? Rate-Sensitive Rotation in Python
Do One-Month Price Extremes Reverse? Signal Evaluation in Python
Do Low-Volatility S&P 500 Stocks Reduce Drawdowns? Factor Test in Python
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 Consumer Staples Margins Shrinking Under Inflation? Gross Margin Trend Analysis in Python

What's the question?

Consumer staples companies are often described as inflation hedges. The logic: people still buy toothpaste, cereal, and soft drinks regardless of price levels, so these firms can pass cost increases through to consumers. If that assumption holds, gross margins should remain stable even when input costs rise.

CPI has remained above 4% year-over-year through mid-2026, the highest sustained inflation since the early 2020s. At the same time, commodity prices for key inputs — cocoa, coffee, sugar, packaging materials — have moved sharply higher. PepsiCo recently reported US volume weakness, suggesting consumers are beginning to resist price increases.

The question is whether the “pricing power” narrative is actually holding in the data. If gross margins are compressing, it means companies are absorbing input cost increases rather than passing them through. If margins are stable, pricing power is intact. If they are expanding, companies have been raising prices faster than their costs are rising.

The approach

The analysis compares two periods for 10 consumer staples companies: a pre-inflation baseline (2019 through 2021) and the most recent four quarters of reported results.

  1. Pull quarterly fundamentals for PEP, KO, PG, CL, WMT, COST, MDLZ, GIS, KHC, and SJM covering the last 7 years
  2. Compute gross margin as (revenue minus cost of revenue) divided by revenue for each quarter
  3. Average gross margin over the 2019-2021 pre-inflation baseline (approximately 12 quarters per company)
  4. Average gross margin over the trailing four quarters
  5. Rank companies by margin change in percentage points

The ticker set spans beverage companies (PEP, KO), household products (PG, CL), grocery retailers (WMT, COST), and packaged food (MDLZ, GIS, KHC, SJM). This diversity exposes which categories have commodity exposure that overwhelms pricing power.

Code

import xfinlink as xfl
import pandas as pd

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

tickers = ["PEP", "KO", "PG", "CL", "WMT", "COST", "MDLZ", "GIS", "KHC", "SJM"]

df = xfl.fundamentals(
    tickers, period_type="quarterly", period="7y",
    fields=["revenue", "cost_of_revenue"]
)

df["gross_margin"] = (df["revenue"] - df["cost_of_revenue"]) / df["revenue"]

pre = df[(df["period_end"] >= "2019-01-01") & (df["period_end"] <= "2021-12-31")]
pre_avg = pre.groupby("ticker")["gross_margin"].mean()

latest = df.sort_values("period_end").groupby("ticker").tail(4)
lat_avg = latest.groupby("ticker")["gross_margin"].mean()

result = pd.DataFrame({
    "Pre-Inflation GM": pre_avg, "Latest GM": lat_avg
}).dropna()
result["Change (pp)"] = (result["Latest GM"] - result["Pre-Inflation GM"]) * 100
result = result.sort_values("Change (pp)")

for t, row in result.iterrows():
    print(f"{t:<6} {row['Pre-Inflation GM']*100:5.1f}% -> {row['Latest GM']*100:5.1f}%  "
          f"{row['Change (pp)']:+5.1f}pp")

Full script with formatting and visualisation: consumer-staples-margin-inflation-python.py

Output

Horizontal bar chart showing gross margin change for 10 consumer staples stocks comparing pre-inflation baseline to latest four quarters, with MDLZ and SJM showing significant compression
Ticker  Pre GM  Lat GM  GM Chg  Pre OM  Lat OM  OM Chg
--------------------------------------------------------
MDLZ     39.4%   28.9%  -10.5pp   14.9%    9.4%   -5.5pp
SJM      38.5%   33.3%   -5.2pp   16.2%   10.1%   -6.1pp
GIS      34.9%   33.5%   -1.4pp   17.1%   15.5%   -1.6pp
COST     13.3%   12.9%   -0.4pp    3.4%    3.8%   +0.4pp
PEP      54.4%   54.2%   -0.2pp   14.5%   12.9%   -1.6pp
PG       50.4%   50.3%   -0.1pp   23.2%   23.2%   -0.0pp
WMT      24.3%   24.2%   -0.1pp    4.3%    4.2%   -0.1pp
CL       60.1%   60.1%   -0.0pp   21.6%   15.4%   -6.2pp
KHC      33.7%   33.9%   +0.2pp   11.5%   16.7%   +5.3pp
KO       61.1%   61.7%   +0.6pp   27.9%   29.2%   +1.3pp

What this tells us

The sector is not experiencing uniform margin compression. Instead, the data reveals a clear split driven by commodity input exposure.

Mondelez (MDLZ) stands out with a 10.5 percentage point gross margin decline, falling from 39.4% to 28.9%. This is the cocoa effect. Cocoa futures roughly tripled between late 2023 and mid-2026, and Mondelez — whose portfolio includes Cadbury, Milka, and Toblerone — has the highest direct cocoa exposure among large-cap consumer staples. JM Smucker (SJM) lost 5.2 percentage points, reflecting elevated coffee bean prices that pressure its Folgers and Dunkin’ branded products.

General Mills (GIS) shows a modest 1.4 percentage point decline. Its commodity basket is more diversified — wheat, corn, sugar, dairy — which dilutes the impact of any single input price spike.

The remaining seven companies show gross margin changes within half a percentage point of zero. Coca-Cola (KO) actually expanded margins by 0.6 percentage points, reaching 61.7%. This reflects KO’s concentrate-based business model, where bottling partners absorb a significant share of input cost volatility. PG, CL, PEP, WMT, and COST all maintained margins within 0.2 percentage points of their pre-inflation levels, confirming that broad pricing power in household goods, beverages, and grocery retail has held.

Operating margins tell a somewhat different story. Colgate-Palmolive (CL) maintained its 60.1% gross margin perfectly but lost 6.2 percentage points of operating margin, suggesting that rising costs are appearing in SG&A (marketing, distribution, and labor) rather than in cost of goods sold.

So what?

The “consumer staples as inflation hedge” narrative is partially correct, but treating the sector as monolithic is a mistake. Of the 10 companies tested, only two — MDLZ and SJM — experienced gross margin compression exceeding 1 percentage point. Both have concentrated exposure to specific commodities (cocoa and coffee) that have experienced extreme price moves.

For portfolio construction, the data suggests differentiating between commodity-specific risk and broad inflation risk. A basket of PG, KO, CL, and WMT has delivered near-zero gross margin erosion through four years of elevated inflation. MDLZ and SJM, while still profitable, are absorbing costs that may take multiple quarters to recover through pricing.

The practical screen is straightforward: compute the trailing-4-quarter gross margin versus a pre-shock baseline. Companies with compression exceeding 2 percentage points warrant closer analysis of their input cost exposure before being treated as defensive holdings.

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

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