"""Exp30: Cascading multi-timeframe strategy. Stage 1: Run formula on 4h, classify each signal window: - WIN: trailing stop profit > 0 - LOSS: trailing stop loss - SKIP: no signal (low conf, no shape, short, cooldown) Stage 2: For LOSS+SKIP periods, zoom into 2h and 1h: - Retrain model on smaller TF data up to that point - Check if formula catches the move at finer granularity Hypothesis: when 4h misses, smaller TF may capture intra-bar moves. """ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src")) sys.path.insert(0, str(Path(__file__).parent.parent)) import numpy as np import torch from dataclasses import dataclass from remizov_trader.core import model as model_mod, signals, risk from remizov_trader.core.net import EnhancedRemizovNet from remizov_trader.core.signals import fetch_ohlcv_ccxt from common.metrics import save_results SHIFT = 7 MIN_CONFIDENCE = 1.5 TRAIN_RATIO = 0.3 ASSETS = [ {"symbol": "ADA/USDC", "ticker": "ADA-USD", "ws": 64, "K": 3}, {"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "ws": 48, "K": 2}, ] FALLBACK_TFS = ["5m", "3m", "1m"] @dataclass class SignalResult: idx: int date: str outcome: str # "win", "loss", "skip_shape", "skip_conf", "skip_short", "skip_cool" pnl_pct: float conf: float corr: float def _train_model(prices, ws): """Train model on first TRAIN_RATIO of data.""" data = signals.prepare_windows(prices, ws, SHIFT) n_train = max(int(len(data) * TRAIN_RATIO), 20) train, test = data[:n_train], data[n_train:] torch.manual_seed(42) np.random.seed(42) mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5, dx=1.0 / ws, use_sde=True) w = np.array([d["norm_input"] for d in train]) t = np.array([d["norm_target"] for d in train]) model_mod.train(mdl, w, t, 200, 0.003) return mdl, train, test def _trailing_stop_pnl(prices, idx, K, entry_price=None): """Compute trailing stop PnL for a long entry at idx.""" entry = entry_price or prices[idx] atr = risk.compute_atr(prices, idx) _, stop_mult = risk.regime_adaptive_params(prices, idx, K) stop_dist = max(atr * stop_mult * 0.5, entry * 0.005) stop = entry - stop_dist best = entry pnl_pct = 0.0 for j in range(1, SHIFT + 1): if idx + j >= len(prices): break p = prices[idx + j] if p > best: best = p stop = best - stop_dist if p <= stop: pnl_pct = (p - entry) / entry * 100 break else: end_idx = min(idx + SHIFT, len(prices) - 1) pnl_pct = (prices[end_idx] - entry) / entry * 100 return pnl_pct def stage1_classify(prices, dates, mdl, test_data, ws, K): """Stage 1: classify each test signal on 4h.""" results = [] last_stop_idx = -999 for d in test_data: idx = d["price_idx"] if idx + SHIFT >= len(prices) or idx < ws + K: continue date_str = str(dates[idx]) if idx < len(dates) else "?" # Cooldown check if idx - last_stop_idx < SHIFT: results.append(SignalResult(idx, date_str, "skip_cool", 0, 0, 0)) continue pred = model_mod.predict(mdl, d["norm_input"]) pred_new = pred[-SHIFT:] # Shape confirmation confirm = prices[idx - K:idx] corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, d["mu"], d["std"], K, 0.5) if not confirmed: results.append(SignalResult(idx, date_str, "skip_shape", 0, 0, float(corr))) continue # Confidence atr = risk.compute_atr(prices, idx) conf = 0.0 if atr > 0: pred_denorm = pred_new * d["std"] + d["mu"] amp = float(np.max(pred_denorm) - np.min(pred_denorm)) conf = abs(corr) * (amp / atr) if conf < MIN_CONFIDENCE: results.append(SignalResult(idx, date_str, "skip_conf", 0, conf, float(corr))) continue # Direction direction = signals.get_direction(pred_new, K) if direction != 1: results.append(SignalResult(idx, date_str, "skip_short", 0, conf, float(corr))) continue # Trade PnL pnl = _trailing_stop_pnl(prices, idx, K) if pnl > 0: results.append(SignalResult(idx, date_str, "win", pnl, conf, float(corr))) else: results.append(SignalResult(idx, date_str, "loss", pnl, conf, float(corr))) last_stop_idx = idx return results def stage2_fallback(ticker, symbol, ws, K, miss_periods, dates_4h): """Stage 2: for missed/loss periods, try smaller TFs.""" fallback_results = {} for tf in FALLBACK_TFS: print(f"\n Fallback TF={tf}...", end=" ", flush=True) try: ohlcv, dates = fetch_ohlcv_ccxt(symbol, tf, "max") except Exception: print("fetch error") continue if ohlcv is None or len(ohlcv) < 1000: print(f"only {len(ohlcv) if ohlcv is not None else 0} bars") continue prices = ohlcv[:, 3] dates_str = np.array([str(d) for d in dates]) # Train model on this TF mdl, train, test = _train_model(prices, ws) # For each miss period, find corresponding bars in smaller TF wins_in_miss = 0 losses_in_miss = 0 total_pnl = 0.0 signals_found = 0 total_miss_periods = 0 for miss in miss_periods: miss_date = miss.date miss_idx_4h = miss.idx # Find the date range: miss_date to miss_date + SHIFT*4h # In smaller TF, this covers more bars if tf.endswith("h"): tf_minutes = int(tf.replace("h", "")) * 60 elif tf.endswith("m"): tf_minutes = int(tf.replace("m", "")) else: tf_minutes = int(tf) bars_per_4h = 4 * 60 // tf_minutes # Find matching index in smaller TF matching = np.where(dates_str == miss_date)[0] if len(matching) == 0: continue total_miss_periods += 1 start_bar = matching[0] end_bar = min(start_bar + SHIFT * bars_per_4h, len(prices) - SHIFT) # Try each bar in the miss window as potential entry best_signal = None best_conf = 0 for bar in range(start_bar, end_bar): if bar < ws + K or bar + SHIFT >= len(prices): continue # Prepare window w = prices[bar - ws - K:bar - K].copy() confirm = prices[bar - K:bar].copy() mu, std = w.mean(), w.std() if std < 1e-10: continue pred = model_mod.predict(mdl, (w - mu) / std) pred_new = pred[-SHIFT:] corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, mu, std, K, 0.5) if not confirmed: continue atr = risk.compute_atr(prices, bar) if atr <= 0: continue pred_denorm = pred_new * std + mu amp = float(np.max(pred_denorm) - np.min(pred_denorm)) conf = abs(corr) * (amp / atr) if conf < MIN_CONFIDENCE: continue direction = signals.get_direction(pred_new, K) if direction != 1: continue if conf > best_conf: best_conf = conf best_signal = bar if best_signal is not None: pnl = _trailing_stop_pnl(prices, best_signal, K) signals_found += 1 total_pnl += pnl if pnl > 0: wins_in_miss += 1 else: losses_in_miss += 1 n = wins_in_miss + losses_in_miss print(f"checked {total_miss_periods} periods, " f"found {signals_found} signals, " f"W/L={wins_in_miss}/{losses_in_miss}, " f"PnL={total_pnl/n:+.3f}%" if n > 0 else f"no trades") fallback_results[tf] = { "miss_periods_checked": total_miss_periods, "signals_found": signals_found, "wins": wins_in_miss, "losses": losses_in_miss, "total_pnl_pct": round(total_pnl, 4), "mean_pnl_pct": round(total_pnl / n, 4) if n > 0 else 0, "wr": round(wins_in_miss / n * 100, 1) if n > 0 else 0, } return fallback_results def main(): results_dir = Path(__file__).parent / "results" results_dir.mkdir(parents=True, exist_ok=True) print("=" * 80) print("EXP30: CASCADING MULTI-TIMEFRAME STRATEGY") print("=" * 80) print("Stage 1: Classify 4h signals → win/loss/skip") print("Stage 2: For losses+skips → try 2h and 1h fallback") all_results = {} for asset in ASSETS: ticker = asset["ticker"] symbol = asset["symbol"] ws, K = asset["ws"], asset["K"] print(f"\n{'═' * 60}") print(f" {ticker} (ws={ws}, K={K})") print(f"{'═' * 60}") # Fetch 4h data ohlcv_4h, dates_4h = fetch_ohlcv_ccxt(symbol, "4h", "max") if ohlcv_4h is None: print(" Failed to fetch 4h data") continue prices_4h = ohlcv_4h[:, 3] dates_4h_str = np.array([str(d) for d in dates_4h]) print(f" 4h: {len(prices_4h)} bars") # Stage 1: Train and classify print(f"\n STAGE 1: Classify 4h signals") mdl, train, test = _train_model(prices_4h, ws) s1_results = stage1_classify(prices_4h, dates_4h_str, mdl, test, ws, K) wins = [r for r in s1_results if r.outcome == "win"] losses = [r for r in s1_results if r.outcome == "loss"] skips_shape = [r for r in s1_results if r.outcome == "skip_shape"] skips_conf = [r for r in s1_results if r.outcome == "skip_conf"] skips_short = [r for r in s1_results if r.outcome == "skip_short"] skips_cool = [r for r in s1_results if r.outcome == "skip_cool"] print(f" Wins: {len(wins):>4d} avg PnL={np.mean([r.pnl_pct for r in wins]):+.3f}%" if wins else " Wins: 0") print(f" Losses: {len(losses):>4d} avg PnL={np.mean([r.pnl_pct for r in losses]):+.3f}%" if losses else " Losses: 0") print(f" Skip shape: {len(skips_shape):>4d}") print(f" Skip conf: {len(skips_conf):>4d}") print(f" Skip short: {len(skips_short):>4d}") print(f" Skip cool: {len(skips_cool):>4d}") total_traded = len(wins) + len(losses) if total_traded > 0: total_pnl = sum(r.pnl_pct for r in wins) + sum(r.pnl_pct for r in losses) print(f" Total: {total_traded} trades, PnL={total_pnl/total_traded:+.3f}%/trade") # Stage 2: Fallback for misses # "Misses" = losses + skips (excluding cooldown which is mechanical) misses = losses + skips_shape + skips_conf + skips_short print(f"\n STAGE 2: Fallback for {len(misses)} miss periods") fallback = stage2_fallback(ticker, symbol, ws, K, misses, dates_4h_str) # Combined analysis print(f"\n COMBINED ANALYSIS:") if total_traded > 0: base_pnl = sum(r.pnl_pct for r in wins) + sum(r.pnl_pct for r in losses) base_trades = total_traded print(f" 4h only: {base_trades} trades, total PnL={base_pnl:+.2f}%") for tf, fb in fallback.items(): if fb["signals_found"] > 0: combined_trades = base_trades + fb["signals_found"] combined_pnl = base_pnl + fb["total_pnl_pct"] print(f" 4h + {tf} fallback: {combined_trades} trades, " f"total PnL={combined_pnl:+.2f}% " f"(+{fb['signals_found']} trades from {tf}, " f"PnL={fb['total_pnl_pct']:+.2f}%)") all_results[ticker] = { "stage1": { "wins": len(wins), "losses": len(losses), "skip_shape": len(skips_shape), "skip_conf": len(skips_conf), "skip_short": len(skips_short), "skip_cool": len(skips_cool), "win_avg_pnl": round(float(np.mean([r.pnl_pct for r in wins])), 4) if wins else 0, "loss_avg_pnl": round(float(np.mean([r.pnl_pct for r in losses])), 4) if losses else 0, "total_pnl": round(sum(r.pnl_pct for r in wins + losses), 4), }, "stage2_fallback": fallback, } # Summary print(f"\n{'═' * 80}") print("SUMMARY: DOES CASCADING HELP?") print(f"{'═' * 80}") for ticker, r in all_results.items(): s1 = r["stage1"] base = s1["total_pnl"] base_n = s1["wins"] + s1["losses"] print(f"\n {ticker}:") print(f" 4h baseline: {base_n} trades, PnL={base:+.2f}%") for tf, fb in r["stage2_fallback"].items(): if fb["signals_found"] > 0: delta = fb["total_pnl_pct"] extra_n = fb["signals_found"] verdict = "HELPS" if delta > 0 else "HURTS" print(f" +{tf} fallback: +{extra_n} trades, " f"Δ PnL={delta:+.2f}% → {verdict}") else: print(f" +{tf} fallback: no signals found") path = save_results(all_results, results_dir, "exp30_cascade") print(f"\nSaved: {path}") if __name__ == "__main__": main()