BLOG

Behind the numbers.

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

How to Get Historical Market Cap Data in Python
How Much of the S&P 500 Survives 20 Years? Index Turnover Analysis in Python
Does Joining the S&P 500 Bring New Institutional Owners? 13F Event Study in Python
Is Volatility Seasonal? Calendar Month Analysis of Realized Volatility in Python
Does Fast Revenue Growth Force Companies to Borrow? Cash Funding Analysis in Python
How Far Back Does SEC EDGAR Data Go?
Are One-Time Charges Really One-Time? Charge Frequency Analysis in Python
Does Buying the Dip Work? Short-Term Reversal by Volatility Regime in Python
Alpha Vantage vs Massive vs xfinlink for Fundamentals
How Long Does a Stock Take to Recover From a 50% Fall? Drawdown Analysis in Python
Do Companies That Shrink Their Share Count Outperform? Net Buyback Yield in Python
How Much Does the Dow's Price Weighting Distort It? Index Weighting Analysis in Python
How to Get SEC Form 4 Insider Trading Data in Python
Can Anything Predict Next Month's Stock Returns? Out-of-Sample R-Squared Testing in Python
How Much of a Stock's Return Comes From Its Sector? Variance Decomposition in Python
Altman Z-Score: Where To Get It in Python
Do Value Screens Agree on Which Stocks Are Cheap? Multiple Overlap Analysis in Python
Annual vs Quarterly Financial Data: Which to Use
Do High Returns on Capital Persist? ROIC Fade Analysis in Python
Does Past Beta Predict Future Beta? Beta Stability Testing in Python
Do Defensive Sectors Actually Defend? Up and Down Capture in Python
How to Choose a Financial Data API
Do Small Caps Actually Beat Large Caps? Size Premium Test in Python
What If You Miss the Market's Best Days? Extreme-Day Analysis in Python
Does Rebalancing Add Return? Fixed-Weight vs Drift Portfolios in Python
Which S&P 500 Companies Are Closest to Default? Merton Distance-to-Default in Python
What Happens to Stocks Removed From the S&P 500? Replacement Pair Analysis in Python
Does the Golden Cross Work? 50/200 Moving Average Crossover Backtest in Python
Financial Data for Academic Finance Research
Does Skipping the Most Recent Month Improve Momentum? S&P 500 Decile Sorts in Python
Does Cointegration Survive Out of Sample? Pairs Trading Validation in Python
Which Dividends Are Not Covered by Cash? Free-Cash-Flow Coverage Screening in Python
GICS vs SIC vs NAICS: Which Industry Classification to Use
How Many Stocks Does It Take to Diversify? Random Portfolio Simulation in Python
How Many Days of Data Does a Volatility Estimate Need? Range-Based Estimators in Python
How Much of S&P 500 Cash Flow Is Stock Compensation? Cross-Sectional Analysis in Python
What Is a 13F Filing? Institutional Holdings Explained
Does Revenue Growth Explain Profit Growth? Cross-Sectional Decomposition in Python
How Much of the Nasdaq 100 Is Already in the S&P 500? Index Overlap Analysis in Python
How Often Does a 99% Value-at-Risk Limit Actually Break? VaR Backtesting in Python
Real-Time vs End-of-Day Market Data: Which Do You Need?
How Concentrated Are S&P 500 Earnings? Point-in-Time Index Analysis in Python
Does Volatility Scale With the Square Root of Time? Variance Ratio Test in Python
Does Goodwill Distort the Price-to-Book Screen? Goodwill-Adjusted Valuation in Python
How Are Shares Outstanding Reported (and Why They Disagree)
Do Low-Volatility Stocks Deliver Better Risk-Adjusted Returns? S&P 500 Quintile Sorts in Python
Does Trend Following Beat Buy and Hold? Time-Series Momentum in Python
Has the Stock-Bond Correlation Flipped? 60/40 Portfolio Risk in Python
What API to Use for a Stock Screener
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 Low-Volatility Stocks Deliver Better Risk-Adjusted Returns? S&P 500 Quintile Sorts in Python

What's the question?

Finance theory prices risk: take more of it, and the market is supposed to pay for it. Equity markets have declined to cooperate for half a century. Fischer Black documented a flat beta-to-return relationship in 1972, and Baker, Bradley and Wurgler reported in 2011 that the least volatile US stocks had beaten the most volatile over four decades.

Two claims travel under the name “low-volatility anomaly”. The strong one says calm stocks earn more outright; the weak one says they earn less but carry so much less risk that return per unit of risk still favours them. Low-volatility funds are sold on the strong claim and defended on the weak one.

Which survives a mechanical test on the S&P 500 over the past decade?

The approach

The universe is the S&P 500 as it stood at each formation date, not as it stands today. That choice decides the answer before any statistic is computed: current membership already reveals which companies survived.

  1. Pull index membership at each 31 December from 2015 to 2025. A company removed during 2018 stays in the 2016 and 2017 universes and disappears afterwards. The eleven snapshots hold 686 companies.
  2. Pull monthly total returns from January 2013 to July 2026, keyed on entity identifier rather than ticker so a series stays continuous through a rename.
  3. Screen the panel. Duplicate rows and non-positive prices go, a name whose monthly total return ever exceeds +200 percent or falls below -90 percent is set aside, not winsorised, and a name without a complete formation window goes unranked.
  4. Rank each year’s members on the annualised standard deviation of their trailing 36 monthly total returns, then cut the ranking into five quintiles. Q1 holds the calmest fifth, Q5 the wildest.
  5. Hold each quintile equal weighted through the following calendar year, and reform every January.

Sharpe here is mean return over volatility, no risk-free deduction; drawdowns use month-end values.

Code

import numpy as np
import pandas as pd
import xfinlink as xfl

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

YEARS = list(range(2016, 2027))

members = {y: sorted(int(e) for e in
                     xfl.index("sp500", as_of=f"{y-1}-12-31")["entity_id"].dropna())
           for y in YEARS}
universe = sorted({e for ids in members.values() for e in ids})

px = pd.concat([xfl.prices(entity_id=universe[i:i + 25], start="2013-01-01",
                           end="2026-07-31", interval="1mo",
                           fields=["close", "return_daily"], max_rows=500000)
                for i in range(0, len(universe), 25)], ignore_index=True)

px = px.drop_duplicates(["entity_id", "date"]).dropna(subset=["return_daily"])
px = px[px["close"] > 0]
px["month"] = px["date"].dt.to_period("M")
rets = px.pivot_table(index="month", columns="entity_id",
                      values="return_daily", aggfunc="first")
rets = rets.drop(columns=[c for c in rets.columns
                          if (rets[c] > 2.0).any() or (rets[c] < -0.90).any()])

legs = {}
for y in YEARS:
    form = pd.period_range(f"{y-3}-01", f"{y-1}-12", freq="M")
    hold = pd.period_range(f"{y}-01", "2026-07" if y == 2026 else f"{y}-12", freq="M")
    window = rets.loc[rets.index.isin(form), [e for e in members[y] if e in rets.columns]]
    ranked = window.columns[window.notna().sum() == 36]   # complete formation window
    vol = window[ranked].std() * np.sqrt(12)
    quintile = pd.qcut(vol.rank(method="first"), 5, labels=[1, 2, 3, 4, 5])
    held = rets.loc[rets.index.isin(hold)]
    for k in range(1, 6):
        legs.setdefault(k, []).append(held[vol.index[quintile == k]].mean(axis=1))

P = pd.DataFrame({f"Q{k}": pd.concat(v).sort_index() for k, v in legs.items()})
for c in P.columns:
    wealth = (1 + P[c]).cumprod()
    print(f"{c}  CAGR {(1 + P[c]).prod() ** (12 / len(P)) - 1:.2%}  "
          f"vol {P[c].std() * np.sqrt(12):.2%}  "
          f"Sharpe {P[c].mean() / P[c].std() * np.sqrt(12):.2f}  "
          f"maxDD {(wealth / wealth.cummax() - 1).min():.1%}")

Full script with formatting and visualisation: low-volatility-anomaly-sp500-quintiles-python.py

Output

Growth of one dollar in five S&P 500 volatility quintiles, 2016 to 2026, with annualised return and volatility per quintile below
Point-in-time S&P 500 volatility quintiles, 2016-01 to 2026-07 (127 months)
Formation: annualised standard deviation of the trailing 36 monthly total returns, measured each 31 December
Portfolios: equal weighted, reformed every January, Sharpe taken without a risk-free deduction

11 membership snapshots cover 686 distinct companies; 5 set aside by the return-bound screen

Formation    Members  Ranked   Q1 vol   Q5 vol
2016             495     472    14.7%    34.1%
2017             496     481    15.3%    36.8%
2018             498     483    15.0%    36.1%
2019             499     485    15.5%    37.4%
2020             500     488    14.7%    36.9%
2021             500     484    19.6%    50.0%
2022             500     485    20.2%    50.7%
2023             499     486    22.8%    54.1%
2024             499     489    20.5%    45.1%
2025             499     487    19.8%    45.9%
2026             496     485    17.5%    44.6%

             Formation vol     CAGR  Ann vol  Sharpe  Worst mo   Max DD
Q1 lowest            17.8%   10.24%   12.83%    0.83    -12.5%   -20.2%
Q2                   22.1%   11.93%   14.47%    0.85    -14.1%   -21.2%
Q3                   25.7%   12.51%   16.90%    0.79    -19.1%   -27.7%
Q4                   30.7%   11.20%   19.42%    0.65    -21.8%   -32.6%
Q5 highest           42.9%   13.21%   24.23%    0.64    -25.6%   -37.7%
All ranked                   12.06%   16.64%    0.77    -18.6%   -27.2%

Calendar year total return (%)
            Q1      Q2      Q3      Q4      Q5     ALL
2016      14.0    13.4    17.5    15.8    15.6    15.3
2017      19.3    17.3    23.4    20.6    12.9    18.7
2018       1.8    -5.3    -7.6   -13.1   -12.6    -7.4
2019      29.2    33.1    31.6    30.6    27.0    30.6
2020       5.1    13.1    13.1    13.1    15.2    12.4
2021      23.5    28.5    28.7    30.7    34.6    29.5
2022      -5.2   -10.3   -13.3   -15.5   -13.1   -11.3
2023       1.4    14.2    16.6    19.7    20.9    14.6
2024      15.1    14.9    13.5     8.5    12.0    12.9
2025       3.3     5.7     6.4     8.5    17.1     8.4
2026       5.6     8.8    11.0    10.2    20.1    11.3

Q1 minus Q5: -6.38% a year, t = -0.83; Q1 ahead in 5 of 11 calendar years
  2016-2020  Q1 return 13.46% Sharpe  1.09   Q5 return 10.80% Sharpe  0.52
  2021-2026  Q1 return  7.44% Sharpe  0.61   Q5 return 15.42% Sharpe  0.75
Q1 geared 1.888x to Q5 volatility: 18.48% a year before financing cost, max drawdown -36.3%
Breakeven financing rate on the borrowed 0.888 of capital: 5.17% a year

2026 sector mix, lowest quintile: Utilities 22, Consumer Staples 17, Industrials 14, Financials 13
2026 sector mix, highest quintile: Information Technology 27, Consumer Discretionary 20, Health Care 13, Industrials 10

What this tells us

The sort works: the calmest fifth averaged 17.8% formation volatility and ran at 12.83% as a portfolio, the wildest 42.9% and 24.23%.

The strong claim fails. The wildest fifth compounded at 13.21% a year against the calmest fifth’s 10.24%, with the equal-weighted average of all ranked names between them at 12.06%, and the ordering across the middle quintiles is not clean. A monthly rebalanced position long the calmest fifth and short the wildest compounds at -6.38% a year, carrying a t-statistic of -0.83, so the disciplined reading is that raw returns are indistinguishable across the sort.

The weak claim holds, on every risk measure at once. Sharpe declines from 0.85 at Q2 to 0.64 at Q5, worst drawdown widens without interruption from 20.2% to 37.7%, and the worst month falls from -12.5% to -25.6%. Q1 gave up 2.97 points of annual return and removed 11.40 points of volatility for it.

Splitting the decade in half explains why practitioners argue about this. From 2016 to 2020, Q1 beat Q5 on return, 13.46% against 10.80%, and doubled its Sharpe, 1.09 against 0.52; textbook anomaly. From 2021 the ordering flipped, Q5 returning 15.42% at a Sharpe of 0.75 against Q1’s 7.44% at 0.61. Most of the reversal sits in 2025 and the first seven months of 2026, when the highest-volatility fifth (27 technology names, 20 consumer discretionary) rode the artificial intelligence trade and the calmest fifth (22 utilities, 17 staples) sat it out. Defence paid in 2018 and 2022, +1.8% against -12.6% and -5.2% against -13.1%.

So what?

Nobody should buy low volatility expecting a higher return. The evidence is absent here, and the five-year reversal shows what that belief costs when the market rewards risk for a stretch.

Buy it for the loss profile instead. Halving the worst month from -25.6% to -12.5% and cutting 17.5 points off the worst drawdown is what the quintile delivers, which matters most under a drawdown limit.

Where borrowing is permitted the comparison changes. Gearing Q1 by 1.888 times brings it to Q5’s volatility and to 18.48% a year before financing cost, 5.27 points ahead, at a shallower worst drawdown of 36.3%. The borrowed 0.888 of capital has to cost under 5.17% a year for that to hold, so the trade turns on the funding rate.

Rebuild the ranking every year on membership as it stood, and check sub-periods first: a full-sample average conceals a factor that ran at a Sharpe of 1.09 for five years and 0.61 for the next five.

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