Composite FamaFrench + AllWeather — Factor-Hedged Strategy Research

Lancer : Codespaces Colab

Strategy #44 | RL-1 Q-Learning · RL-2 PPO · RL-3 Reward Shaping · RL-4 Multi-Asset · RL-5 Overlay · RL-6 GRPO · Composite FF+AW

Objectifs

  • Combiner FamaFrench factor rotation (VLUE/MTUM/SIZE/QUAL/USMV) avec le socle defensif AllWeather (SPY/IEF/GLD/XLP)
  • Architecture inspiree de Framework_Composite_TrendWeather (Sharpe 1.155)
  • Signal FamaFrench : momentum risque-ajuste (return 252d / vol 63d) avec skip-month
  • Signal AllWeather : allocation statique 30/30/30/10
  • Sweep allocation FF50-AW50 a FF80-AW20
  • Walk-forward 5-fold, 4 seeds (0/1/7/42), verdict honnete

Architecture

Composant Allocation Signal
FamaFrench 50-80% Rotation trimestrielle, top-2 facteurs par momentum risque-ajuste
AllWeather 20-50% Allocation statique SPY 30% / IEF 30% / GLD 30% / XLP 10%

Cible : Sharpe > 0.7 sur 2015-2025. Baseline = SPY B&H.

Duree estimee : ~2 min | Prerequis : pandas, numpy, panier data

Navigation : Index recherche | << research_btc_ml | research_composite_mom_regime >>

import numpy as np
import pandas as pd
from pathlib import Path
import warnings
warnings.filterwarnings('ignore')

RESEARCH_DIR = Path(".")
DATASET_DIR = RESEARCH_DIR.parent / "datasets" / "panier"
SEEDS = [0, 1, 7, 42]
N_SPLITS = 5
FEE_BPS = 5  # transaction cost

# Factor ETFs (iShares Fama-French)
FF_TICKERS = ["VLUE", "MTUM", "SIZE", "QUAL", "USMV"]
# AllWeather defensive base
AW_TICKERS = ["SPY", "IEF", "GLD", "XLP"]
AW_WEIGHTS = {"SPY": 0.30, "IEF": 0.30, "GLD": 0.30, "XLP": 0.10}

print(f"FamaFrench factors: {FF_TICKERS}")
print(f"AllWeather: {AW_TICKERS} with weights {AW_WEIGHTS}")
FamaFrench factors: ['VLUE', 'MTUM', 'SIZE', 'QUAL', 'USMV']
AllWeather: ['SPY', 'IEF', 'GLD', 'XLP'] with weights {'SPY': 0.3, 'IEF': 0.3, 'GLD': 0.3, 'XLP': 0.1}

1. Chargement des données

On charge les prix depuis le panier CSV. Si indisponible, on telecharge via yfinance.

def load_prices(tickers):
    """Load daily close prices for given tickers. Try panier CSV first, then yfinance."""
    panier_path = DATASET_DIR / "panier_close_all.csv"
    all_tickers = list(set(tickers))
    
    prices = {}
    if panier_path.exists():
        df = pd.read_csv(panier_path, index_col=0, parse_dates=True)
        for t in all_tickers:
            if t in df.columns:
                prices[t] = df[t].dropna()
                print(f"  {t}: loaded from panier ({len(prices[t])} days)")
    
    missing = [t for t in all_tickers if t not in prices]
    if missing:
        try:
            import yfinance as yf
            data = yf.download(missing, start="2010-01-01", end="2026-05-01", auto_adjust=True)["Close"]
            if len(missing) == 1:
                data = data.to_frame(missing[0])
            for t in missing:
                prices[t] = data[t].dropna()
                print(f"  {t}: loaded from yfinance ({len(prices[t])} days)")
        except Exception as e:
            print(f"  yfinance unavailable: {e}")
            for t in missing:
                prices[t] = pd.Series(dtype=float)
    
    # Align to common index
    price_df = pd.DataFrame(prices)
    price_df.index = pd.DatetimeIndex(price_df.index)
    price_df = price_df.sort_index().ffill().dropna()
    print(f"\nCombined: {price_df.shape[1]} tickers, {price_df.shape[0]} days [{price_df.index.min().date()} .. {price_df.index.max().date()}]")
    return price_df

all_tickers = list(set(FF_TICKERS + AW_TICKERS))
prices = load_prices(all_tickers)
prices.head()
  GLD: loaded from yfinance (4106 days)
  VLUE: loaded from yfinance (3279 days)
  USMV: loaded from yfinance (3652 days)
  IEF: loaded from yfinance (4106 days)
  SPY: loaded from yfinance (4106 days)
  XLP: loaded from yfinance (4106 days)
  SIZE: loaded from yfinance (3279 days)
  MTUM: loaded from yfinance (3279 days)
  QUAL: loaded from yfinance (3216 days)

Combined: 9 tickers, 3216 days [2013-07-18 .. 2026-04-30]
GLD VLUE USMV IEF SPY XLP SIZE MTUM QUAL
Date
2013-07-18 124.010002 40.018391 26.503557 76.868149 135.416565 29.437634 42.695633 46.504517 41.594906
2013-07-19 125.110001 39.945259 26.566196 77.289368 135.657150 29.607628 42.695633 46.710789 41.271446
2013-07-22 128.839996 40.054935 26.574026 77.281868 135.921783 29.543871 43.468414 46.770947 41.470516
2013-07-23 129.710007 40.054935 26.542713 77.191589 135.633072 29.487207 43.468414 46.693600 41.404152
2013-07-24 127.480003 40.054935 26.370449 76.672562 135.135925 29.295961 43.468414 46.530300 41.346096

2. Signaux FamaFrench et AllWeather

FamaFrench : momentum risque-ajuste (252d return / 63d vol) avec skip-month (evite le biais de reversal a 1 mois). Filtre regime via SPY > SMA200.

AllWeather : allocation statique 30/30/30/10 rebalancee mensuellement.

def compute_ff_signals(prices, ff_tickers=FF_TICKERS, lookback=252, skip_days=21, vol_window=63):
    """Compute FamaFrench risk-adjusted momentum signals.
    
    Returns DataFrame of risk-adjusted momentum scores per factor per day.
    Signal = (252d-21d return) / (63d annualized vol).
    """
    signals = pd.DataFrame(index=prices.index, columns=ff_tickers, dtype=float)
    
    for t in ff_tickers:
        if t not in prices.columns:
            continue
        close = prices[t]
        ret_252 = close / close.shift(lookback) - 1  # 12m return
        ret_skip = close.shift(skip_days) / close.shift(lookback) - 1  # skip-month return
        vol_63 = close.pct_change().rolling(vol_window, min_periods=vol_window).std() * np.sqrt(252)
        
        # Risk-adjusted momentum (momentum Sharpe)
        risk_adj = ret_skip / vol_63.replace(0, np.nan)
        signals[t] = risk_adj
    
    return signals


def compute_spy_regime(prices, sma_period=200):
    """SPY > SMA200 regime filter."""
    if "SPY" not in prices.columns:
        return pd.Series(True, index=prices.index)
    spy_close = prices["SPY"]
    sma = spy_close.rolling(sma_period, min_periods=sma_period).mean()
    return spy_close > sma


ff_signals = compute_ff_signals(prices)
regime = compute_spy_regime(prices)

print(f"FF signals shape: {ff_signals.shape}")
print(f"Regime: {regime.sum()}/{len(regime)} days risk-on ({regime.mean()*100:.1f}%)")
print(f"\nFF signal stats (last available date):")
last_signals = ff_signals.dropna(how='all').iloc[-1]
print(last_signals.to_string())
FF signals shape: (3216, 5)
Regime: 2509/3216 days risk-on (78.0%)

FF signal stats (last available date):
VLUE    2.191348
MTUM    0.600456
SIZE    0.884477
QUAL    0.935232
USMV    0.271809

Exercice 1 – Score factoriel composite multi-signal

Le notebook selectionne les facteurs FamaFrench sur un unique signal : le momentum risque-ajuste (252d return / 63d vol). L’hypothese #3 du notebook suggere que ce signal pourrait etre ameliore. Une approche classique (cf. Asness, Moskowitz & Pedersen 2013, “Value and Momentum Everywhere”) consiste a combiner plusieurs signaux orthogonaux (momentum + value + low-volatility) en un score composite z-score, puis a sélectionner les top-N facteurs sur ce composite.

Objectif : completer la fonction ci-dessous pour calculer un score factoriel composite combinant le momentum risque-ajuste (déjà calcule dans ff_signals) avec un signal low-volatility (inverse de la volatilite realisee), chacun normalise en z-score cross-sectionnel.

Indices : - Étape 1 : recuperer le momentum risque-ajuste depuis ff_signals (déjà calcule). - Étape 2 : calculer un signal low-vol = 1 / vol_63d_annualisee pour chaque facteur. - Étape 3 : z-score cross-sectionnel de chaque signal (par date), puis combiner 50/50 (ou autre ponderation) en un score composite. Retourner un DataFrame aligne sur prices.index.

# Exercice 1 : Score factoriel composite multi-signal (momentum + low-vol)
# TODO etudiant : completer la fonction ci-dessous
def compute_composite_factor_score(prices, ff_tickers=FF_TICKERS,
                                    lookback=252, skip_days=21, vol_window=63,
                                    mom_weight=0.5, vol_weight=0.5):
    """Score factoriel composite = w_mom * z(risk_adj_momentum) + w_vol * z(low_vol).

    Indice :
      - momentum risque-ajuste : reutiliser la logique de compute_ff_signals
        (ret_skip / vol_63, avec ret_skip = close.shift(skip_days)/close.shift(lookback) - 1)
      - low_vol : 1 / vol_63_annualisee
      - z-score cross-sectionnel par date (axis=1), puis combiner lineairement.
    Retourner un DataFrame indexe par prices.index, colonnes = ff_tickers.
    """
    # TODO etudiant : momentum risque-ajuste (z-score cross-sectionnel)
    # TODO etudiant : low-vol = 1/vol_annualisee (z-score cross-sectionnel)
    # TODO etudiant : composite = mom_weight*z_mom + vol_weight*z_vol
    composite = None  # TODO etudiant : DataFrame pandas
    return composite

print("Exercice 1 a completer : implementer compute_composite_factor_score (momentum + low-vol)")
Exercice 1 a completer : implementer compute_composite_factor_score (momentum + low-vol)

3. Stratégie composite avec walk-forward

On combine FamaFrench (top-N facteurs par momentum risque-ajuste) + AllWeather (allocation statique). Walk-forward 5-fold expanding avec bornee, 4 seeds.

def walk_forward_composite(prices, ff_alloc, top_n=2, seed=0):
    """Walk-forward validation for FF+AW composite.
    
    ff_alloc: fraction allocated to FamaFrench (0.5 to 0.8)
    aw_alloc: 1 - ff_alloc goes to AllWeather
    top_n: number of top factors to hold in FF sleeve
    
    Returns dict with Sharpe, CAGR, max DD, and per-fold details.
    """
    np.random.seed(seed)
    aw_alloc = 1.0 - ff_alloc
    
    ff_signals = compute_ff_signals(prices)
    regime = compute_spy_regime(prices)
    
    # Daily returns
    returns = prices.pct_change().shift(-1)  # next-day return
    
    n = len(prices)
    fold_size = n // (N_SPLITS + 1)
    if fold_size < 300:
        return None
    
    all_dates = []
    all_port_ret = []
    all_bh_ret = []
    
    for k in range(1, N_SPLITS + 1):
        tr_end = fold_size * k
        te_end = min(tr_end + fold_size, n)
        tr_start = max(0, tr_end - 1500)  # bounded train window
        
        if te_end - tr_end < 60:
            continue
        
        # Out-of-test period
        for i in range(tr_end, te_end):
            date = prices.index[i]
            sig_row = ff_signals.iloc[i] if i < len(ff_signals) else None
            is_risk_on = regime.iloc[i] if i < len(regime) else True
            
            if sig_row is None or sig_row.isna().all():
                continue
            
            # --- FF sleeve: select top_n factors by risk-adjusted momentum ---
            ff_weights = {}
            if is_risk_on:
                sorted_factors = sig_row.dropna().sort_values(ascending=False)
                positive = sorted_factors[sorted_factors > 0]
                selected = positive.head(top_n).index.tolist()
                
                if not selected:
                    selected = ["USMV"]  # defensive fallback
                
                ff_w = ff_alloc / len(selected)
                for t in selected:
                    ff_weights[t] = ff_w
            else:
                # Risk-off: FF sleeve goes to USMV
                ff_weights["USMV"] = ff_alloc
            
            # --- AW sleeve: static allocation ---
            aw_weights = {}
            for t, w in AW_WEIGHTS.items():
                aw_weights[t] = w * aw_alloc
            
            # --- Combine ---
            combined = {}
            for t, w in ff_weights.items():
                combined[t] = combined.get(t, 0) + w
            for t, w in aw_weights.items():
                combined[t] = combined.get(t, 0) + w
            
            # Compute portfolio return (next day)
            if i + 1 < len(returns):
                port_ret = 0.0
                for t, w in combined.items():
                    if t in returns.columns and not np.isnan(returns.iloc[i + 1].get(t, np.nan)):
                        port_ret += w * returns.iloc[i + 1].get(t, 0)
                all_port_ret.append(port_ret)
                all_dates.append(date)
                # BH = equal weight all tickers
                bh_ret = returns.iloc[i + 1][[t for t in combined if t in returns.columns]].mean()
                all_bh_ret.append(bh_ret if not np.isnan(bh_ret) else 0)
    
    if len(all_port_ret) < 100:
        return None
    
    port_ret = np.array(all_port_ret)
    bh_ret = np.array(all_bh_ret)
    
    # Apply transaction costs (approx: penalize turnover)
    # Simple approximation: monthly rebalance ~0.5% round-trip per month
    monthly_tc = (FEE_BPS / 10000) * 2  # round-trip
    port_ret_net = port_ret - monthly_tc / 21  # amortized daily
    
    def sharpe(r):
        if len(r) < 30 or np.std(r, ddof=1) < 1e-12:
            return np.nan
        return float(np.mean(r) / np.std(r, ddof=1) * np.sqrt(252))
    
    def max_dd(r):
        cum = np.cumprod(1 + r)
        peak = np.maximum.accumulate(cum)
        dd = (cum - peak) / peak
        return float(dd.min())
    
    def cagr(r):
        cum = np.prod(1 + r)
        years = len(r) / 252
        return float(cum ** (1 / years) - 1) if years > 0 and cum > 0 else np.nan
    
    # SPY B&H baseline
    spy_ret = returns["SPY"].dropna().values if "SPY" in returns.columns else np.array([])
    spy_sharpe = sharpe(spy_ret) if len(spy_ret) >= 100 else np.nan
    
    return {
        "sharpe_gross": sharpe(port_ret),
        "sharpe_net": sharpe(port_ret_net),
        "sharpe_bh": sharpe(bh_ret),
        "sharpe_spy": spy_sharpe,
        "cagr_gross": cagr(port_ret),
        "cagr_net": cagr(port_ret_net),
        "max_dd_gross": max_dd(port_ret),
        "max_dd_net": max_dd(port_ret_net),
        "n_obs": len(port_ret),
        "ff_alloc": ff_alloc,
        "top_n": top_n,
        "seed": seed,
    }


# Quick test
test = walk_forward_composite(prices, ff_alloc=0.6, top_n=2, seed=0)
if test:
    print(f"Quick test (FF60/AW40, top=2): Sharpe gross={test['sharpe_gross']:.3f}, net={test['sharpe_net']:.3f}, SPY={test['sharpe_spy']:.3f}")
else:
    print("Quick test: insufficient data")
Quick test (FF60/AW40, top=2): Sharpe gross=0.997, net=0.901, SPY=0.852

4. Sweep allocation FF/AW + top_n

Sweep: FF allocation (50/60/70/80%) x top_n (1/2/3) x 4 seeds. Verdict honnete BEATS/NO BEATS/INCONCLUSIVE.

from itertools import product

FF_ALLOCS = [0.5, 0.6, 0.7, 0.8]
TOP_N_VALUES = [1, 2, 3]
EDGE_SIGMA = 2.0

rows = []
total = len(FF_ALLOCS) * len(TOP_N_VALUES) * len(SEEDS)
n = 0

for ff_alloc, top_n, seed in product(FF_ALLOCS, TOP_N_VALUES, SEEDS):
    n += 1
    result = walk_forward_composite(prices, ff_alloc=ff_alloc, top_n=top_n, seed=seed)
    if result is None:
        print(f"[{n}/{total}] FF{ff_alloc:.0%}/top={top_n}/seed={seed} SKIP")
        continue
    rows.append(result)
    print(f"[{n}/{total}] FF{ff_alloc:.0%}/top={top_n}/seed={seed} "
          f"Sharpe net={result['sharpe_net']:.3f} SPY={result['sharpe_spy']:.3f} "
          f"CAGR={result['cagr_net']:.3f}")

print(f"\nTotal: {len(rows)} combos completed")
[1/48] FF50%/top=1/seed=0 Sharpe net=0.957 SPY=0.852 CAGR=0.112
[2/48] FF50%/top=1/seed=1 Sharpe net=0.957 SPY=0.852 CAGR=0.112
[3/48] FF50%/top=1/seed=7 Sharpe net=0.957 SPY=0.852 CAGR=0.112
[4/48] FF50%/top=1/seed=42 Sharpe net=0.957 SPY=0.852 CAGR=0.112
[5/48] FF50%/top=2/seed=0 Sharpe net=0.933 SPY=0.852 CAGR=0.107
[6/48] FF50%/top=2/seed=1 Sharpe net=0.933 SPY=0.852 CAGR=0.107
[7/48] FF50%/top=2/seed=7 Sharpe net=0.933 SPY=0.852 CAGR=0.107
[8/48] FF50%/top=2/seed=42 Sharpe net=0.933 SPY=0.852 CAGR=0.107
[9/48] FF50%/top=3/seed=0 Sharpe net=0.912 SPY=0.852 CAGR=0.104
[10/48] FF50%/top=3/seed=1 Sharpe net=0.912 SPY=0.852 CAGR=0.104
[11/48] FF50%/top=3/seed=7 Sharpe net=0.912 SPY=0.852 CAGR=0.104
[12/48] FF50%/top=3/seed=42 Sharpe net=0.912 SPY=0.852 CAGR=0.104
[13/48] FF60%/top=1/seed=0 Sharpe net=0.927 SPY=0.852 CAGR=0.116
[14/48] FF60%/top=1/seed=1 Sharpe net=0.927 SPY=0.852 CAGR=0.116
[15/48] FF60%/top=1/seed=7 Sharpe net=0.927 SPY=0.852 CAGR=0.116
[16/48] FF60%/top=1/seed=42 Sharpe net=0.927 SPY=0.852 CAGR=0.116
[17/48] FF60%/top=2/seed=0 Sharpe net=0.901 SPY=0.852 CAGR=0.110
[18/48] FF60%/top=2/seed=1 Sharpe net=0.901 SPY=0.852 CAGR=0.110
[19/48] FF60%/top=2/seed=7 Sharpe net=0.901 SPY=0.852 CAGR=0.110
[20/48] FF60%/top=2/seed=42 Sharpe net=0.901 SPY=0.852 CAGR=0.110
[21/48] FF60%/top=3/seed=0 Sharpe net=0.878 SPY=0.852 CAGR=0.106
[22/48] FF60%/top=3/seed=1 Sharpe net=0.878 SPY=0.852 CAGR=0.106
[23/48] FF60%/top=3/seed=7 Sharpe net=0.878 SPY=0.852 CAGR=0.106
[24/48] FF60%/top=3/seed=42 Sharpe net=0.878 SPY=0.852 CAGR=0.106
[25/48] FF70%/top=1/seed=0 Sharpe net=0.897 SPY=0.852 CAGR=0.120
[26/48] FF70%/top=1/seed=1 Sharpe net=0.897 SPY=0.852 CAGR=0.120
[27/48] FF70%/top=1/seed=7 Sharpe net=0.897 SPY=0.852 CAGR=0.120
[28/48] FF70%/top=1/seed=42 Sharpe net=0.897 SPY=0.852 CAGR=0.120
[29/48] FF70%/top=2/seed=0 Sharpe net=0.870 SPY=0.852 CAGR=0.113
[30/48] FF70%/top=2/seed=1 Sharpe net=0.870 SPY=0.852 CAGR=0.113
[31/48] FF70%/top=2/seed=7 Sharpe net=0.870 SPY=0.852 CAGR=0.113
[32/48] FF70%/top=2/seed=42 Sharpe net=0.870 SPY=0.852 CAGR=0.113
[33/48] FF70%/top=3/seed=0 Sharpe net=0.845 SPY=0.852 CAGR=0.108
[34/48] FF70%/top=3/seed=1 Sharpe net=0.845 SPY=0.852 CAGR=0.108
[35/48] FF70%/top=3/seed=7 Sharpe net=0.845 SPY=0.852 CAGR=0.108
[36/48] FF70%/top=3/seed=42 Sharpe net=0.845 SPY=0.852 CAGR=0.108
[37/48] FF80%/top=1/seed=0 Sharpe net=0.869 SPY=0.852 CAGR=0.124
[38/48] FF80%/top=1/seed=1 Sharpe net=0.869 SPY=0.852 CAGR=0.124
[39/48] FF80%/top=1/seed=7 Sharpe net=0.869 SPY=0.852 CAGR=0.124
[40/48] FF80%/top=1/seed=42 Sharpe net=0.869 SPY=0.852 CAGR=0.124
[41/48] FF80%/top=2/seed=0 Sharpe net=0.840 SPY=0.852 CAGR=0.116
[42/48] FF80%/top=2/seed=1 Sharpe net=0.840 SPY=0.852 CAGR=0.116
[43/48] FF80%/top=2/seed=7 Sharpe net=0.840 SPY=0.852 CAGR=0.116
[44/48] FF80%/top=2/seed=42 Sharpe net=0.840 SPY=0.852 CAGR=0.116
[45/48] FF80%/top=3/seed=0 Sharpe net=0.813 SPY=0.852 CAGR=0.110
[46/48] FF80%/top=3/seed=1 Sharpe net=0.813 SPY=0.852 CAGR=0.110
[47/48] FF80%/top=3/seed=7 Sharpe net=0.813 SPY=0.852 CAGR=0.110
[48/48] FF80%/top=3/seed=42 Sharpe net=0.813 SPY=0.852 CAGR=0.110

Total: 48 combos completed

5. Aggregation et verdict

Edge >= 2 sigma cross-seed pour signal. Verdict honnete BEATS/NO BEATS/INCONCLUSIVE.

def aggregate_results(rows):
    """Aggregate sweep results with cross-seed edge validation."""
    from collections import defaultdict
    
    by_config = defaultdict(list)
    for r in rows:
        key = (r["ff_alloc"], r["top_n"])
        by_config[key].append(r)
    
    edges = []
    for (ff_a, top_n), group in by_config.items():
        deltas = [r["sharpe_net"] - r["sharpe_spy"] for r in group 
                  if not np.isnan(r["sharpe_net"]) and not np.isnan(r["sharpe_spy"])]
        if len(deltas) >= 2:
            mu = float(np.mean(deltas))
            sd = float(np.std(deltas, ddof=1))
            sigma_edge = mu / sd if sd > 1e-9 else np.nan
            is_signal = (not np.isnan(sigma_edge)) and sigma_edge >= EDGE_SIGMA
            edges.append({
                "ff_alloc": ff_a, "top_n": top_n,
                "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(1 for e in edges if e["is_signal"])
    median_sharpe = float(np.median([r["sharpe_net"] for r in rows 
                                     if not np.isnan(r.get("sharpe_net", np.nan))])) if rows else np.nan
    
    if 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 FF+AW VERDICT: {summary['verdict']}")
    print(f"Signal configs: {summary['n_signal']}/{summary['n_configs']}")
    print(f"Median composite Sharpe: {summary['median_sharpe']:.3f}")
    print()
    
    # Summary table
    print("Per-config results:")
    print(f"{'Config':<20} {'Sharpe':>8} {'SPY':>8} {'Delta':>8} {'Edge':>8} {'Signal':>8}")
    print("-"*70)
    for e in sorted(summary["configs"], key=lambda x: x["mean_delta"], reverse=True):
        cfg = f"FF{e['ff_alloc']:.0%}/top{e['top_n']}"
        sig = "YES" if e["is_signal"] else "no"
        print(f"{cfg:<20} {e['mean_sharpe']:>8.3f} {e['mean_spy']:>8.3f} "
              f"{e['mean_delta']:>+8.3f} {e['sigma_edge']:>8.2f} {sig:>8}")
    print()
    
    # Best CAGR
    best_cagr = max(summary["configs"], key=lambda x: x["mean_cagr"])
    print(f"Best CAGR: FF{best_cagr['ff_alloc']:.0%}/top{best_cagr['top_n']} = {best_cagr['mean_cagr']:.3f}")
else:
    print("No results to aggregate")
============================================================
COMPOSITE FF+AW VERDICT: NO BEATS
Signal configs: 0/12
Median composite Sharpe: 0.888

Per-config results:
Config                 Sharpe      SPY    Delta     Edge   Signal
----------------------------------------------------------------------
FF50%/top1              0.957    0.852   +0.105      nan       no
FF50%/top2              0.933    0.852   +0.081      nan       no
FF60%/top1              0.927    0.852   +0.075      nan       no
FF50%/top3              0.912    0.852   +0.060      nan       no
FF60%/top2              0.901    0.852   +0.049      nan       no
FF70%/top1              0.897    0.852   +0.045      nan       no
FF60%/top3              0.878    0.852   +0.026      nan       no
FF70%/top2              0.870    0.852   +0.018      nan       no
FF80%/top1              0.869    0.852   +0.017      nan       no
FF70%/top3              0.845    0.852   -0.007      nan       no
FF80%/top2              0.840    0.852   -0.012      nan       no
FF80%/top3              0.813    0.852   -0.039      nan       no

Best CAGR: FF80%/top1 = 0.124

Lecture du verdict

Les deltas par config sont positifs (jusqu’à +0.105) mais aucune des 12 configs ne franchit le critère de signal (0/12, edge non calculable) : la médiane des composites (0.888) dépasse le SPY (0.852) sans que l’avantage soit séparable du bruit. La décomposition FF/AW ne produit pas de combinaison identifiable sur cette fenêtre.

6. Visualisation

import matplotlib.pyplot as plt

if rows:
    fig, axes = plt.subplots(1, 3, figsize=(16, 5))
    
    # 1. Sharpe by allocation
    for top_n in TOP_N_VALUES:
        subset = [r for r in rows if r["top_n"] == top_n]
        if not subset:
            continue
        allocs = sorted(set(r["ff_alloc"] for r in subset))
        sharpes = [np.mean([r["sharpe_net"] for r in subset if r["ff_alloc"] == a]) for a in allocs]
        axes[0].plot([f"{a:.0%}" for a in allocs], sharpes, marker="o", label=f"top={top_n}")
    axes[0].axhline(y=rows[0]["sharpe_spy"], color="red", linestyle="--", label="SPY B&H")
    axes[0].set_title("Net Sharpe by FF Allocation")
    axes[0].set_ylabel("Annualized Sharpe")
    axes[0].legend()
    axes[0].grid(True, alpha=0.3)
    
    # 2. Delta Sharpe distribution
    deltas = [r["sharpe_net"] - r["sharpe_spy"] for r in rows 
              if not np.isnan(r["sharpe_net"]) and not np.isnan(r["sharpe_spy"])]
    axes[1].hist(deltas, bins=20, edgecolor="black", alpha=0.7)
    axes[1].axvline(x=0, color="red", linestyle="--", label="SPY parity")
    axes[1].set_title(f"Delta Sharpe distribution (mean={np.mean(deltas):.3f})")
    axes[1].set_xlabel("Delta Sharpe (composite - SPY)")
    axes[1].legend()
    axes[1].grid(True, alpha=0.3)
    
    # 3. CAGR vs MaxDD scatter
    cagrs = [r["cagr_net"] for r in rows if not np.isnan(r.get("cagr_net", np.nan))]
    mdds = [r["max_dd_net"] for r in rows if not np.isnan(r.get("max_dd_net", np.nan))]
    if cagrs and mdds:
        axes[2].scatter(mdds, cagrs, alpha=0.6, s=40)
        axes[2].set_xlabel("Max Drawdown")
        axes[2].set_ylabel("Net CAGR")
        axes[2].set_title("CAGR vs MaxDD")
        axes[2].grid(True, alpha=0.3)
    
    plt.tight_layout()
    plt.savefig("composite_ff_aw_results.png", dpi=100, bbox_inches="tight")
    plt.show()
    print("Figure saved: composite_ff_aw_results.png")
else:
    print("No data to plot")

Figure saved: composite_ff_aw_results.png

Conclusion

Ce notebook reproduit l’architecture du Framework Composite TrendWeather avec les signaux FamaFrench (rotation factorielle) et AllWeather (socle defensif). Le sweep FF50-AW50 a FF80-AW20 avec top-1/2/3 facteurs et 4 seeds determine si la combinaison bat le SPY B&H.

Hypotheses testees : 1. La decorrelation facteur/macro du composite ameliore le Sharpe vs chaque composant seul 2. Un FF60-AW40 ou FF70-AW30 offre le meilleur compromis rendement/risque 3. Le momentum risque-ajuste est superieur au momentum brut pour la sélection factorielle

Baseline : SPY Buy & Hold (Sharpe ~0.78-1.15 selon periode).

7. Exercices d’extension

Les exercices ci-dessous explorent deux choix de design du notebook : (a) l’allocation AllWeather est statique (30/30/30/10 fixe) ; (b) la validation walk-forward est naive (expanding, sans embargo), ce qui peut laisser fuiter de l’information a la frontiere train/test. Ils restent stubs (a completer) – le notebook s’execute de bout en bout même non resolus.

Exercice 2 – AllWeather dynamique (ponderation inverse-volatilite)

Le notebook alloue le socle AllWeather de maniere statique (AW_WEIGHTS = {SPY:0.30, IEF:0.30, GLD:0.30, XLP:0.10}). Une allocation statique ne s’adapte pas aux changements de volatilite relative entre les classes d’actifs (ex: TLT/IEF devient très volatil en 2022). Une alternative dynamique est la ponderation inverse-volatilite (cf. le notebook research_risk_parity.ipynb) : chaque actif AllWeather recoit un poids proportionnel a l’inverse de sa volatilite realisee glissante.

Objectif : ecrire une fonction qui calcule, a chaque date de rebalancement, les poids inverse-volatilite du socle AllWeather (SPY/IEF/GLD/XLP).

Indices : - Étape 1 : volatilite glissante annualisee (fenêtre 63j) pour chaque ticker AllWeather. - Étape 2 : poids inverse-vol = (1/vol_i) / sum_j(1/vol_j), normalises a 1. - Étape 3 : resampler au rebalancement mensuel (1er jour ouvre), forward-fill.

# Exercice 2 : AllWeather dynamique (ponderation inverse-volatilite)
# TODO etudiant : completer la fonction ci-dessous
def compute_dynamic_aw_weights(prices, aw_tickers=AW_TICKERS, vol_window=63):
    """Poids AllWeather dynamiques = inverse-volatilite, rebalances mensuellement.

    Indice :
      - ret = prices[aw_tickers].pct_change()
      - vol_ann = ret.rolling(vol_window).std() * sqrt(252)
      - inv_vol = 1/vol_ann ; weights = inv_vol.div(inv_vol.sum(axis=1), axis=0)
      - resampler au 1er jour ouvre de chaque mois (resample('MS').first()), ffill.
    Retourner un DataFrame indexe par prices.index, colonnes = aw_tickers, lignes sommant a 1.
    """
    # TODO etudiant : volatilite glissante annualisee par ticker AW
    # TODO etudiant : poids inverse-vol normalises
    # TODO etudiant : resample mensuel + forward-fill
    aw_weights = None  # TODO etudiant : DataFrame pandas
    return aw_weights

print("Exercice 2 a completer : implementer compute_dynamic_aw_weights (inverse-vol)")
Exercice 2 a completer : implementer compute_dynamic_aw_weights (inverse-vol)

Exercice 3 – Walk-forward purge et embargue (anti-fuite)

La validation walk-forward du notebook (section 3) est naive : la fenêtre de test suit immediatement la fenêtre d’entrainement, sans geler (purge) ni embargo. En presence de signaux a memoire (le momentum 252j chevauche la frontiere), cela peut fuir de l’information du train vers le test et surestimer l’edge. Lopez de Prado (Advances in Financial Machine Learning, ch.7) preconise un walk-forward purgé (retirer k observations a la fin du train) et embargué (retirer k observations au debut du test).

Objectif : ecrire une fonction qui genere les indices (train_start, train_end, test_start, test_end) d’un walk-forward purgé + embargué.

Indices : - Étape 1 : decouper la serie en N_SPLITS+1 blocs consecutifs (comme le notebook). - Étape 2 : pour chaque fold, train = blocs précédents, test = bloc courant. - Étape 3 : purger = tronquer la fin du train de k obs ; embargo = tronquer le debut du test de k obs (k = ex: 21 jours ~ 1 mois de chevauchement momentum). - Retourner une liste de tuples (tr_start, tr_end, te_start, te_end).

# Exercice 3 : Walk-forward purge + embargo (Lopez de Prado, AFML ch.7)
# TODO etudiant : completer la fonction ci-dessous
def purged_embargoed_folds(n_obs, n_splits=5, embargo=21):
    """Genere les index (tr_start, tr_end, te_start, te_end) d'un walk-forward purge+embargo.

    Indice :
      - fold_size = n_obs // (n_splits + 1)
      - pour k in 1..n_splits :
          tr_end_raw = fold_size * k
          te_start_raw = tr_end_raw
          te_end = min(te_start_raw + fold_size, n_obs)
          PURGE : tr_end = tr_end_raw - embargo
          EMBARGO : te_start = te_start_raw + embargo
          tr_start = 0 (expanding) ou max(0, tr_end - max_train) (bounded)
      - eviter les folds vides (te_end <= te_start).
    Retourner une liste de tuples (tr_start, tr_end, te_start, te_end).
    """
    # TODO etudiant : boucle sur les folds avec purge + embargo
    folds = None  # TODO etudiant : liste de tuples (tr_start, tr_end, te_start, te_end)
    return folds

print("Exercice 3 a completer : implementer purged_embargoed_folds (anti-fuite)")
Exercice 3 a completer : implementer purged_embargoed_folds (anti-fuite)
Retour au sommet