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

What Is Survivorship Bias in Backtesting?

Survivorship bias is the error of testing a strategy on the companies that were still standing at the end of the test window. Draw a universe from today’s S&P 500, or from a price file that only holds symbols still trading, and every bankruptcy, buyout and quiet delisting has already been swept out of the sample before the first line of code runs. The result is a backtest that reports returns nobody could have earned. The correction is mechanical rather than clever: take index membership as it stood on the formation date, keep the names that later disappeared, and hold each one to its final traded price.

Where does the bias get in?

Usually at the universe, and usually without anyone noticing the moment it happens. The universe gets chosen from a current list, because a current list is what is easy to obtain: the Wikipedia page of S&P 500 components, a broker export, a screener result. Every name on that list passed a test the strategy knows nothing about, which is that the company survived and stayed large enough to remain in the index.

The price source is the other common entrance. Some feeds serve whatever the symbol currently maps to and nothing else, so a query for a company acquired in 2016 returns an empty frame, an unrelated fund, or an error. Whatever the strategy does with those failures, dropping them, filling them forward, or skipping the ticker entirely, the effect is the same: the losers leave and the average improves.

A third path is narrower but nastier. Ticker symbols get reassigned. If the backtest is keyed on the symbol rather than on the company, a 2015 position can silently become a different business by 2024, and the returns stitched across the handover belong to nobody.

How much does the index actually turn over?

Enough that the choice of universe dominates most of the parameters people spend their time tuning. On the S&P 500 roster of 29 July 2016, 142 of the 495 names are absent from the roster today, a little under 29% in ten years. The membership event log records 189 removals over the same decade, a larger number because it also counts companies that joined after 2016 and left again before now.

The distortion those removals cause has been measured directly. Running one identical revenue-growth screen over two universes that differ in nothing except point-in-time membership, the point-in-time version compounded at 8.74% a year against 18.79% for the contaminated version between June 2021 and July 2026. Ten percentage points a year of pure hindsight, from one choice about which list to start from, across five years.

How do you build a point-in-time universe?

Ask the data source for membership on the date the portfolio forms, not membership today.

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

past = xfl.index("sp500", as_of="2016-07-29")   # membership as it stood then
now = xfl.index("sp500")                        # membership today

gone = set(past["entity_id"]) - set(now["entity_id"])
print(len(past), len(now), len(gone))

Output:

495 499 142

Those 142 entity identifiers are the sample. A backtest that never sees them is not a backtest of the strategy; it is a backtest of the strategy plus a decade of hindsight about which companies would still exist. The as_of parameter carries no extra cost on a paid plan, and a free key allows 50 historical snapshots per day.

What happens to the companies that leave?

Leaving the index is often not failure at all: companies get acquired, taken private, or restructured out of eligibility. Each departure still needs a rule, and the workable one is to hold the position to the last available price and then redeploy the proceeds. Prices that run past the delisting date are the part many free sources cannot supply.

Company Ticker Last traded Last close
Starwood Hotels & Resorts HOT 2016-09-22 $77.05
Legg Mason LM 2020-07-31 $49.99
First Republic Bank FRCB 2026-07-24 $0.0004

Starwood’s last trade was $77.05 on 22 September 2016, the session before Marriott completed the acquisition, so a position in it was cashed out near its peak. First Republic tells the opposite story and tells it in a way that matters for measurement: taken into FDIC receivership on 1 May 2023, the shares still change hands over the counter at four hundredths of a cent. A backtest keyed on “is this ticker still in the index” throws that away and books nothing. A backtest that keeps the position books a total loss, which is what actually happened to the shareholder.

Does the ticker still point at the same company?

Not always, and the failure is silent.

info = xfl.resolve("EMC")
for e in info["data"]["EMC"]["entities"]:
    print(e["name"], e["entity_id"], e["ticker_valid_from"], "->", e["ticker_valid_to"])

Output:

E M C CORP MA    8539   1988-03-22 -> 2016-09-06
GLOBAL X FUNDS  69408   2023-05-15 -> None

EMC Corp used that symbol until Dell acquired it in September 2016. Seven years later an exchange-traded fund took it over. A price request for EMC today returns the fund, which is correct behaviour and completely wrong for a study of the 2016 S&P 500. Permanent entity identifiers are what keep the two apart; the same problem shows up under ticker changes at META, GM and DELL.

Where can you get the data?

Every entry below was checked against the provider’s own pages or API on 27 July 2026.

Source What it provides for this problem
Wikipedia, “List of S&P 500 companies” A current components table, plus a table its own heading calls “Selected changes to the list of S&P 500 components”
Alpha Vantage LISTING_STATUS CSV of active or delisted US listings with ipoDate and delistingDate, filtered by a date parameter
Massive (polygon.io) all-tickers A date parameter to “retrieve tickers available on that date” and an active flag for delisted symbols
yfinance Per-symbol data from Yahoo Finance; the API reference lists no function for index constituents or membership history
xfinlink index(as_of=) membership on any date, index_events() as a dated add and remove log, prices for delisted companies, and resolve() for reassigned symbols

Sources in row order: the Wikipedia list of S&P 500 companies; the Alpha Vantage documentation and a live LISTING_STATUS call for 10 July 2014; the Massive all-tickers reference, reached because polygon.io redirects to massive.com; the yfinance API reference; the xfinlink docs.

Alpha Vantage and Massive both answer the question “which securities existed and traded on this date”, which is genuinely useful and covers the delisting half of the problem. Neither answers “which of them were in the index on that date”, and that is the half the backtest depends on. Working the membership question out from index provider press releases is possible; it is also weeks of work for something that should be one function call. Full price history for delisted companies runs back to 1996 on the $29 Pro plan.

FAQ

Is survivorship bias the same as look-ahead bias?
No. Look-ahead bias uses information that was not public yet, such as a fiscal-year figure on the day the year ended rather than the day it was filed. Survivorship bias uses a universe that was not knowable yet. A backtest can suffer from either alone, and many suffer from both.

Does survivorship bias always inflate returns?
For long-only equity strategies, almost always, because the excluded names are disproportionately the ones that went to zero. The sign can flip for strategies designed to profit from distress, where removing the failures removes the gains.

How far back does point-in-time membership need to go?
As far back as the backtest starts, plus whatever lookback the signal needs. Ten years of history covers roughly 29% turnover in the S&P 500, so any test spanning a decade or more is dominated by this choice rather than nudged by it.

Can this be done on a free plan?
Historical membership snapshots, yes: a free key allows 50 as-of calls per day. Price histories for delisted companies from the 1990s and 2000s need a paid plan, since the free tier serves a rolling one-year window.

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