""" Regime analysis: when does the model profit vs fail? For each asset, run walk-forward and for every fold record: - date range - accuracy - market regime (trend direction, volatility, drawdown) - which predictions were right/wrong Then segment into "profitable" vs "losing" folds and find patterns. """ from __future__ import annotations import warnings from datetime import date import numpy as np from scipy import stats from sklearn.linear_model import LogisticRegression from sklearn.preprocessing import StandardScaler from data_v2 import fetch_asset, make_windows from retest_all import ( create_model, train_model, extract_sde, extract_technical, WINDOW_SIZE, SHIFT, STRIDE, N_STEPS, TOTAL_TIME, LR, INITIAL_TRAIN, TEST_CHUNK, FIRST_EPOCHS, FINETUNE_EPOCHS, MC_SAMPLES, RANDOM_STATE, ) warnings.filterwarnings("ignore") ASSETS = ["BTC-USD", "ETH-USD", "SOL-USD", "BNB-USD"] def classify_regime( prices: np.ndarray, dates: list[date], start_date: date, end_date: date, ) -> dict: """Classify market regime for a date range.""" date_to_idx = {d: i for i, d in enumerate(dates)} # Find indices si = None for offset in range(5): from datetime import timedelta for sign in [0, -1, 1]: candidate = start_date + timedelta(days=sign * offset) si = date_to_idx.get(candidate) if si is not None: break if si is not None: break ei = None for offset in range(5): from datetime import timedelta for sign in [0, 1, -1]: candidate = end_date + timedelta(days=sign * offset) ei = date_to_idx.get(candidate) if ei is not None: break if ei is not None: break if si is None or ei is None or ei <= si: return {"trend": "unknown", "vol": 0, "return_pct": 0, "drawdown": 0} # Extend context: look at prices from 30 days before to end ctx_start = max(0, si - 30) p = prices[ctx_start:ei + 1] p_fold = prices[si:ei + 1] if len(p_fold) < 2: return {"trend": "unknown", "vol": 0, "return_pct": 0, "drawdown": 0} # Return over fold period ret = (p_fold[-1] / p_fold[0] - 1) * 100 # Trend: linear regression slope x = np.arange(len(p_fold)) slope = np.polyfit(x, p_fold, 1)[0] slope_pct = slope / p_fold.mean() * 100 # % per day # Volatility: annualized from daily returns daily_ret = np.diff(np.log(p_fold)) vol = daily_ret.std() * np.sqrt(365) * 100 if len(daily_ret) > 1 else 0 # Max drawdown in fold cummax = np.maximum.accumulate(p_fold) drawdowns = (p_fold - cummax) / cummax * 100 max_dd = drawdowns.min() # Classify trend if ret > 5: trend = "BULL" elif ret < -5: trend = "BEAR" else: trend = "FLAT" # Volatility regime if vol > 80: vol_regime = "HIGH_VOL" elif vol > 40: vol_regime = "MED_VOL" else: vol_regime = "LOW_VOL" return { "trend": trend, "vol_regime": vol_regime, "vol": vol, "return_pct": ret, "slope_pct": slope_pct, "drawdown": max_dd, } def walk_forward_detailed( asset: str, prices: np.ndarray, all_dates: list[date], data: dict, ) -> list[dict]: """Walk-forward with detailed per-fold analysis.""" labels = data["labels"] n = len(labels) n_folds = (n - INITIAL_TRAIN) // TEST_CHUNK if n_folds < 3: return [] model = None folds = [] for fold in range(n_folds): bnd = INITIAL_TRAIN + fold * TEST_CHUNK te = min(bnd + TEST_CHUNK, n) tl = labels[bnd:te] if len(tl) == 0: break # Dates for this fold fold_dates = data["dates"][bnd:te] fold_start = fold_dates[0] fold_end = fold_dates[-1] # Train / fine-tune if model is None: model = create_model(WINDOW_SIZE, use_sde=True) ep = FIRST_EPOCHS else: ep = FINETUNE_EPOCHS train_model(model, data["windows"][:bnd], data["targets"][:bnd], ep) sigma_val = model.layer.sigma.mean().item() # Features sde_tr = extract_sde(model, data["windows"][:bnd]) sde_te = extract_sde(model, data["windows"][bnd:te]) tech_tr = extract_technical(data["windows"][:bnd]) tech_te = extract_technical(data["windows"][bnd:te]) X_tr = np.nan_to_num(np.hstack([sde_tr, tech_tr])) X_te = np.nan_to_num(np.hstack([sde_te, tech_te])) sc = StandardScaler() Xtr = sc.fit_transform(X_tr) Xte = sc.transform(X_te) clf = LogisticRegression( penalty="l1", solver="saga", C=1.0, l1_ratio=1.0, max_iter=2000, random_state=RANDOM_STATE, ) clf.fit(Xtr, labels[:bnd]) preds = clf.predict(Xte) proba = clf.predict_proba(Xte) acc = np.mean(preds == tl) n_correct = int(np.sum(preds == tl)) # Confidence: mean probability of predicted class confidence = np.mean(np.max(proba, axis=1)) # Market regime regime = classify_regime(prices, all_dates, fold_start, fold_end) # Per-prediction details pred_details = [] for j in range(len(tl)): pred_details.append({ "date": fold_dates[j], "pred": int(preds[j]), "true": int(tl[j]), "correct": bool(preds[j] == tl[j]), "confidence": float(np.max(proba[j])), }) folds.append({ "fold": fold, "start": fold_start, "end": fold_end, "acc": acc, "n_correct": n_correct, "n_total": len(tl), "sigma": sigma_val, "confidence": confidence, "predictions": pred_details, **regime, }) return folds def analyze_regimes(asset: str, folds: list[dict]): """Analyze which regimes produce profits vs losses.""" if not folds: return print(f"\n{'=' * 75}") print(f" {asset} — REGIME ANALYSIS") print(f"{'=' * 75}") # ── Per-fold table ── print(f"\n {'Fold':>4s} {'Dates':>25s} {'Acc':>5s} {'Trend':>5s} " f"{'Ret%':>6s} {'Vol':>5s} {'DD%':>6s} {'Sigma':>6s} {'Conf':>5s}") print(f" {'─' * 75}") for f in folds: print(f" {f['fold']:>4d} {str(f['start'])}→{str(f['end'])} " f"{f['acc']:>4.0%} {f['trend']:>5s} " f"{f['return_pct']:>+5.1f} {f['vol']:>5.0f} " f"{f['drawdown']:>+5.1f} {f['sigma']:>6.3f} {f['confidence']:>4.1%}") # ── Group by trend ── print(f"\n BY TREND:") for trend in ["BULL", "BEAR", "FLAT"]: tf = [f for f in folds if f["trend"] == trend] if not tf: continue avg_acc = np.mean([f["acc"] for f in tf]) n_folds_t = len(tf) total_correct = sum(f["n_correct"] for f in tf) total_preds = sum(f["n_total"] for f in tf) avg_ret = np.mean([f["return_pct"] for f in tf]) print(f" {trend:<5s}: {avg_acc:.1%} acc ({total_correct}/{total_preds}) " f"across {n_folds_t} folds, avg return={avg_ret:+.1f}%") # ── Group by volatility ── print(f"\n BY VOLATILITY:") for vol_r in ["LOW_VOL", "MED_VOL", "HIGH_VOL"]: vf = [f for f in folds if f.get("vol_regime") == vol_r] if not vf: continue avg_acc = np.mean([f["acc"] for f in vf]) n_folds_v = len(vf) avg_vol = np.mean([f["vol"] for f in vf]) print(f" {vol_r:<8s}: {avg_acc:.1%} acc across {n_folds_v} folds " f"(avg vol={avg_vol:.0f}%)") # ── Profitable vs losing folds ── profitable = [f for f in folds if f["acc"] > 0.55] losing = [f for f in folds if f["acc"] < 0.45] neutral = [f for f in folds if 0.45 <= f["acc"] <= 0.55] print(f"\n PROFITABLE FOLDS (acc > 55%): {len(profitable)}/{len(folds)}") if profitable: p_trends = [f["trend"] for f in profitable] p_vols = [f["vol"] for f in profitable] p_sigmas = [f["sigma"] for f in profitable] p_dds = [f["drawdown"] for f in profitable] p_rets = [f["return_pct"] for f in profitable] print(f" Trends: {dict((t, p_trends.count(t)) for t in set(p_trends))}") print(f" Avg vol: {np.mean(p_vols):.0f}%, avg return: {np.mean(p_rets):+.1f}%") print(f" Avg sigma: {np.mean(p_sigmas):.3f}, avg DD: {np.mean(p_dds):.1f}%") print(f"\n LOSING FOLDS (acc < 45%): {len(losing)}/{len(folds)}") if losing: l_trends = [f["trend"] for f in losing] l_vols = [f["vol"] for f in losing] l_sigmas = [f["sigma"] for f in losing] l_dds = [f["drawdown"] for f in losing] l_rets = [f["return_pct"] for f in losing] print(f" Trends: {dict((t, l_trends.count(t)) for t in set(l_trends))}") print(f" Avg vol: {np.mean(l_vols):.0f}%, avg return: {np.mean(l_rets):+.1f}%") print(f" Avg sigma: {np.mean(l_sigmas):.3f}, avg DD: {np.mean(l_dds):.1f}%") print(f"\n NEUTRAL FOLDS (45-55%): {len(neutral)}/{len(folds)}") # ── Statistical tests: does regime predict accuracy? ── print(f"\n REGIME-ACCURACY CORRELATIONS:") accs = np.array([f["acc"] for f in folds]) rets = np.array([f["return_pct"] for f in folds]) vols = np.array([f["vol"] for f in folds]) sigmas = np.array([f["sigma"] for f in folds]) dds = np.array([f["drawdown"] for f in folds]) confs = np.array([f["confidence"] for f in folds]) for name, vals in [ ("return%", rets), ("volatility", vols), ("sigma", sigmas), ("drawdown", dds), ("confidence", confs), ]: if len(vals) > 3 and vals.std() > 1e-10: r, p = stats.spearmanr(vals, accs) sig = "**" if p < 0.05 else "" print(f" {name:<12s} r={r:+.3f} p={p:.3f} {sig}") # ── Consecutive streaks ── print(f"\n PREDICTION STREAKS:") all_preds = [] for f in folds: all_preds.extend(f["predictions"]) correct_streak, wrong_streak = 0, 0 max_correct, max_wrong = 0, 0 streaks_correct, streaks_wrong = [], [] for p in all_preds: if p["correct"]: correct_streak += 1 if wrong_streak > 0: streaks_wrong.append(wrong_streak) max_wrong = max(max_wrong, wrong_streak) wrong_streak = 0 else: wrong_streak += 1 if correct_streak > 0: streaks_correct.append(correct_streak) max_correct = max(max_correct, correct_streak) correct_streak = 0 if correct_streak > 0: streaks_correct.append(correct_streak) max_correct = max(max_correct, correct_streak) if wrong_streak > 0: streaks_wrong.append(wrong_streak) max_wrong = max(max_wrong, wrong_streak) print(f" Max correct streak: {max_correct}") print(f" Max wrong streak: {max_wrong}") if streaks_correct: print(f" Avg correct streak: {np.mean(streaks_correct):.1f}") if streaks_wrong: print(f" Avg wrong streak: {np.mean(streaks_wrong):.1f}") # ── Time evolution ── print(f"\n ACCURACY OVER TIME (quarters):") # Group by quarters quarters = {} for f in folds: q = f"{f['start'].year}Q{(f['start'].month - 1) // 3 + 1}" if q not in quarters: quarters[q] = {"correct": 0, "total": 0} quarters[q]["correct"] += f["n_correct"] quarters[q]["total"] += f["n_total"] for q in sorted(quarters): qd = quarters[q] qacc = qd["correct"] / qd["total"] if qd["total"] > 0 else 0 bar = "█" * int(qacc * 20) + "░" * (20 - int(qacc * 20)) print(f" {q}: {bar} {qacc:.0%} ({qd['correct']}/{qd['total']})") def main(): for asset in ASSETS: prices, dates = fetch_asset(asset) data = make_windows(prices, dates, WINDOW_SIZE, SHIFT, STRIDE, use_returns=False) n = len(data["labels"]) n_up = data["labels"].sum() print(f"\n {asset}: {n} windows (up={n_up}, down={n - n_up})") folds = walk_forward_detailed(asset, prices, dates, data) analyze_regimes(asset, folds) # ── Cross-asset summary ── print(f"\n\n{'=' * 75}") print(f" CROSS-ASSET PATTERNS") print(f"{'=' * 75}") print(f"\n Key questions:") print(f" 1. Is there a regime where ALL models profit?") print(f" 2. Is there a regime where ALL models fail?") print(f" 3. Can we filter trades by regime to improve results?") if __name__ == "__main__": main()