Market Breadth Analyzer
import pandas as pd, numpy as np
class MarketBreadthAnalyzer:
@staticmethod
def scan_breadth(pairs_data: dict, trend_threshold: float = 25) -> dict:
trending_up = []; trending_down = []; ranging = []
for sym, df in pairs_data.items():
if df.empty or len(df) < 50: continue
close = df["close"]
ema50 = close.ewm(span=50).mean().iloc[-1]
plus_dm = df["high"].diff().clip(lower=0).rolling(14).mean()
minus_dm = (-df["low"].diff()).clip(lower=0).rolling(14).mean()
atr = (df["high"] - df["low"]).rolling(14).mean()
dx = abs(plus_dm - minus_dm) / (plus_dm + minus_dm + 1e-10) * 100
adx = dx.rolling(14).mean().iloc[-1]
if adx > trend_threshold and close.iloc[-1] > ema50: trending_up.append(sym)
elif adx > trend_threshold and close.iloc[-1] < ema50: trending_down.append(sym)
else: ranging.append(sym)
total = len(trending_up) + len(trending_down) + len(ranging)
return {
"trending_up": trending_up, "trending_down": trending_down, "ranging": ranging,
"breadth_score": round((len(trending_up) - len(trending_down)) / max(total, 1) * 100, 1),
"pct_trending": round((len(trending_up) + len(trending_down)) / max(total, 1) * 100, 1),
"market_mode": "TRENDING" if len(trending_up) + len(trending_down) > len(ranging) else "RANGE-BOUND",
"bias": "RISK-ON" if len(trending_up) > len(trending_down) * 1.5 else "RISK-OFF" if len(trending_down) > len(trending_up) * 1.5 else "MIXED",
}
@staticmethod
def breadth_divergence(breadth_history: list[dict], index_prices: list[float]) -> dict:
"""Detect divergence between breadth and price index."""
if len(breadth_history) < 5 or len(index_prices) < 5:
return {"divergence": "INSUFFICIENT_DATA"}
recent_breadth = [b["breadth_score"] for b in breadth_history[-5:]]
breadth_trend = recent_breadth[-1] - recent_breadth[0]
price_trend = index_prices[-1] - index_prices[0]
if price_trend > 0 and breadth_trend < -10:
return {"divergence": "BEARISH", "signal": "Price rising but fewer pairs trending up — rally weakening"}
elif price_trend < 0 and breadth_trend > 10:
return {"divergence": "BULLISH", "signal": "Price falling but more pairs turning up — selloff exhausting"}
return {"divergence": "NONE", "signal": "Breadth confirms price action"}
Interpretation Guide
| Breadth Score |
Market Mode |
Strategy Implication |
| > +60 |
Strong risk-on |
Trend-following, momentum strategies |
| +20 to +60 |
Moderate bullish |
Selective breakouts, reduced position size |
| -20 to +20 |
Mixed/neutral |
Mean reversion, range strategies |
| -60 to -20 |
Moderate bearish |
Short setups, defensive positioning |
| < -60 |
Strong risk-off |
Counter-trend caution, hedge existing longs |
Usage
breadth = MarketBreadthAnalyzer.scan_breadth(pairs_data)
print(f"Market: {breadth['market_mode']} | Bias: {breadth['bias']} | {breadth['pct_trending']}% trending")
div = MarketBreadthAnalyzer.breadth_divergence(breadth_history, dxy_prices)
if div["divergence"] != "NONE":
print(f"WARNING: {div['divergence']} divergence — {div['signal']}")
1---2name: market-breadth-analyzer3description: Market breadth — how many pairs trending vs ranging, overall market health, breadth divergence. Use for "market breadth, breadth scan, market health, how many trending, broad market, pairs trending", or any related query. Works with trading-brain and relevant analysis/strategy skills.4---56# Market Breadth Analyzer78```python9import pandas as pd, numpy as np1011class MarketBreadthAnalyzer:12 @staticmethod13 def scan_breadth(pairs_data: dict, trend_threshold: float = 25) -> dict:14 trending_up = []; trending_down = []; ranging = []15 for sym, df in pairs_data.items():16 if df.empty or len(df) < 50: continue17 close = df["close"]18 ema50 = close.ewm(span=50).mean().iloc[-1]19 plus_dm = df["high"].diff().clip(lower=0).rolling(14).mean()20 minus_dm = (-df["low"].diff()).clip(lower=0).rolling(14).mean()21 atr = (df["high"] - df["low"]).rolling(14).mean()22 dx = abs(plus_dm - minus_dm) / (plus_dm + minus_dm + 1e-10) * 10023 adx = dx.rolling(14).mean().iloc[-1]24 if adx > trend_threshold and close.iloc[-1] > ema50: trending_up.append(sym)25 elif adx > trend_threshold and close.iloc[-1] < ema50: trending_down.append(sym)26 else: ranging.append(sym)27 total = len(trending_up) + len(trending_down) + len(ranging)28 return {29 "trending_up": trending_up, "trending_down": trending_down, "ranging": ranging,30 "breadth_score": round((len(trending_up) - len(trending_down)) / max(total, 1) * 100, 1),31 "pct_trending": round((len(trending_up) + len(trending_down)) / max(total, 1) * 100, 1),32 "market_mode": "TRENDING" if len(trending_up) + len(trending_down) > len(ranging) else "RANGE-BOUND",33 "bias": "RISK-ON" if len(trending_up) > len(trending_down) * 1.5 else "RISK-OFF" if len(trending_down) > len(trending_up) * 1.5 else "MIXED",34 }3536 @staticmethod37 def breadth_divergence(breadth_history: list[dict], index_prices: list[float]) -> dict:38 """Detect divergence between breadth and price index."""39 if len(breadth_history) < 5 or len(index_prices) < 5:40 return {"divergence": "INSUFFICIENT_DATA"}41 recent_breadth = [b["breadth_score"] for b in breadth_history[-5:]]42 breadth_trend = recent_breadth[-1] - recent_breadth[0]43 price_trend = index_prices[-1] - index_prices[0]44 if price_trend > 0 and breadth_trend < -10:45 return {"divergence": "BEARISH", "signal": "Price rising but fewer pairs trending up — rally weakening"}46 elif price_trend < 0 and breadth_trend > 10:47 return {"divergence": "BULLISH", "signal": "Price falling but more pairs turning up — selloff exhausting"}48 return {"divergence": "NONE", "signal": "Breadth confirms price action"}49```5051## Interpretation Guide5253| Breadth Score | Market Mode | Strategy Implication |54| --- | --- | --- |55| > +60 | Strong risk-on | Trend-following, momentum strategies |56| +20 to +60 | Moderate bullish | Selective breakouts, reduced position size |57| -20 to +20 | Mixed/neutral | Mean reversion, range strategies |58| -60 to -20 | Moderate bearish | Short setups, defensive positioning |59| < -60 | Strong risk-off | Counter-trend caution, hedge existing longs |6061## Usage6263```python64breadth = MarketBreadthAnalyzer.scan_breadth(pairs_data)65print(f"Market: {breadth['market_mode']} | Bias: {breadth['bias']} | {breadth['pct_trending']}% trending")6667div = MarketBreadthAnalyzer.breadth_divergence(breadth_history, dxy_prices)68if div["divergence"] != "NONE":69 print(f"WARNING: {div['divergence']} divergence — {div['signal']}")70```