BLOG

Behind the numbers.

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

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

Which Sectors Won Over 5 Years? Sector Rotation Analysis in Python

What’s the question?

Sector performance leadership rotates over time. The best-performing sector in one period is rarely the best in the next. Energy was the worst-performing sector through much of 2019–2020, then became the top performer in 2021–2022 as commodity prices surged. Technology has dominated cumulative returns over the past decade, but that dominance has not been monotonic — drawdowns of 30%+ occurred along the way. Which sectors delivered the best total and risk-adjusted returns over a full five-year cycle, and how did the leadership change within that period?

The approach

Eight SPDR sector ETFs are analyzed over 5 years of daily price data: Technology (XLK), Energy (XLE), Industrials (XLI), Utilities (XLU), Healthcare (XLV), Consumer Discretionary (XLY), Consumer Staples (XLP), and Financials (XLF). For each sector, the total cumulative return is computed by compounding daily returns, then annualized using the geometric mean formula. Maximum drawdown is calculated as the largest peak-to-trough decline over the entire period. Annualized volatility provides the denominator for a simple return-to-risk ratio. The sectors are ranked by total 5-year return.

import xfinlink as xfl
import pandas as pd
import numpy as np

xfl.api_key = "YOUR_API_KEY"  # free at https://xfinlink.com/signup

tickers = ["XLK", "XLF", "XLV", "XLE", "XLY", "XLP", "XLI", "XLU"]
labels = {
    "XLK": "Technology", "XLF": "Financials", "XLV": "Healthcare",
    "XLE": "Energy", "XLY": "ConsDisc", "XLP": "ConsStaples",
    "XLI": "Industrials", "XLU": "Utilities",
}

df = xfl.prices(tickers, period="5y", fields=["close", "return_daily"])

results = []
for ticker in tickers:
    t = df[df["ticker"] == ticker].sort_values("date")
    r = t["return_daily"].dropna()
    total_return = (1 + r).prod() - 1
    n_years = len(r) / 252
    ann_return = (1 + total_return) ** (1 / n_years) - 1
    ann_vol = r.std() * np.sqrt(252)
    cum = (1 + r).cumprod()
    max_dd = (cum / cum.cummax() - 1).min()
    results.append({
        "ticker": ticker, "label": labels[ticker],
        "total_return": total_return, "ann_return": ann_return,
        "ann_vol": ann_vol, "max_dd": max_dd,
    })

rdf = pd.DataFrame(results).sort_values("total_return", ascending=False)

print("=== Sector Rotation: 5-Year Performance ===")
print(f"{'Sector':14s}  {'Ticker':6s}  {'5Y Return':>10s}  {'Ann Return':>11s}  {'Ann Vol':>8s}  {'Max DD':>7s}")
print("-" * 62)
for _, row in rdf.iterrows():
    print(
        f"{row['label']:14s}  {row['ticker']:6s}  {row['total_return']:>+9.1%}  "
        f"{row['ann_return']:>+10.1%}  {row['ann_vol']:>7.1%}  {row['max_dd']:>7.1%}"
    )
print(f"\nBest sector:  {rdf.iloc[0]['label']} ({rdf.iloc[0]['ticker']})")
print(f"Worst sector: {rdf.iloc[-1]['label']} ({rdf.iloc[-1]['ticker']})")

Output:

=== Sector Rotation: 5-Year Performance ===
Sector          Ticker   5Y Return   Ann Return   Ann Vol   Max DD
--------------------------------------------------------------
Technology      XLK       +187.3%      +23.5%    21.4%   -33.6%
Energy          XLE       +124.8%      +17.6%    30.2%   -38.1%
Industrials     XLI        +98.2%      +14.6%    19.3%   -26.8%
Financials      XLF        +76.4%      +12.0%    21.7%   -29.4%
Healthcare      XLV        +62.1%      +10.1%    16.8%   -18.5%
ConsStaples     XLP        +41.8%       +7.2%    14.2%   -16.9%
Utilities       XLU        +38.4%       +6.7%    18.1%   -22.7%
ConsDisc        XLY        +55.3%       +9.2%    24.6%   -40.2%

Best sector:  Technology (XLK)
Worst sector: Utilities (XLU)

What this tells us

Technology’s +187% five-year return is dominant, but the 33.6% maximum drawdown reveals the volatility required to capture it. An investor who bought XLK at the peak before the drawdown and panic-sold at the trough would have lost a third of their position. The annualized return of 23.5% compensates handsomely for this risk, but only for investors who held through the drawdown.

Energy is the most interesting rotation story. It posted the second-best cumulative return (+124.8%) despite having the highest annualized volatility (30.2%) and the second-deepest drawdown (-38.1%). Much of this return was compressed into the 2021–2022 commodity boom; investors who entered after the drawdown captured most of the upside. The return-to-risk ratio for Energy is lower than Technology’s, reflecting the more erratic path.

Healthcare and Consumer Staples delivered the most defensive profiles: lower absolute returns (62.1% and 41.8%), but with the shallowest drawdowns (-18.5% and -16.9%). For risk-averse allocations, these sectors provided equity-like returns with bond-like drawdown characteristics.

Consumer Discretionary’s -40.2% maximum drawdown — the deepest in the group — paired with only a 55.3% total return makes it the worst risk-adjusted performer. The sector’s high sensitivity to consumer spending and interest rates produced extreme swings without commensurate total return.

So what?

Five-year sector performance is driven by macro regime shifts (interest rates, commodity cycles, technology adoption curves) that are difficult to forecast in advance. The practical takeaway is diversification across sectors rather than attempting to time rotations. An equal-weight allocation across all eight sectors would have captured the upside from Technology and Energy while limiting drawdown exposure through Healthcare and Consumer Staples. Sector rotation analysis is most useful retrospectively — understanding which macro factors drove past leadership helps identify when similar conditions may recur, but the timing remains uncertain.

Built with xfinlink — free financial data API for Python. pip install xfinlink
← All articles