BLOG

Behind the numbers.

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

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

Is the Semiconductor Rally Broadening Beyond NVIDIA? Return Dispersion Analysis in Python

What's the question?

Semiconductor stocks now represent nearly 20% of the S&P 500. For much of 2024 and 2025, the rally was concentrated in two names: NVIDIA and Broadcom, both benefiting directly from AI accelerator demand. In mid-2026, a different pattern has emerged. Memory stocks like Micron jumped 4.5% in a single session in early July. Equipment makers AMAT, LRCX, and KLAC have posted strong multi-month runs. AMD has more than doubled over 60 trading days.

The question is whether the semiconductor rally is broadening — with gains spreading across the ecosystem — or whether the sector is merely rotating leadership from one narrow set to another. These are different conditions with different implications. A broad rally reflects sector-wide demand growth and is more likely to persist. A rotation from one concentrated leader to another signals stock-specific catalysts rather than fundamental breadth, and may not sustain.

Return dispersion provides a direct measurement. Cross-sectional dispersion is the standard deviation of returns across stocks on a given day. When dispersion is low, stocks move together — the rally is broad. When dispersion is high, individual stocks diverge sharply — leadership is narrow, even if multiple names are rising. A complementary measure is breadth: how many of the 10 semiconductor stocks trade above their 60-day moving average.

The approach

  1. Pull one year of daily returns for 10 semiconductor stocks spanning AI chips (NVDA, AVGO), general-purpose logic (AMD, QCOM), memory (MU, MRVL), and equipment (AMAT, LRCX, KLAC, TXN)
  2. Compute rolling 60-day cross-sectional return dispersion — the average daily standard deviation across all 10 stocks over trailing 60 days
  3. Compute each stock’s rolling 60-day cumulative return to track momentum leadership
  4. Build a normalized price index from daily returns and count how many of the 10 stocks trade above their 60-day moving average
  5. Compare the latest breadth and dispersion readings against their historical averages

Code

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

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

tickers = ["NVDA", "MU", "AVGO", "AMD", "AMAT", "LRCX", "KLAC", "MRVL", "QCOM", "TXN"]
df = xfl.prices(tickers, period="1y", fields=["return_daily"])

ret = df.pivot_table(index="date", columns="ticker", values="return_daily")
ret = ret.sort_index().dropna()

# Cross-sectional dispersion: std of returns across stocks each day
daily_cross_std = ret.std(axis=1)
rolling_dispersion = daily_cross_std.rolling(60).mean()

# Rolling 60-day cumulative return
rolling_cum = ret.rolling(60).apply(lambda x: (1 + x).prod() - 1)

# Normalized price index from returns, then 60-day MA
price_idx = (1 + ret).cumprod() * 100
ma60 = price_idx.rolling(60).mean()
above_ma = (price_idx > ma60).sum(axis=1)

latest_disp = rolling_dispersion.dropna().iloc[-1]
avg_disp = rolling_dispersion.dropna().mean()
latest_above = price_idx.iloc[-1] > ma60.iloc[-1]

for t in sorted(tickers, key=lambda x: rolling_cum.iloc[-1][x], reverse=True):
    cum = rolling_cum.iloc[-1][t]
    pct = (price_idx.iloc[-1][t] / ma60.iloc[-1][t] - 1) * 100
    status = "ABOVE" if latest_above[t] else "BELOW"
    print(f"{t:<6} 60d={cum:+.1%}  MA_gap={pct:+.1f}%  {status}")

print(f"\nBreadth: {int(above_ma.iloc[-1])}/{len(tickers)}")
print(f"Dispersion: {latest_disp:.4f} (avg {avg_disp:.4f})")

Full script with formatting and visualisation: semiconductor-breadth-dispersion-python.py

Output

Rolling 60-day cross-sectional return dispersion for 10 semiconductor stocks, showing a steep rise above the historical average from May 2026 onward
Observation period: 2025-07-10 to 2026-07-09
Trading days: 251

Ticker     60d Return    vs 60d MA     Status
--------------------------------------------
MU           +132.5%       +20.9%      ABOVE
AMD          +121.5%       +22.5%      ABOVE
MRVL          +85.3%       +12.5%      ABOVE
AMAT          +48.8%       +21.0%      ABOVE
QCOM          +45.6%        -1.8%      BELOW
TXN           +42.4%        +6.7%      ABOVE
LRCX          +32.1%       +11.5%      ABOVE
KLAC          +29.8%       +11.0%      ABOVE
NVDA           +7.1%        -2.6%      BELOW
AVGO           +5.6%        -1.3%      BELOW

Breadth: 7/10 stocks above 60-day MA
Historical average breadth: 7.6/10

Return dispersion (60d rolling avg): 0.0323
Historical average dispersion:       0.0232
Current dispersion is 40% above average (leadership is narrow)

What this tells us

The breadth and dispersion readings tell two different stories, and the contradiction is informative.

Seven of ten stocks trade above their 60-day moving average. That figure is near the historical average of 7.6, suggesting broad participation. But return dispersion is 40% above its historical average and has been rising steeply since May 2026. The chart shows dispersion breaking away from its mean in April and accelerating through July.

The resolution lies in the magnitude differences. All ten stocks have positive 60-day cumulative returns, but the range spans from +5.6% (AVGO) to +132.5% (MU) — a 127-percentage-point spread. MU and AMD have each more than doubled in 60 trading days. NVDA and AVGO, the two stocks that led the semiconductor rally in 2024–2025, are the weakest performers in the group at +7.1% and +5.6% respectively. Both sit slightly below their 60-day moving averages.

This is not a broadening rally in the traditional sense. It is a rotation of leadership within semiconductors. Memory stocks (MU, MRVL) and equipment makers (AMAT, LRCX, KLAC) have replaced AI accelerator names as momentum leaders. The three stocks below their 60-day moving average — NVDA, AVGO, and QCOM — are the ones that led the prior cycle.

So what?

The distinction between broadening and rotation matters for positioning. A broadening rally supports sector-level bets (semiconductor ETFs, equal-weight baskets). A rotation favors stock selection and underweights prior leaders.

The current data supports the rotation interpretation. An equal-weight semiconductor basket would have gained roughly 55% over 60 days, but most of that return came from two stocks. Meanwhile, NVDA and AVGO — the largest weights in capitalization-weighted semiconductor indices — contributed the least. Anyone holding SMH (the VanEck Semiconductor ETF) at cap-weighted proportions captured a fraction of the sector’s best-performing names.

For portfolio construction, the dispersion reading of 0.0323 — 40% above average — signals that idiosyncratic risk within semiconductors is elevated. Pair trades within the sector (long laggards, short leaders) become more attractive when dispersion is high. Sector-level hedges become less effective because individual stock behavior dominates. Monitoring dispersion provides a real-time gauge of whether the sector is trading as a group or as a collection of individual stories.

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