def load_prices(tickers): panier_path = DATASET_DIR /"panier_close_all.csv" prices = {}if panier_path.exists(): df = pd.read_csv(panier_path, index_col=0, parse_dates=True)for t in tickers:if t in df.columns: prices[t] = df[t].dropna() missing = [t for t in tickers if t notin prices]if missing:try:import yfinance as yf data = yf.download(missing, start="2010-01-01", end="2026-05-01", auto_adjust=True)["Close"]iflen(missing) ==1: data = data.to_frame(missing[0])for t in missing: prices[t] = data[t].dropna()exceptException:pass price_df = pd.DataFrame(prices).sort_index().ffill().dropna() price_df.index = pd.DatetimeIndex(price_df.index)print(f"Loaded: {price_df.shape[1]} tickers, {price_df.shape[0]} days [{price_df.index.min().date()} .. {price_df.index.max().date()}]")return price_dfall_tickers =list(set(SM_TICKERS + RS_TICKERS))prices = load_prices(all_tickers)prices.head()
Loaded: 4 tickers, 4106 days [2010-01-04 .. 2026-04-30]
IEF
QQQ
GLD
SPY
Date
2010-01-04
61.548901
40.290791
109.800003
84.796387
2010-01-05
61.819103
40.290791
109.699997
85.020821
2010-01-06
61.569653
40.047764
111.510002
85.080704
2010-01-07
61.569653
40.073792
110.820000
85.439880
2010-01-08
61.645866
40.403618
111.370003
85.724182
2. Signaux SectorMomentum et RegimeSwitching
SectorMomentum : composite momentum multi-lookback (1m/3m/6m/12m, poids 0.4/0.2/0.2/0.2). Top ticker par momentum, filtre SMA200.
RegimeSwitching : detection regime via SPY vs SMA50/SMA200. Bull=momentum risque-ajuste sur risky, Bear/Sideways=mean-reversion RSI+defensive.
def compute_sm_signal(prices, tickers=SM_TICKERS, lookbacks=SM_LOOKBACKS, weights=SM_WEIGHTS):"""SectorMomentum: composite momentum score per ticker per day.""" scores = pd.DataFrame(index=prices.index, columns=tickers, dtype=float)for t in tickers:if t notin prices.columns:continue close = prices[t] score = pd.Series(0.0, index=prices.index)for lb, w inzip(lookbacks, weights): mom = close / close.shift(lb) -1 score += w * mom scores[t] = scorereturn scoresdef compute_regime(prices, sma_short=50, sma_long=200):"""Detect market regime: bull/bear/sideways based on SPY vs SMA50/SMA200."""if"SPY"notin prices.columns:return pd.Series("bull", index=prices.index) spy = prices["SPY"] sma_s = spy.rolling(sma_short, min_periods=sma_short).mean() sma_l = spy.rolling(sma_long, min_periods=sma_long).mean() regime = pd.Series("sideways", index=prices.index) regime[(spy > sma_l) & (sma_s > sma_l)] ="bull" regime[(spy < sma_l) & (sma_s < sma_l)] ="bear"return regimedef compute_rsi(close, period=14):"""Compute RSI.""" delta = close.diff() gain = delta.clip(lower=0).rolling(period, min_periods=period).mean() loss =-delta.clip(upper=0).rolling(period, min_periods=period).mean() rs = gain / loss.replace(0, np.nan)return100-100/ (1+ rs)sm_scores = compute_sm_signal(prices)regime = compute_regime(prices)print(f"SM scores shape: {sm_scores.shape}")regime_counts = regime.value_counts()print(f"Regime distribution: {dict(regime_counts)}")
def aggregate_results(rows):from collections import defaultdict by_config = defaultdict(list)for r in rows: by_config[r["sm_alloc"]].append(r) edges = []for sm_a, group in by_config.items(): deltas = [r["sharpe_net"] - r["sharpe_spy"] for r in groupifnot np.isnan(r["sharpe_net"]) andnot np.isnan(r["sharpe_spy"])]iflen(deltas) >=2: mu =float(np.mean(deltas)) sd =float(np.std(deltas, ddof=1)) sigma_edge = mu / sd if sd >1e-9else np.nan is_signal = (not np.isnan(sigma_edge)) and sigma_edge >= EDGE_SIGMA edges.append({"sm_alloc": sm_a,"mean_delta": mu, "std_delta": sd,"sigma_edge": sigma_edge, "is_signal": is_signal,"mean_sharpe": float(np.mean([r["sharpe_net"] for r in group])),"mean_spy": float(np.mean([r["sharpe_spy"] for r in group])),"mean_cagr": float(np.mean([r["cagr_net"] for r in group])), }) n_signal =sum(1for e in edges if e["is_signal"]) median_sharpe =float(np.median([r["sharpe_net"] for r in rowsifnot np.isnan(r.get("sharpe_net", np.nan))])) if rows else np.nanif n_signal ==0: verdict ="NO BEATS"elif n_signal >=max(1, len(edges) //3): verdict ="BEATS"else: verdict ="INCONCLUSIVE"return {"verdict": verdict, "n_signal": n_signal, "n_configs": len(edges),"median_sharpe": median_sharpe, "configs": edges}if rows: summary = aggregate_results(rows)print("="*60)print(f"COMPOSITE Mom+Regime VERDICT: {summary['verdict']}")print(f"Signal configs: {summary['n_signal']}/{summary['n_configs']}")print(f"Median composite Sharpe: {summary['median_sharpe']:.3f}")print()print(f"{'Config':<15}{'Sharpe':>8}{'SPY':>8}{'Delta':>8}{'Edge':>8}{'Signal':>8}")print("-"*55)for e insorted(summary["configs"], key=lambda x: x["mean_delta"], reverse=True): sig ="YES"if e["is_signal"] else"no"print(f"SM{e['sm_alloc']:.0%}/RS{1-e['sm_alloc']:.0%}"f"{'':>5}{e['mean_sharpe']:>8.3f}{e['mean_spy']:>8.3f} "f"{e['mean_delta']:>+8.3f}{e['sigma_edge']:>8.2f}{sig:>8}")else:print("No results to aggregate")
============================================================
COMPOSITE Mom+Regime VERDICT: NO BEATS
Signal configs: 0/4
Median composite Sharpe: 0.914
Config Sharpe SPY Delta Edge Signal
-------------------------------------------------------
SM50%/RS50% 0.942 0.887 +0.055 nan no
SM60%/RS40% 0.927 0.887 +0.040 nan no
SM70%/RS30% 0.902 0.887 +0.015 nan no
SM80%/RS20% 0.869 0.887 -0.018 nan no
Lecture du verdict
Le composite Mom+Regime suit une pente décroissante quand la part SectorMomentum augmente (Sharpe 0.942 → 0.869 de SM50 à SM80) et aucune des 4 configs ne signale (0/4) : la médiane (0.914) dépasse le SPY (0.887) en apparence, mais le filtre régime n’ajoute pas d’edge séparable. La décomposition ne bat pas la baseline sur cette fenêtre.
6. Visualisation
import matplotlib.pyplot as pltif rows: fig, axes = plt.subplots(1, 2, figsize=(12, 5))# 1. Sharpe by SM allocation allocs =sorted(set(r["sm_alloc"] for r in rows)) mean_sharpes = [np.mean([r["sharpe_net"] for r in rows if r["sm_alloc"] == a]) for a in allocs] std_sharpes = [np.std([r["sharpe_net"] for r in rows if r["sm_alloc"] == a]) for a in allocs] axes[0].errorbar([f"{a:.0%}"for a in allocs], mean_sharpes, yerr=std_sharpes, marker="o", capsize=5, label="Composite") spy_sharpe = rows[0]["sharpe_spy"] axes[0].axhline(y=spy_sharpe, color="red", linestyle="--", label=f"SPY B&H ({spy_sharpe:.2f})") axes[0].set_title("Net Sharpe by SM Allocation") axes[0].set_ylabel("Annualized Sharpe") axes[0].legend() axes[0].grid(True, alpha=0.3)# 2. Delta distribution deltas = [r["sharpe_net"] - r["sharpe_spy"] for r in rowsifnot np.isnan(r["sharpe_net"]) andnot np.isnan(r["sharpe_spy"])] axes[1].hist(deltas, bins=15, edgecolor="black", alpha=0.7) axes[1].axvline(x=0, color="red", linestyle="--", label="SPY parity") axes[1].set_title(f"Delta Sharpe (mean={np.mean(deltas):.3f})") axes[1].set_xlabel("Delta Sharpe (composite - SPY)") axes[1].legend() axes[1].grid(True, alpha=0.3) plt.tight_layout() plt.savefig("composite_mom_regime_results.png", dpi=100, bbox_inches="tight") plt.show()else:print("No data to plot")
Conclusion
Ce notebook combine SectorMomentum (composite momentum multi-lookback sur SPY/IEF/GLD) avec RegimeSwitching (filtre bull/bear/sideways adaptant l’allocation entre momentum et mean-reversion RSI). Le sweep SM50-RS50 a SM80-RS20 avec 4 seeds determine si la combinaison bat SPY B&H.
Hypotheses testees : 1. La decorrelation regime/momentum du composite ameliore le Sharpe vs chaque composant seul 2. Le filtre regime evite les pertes en bear market (TLT->IEF + defensive allocation) 3. Le composite momentum multi-lookback est plus robuste qu’un seul lookback