BLOG

Behind the numbers.

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

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

Does Volatility Targeting Improve Sharpe Ratios? Seven-Asset Backtest in Python

What's the question?

Volatility clusters. Quiet days tend to follow quiet days and violent days follow violent days, a property of asset returns documented since Mandelbrot studied cotton prices in 1963. Realised volatility over the past month therefore says something about volatility over the next few days, though nothing reliable about direction.

Volatility targeting turns that property into a position-sizing rule: hold an amount inversely proportional to recent realised volatility, so exposure rises when markets are calm and falls when they are turbulent. Moreira and Muir published a version of this in the Journal of Finance in 2017 and reported large Sharpe ratio gains, and volatility scaling is now standard machinery in managed futures and risk premia products.

The narrower question is whether the rule survives mechanical application across asset classes, with the volatility estimate lagged so that nothing measured on a trading day can influence the position held during it.

The approach

Seven exchange-traded funds span US large caps (SPY), US small caps (IWM), developed international equity (EFA), emerging markets (EEM), listed real estate (VNQ), long-dated Treasuries (TLT) and gold (GLD). Daily total returns run from January 2007 to July 2026, covering the 2008 crash, March 2020 and the 2022 rates repricing.

  1. Measure realised volatility as the standard deviation of the previous 20 daily returns, annualised by the square root of 252.
  2. Lag it one day, so the position taken on any trading day uses only volatility observable through the prior close.
  3. Set exposure to a 15% annualised target divided by the lagged estimate, capped at 2.0x. The cap matters: uncapped exposure reached 4.7x in the calm of August 2017.
  4. Charge one basis point on the notional traded whenever exposure changes.
  5. Rescale the targeted series by a constant so its full-sample volatility matches buy and hold, making growth and drawdown comparable. Sharpe is unaffected by constant scaling.
  6. Run it again with the lag removed, as a control on how much a one-day timing error flatters the result.

Step 6 is the part most backtests skip. A rule that sizes today’s position using today’s volatility looks like a strategy and behaves like a forecast of something already known.

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

TICKERS = ["SPY", "IWM", "EFA", "EEM", "VNQ", "TLT", "GLD"]
TARGET_VOL, LOOKBACK, MAX_LEVERAGE, COST = 0.15, 20, 2.0, 0.0001

px = pd.concat([xfl.prices(t, start="2006-11-01", fields=["close", "return_daily"])
                for t in TICKERS], ignore_index=True)

def sharpe(r):
    return r.mean() / r.std() * np.sqrt(252)

def backtest(returns, lag):
    """lag=1 uses only information available before the trading day; lag=0 peeks."""
    realised = returns.rolling(LOOKBACK).std() * np.sqrt(252)
    weight = (TARGET_VOL / realised.shift(lag)).clip(upper=MAX_LEVERAGE)
    frame = pd.DataFrame({"r": returns, "w": weight}).dropna()
    frame = frame[frame.index >= "2007-01-01"]
    turnover = frame["w"].diff().abs().fillna(0.0)
    return frame["r"], frame["w"] * frame["r"] - COST * turnover

for t in TICKERS:
    r = px[px["ticker"] == t].sort_values("date").set_index("date")["return_daily"].dropna()
    bh, net = backtest(r, lag=1)
    _, peek = backtest(r, lag=0)
    print(f"{t}: buy-and-hold {sharpe(bh):.2f}  targeted {sharpe(net):.2f}  "
          f"look-ahead {sharpe(peek):.2f}")

Full script with formatting and visualisation: volatility-targeting-sharpe-ratio-backtest-python.py

Output

Sharpe ratios for seven ETFs under buy and hold, volatility targeting and a look-ahead control, 2007 to 2026.
Volatility targeting versus buy and hold, 2007-01-01 to 2026-07-24
20-day realised volatility, 15% annualised target, leverage capped at 2.0x, 1bp per unit traded
Sharpe ratio here is mean return over volatility, no risk-free deduction

Ticker     Days  B&H Sharpe  Targeted  Avg exposure  Turnover
-------------------------------------------------------------
SPY        4920        0.62      0.75          1.18     10.3x
IWM        4920        0.45      0.39          0.84      8.3x
EFA        4920        0.32      0.25          1.05      9.5x
EEM        4920        0.31      0.23          0.82      8.2x
VNQ        4920        0.32      0.45          0.94      8.9x
TLT        4920        0.26      0.30          1.20     10.2x
GLD        4920        0.59      0.64          1.07     10.6x

Volatility-matched comparison (both series rescaled to equal volatility)
Ticker     B&H CAGR  Targeted   B&H MaxDD  Targeted   Ann vol
-------------------------------------------------------------
SPY          10.7%     13.7%      -55.2%    -42.2%     19.6%
IWM           8.4%      6.7%      -59.0%    -45.4%     24.7%
EFA           4.8%      3.1%      -61.0%    -46.9%     21.6%
EEM           4.7%      2.5%      -66.4%    -59.7%     28.0%
VNQ           5.4%      9.2%      -73.1%    -53.8%     29.5%
TLT           2.8%      3.5%      -48.4%    -46.8%     15.0%
GLD           9.5%     10.4%      -45.6%    -57.8%     18.1%

Look-ahead control: same rule, volatility measured through the trading day itself
Ticker    Correct lag  Same-day peek  Inflation
-----------------------------------------------
SPY              0.75           1.04       0.29
IWM              0.39           0.55       0.16
EFA              0.25           0.45       0.20
EEM              0.23           0.38       0.15
VNQ              0.45           0.63       0.18
TLT              0.30           0.33       0.03
GLD              0.64           0.81       0.17

Median Sharpe: buy and hold 0.32, targeted 0.39, targeted with same-day peek 0.55
Median max drawdown: buy and hold -59.0%, targeted -46.9%
Sharpe improved on 4 of 7 assets; drawdown shrank on 6 of 7

What this tells us

Two results point in different directions, and the split is the finding.

Drawdown control works almost everywhere. Six of seven assets took a smaller worst-case loss, and the median maximum drawdown fell from 59.0% to 46.9% at matched volatility. The mechanism is direct: 2008, 2020 and 2022 each began with a volatility spike, so every subsequent leg down arrived with exposure already cut, and SPY exposure averaged 0.30 across September and October 2008. Real estate improved most, from 73.1% to 53.8%.

Return improvement is far less uniform. Sharpe rose on four assets and fell on three: SPY gained most, 0.62 to 0.75, while EEM fell from 0.31 to 0.23. The reason is symmetric to the reason drawdowns improved, because rebounds also arrive during high-volatility periods, and in emerging markets and small caps they were violent enough that being underweight through them cost more than the avoided losses were worth. Gold shows a third pattern, its Sharpe improving while its drawdown got worse: the 45.6% slide that ended in December 2015 was a slow grind at ordinary volatility, which the rule met with average exposure of 1.03.

The look-ahead control prices a single day of hindsight. Median Sharpe jumps from 0.39 to 0.55 once the volatility estimate may include the day being traded, and SPY jumps from 0.75 to 1.04. Nothing changed but the timestamp on one input.

Costs are not the constraint. Annual turnover runs 8.2 to 10.6 times capital, yet at one basis point that removes about one hundredth of a Sharpe point, and at five basis points the median targeted Sharpe still holds at 0.37.

So what?

Treat volatility targeting as a risk-shaping tool rather than a return-improving one. The drawdown evidence holds across six of seven asset classes and three separate crises; the Sharpe evidence does not, and applying the rule to emerging markets or small caps in the expectation of better risk-adjusted returns has the historical record pointing the other way.

The practical order when sizing positions is to decide first whether a smaller worst case is worth surrendering part of the rebound, then apply the rule only where that trade is acceptable. The same four-of-seven split held at lookbacks of 10, 60 and 120 days and at targets of 10% and 20%, so the specific parameters are not doing the work.

For anyone reading someone else’s volatility-scaled backtest, run the lag-zero control first. It takes one changed argument, and it separates a genuine 0.75 from a hindsight-assisted 1.04.

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