BLOG

Behind the numbers.

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

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

How Many Days of Data Does a Volatility Estimate Need? Range-Based Estimators in Python

What’s the question?

Volatility feeds almost every risk calculation, and it is never observed directly. It has to be estimated from past prices, so every estimate carries sampling error. The standard recipe squares daily log returns and averages them: one number per day, and everything the price did in between is discarded.

Picture a fund that opens at 100, trades up to 104, sinks to 97, and closes at 100. The close-to-close return is zero. The day was violent and the estimator records nothing.

Four estimators read the rest of the bar. Parkinson (1980) uses the high-low range, whose expected square for a driftless random walk is 4·ln(2) times the variance. Garman-Klass (1980) folds in the open and the close. Rogers-Satchell (1991) rearranges the terms so that a price with drift does not bias the answer. Yang-Zhang (2000) adds a term for the gap between yesterday’s close and today’s open, which the other three cannot see.

The textbook claim: a day’s high-low range carries roughly five times the information about volatility that the close does. That figure comes from a model with fixed volatility and a continuously watched price path. Real bars honour neither condition.

The approach

True volatility is unknown and it moves, so estimator error cannot be measured against it. A split sample gets around that.

  1. Eight liquid ETFs over ten years, 2016-08-01 to 2026-08-03, spanning US large, small and mega caps (SPY, IWM, DIA), markets outside the US (EFA, EEM), long Treasuries (TLT) and two sectors (XLK, XLF). Each fund has a bar for every session in the window.
  2. Convert each bar to logs relative to the prior close, after multiplying the open, high and low by adj_close/close so that a share split registers as a change of units rather than an overnight move.
  3. Cut each series into consecutive blocks of 22 trading days, sending odd-numbered days into one half and even-numbered days into the other. Both halves hold 11 days from the same month of market conditions.
  4. Compute all five estimators on each half and take the difference of their logs. The two halves measure the same volatility, so what separates them is sampling noise.
  5. Precision is the variance of the close-to-close differences divided by the variance of the estimator’s own, pooled across 912 block pairs.

A precision of 4 means one day of that estimator carries as much information as four days of closes.

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", "DIA", "EFA", "EEM", "TLT", "XLK", "XLF"]
NAMES = ["close_to_close", "parkinson", "garman_klass", "rogers_satchell", "yang_zhang"]
NHALF = 11

px = xfl.prices(TICKERS, start="2016-08-01", end="2026-08-03",
                fields=["open", "high", "low", "close", "adj_close"])

def estimators(o, h, l, c):
    """Daily variance estimates. Inputs are logs relative to the prior close."""
    n = len(c)
    hl, co, u, d = h - l, c - o, h - o, l - o
    rs = np.mean(u * (u - co) + d * (d - co))
    k = 0.34 / (1.34 + (n + 1) / (n - 1))
    return {
        "close_to_close": np.mean(c ** 2),
        "parkinson": np.mean(hl ** 2) / (4 * np.log(2)),
        "garman_klass": np.mean(0.5 * hl ** 2 - (2 * np.log(2) - 1) * co ** 2),
        "rogers_satchell": rs,
        "yang_zhang": np.var(o, ddof=1) + k * np.var(co, ddof=1) + (1 - k) * rs,
    }

gaps = []
for tk in TICKERS:
    t = px[px["ticker"] == tk].sort_values("date")
    f = t["adj_close"] / t["close"]      # split factor: puts o/h/l on the adj_close basis
    prev = t["adj_close"].shift(1)
    m = pd.DataFrame({"o": np.log(t["open"] * f / prev), "h": np.log(t["high"] * f / prev),
                      "l": np.log(t["low"] * f / prev), "c": np.log(t["adj_close"] / prev)
                      }).dropna().to_numpy()
    for b in range(len(m) // (2 * NHALF)):
        blk = m[b * 2 * NHALF:(b + 1) * 2 * NHALF]
        A, B = estimators(*blk[0::2].T), estimators(*blk[1::2].T)
        gaps.append({k: np.log(A[k]) - np.log(B[k]) for k in NAMES})

G = pd.DataFrame(gaps)
base = G["close_to_close"].var(ddof=1)
for k in NAMES:
    print(f"{k:>16} precision={base / G[k].var(ddof=1):.2f}")

Full script with formatting and visualisation: range-based-volatility-estimators-python.py

Output

Bar chart: precision per day of data relative to close-to-close, with Garman-Klass at 4.16 times, Parkinson at 3.59, Rogers-Satchell at 3.44 and Yang-Zhang at 2.99, and dots showing each of the eight funds
Annualised volatility by estimator, 20,120 daily bars, 2016-08-01 to 2026-08-03

        Close-to-close  Parkinson  Garman-Klass  Rogers-Satchell  Yang-Zhang
ticker
SPY              18.07      13.78         13.87            14.03       18.18
IWM              23.14      18.62         18.84            19.03       23.76
DIA              17.64      12.92         12.92            13.05       17.36
EFA              17.28      10.13         10.06            10.12       17.40
EEM              20.98      11.84         11.85            12.00       21.10
TLT              14.84      10.09         10.00             9.91       14.80
XLK              24.96      18.60         18.37            18.39       24.40
XLF              22.19      16.62         16.85            17.15       22.88

Sampling noise, 912 odd/even half-block pairs of 11 days each

       estimator  ann vol %  noise sd  precision  days for 21
  Close-to-close      20.13     0.740       1.00         21.0
       Parkinson      14.44     0.391       3.59          5.9
    Garman-Klass      14.47     0.363       4.16          5.0
 Rogers-Satchell      14.60     0.399       3.44          6.1
      Yang-Zhang      20.28     0.427       2.99          7.0

precision range across the eight funds
        Parkinson: 2.52 to 4.60
     Garman-Klass: 2.98 to 5.22
  Rogers-Satchell: 2.66 to 4.48
       Yang-Zhang: 1.80 to 4.64

What this tells us

The high and low are worth a great deal. Garman-Klass extracts 4.16 times as much precision per day as close-to-close, so five trading days of open-high-low-close bars pin down volatility as tightly as 21 days of closing prices. Parkinson reaches 3.59 and Rogers-Satchell 3.44, both using less of the bar.

The levels tell a second story. Across the pooled sample, Parkinson, Garman-Klass and Rogers-Satchell read about 28 percent below close-to-close in volatility terms, which is roughly half the variance, though the size of that gap varies from fund to fund. They see the trading session and nothing outside it. Yang-Zhang, the one estimator carrying a gap term, lands within 3.2 percent of close-to-close on all eight funds while still delivering 2.99 times the precision. Same quantity, one third of the data.

Measured precision sits below the published figures of 5.2 for Parkinson and 7.4 for Garman-Klass, for the two reasons named earlier: volatility moves inside a 22-day block, adding noise that every estimator inherits and dragging the ratios toward one, and discrete trading clips the true high and low. These figures are a floor.

Yang-Zhang’s precision varies most across funds, from 1.80 on EEM to 4.64 on XLK. Its gap term is an ordinary variance of 11 numbers and inherits close-to-close’s inefficiency, so the more of the daily move that lands before the opening bell, the less Yang-Zhang gains. EEM and EFA track markets that trade while the US is shut, which is why their session-only estimates sit furthest below close-to-close: 10.13 against 17.28 for EFA.

So what?

Pick the estimator to match the risk being measured, then shorten the window.

For total daily volatility, the input to position sizing and risk limits, Yang-Zhang is the choice. Seven trading days of it match 21 days of closes, and a rolling window lags a change in volatility by roughly half its length, so the shorter window turns about a week sooner at the same noise level. For session risk, where execution and stop placement live, Garman-Klass does the same job in five days.

Levels must not be mixed. Replacing a close-to-close volatility with a Parkinson volatility looks like a 28 percent fall in risk that has not happened, and an option priced off that number will be too cheap. Any cross-desk or cross-vendor comparison has to establish which estimator produced each figure first.

Before committing, measure how much of a fund’s move lands outside the session. Where that share is large, as it is for funds tracking foreign markets, the gain is real but smaller than the headline.

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