BLOG

Behind the numbers.

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

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 Track S&P 500 Additions and Removals Over Time in 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 Ticker Recycling Corrupt a Mean-Reversion Backtest? Entity-Resolved Z-Scores in Python

What's the question?

A ticker is a mailing address, not an identity. When a company delists or restructures, the exchange may hand its symbol to an entirely different business. The symbol persists. The company behind it does not.

A price series keyed on the symbol therefore splices two unrelated companies into one continuous history. A z-score mean-reversion signal — how far a price has strayed from its recent average, in units of its recent standard deviation — is defined entirely by a rolling lookback window. If that window holds a different company’s prices, the signal is meaningless. The hypothesis under test: a symbol handover injects false signals that are not marginal noise but confident, tradeable, and wrong.

The approach

The test case is the symbol AA. On 1 November 2016 Alcoa Inc renamed itself Arconic (today Howmet Aerospace), keeping its SEC filer identity, and spun off a new aluminium business, Alcoa Corporation, which took AA. SEC EDGAR confirms both legs to the day: CIK 0000004281 became "Arconic Inc." on 1 November 2016 and trades as HWM today; CIK 0001675149 shed the name "Alcoa Upstream Corp" on 31 October 2016. The dates are consecutive trading days, and the two filers sit in different sectors.

xfl.prices("AA") does not return a spliced series; it returns Alcoa Corporation only. The naive series below reconstructs what symbol-keyed data produces, without hand-picking dates: the API stamps each row with the ticker that entity traded under that day, so selecting on ticker == "AA" across both entities reproduces symbol-keyed data exactly.

  1. Read the entity history for AA with resolve()
  2. Pull both entities: Alcoa Corporation via AA, the prior holder via HWM
  3. Build the naive series by symbol, the resolved series by entity
  4. Compute a 20-day rolling z-score on each; flag entries at |z| > 2
  5. Compare signal counts after the handover, then price the phantom trades

Adjusted close is used throughout, to avoid also stepping across Arconic’s October 2016 reverse split.

Code

import xfinlink as xfl
import pandas as pd

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

START, END, WINDOW, THRESH = "2016-08-01", "2017-02-28", 20, 2.0

# Who has held the symbol "AA"?
for e in xfl.resolve("AA")["data"]["AA"]["entities"]:
    print(e["name"], e["cik"], e["ticker_valid_from"], "->", e["ticker_valid_to"] or "present")

# prices("AA") returns ONLY the current holder (Alcoa Corp).
# The prior holder is reached through the symbol it trades under today: HWM.
old = xfl.prices("HWM", start=START, end=END, fields=["adj_close"])
new = xfl.prices("AA",  start=START, end=END, fields=["adj_close"])
both = pd.concat([old, new], ignore_index=True)

# NAIVE: select on the SYMBOL -> whatever company held "AA" that day.
naive = both[both["ticker"] == "AA"].sort_values("date").reset_index(drop=True)
# RESOLVED: select on the ENTITY -> one company, no splice.
resolved = both[both["entity_id"] == new["entity_id"].iloc[0]].sort_values("date").reset_index(drop=True)

def zscore(d):
    d = d.copy()
    m = d["adj_close"].rolling(WINDOW).mean()
    s = d["adj_close"].rolling(WINDOW).std()
    d["z"] = (d["adj_close"] - m) / s
    return d

naive, resolved = zscore(naive), zscore(resolved)

win  = naive[naive["date"] >= "2016-11-01"].head(WINDOW)
winr = resolved[resolved["date"] >= "2016-11-01"].head(WINDOW)
sigs = win[win["z"].abs() > THRESH]

print("naive   :", win["z"].notna().sum(), "scored,", len(sigs), "signals, max|z| =", round(win["z"].abs().max(), 2))
print("resolved:", winr["z"].notna().sum(), "scored,", int((winr["z"].abs() > THRESH).sum()), "signals")

Full script with formatting and visualisation: ticker-recycling-mean-reversion-backtest-python.py

Output

Two-panel chart of the symbol AA in 2016. The top panel shows the naive symbol-keyed price series in red splicing Alcoa Inc into Alcoa Corp at 1 November 2016, against the entity-resolved Alcoa Corp series in blue. The bottom panel shows the 20-day z-score, with six phantom signals above the +2 threshold in the weeks after the splice.
==========================================================================
ENTITY HISTORY FOR SYMBOL 'AA'
==========================================================================
  HOWMET AEROSPACE INC   CIK 0000004281  1962-07-02 -> 2016-10-31  (Industrials)
  ALCOA CORP             CIK 0001675149  2016-11-01 -> present  (Materials)

Naive symbol-keyed series: 146 rows, 2016-08-01 -> 2017-02-28
   ALCOA CORP             2016-11-01 -> 2017-02-28  (81 days)
   HOWMET AEROSPACE INC   2016-08-01 -> 2016-10-31  (65 days)
Entity-resolved series:    81 rows, 2016-11-01 -> 2017-02-28

==========================================================================
THE SPLICE (no gap: consecutive trading days)
==========================================================================
  2016-10-31  AA =  21.54   HOWMET AEROSPACE INC
  2016-11-01  AA =  23.00   ALCOA CORP
  Implied one-day return: +6.78%  -- earned by no shareholder of either company

==========================================================================
FIRST 20 TRADING DAYS AFTER SPLICE (2016-11-01 -> 2016-11-29)
==========================================================================
  Naive    : 20 days scored, 6 signals (|z|>2.0), max|z| = 2.58
  Resolved :  1 days scored, 0 signals -- insufficient history to score the rest

  Phantom trades (z > +2 => mean-reversion SHORT, 5-day hold):
    2016-11-03  z=+2.06  short 24.15 -> cover 29.10    -20.50%
    2016-11-04  z=+2.42  short 25.20 -> cover 29.30    -16.27%
    2016-11-07  z=+2.12  short 25.08 -> cover 29.62    -18.10%
    2016-11-08  z=+2.29  short 26.40 -> cover 30.21    -14.43%
    2016-11-09  z=+2.58  short 28.72 -> cover 31.42     -9.40%
    2016-11-10  z=+2.21  short 29.10 -> cover 31.85     -9.45%

  6 phantom shorts | mean -14.69% | cumulative -88.15% | win rate 0%
  Alcoa Corp over the same stretch: 23.00 -> 31.85 (+38.5%)

==========================================================================
OTHER S&P 500 SYMBOLS WITH AN EDGAR-CONFIRMED HANDOVER BETWEEN DISTINCT FILERS
==========================================================================
  (entity_name is the filer's CURRENT legal name, not its name at the time)
  GM:
     General Motors Corporation (pre-2009 bankruptcy) CIK 0000040730  1962-07-02 -> 2009-06-01
     General Motors Company                           CIK 0001467858  2010-11-18 -> present
  DELL:
     DELL INC                                         CIK 0000826083  1988-06-22 -> 2013-10-29
     DELL TECHNOLOGIES INC                            CIK 0001571996  2018-12-28 -> present
  BG:
     CALERES INC                                      CIK 0000014707  1977-04-04 -> 1999-05-27
     BUNGE GLOBAL S A                                 CIK 0001996862  2001-08-02 -> present

What this tells us

The naive series scores all 20 days after the handover and fires 6 signals. The resolved series scores 1 and fires none, correctly reporting that Alcoa Corporation lacks 20 days of history. The naive series believes it has 20 days; nineteen belong to an aerospace company. Its rolling mean on 3 November sits near Arconic’s $20 level, while Alcoa Corporation opened at $23.00 and ran higher. The z-score reads the new company as stretched above an average that is not its own.

The damage is directional, not random. All 6 signals point the same way, and Alcoa Corporation rallied 38.5% over the following fortnight. Priced against real closes, the phantom shorts return a mean of -14.69% with a 0% win rate. A researcher would conclude the strategy fails on AA. It never traded AA. A data defect did.

The maximum |z| is 2.58 — not an outlier. A 10-sigma print would be caught by any sanity filter, whereas a cluster between 2.0 and 2.6 looks like a textbook setup, which is why this error survives review. The contamination is bounded: the two z-series agree to machine precision from 29 November, exactly 20 trading days after the handover, once the window flushes the last Arconic price. The handover left no other trace: no date gap, no jump, and the name said Alcoa on both sides.

So what?

Resolve identity before computing anything with a lookback. Any statistic with a memory — a rolling mean, a volatility estimate, a beta — inherits whatever the window contains, and a window is exactly where a splice hides. Two practices follow: key every series on a persistent entity identifier, and require the lookback window to sit entirely within one entity’s life, suppressing signals until it does. That second rule alone eliminates all 6 phantom trades here.

AA is not a special case. Three current S&P 500 symbols show the same structure, each confirmed the same way: distinct filer CIKs, a rename or exit matching the handover date, and the current holder checked against EDGAR’s ticker registry. GM passed from General Motors Corporation — Motors Liquidation Company after 2009 — to General Motors Company in 2010; DELL from Dell Inc, taken private in 2013, to Dell Technologies in 2018; BG from Brown Group, today Caleres, to Bunge in 2001. Three is a floor: EDGAR does not record historical ticker assignments, and delisted names — where recycling concentrates — are excluded.

Screening entity history costs one resolve() call. Attributing a data defect to a strategy costs considerably more.

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