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

How Long Does a Stock Take to Recover From a 50% Fall? Drawdown Analysis in Python

What’s the question?

A drawdown is the fall from a running high to a later low, and its recovery is the month the price first closes back above that old high. Index history makes both look survivable: the S&P 500 has recovered every fall it ever suffered, and the worst took close to seven years.

Individual stocks are a different problem, for a mechanical reason. An index is a portfolio with a maintenance rule, so companies that fail get removed and replaced; it recovers partly because its failures are deleted from it, while the shareholder who owned the failure keeps the loss. Two numbers decide what a 50% fall in one company costs: the wait when the price does come back, and how often it never comes back.

The approach

A study built on today’s index members would measure the recovery record of companies selected for having recovered.

  1. Take the S&P 500 roster as it stood at each year end from 1995 to 2025, plus July 2026. The union is 1,133 companies, keyed on a persistent company identifier rather than a ticker string, so a symbol reused by a later listing cannot contaminate an earlier one.
  2. Pull monthly split-adjusted closes from January 1996 to July 2026. A raw close steps across every split and would manufacture falls that never happened.
  3. Track each company from the month it joined the index, and stop its series where trading stops. A company delisted in 2009 has a series that ends in 2009.
  4. Cut every series into episodes: from a running high, to the lowest point before that high is regained, to the month the price closes back above it. Falls shallower than 20% are ignored.
  5. Handle censoring. A stock that hit its low in 2024 cannot be watched for five years, so it drops from the five-year figure rather than counting as a failure, while a company that stopped trading below its old high counts as a failure at every horizon.

Series without a clean single-symbol monthly record for the window drop out, leaving 871 companies, 524 of them still trading in July 2026. Prices are adjusted for splits and not for spin-offs, so a company that handed a large division to its own shareholders registers a fall its holders did not suffer, which makes the figures conservative.

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

roster = pd.concat([xfl.index("sp500", as_of=d)[["entity_id", "added_date"]]
                    for d in [f"{y}-12-31" for y in range(1995, 2026)] + ["2026-07-31"]])
joined = pd.to_datetime(roster.groupby("entity_id")["added_date"].min()).dt.to_period("M")
ids = sorted(joined.index)

frames = []
for i in range(0, len(ids), 40):
    frames.append(xfl.prices(entity_id=ids[i:i + 40], start="1996-01-01",
                             end="2026-07-31", interval="1mo",
                             fields=["adj_close"], max_rows=500000))
px = pd.concat(frames, ignore_index=True)
px["m"] = pd.to_datetime(px["date"]).dt.to_period("M")
px = px[px["m"] >= px["entity_id"].map(joined)].sort_values(["entity_id", "m"])

def episodes(values):
    out, peak, pi, low, li, live = [], values[0], 0, values[0], 0, False
    for i in range(1, len(values)):
        x = values[i]
        if x >= peak:
            if live:
                out.append((pi, li, i, 1 - low / peak))
                live = False
            peak, pi, low, li = x, i, x, i
        elif not live:
            live, low, li = True, x, i
        elif x < low:
            low, li = x, i
    if live:
        out.append((pi, li, None, 1 - low / peak))
    return out

def share_back(frame, h):
    hit = frame["recovered"] & (frame["months"] <= h)
    countable = hit | ~frame["trading"] | (frame["watched"] >= h)
    return hit.sum() / countable.sum() * 100

Full script with formatting and visualisation: how-long-do-stock-drawdowns-take-to-recover-python.py

Output

Recovery curves showing the share of falls back above the old high against months since the low, one line per depth bucket, with a stacked bar panel splitting each bucket into recoveries within one, two and five years and those still down after five
point-in-time S&P 500 rosters, 32 dates 1995-2026: 1133 distinct companies
monthly split-adjusted closes 1996-01 to 2026-07: 271,842 bars on 1047 companies
each series starts the month the company joined the index: 198,464 bars
52 companies truncated at a break in trading
set aside: 41 where a symbol reappears after another, 36 with a price step above 50% at a symbol change,
           39 with a single month beyond +200% or -90%, 117 with under 36 months
sample: 871 companies, 174,859 monthly bars, 524 still trading at 2026-07

falls of 20% or deeper from a running high: 2,611 episodes on 868 companies

fall      episodes   within 1yr    within 2yr    within 5yr   median  never
20-30%         872   82.5% ( 815)   96.3% ( 812)   98.6% ( 812)       7   8.0%
30-50%         826   44.1% ( 765)   76.5% ( 754)   94.1% ( 731)      13  14.9%
50-70%         449   10.2% ( 400)   32.2% ( 385)   71.6% ( 370)      34  29.6%
70%+           464    0.7% ( 424)    4.4% ( 407)   23.4% ( 398)      61  59.9%
counts in brackets are the episodes countable at that horizon; median months is measured from the low, over recoveries only

where every episode stands at 2026-07
fall      episodes   back above the old high   below it, still trading   series ends first
20-30%         872         802 (92.0%)                60 ( 6.9%)             10 ( 1.1%)
30-50%         826         703 (85.1%)                95 (11.5%)             28 ( 3.4%)
50-70%         449         316 (70.4%)                83 (18.5%)             50 (11.1%)
70%+           464         186 (40.1%)               121 (26.1%)            157 (33.8%)

falls of 50% or more: 913 episodes on 653 companies
  back above the old high within  1 year :   5.3%  (44/824)
  back above the old high within  2 years:  17.9%  (142/792)
  back above the old high within  5 years:  46.6%  (358/768)
  back above the old high within 10 years:  62.4%  (458/734)
  median months from the low, over recoveries only: 47
  never got back: 411 of 913 (45.0%)

longest waits from the low back to the old high
              company  sym    peak     low    back fall % months
          CORNING INC  GLW 2000-08 2002-07 2026-02   98.5  283.0
    CISCO SYSTEMS INC CSCO 2000-03 2002-09 2026-01   86.4  280.0
           NETAPP INC NTAP 2000-09 2001-09 2024-06   94.7  273.0
         QUALCOMM INC QCOM 1999-12 2002-07 2019-12   84.4  209.0
           INTEL CORP INTC 2000-08 2009-02 2026-04   83.0  206.0
 BANK OF AMERICA CORP  BAC 2006-10 2009-02 2025-12   92.7  202.0
TENET HEALTHCARE CORP  THC 2002-05 2009-01 2025-09   97.8  200.0
           CIENA CORP CIEN 2001-11 2009-02 2025-09   95.7  199.0

deepest falls on companies whose price series ends before recovery
                      company  sym    peak     low fall % last month
                RITE AID CORP  RAD 1998-12 2023-09  100.0    2023-10
    FLEETWOOD ENTERPRISES INC  FLE 1998-02 2009-01   99.9    2009-01
         CONEXANT SYSTEMS INC CNXT 2000-02 2009-02   99.9    2011-04
FRONTIER COMMUNICATIONS PRINT  FTR 2007-05 2020-04   99.9    2020-04
                 VISTEON CORP   VC 2001-07 2009-03   99.9    2009-03
          PEABODY ENERGY CORP  BTU 2008-06 2016-04   99.9    2016-04
       CHESAPEAKE ENERGY CORP  CHK 2008-06 2020-06   99.9    2020-06
            PENNEY J C CO INC  JCP 2007-03 2020-05   99.8    2020-05

What this tells us

Depth does not scale the wait, it changes the outcome. A fall of 20% to 30% is a routine interruption: 82.5% are over within a year, the median takes 7 months from the low, and 8.0% have not recovered. A fall of 50% or more sits elsewhere entirely, with 5.3% back inside a year, 46.6% inside five, and 45.0% of those 913 episodes never getting back.

The break comes between the 30-50% bucket and the 50-70% bucket. One-year recovery drops from 44.1% to 10.2% and the median wait from the low goes from 13 months to 34. Halving is not twice as bad as a quarter fall; it is a different kind of event, because a price that has halved usually reflects a change in what the business is worth rather than in what the market will pay for it.

Below 70% the arithmetic turns hostile, since regaining the old high then requires a 233% gain. Of the 464 falls that deep, 157 belong to companies whose price series ends first, the polite description of Rite Aid, Chesapeake Energy and the rest of that table; another 121 are still under water and trading. The 61-month median here covers only the 40.1% that made it back, so it understates the wait facing a holder at the low.

Recoveries that do arrive can take decades. Corning regained its August 2000 high in February 2026, 283 months after the 2002 low; Cisco needed 280 months and Bank of America 202, each of them large and continuously listed for the whole wait.

So what?

Size single positions against the tail rather than the average. A position that halves has a 45% historical chance of never returning to its old high, and a median wait near four years if it does. Depth is the strongest cheap signal about what follows, and it argues for cutting deep losers instead of averaging into them.

Index recovery statistics do not transfer to single names. The S&P 500 regained its August 2000 high in May 2007, 81 months later, because it dropped the companies that did not; Corning, Cisco and Intel, index members throughout, needed between 17 and 24 years from their lows.

For a tail-risk model, the split between the two failure modes matters more than the headline rate. Among 70%-plus falls, 33.8% ended with the series ending, a default-like outcome that belongs in a credit-shaped model, and 26.1% are still open, which is a live position with option value. Running this on a specific universe takes one roster pull and one price pull, and returns depth-conditional recovery odds for the book actually held.

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