BLOG

Behind the numbers.

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

Which Assets Hedge Inflation Shocks? Macro Factor Betas in Python
Does Covariance Shrinkage Beat the Sample Covariance? Minimum-Variance Portfolios in Python
Do Faster Inventory Turns Mean Thinner Margins? Gross Margin Return on Inventory in Python
SEC EDGAR API vs Fundamentals API: Which to Use
Does Fast Earnings Growth Persist? Rank Correlation Analysis in Python
Split Adjustment Explained: Adjusted Close vs Close
Which Trading Day of the Month Pays Best? Turn-of-the-Month Analysis in Python
Can You Use Yahoo Finance Data Commercially?
How Many Independent Bets Does a Nine-Sector Portfolio Give You? Eigenvalue Analysis in Python
Which Volatility Forecast Wins One Month Ahead? HAR vs EWMA in Python
How Concentrated Are Institutional Equity Portfolios? Form 13F Concentration Analysis in Python
Do Stocks Earn Their Returns Overnight or Intraday? Return Decomposition in Python
When Do Corporate Insiders Actually Trade? Form 4 Timing Analysis in Python
Data Requirements for Backtesting a Trading Strategy
What Is Survivorship Bias in Backtesting?
Do High Dividend Yields Come From Bigger Payouts or Falling Prices? Yield Decomposition in Python
Do Stocks Fall Harder Than They Rise? Downside Beta vs Upside Beta in Python
Does Volatility Targeting Improve Sharpe Ratios? Seven-Asset Backtest in Python
Free Stock Market Data APIs: What You Actually Get
How to Give an LLM Financial Data With an MCP Server
Does Post-Earnings Announcement Drift Survive Real Filing Dates? PEAD Event Study in Python
Do Insider Buying Clusters Predict Returns? Signal Testing in Python
Does the S&P 500 Index Effect Still Exist? Event Study in Python
Are Companies Leaving the S&P 500 Faster Than They Used To? Index Survival Analysis in Python
Does Gross Profitability Predict Stock Returns? Quintile Factor Test in Python
What Growth Rate Is the Market Pricing In? Reverse DCF in Python
Does a Strong Balance Sheet Cushion Drawdowns? Leverage and Downside Risk in Python
Does Ticker Recycling Corrupt a Mean-Reversion Backtest? Entity-Resolved Z-Scores in Python
How Much of a Growth Screen's Backtested Edge Is Survivorship Bias? Point-in-Time Index Testing in Python
Why Do Leveraged ETFs Decay? Measuring Volatility Drag in Python
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 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 Faster Inventory Turns Mean Thinner Margins? Gross Margin Return on Inventory in Python

What's the question?

There are two ways to make money from a warehouse. Sell each item at a wide markup and accept that it sits for months, or take a narrow markup and move the stock quickly. Both models survive.

Retail buyers formalise that tradeoff with gross margin return on inventory, usually shortened to GMROI: gross profit divided by the inventory carried to produce it. A GMROI of 3 means every dollar tied up in stock threw off three dollars of gross profit. It decomposes into gross margin and inventory turnover, the latter being cost of revenue divided by inventory.

The question is whether the two parts cancel. Competition says they should: if rapid turnover were free money, capital would move into the fast businesses until their margins fell far enough to equalise the return on stock. Exact cancellation would leave GMROI constant across companies and velocity worth nothing. Partial cancellation would mean the fast businesses keep something real, more gross profit from the same dollar of working capital.

The approach

The test measures both components for one fiscal year and asks how completely one offsets the other across the index.

  1. Universe: companies in the S&P 500 today. Financials, utilities and real estate drop out, since their balance sheets carry no product inventory cycle.
  2. Filings: the latest annual report per company with a fiscal year ending on or after 1 June 2025, so January and May year ends sit alongside December filers.
  3. Cross-check: the reported gross profit line and revenue minus cost of revenue must agree within 2 percent of revenue. Revenue stated gross of excise taxes against a cost line stated net of them, which is how tobacco companies report, inflates the margin, and companies where the two disagree drop from the sample.
  4. Inventory floor: inventory of at least 2 percent of revenue, about a week of sales, so the ratios describe a real stock cycle rather than a rounding item.

That leaves 206 companies. Fitting the relationship in logs makes the slope an elasticity: -1 means margin falls in exact proportion to the rise in turnover and GMROI is constant, while anything shallower means velocity pays.

Code

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

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

FIELDS = ["revenue", "cost_of_revenue", "gross_profit", "inventory"]

uni = xfl.index("sp500")
tickers = sorted(uni.loc[uni["removed_date"].isna(), "ticker"].dropna().unique())

f = xfl.fundamentals(tickers, period_type="annual", start="2025-06-01",
                     version="restated", fields=FIELDS)
latest = f.sort_values("period_end").groupby("ticker").tail(1)

s = latest[~latest["gics_sector"].isin({"Financials", "Utilities", "Real Estate"})]
s = s.dropna(subset=FIELDS)
s = s[(s[FIELDS] > 0).all(axis=1)].copy()
s["gross_profit_calc"] = s["revenue"] - s["cost_of_revenue"]
gap = (s["gross_profit"] - s["gross_profit_calc"]).abs() / s["revenue"]
s = s[(gap <= 0.02) & (s["inventory"] >= 0.02 * s["revenue"])]

s["gross_margin"] = s["gross_profit_calc"] / s["revenue"]
s["turns"] = s["cost_of_revenue"] / s["inventory"]
s["days_inventory"] = 365 / s["turns"]
s["gmroi"] = s["gross_profit_calc"] / s["inventory"]

fit = stats.linregress(np.log(s["turns"]), np.log(s["gross_margin"]))
s["quintile"] = pd.qcut(s["turns"], 5, labels=["Q1 slowest", "Q2", "Q3", "Q4", "Q5 fastest"])

print(f"slope {fit.slope:+.3f}  R2 {fit.rvalue ** 2:.3f}  p {fit.pvalue:.2g}")
print(s.groupby("quintile", observed=True)[["days_inventory", "gross_margin", "gmroi"]].median())

Full script with formatting and visualisation: inventory-turns-gross-margin-tradeoff-python.py

Output

Scatter of inventory turns against gross margin for 206 current S&P 500 members with a fitted power law of slope -0.51, above a bar chart of median gross margin return on inventory by turnover quintile
Sample: 206 current S&P 500 members, latest annual filing (2025-06-27 to 2026-05-31)

log gross margin on log turns: slope -0.512  R2 0.296  p 3.1e-17
Spearman turns vs gross margin: -0.545 (p 2.4e-17)
Spearman turns vs GMROI:        +0.139 (p 0.046)

Turnover quintile      n   days of inventory   gross margin   GMROI
Q1 slowest           42             193            63%     2.76
Q2                   41             118            41%     2.22
Q3                   41              86            39%     2.67
Q4                   41              64            31%     2.61
Q5 fastest           41              32            26%     4.15

Highest gross profit per dollar of inventory
  FFIV  F 5 INC                           49 days    81%   32.55
  KMI   KINDER MORGAN INC                 38 days    67%   19.87
  COP   CONOCOPHILLIPS                    31 days    62%   19.55
  AVGO  BROADCOM INC                      40 days    68%   19.07
  TRGP  TARGA RESOURCES CORP              15 days    38%   15.19
Lowest gross profit per dollar of inventory
  BG    BUNGE GLOBAL S A                  72 days     5%    0.26
  DOW   DOW INC                           64 days     6%    0.38
  CAH   CARDINAL HEALTH INC               29 days     4%    0.49
  ADM   ARCHER DANIELS MIDLAND CO         50 days     6%    0.49
  SMCI  SUPER MICRO COMPUTER INC          87 days    11%    0.52

Sector medians (sectors with at least 5 names)
  Materials                 26      67 days    28%    1.89
  Consumer Discretionary    25     103 days    37%    2.22
  Information Technology    40     109 days    48%    2.54
  Industrials               37      91 days    38%    2.67
  Consumer Staples          30      67 days    34%    2.93
  Health Care               39     123 days    64%    3.97
  Energy                     8      27 days    34%    9.33

What this tells us

The tradeoff is real. Rank correlation between turnover and gross margin is -0.545 across 206 companies, and the quintile medians fall from 63 percent at 193 days of inventory to 26 percent at 32 days. The slowest quintile carries six times the stock of the fastest and prices its goods at more than twice the markup.

The tradeoff is also incomplete. The fitted elasticity is -0.512, so doubling inventory turnover comes with a gross margin about 30 percent lower, not 50 percent lower. Full compensation requires -1. At roughly half that, faster companies retain part of the benefit of velocity: 4.15 dollars of gross profit per dollar of stock in the fastest quintile against 2.61 in the fourth.

The advantage is concentrated rather than gradual. Quintiles two through four cluster between 2.22 and 2.67, and the rank correlation between turnover and GMROI is only +0.139, marginal at p = 0.046. Turning stock faster does not order companies by return on inventory; it separates the extremes.

What drives GMROI is business model, not operating quality. The spread runs from 0.26 at Bunge, an agricultural processor whose 5 percent margin leaves almost nothing per dollar of grain in silos, to 32.55 at F5, which sells software-heavy networking gear at an 81 percent margin on seven weeks of hardware. Sector medians span 1.89 in materials to 9.33 in energy, where midstream operators hold under a month of stock.

So what?

Gross margin on its own does not travel between velocity regimes. Cardinal Health at 4 percent and Vertex Pharmaceuticals at 86 percent are not on the same scale, and a screen that ranks on margin alone ranks industries rather than companies. Dividing gross profit by inventory puts both on one axis; the benchmark that keeps the comparison honest is the sector median, not the market median.

The measure earns its keep inside a single company over time. A GMROI that falls while margin holds steady means stock is accumulating faster than sales, which is the standard prelude to a write-down. A GMROI that falls while turnover holds steady means the goods are moving only because they are being discounted. Both look identical in a headline revenue number.

For a working screen: rank on GMROI within sector, then split the year-on-year change into the margin term and the turnover term. The direction of the change matters more than the level, which the industry mostly sets.

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

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