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 a Strong Balance Sheet Cushion Drawdowns? Leverage and Downside Risk in Python

What's the question?

"Quality" is supposed to protect on the downside. The claim that low-leverage firms fall less when markets fall is intuitive: a company with little debt has no lender to satisfy, no covenant to breach, and no refinancing to arrange at the worst moment. It is rarely tested.

Two terms define the test. Net debt to EBITDA measures balance-sheet leverage: total debt minus cash, divided by earnings before interest, tax, depreciation and amortisation — roughly how many years of operating earnings would repay borrowings. A negative value means more cash than debt. Maximum drawdown is the largest peak-to-trough decline over a window.

The practical question: does sorting on balance-sheet strength buy drawdown protection, or is it paying for a story?

The approach

Three selloffs: 2018 Q4 (20 Sep to 24 Dec 2018), COVID (19 Feb to 23 Mar 2020), and the 2022 bear market (3 Jan to 12 Oct 2022). One window is a single observation; three can disagree, and disagreement is informative.

  1. Build each universe point-in-time, via xfl.index("sp500", as_of=start). Using today’s membership to study a past drawdown is survivorship bias, especially damaging here: the firms later removed are disproportionately the ones that broke, and indebted firms break more often.
  2. Rank on leverage that was already public. Only fiscal quarters ending 120+ days before the window opens are used, clearing the 60-day annual and 40-day quarterly SEC filing deadlines. TTM EBITDA sums the last four.
  3. Measure max drawdown from return_daily, not raw closes, which step across splits and fabricate false drawdowns.
  4. Exclude Financials and Real Estate, where leverage is the business model rather than distress.
  5. Require positive TTM EBITDA, since the ratio is uninterpretable in sign when EBITDA is negative. Ranking rather than averaging stops extremes dragging bucket means.
  6. Sort into quintiles and test, with a Welch t-test on Q5 minus Q1 and a Spearman rank correlation.
  7. Repeat the correlation sector-neutral, ranking leverage and drawdown within GICS sector.

About 70 names per quintile. Drawdowns are negative, so a positive correlation means more leverage went with a shallower decline. One disclosure: statements are as currently restated, not as originally reported.

Code

import xfinlink as xfl
import pandas as pd
from scipy import stats

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

EPISODES = [("2018 Q4 selloff", "2018-09-20", "2018-12-24"),
            ("COVID crash",     "2020-02-19", "2020-03-23"),
            ("2022 bear market", "2022-01-03", "2022-10-12")]
EXCLUDE = {"Financials", "Real Estate"}

for name, start, end in EPISODES:
    cutoff = (pd.Timestamp(start) - pd.Timedelta(days=120)).strftime("%Y-%m-%d")
    universe = sorted(xfl.index("sp500", as_of=start)["ticker"].unique().tolist())

    f = xfl.fundamentals(universe, period_type="quarterly",
                         start=(pd.Timestamp(cutoff) - pd.Timedelta(days=500)).strftime("%Y-%m-%d"),
                         end=cutoff, fields=["ebitda", "total_debt", "cash_and_equivalents"])
    f["period_end"] = pd.to_datetime(f["period_end"])
    f = f.dropna(subset=["ebitda", "total_debt", "cash_and_equivalents"])

    lev = []
    for tk, g in f.sort_values(["ticker", "period_end"]).groupby("ticker"):
        g = g.drop_duplicates("period_end", keep="last").tail(4)
        if len(g) < 4:
            continue
        last, ttm = g.iloc[-1], g["ebitda"].sum()
        lev.append({"ticker": tk, "gics_sector": last["gics_sector"], "ttm_ebitda": ttm,
                    "net_debt_to_ebitda": (last["total_debt"] - last["cash_and_equivalents"]) / ttm})
    lev = pd.DataFrame(lev)
    lev = lev[~lev["gics_sector"].isin(EXCLUDE) & (lev["ttm_ebitda"] > 0)]

    p = xfl.prices(universe, start=start, end=end,
                   fields=["close", "return_daily"], max_rows=500000)
    assert p["ticker"].nunique() / len(universe) > 0.95, "panel truncated"

    dd = []
    for tk, g in p.sort_values(["ticker", "date"]).groupby("ticker"):
        r = g["return_daily"].dropna()
        cum = (1 + r).cumprod()
        dd.append({"ticker": tk, "max_dd": float((cum / cum.cummax() - 1).min())})

    m = lev.merge(pd.DataFrame(dd), on="ticker", how="inner")
    m["quintile"] = pd.qcut(m["net_debt_to_ebitda"], 5, labels=["Q1", "Q2", "Q3", "Q4", "Q5"])

    rho, rp = stats.spearmanr(m["net_debt_to_ebitda"], m["max_dd"])
    e = m[m.groupby("gics_sector")["ticker"].transform("size") >= 5].copy()
    e["lev_r"] = e.groupby("gics_sector")["net_debt_to_ebitda"].rank(pct=True)
    e["dd_r"] = e.groupby("gics_sector")["max_dd"].rank(pct=True)
    sn_rho, sn_p = stats.spearmanr(e["lev_r"], e["dd_r"])

    print(f"{name}: raw rho={rho:+.3f} (p={rp:.4f})  sector-neutral rho={sn_rho:+.3f} (p={sn_p:.4f})")

Full script with formatting and visualisation: balance-sheet-drawdown-protection-python.py

Output

Top panel: mean maximum drawdown by net debt to EBITDA quintile across the 2018 Q4 selloff, COVID crash and 2022 bear market. Bottom panel: raw versus sector-neutral correlation of leverage with drawdown for each episode.
============================================================================================
SAMPLE — point-in-time S&P 500 members, ex-Financials/Real Estate, TTM EBITDA > 0
============================================================================================
         episode                   window ranked_on_data_to  universe  ex_fin_re  ebitda_pos  final_n
 2018 Q4 selloff 2018-09-20 to 2018-12-24        2018-05-23       497        360         352      327
     COVID crash 2020-02-19 to 2020-03-23        2019-10-22       500        372         369      352
2022 bear market 2022-01-03 to 2022-10-12        2021-09-05       499        381         365      352

============================================================================================
MAX DRAWDOWN BY NET DEBT / EBITDA QUINTILE  (leverage known before the window opens)
============================================================================================

2018 Q4 selloff  (n=327)
   Q1 (least levered)   n= 66   median net debt/EBITDA  -0.36x   mean max drawdown  -25.91%
   Q2                   n= 65   median net debt/EBITDA   0.91x   mean max drawdown  -24.16%
   Q3                   n= 65   median net debt/EBITDA   1.69x   mean max drawdown  -23.13%
   Q4                   n= 65   median net debt/EBITDA   2.58x   mean max drawdown  -24.26%
   Q5 (most levered)    n= 66   median net debt/EBITDA   5.08x   mean max drawdown  -20.03%
   Q5 minus Q1: +5.89 pp   Welch t=+3.29  p=0.0013
   Spearman rho(leverage, max drawdown) = +0.187  p=0.0007

COVID crash  (n=352)
   Q1 (least levered)   n= 71   median net debt/EBITDA  -0.31x   mean max drawdown  -36.56%
   Q2                   n= 70   median net debt/EBITDA   0.95x   mean max drawdown  -40.11%
   Q3                   n= 70   median net debt/EBITDA   1.84x   mean max drawdown  -40.29%
   Q4                   n= 70   median net debt/EBITDA   2.71x   mean max drawdown  -43.20%
   Q5 (most levered)    n= 71   median net debt/EBITDA   4.89x   mean max drawdown  -44.84%
   Q5 minus Q1: -8.28 pp   Welch t=-3.55  p=0.0005
   Spearman rho(leverage, max drawdown) = -0.186  p=0.0005

2022 bear market  (n=352)
   Q1 (least levered)   n= 71   median net debt/EBITDA  -0.60x   mean max drawdown  -38.64%
   Q2                   n= 70   median net debt/EBITDA   0.71x   mean max drawdown  -33.12%
   Q3                   n= 70   median net debt/EBITDA   1.55x   mean max drawdown  -31.43%
   Q4                   n= 70   median net debt/EBITDA   2.58x   mean max drawdown  -30.04%
   Q5 (most levered)    n= 71   median net debt/EBITDA   5.41x   mean max drawdown  -30.24%
   Q5 minus Q1: +8.40 pp   Welch t=+4.33  p=0.0000
   Spearman rho(leverage, max drawdown) = +0.243  p=0.0000

============================================================================================
SECTOR MIX OF THE EXTREME QUINTILES
============================================================================================

2018 Q4 selloff
   Q1 (least levered)   Information Technology 19, Health Care 13, Consumer Discretionary 13
   Q5 (most levered)    Utilities 23, Consumer Discretionary 10, Industrials 9

COVID crash
   Q1 (least levered)   Information Technology 18, Health Care 16, Industrials 12
   Q5 (most levered)    Utilities 25, Consumer Discretionary 13, Consumer Staples 7

2022 bear market
   Q1 (least levered)   Information Technology 22, Consumer Discretionary 16, Industrials 12
   Q5 (most levered)    Utilities 25, Consumer Discretionary 12, Health Care 7

============================================================================================
SECTOR-NEUTRAL TEST — rank leverage and drawdown WITHIN sector, then correlate
============================================================================================
2018 Q4 selloff    n=327  raw rho=+0.187 (p=0.0007)   sector-neutral rho=+0.011 (p=0.8443)
COVID crash        n=352  raw rho=-0.186 (p=0.0005)   sector-neutral rho=-0.251 (p=0.0000)
2022 bear market   n=352  raw rho=+0.243 (p=0.0000)   sector-neutral rho=+0.112 (p=0.0359)

What this tells us

The sign flips across episodes, and every raw result is statistically significant.

In two of the three selloffs the most indebted firms fell less. In 2018 the least levered quintile lost 25.91% against 20.03% for the most levered — a 5.89 point spread favouring leverage, t=+3.29, p=0.0013. In 2022 the gap is wider: 38.64% against 30.24%, 8.40 points at p<0.0001. Either alone would suggest a strong balance sheet made drawdowns worse. COVID reverses it: 36.56% against 44.84%, leverage costing 8.28 points at p=0.0005.

The sector mix explains the contradiction. The most levered quintile is dominated by Utilities in all three episodes, 23 to 25 names out of roughly 70, while the least levered is led by Information Technology. A leverage quintile is largely a sector bet wearing a balance-sheet label.

The sector-neutral test confirms this. Ranking within sector, the 2018 effect collapses from +0.187 to +0.011 at p=0.8443 — indistinguishable from zero. The 2022 effect falls by more than half, from +0.243 to +0.112, surviving only marginally at p=0.0359. Both apparent "leverage protects" results were mostly sector composition: the 2022 rate shock repriced long-duration technology equity for reasons unrelated to balance sheets.

Only COVID strengthens under the control, from -0.186 to -0.251 at p<0.0001. That is the one episode striking the mechanism leverage operates through: a shutdown stops revenue while interest and principal remain contractually due. The extremes are real — in June 2021 Las Vegas Sands carried $26.9bn of net debt against $136m of trailing EBITDA, near 198x, casinos shut.

So what?

Balance-sheet strength is not a general-purpose drawdown hedge. It is insurance against one peril: a shock that interrupts cash flow. It paid in COVID and not in a rate-driven repricing, where duration mattered more than gearing.

Three consequences follow. First, sort leverage within sector, never across it: a raw leverage screen delivers a utilities overweight, and the manager should know whether that is intended. Second, size the expectation to the scenario — against a demand collapse, low leverage helps; against rising discount rates, it is close to irrelevant. Third, treat any single-episode quality backtest with suspicion. Each window here, alone, produces a significant result, and two of the three point the wrong way.

The discipline generalises: before attributing a cross-sectional result to the characteristic named in the sort, neutralise the obvious confounder and check whether it survives.

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