import os import glob import pickle import pandas as pd import numpy as np from datetime import datetime from generate_report import TICKER_EMOJI CORR_THRESHOLD = 0.80 CORR_WINDOW = 60 # rolling window for correlation def run_ensemble(policies, oos_start, label, output_file, mode='dynamic', custom_weights=None): """Run ensemble simulation on a dict of {name: {values, holdings, ...}}.""" all_values = pd.DataFrame({p: policies[p]['values'] for p in policies}).ffill() all_returns = all_values.pct_change().fillna(0) # Blended momentum metrics rolling_20d = all_values.pct_change(20).fillna(0) rolling_60d = all_values.pct_change(60).fillna(0) rolling_vol60 = all_returns.rolling(60).std() * (252 ** 0.5) ensemble_value = 1000.0 ensemble_values = [] ensemble_events = [] prev_ensemble_alloc = {} prev_policy_holdings = {} last_trade_value = 1000.0 dates = rolling_60d.index start_idx = 60 # minimum burn-in for 60d rolling if oos_start: for i, dt in enumerate(dates): if dt >= oos_start: start_idx = max(start_idx, i) break for i in range(start_idx, len(dates)): date = dates[i] ret_20 = rolling_20d.iloc[i-1].dropna() ret_60 = rolling_60d.iloc[i-1].dropna() target_policy_weights = {} if mode == 'static': valid_policies = [p for p in policies if p in all_returns.columns] if valid_policies: if custom_weights: # Filter and re-normalize custom weights w_dict = {p: custom_weights[p] for p in valid_policies if p in custom_weights} total = sum(w_dict.values()) if total > 0: target_policy_weights = {p: v/total for p, v in w_dict.items()} else: target_policy_weights = {p: 1.0 / len(valid_policies) for p in valid_policies} else: if len(ret_60) == 0: pass else: # Dual Momentum: Must be positive on BOTH 20d and 60d horizons positive_rets = {k: ret_20[k] for k in ret_20.keys() if ret_20[k] > 0 and ret_60.get(k, 0) > 0} if not positive_rets: pass else: pos_policies = list(positive_rets.keys()) if len(pos_policies) > 1: lookback_start = max(0, i - CORR_WINDOW) recent_rets = all_returns.iloc[lookback_start:i][pos_policies] corr_matrix = recent_rets.corr() # Equal weight with correlation penalty adjusted = {} cluster_size = {} for p in pos_policies: count = sum(1 for q in pos_policies if corr_matrix.loc[p, q] > CORR_THRESHOLD) cluster_size[p] = count adjusted[p] = 1.0 / cluster_size[p] else: adjusted = {k: 1.0 for k in pos_policies} total_score = sum(adjusted.values()) target_policy_weights = {k: v/total_score for k, v in adjusted.items()} # Build ensemble allocation from policy holdings ensemble_alloc = {} curr_policy_holdings = {} for p, w in target_policy_weights.items(): if p in policies and 'holdings' in policies[p]: h_df = policies[p]['holdings'] if date in h_df.index: h = h_df.loc[date].to_dict() else: h = {'BIL': 1.0} curr_policy_holdings[p] = {k: v for k, v in h.items() if v > 0} for asset, a_w in h.items(): if a_w > 0: ensemble_alloc[asset] = ensemble_alloc.get(asset, 0) + a_w * w if not ensemble_alloc: ensemble_alloc = {'BIL': 1.0} # Evolve NAV daily_ret = 0.0 for p, w in target_policy_weights.items(): if p in all_returns.columns: daily_ret += w * all_returns[p].iloc[i] if not target_policy_weights: daily_ret = 0.0 ensemble_value *= (1 + daily_ret) ensemble_values.append((date, ensemble_value)) # Detect allocation changes def get_sig_alloc(alloc): return {k: round(v, 2) for k, v in alloc.items() if round(v, 2) > 0} sig_prev = get_sig_alloc(prev_ensemble_alloc) sig_curr = get_sig_alloc(ensemble_alloc) trade_event = sig_prev != sig_curr if trade_event or date == dates[-1]: realized = "" if trade_event and last_trade_value is not None: ret = (ensemble_value / last_trade_value - 1) * 100 icon = "🌲" if ret >= 0 else "šŸ" realized = f"{icon} **{ret:+.2f}%**" recent_vals = [x[1] for x in ensemble_values[-21:]] vol = 0.0 win_ret = 0.0 if len(recent_vals) > 1: r = pd.Series(recent_vals).pct_change().dropna() vol = r.std() * (252**0.5) * 100 if len(r) > 1 else 0.0 win_ret = (recent_vals[-1] / recent_vals[0] - 1) * 100 event_type = "šŸŽÆ **TRADE**" if trade_event else "šŸ“ DAILY" event_dict = { "Date": date.strftime('%Y-%m-%d'), "Event": event_type, "Realized": realized, "20d Ret": f"{win_ret:+.2f}%", "Vol": f"{vol:.1f}%", } all_assets = sorted(list(set(sig_curr.keys()) | set(sig_prev.keys()))) for asset in all_assets: c_val = sig_curr.get(asset, 0) p_val = sig_prev.get(asset, 0) if c_val == 0 and p_val == 0: continue emoji = TICKER_EMOJI.get(asset, 'šŸ“¦') diff = c_val - p_val changed_policies = [] if diff != 0: for p in target_policy_weights.keys(): pr_v = prev_policy_holdings.get(p, {}).get(asset, 0) cu_v = curr_policy_holdings.get(p, {}).get(asset, 0) if pr_v != cu_v: changed_policies.append(p) if c_val > 0: s = f"{c_val:.0%}" if diff != 0: s += f" ({diff:+.0%})" if changed_policies: s += f" [{', '.join(changed_policies)}]" event_dict[f"{emoji} {asset}"] = s elif p_val > 0: s = f"0% ({diff:+.0%})" if changed_policies: s += f" [{', '.join(changed_policies)}]" event_dict[f"{emoji} {asset}"] = s ensemble_events.append(event_dict) if trade_event: last_trade_value = ensemble_value prev_ensemble_alloc = sig_curr prev_policy_holdings = curr_policy_holdings # Write report events_df = pd.DataFrame(ensemble_events) if len(events_df) > 0: events_df = events_df.iloc[::-1] events_df = events_df.fillna("") cols = ["Date", "Event", "Realized", "20d Ret", "Vol"] asset_cols = sorted([c for c in events_df.columns if c not in cols]) events_df = events_df[cols + asset_cols] with open(output_file, "w") as f: f.write(f"# Event History: {label}\n\n") f.write(events_df.to_markdown(index=False)) ret_pct = (ensemble_value / 1000 - 1) * 100 # Compute last-1-month (21 trading days) return ret_1m = 0.0 val_series = pd.Series([x[1] for x in ensemble_values], index=[x[0] for x in ensemble_values]) if len(ensemble_values) >= 21: val_21d_ago = ensemble_values[-21][1] ret_1m = (ensemble_value / val_21d_ago - 1) * 100 daily_rets = val_series.pct_change().dropna() vol = daily_rets.std() * (252**0.5) * 100 if len(daily_rets) > 1 else 0.0 mdd = ((val_series / val_series.cummax()) - 1).min() * 100 if len(val_series) > 0 else 0.0 print(f" [{label}] 2y: {ret_pct:+.2f}% 1m: {ret_1m:+.2f}% Vol: {vol:.2f}% MDD: {mdd:.2f}% → {output_file}") return ensemble_value, ret_1m, vol, mdd def main(): import glob pkl_files = sorted(glob.glob("build_cache/P*_simple.pkl")) # Load all policies for all 3 model ages raw_policies = {} # 2y old model holdout_policies = {} # 1m old model latest_policies = {} # just-trained model (no holdout) oos_start_dates = [] holdout_start_dates = [] for f in pkl_files: p_name = os.path.basename(f).split('_')[0] # Exclude basic buy-and-hold policies (P1-P9) from the ensemble if len(p_name) == 2 and p_name.startswith('P') and p_name[1].isdigit(): continue try: with open(f, 'rb') as fp: d = pickle.load(fp) if 'raw_results' in d: raw_policies[p_name] = d['raw_results'] if 'oos_start_date' in d: oos_start_dates.append(pd.to_datetime(d['oos_start_date'])) if 'holdout_results' in d: hr = d['holdout_results'] h_vals = hr.get('values_full', hr.get('values')) h_hold = hr.get('holdings_full', hr.get('holdings')) if h_vals is not None and h_hold is not None: holdout_policies[p_name] = { 'values': h_vals, 'holdings': h_hold, } if 'oos_start_date' in hr: holdout_start_dates.append(pd.to_datetime(hr['oos_start_date'])) if 'latest_results' in d: lr = d['latest_results'] if lr.get('values') is not None and lr.get('holdings') is not None: latest_policies[p_name] = { 'values': lr['values'], 'holdings': lr['holdings'], } except Exception as e: pass if not raw_policies and not holdout_policies and not latest_policies: print("No policies loaded.") return global_oos_start = max(oos_start_dates) if oos_start_dates else None global_holdout_start = max(holdout_start_dates) if holdout_start_dates else None print("=" * 60) print("Meta-Ensemble Builder") print("=" * 60) # --- 1. Old Model (2y old) --- val_old, ret_old_1m, vol_old, mdd_old = 0, 0, 0, 0 if raw_policies: print(f"\nšŸ“Š Old Model (2y old) ({len(raw_policies)} policies, start={global_oos_start})") val_old, ret_old_1m, vol_old, mdd_old = run_ensemble(raw_policies, global_oos_start, "Old Model (2y old, Static Equal-Weight)", "logs/Ensemble_OldModel_events.md", mode='static') # --- 2. Recent Model (1m old) --- val_1m, ret_1m_1m, vol_1m, mdd_1m = 0, 0, 0, 0 if holdout_policies: print(f"\nšŸ“Š Recent Model (1m old) ({len(holdout_policies)} policies, start={global_oos_start})") val_1m, ret_1m_1m, vol_1m, mdd_1m = run_ensemble(holdout_policies, global_oos_start, "Recent Model (1m old, Static Equal-Weight)", "logs/Ensemble_Holdout_events.md", mode='static') # --- 3. Latest Model (just trained) --- val_latest, ret_latest_1m, vol_latest, mdd_latest = 0, 0, 0, 0 if latest_policies: print(f"\nšŸ“Š Latest Model (just trained) ({len(latest_policies)} policies, start={global_oos_start})") val_latest, ret_latest_1m, vol_latest, mdd_latest = run_ensemble(latest_policies, global_oos_start, "Latest Model (just trained, Static Equal-Weight)", "logs/Ensemble_Latest_events.md", mode='static') # --- 4. Custom Robust Alpha Ensemble (70% P14 / 30% P30) --- robust_weights = {'P14': 0.7, 'P30': 0.3} val_ra_1m, ret_ra_1m_1m, vol_ra_1m, mdd_ra_1m = 0, 0, 0, 0 if 'P14' in holdout_policies and 'P30' in holdout_policies: print(f"\nšŸ’Ž Robust Alpha (1m old) (70/30) (start={global_oos_start})") val_ra_1m, ret_ra_1m_1m, vol_ra_1m, mdd_ra_1m = run_ensemble(holdout_policies, global_oos_start, "Robust Alpha (1m old, 70/30)", "logs/Ensemble_RobustAlpha_1m_events.md", mode='static', custom_weights=robust_weights) val_ra_latest, ret_ra_latest_1m, vol_ra_latest, mdd_ra_latest = 0, 0, 0, 0 if 'P14' in latest_policies and 'P30' in latest_policies: print(f"\nšŸ’Ž Robust Alpha (Latest) (70/30) (start={global_oos_start})") val_ra_latest, ret_ra_latest_1m, vol_ra_latest, mdd_ra_latest = run_ensemble(latest_policies, global_oos_start, "Robust Alpha (Latest, 70/30)", "logs/Ensemble_RobustAlpha_Latest_events.md", mode='static', custom_weights=robust_weights) # --- Comparison Summary --- ret_old_pct = (val_old / 1000 - 1) * 100 if val_old else 0 ret_1m_pct = (val_1m / 1000 - 1) * 100 if val_1m else 0 ret_latest_pct = (val_latest / 1000 - 1) * 100 if val_latest else 0 ret_ra_1m_pct = (val_ra_1m / 1000 - 1) * 100 if val_ra_1m else 0 ret_ra_latest_pct = (val_ra_latest / 1000 - 1) * 100 if val_ra_latest else 0 print(f"\n{'='*75}") print(f" Ensemble Comparison Summary") print(f"{'='*75}") print(f" Total Ret Last 1m MDD Vol") print(f" [Full EW] 2y Old: {ret_old_pct:>+8.2f}% {ret_old_1m:>+6.2f}% {mdd_old:>+7.2f}% {vol_old:>5.2f}%") print(f" [Full EW] 1m Old: {ret_1m_pct:>+8.2f}% {ret_1m_1m:>+6.2f}% {mdd_1m:>+7.2f}% {vol_1m:>5.2f}%") print(f" [Full EW] Latest: {ret_latest_pct:>+8.2f}% {ret_latest_1m:>+6.2f}% {mdd_latest:>+7.2f}% {vol_latest:>5.2f}%") print(f" {'-'*71}") print(f" [RA 70/30] 1m Old: {ret_ra_1m_pct:>+8.2f}% {ret_ra_1m_1m:>+6.2f}% {mdd_ra_1m:>+7.2f}% {vol_ra_1m:>5.2f}%") print(f" [RA 70/30] Latest: {ret_ra_latest_pct:>+8.2f}% {ret_ra_latest_1m:>+6.2f}% {mdd_ra_latest:>+7.2f}% {vol_ra_latest:>5.2f}%") print(f"{'='*75}") print("\nDone.") if __name__ == "__main__": main()