"""Exp29b: ADA+DOGE timeframe scan with correct K values. ADA: ws=64, K=3 (prod) DOGE: ws=48, K=2 (prod) """ 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 scipy import stats 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 TIMEFRAMES = ["1h", "2h", "4h", "6h", "12h"] ASSETS = [ {"symbol": "ADA/USDC", "ticker": "ADA-USD", "ws": 64, "K": 3}, {"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "ws": 48, "K": 2}, ] def _run_tests(prices, ws, K): data = signals.prepare_windows(prices, ws, SHIFT) n_train = max(int(len(data) * TRAIN_RATIO), 20) train, test = data[:n_train], data[n_train:] if len(test) < 20: return None 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) # Amplitude correlation pred_amps, actual_amps = [], [] for d in test: idx = d["price_idx"] if idx + SHIFT >= len(prices): continue pred = model_mod.predict(mdl, d["norm_input"]) pred_new = pred[-SHIFT:] pred_denorm = pred_new * d["std"] + d["mu"] pred_amps.append(float(np.max(pred_denorm) - np.min(pred_denorm))) future = prices[idx:idx + SHIFT] actual_amps.append(float(np.max(future) - np.min(future))) if len(pred_amps) < 20: return None r_amp, _ = stats.pearsonr(pred_amps, actual_amps) # Conf-filtered PnL with trailing stop trade_pnls = [] for d in test: idx = d["price_idx"] if idx + SHIFT >= len(prices) or idx < ws + K: continue pred = model_mod.predict(mdl, d["norm_input"]) pred_new = pred[-SHIFT:] confirm = prices[idx - K:idx] corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, d["mu"], d["std"], K, 0.5) if not confirmed: continue atr = risk.compute_atr(prices, idx) if atr <= 0: continue 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: continue direction = signals.get_direction(pred_new, K) if direction != 1: continue entry = 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: pnl_pct = (prices[min(idx + SHIFT, len(prices) - 1)] - entry) / entry * 100 trade_pnls.append(pnl_pct) n_trades = len(trade_pnls) if n_trades < 3: return { "r_amp": round(float(r_amp), 4), "mean_pnl": 0, "n_trades": n_trades, "wr": 0, "p_positive": 0, "ci_lo": 0, "ci_hi": 0, } mean_pnl = float(np.mean(trade_pnls)) wr = sum(1 for t in trade_pnls if t > 0) / n_trades * 100 arr = np.array(trade_pnls) means = np.array([float(np.mean(np.random.choice(arr, len(arr), replace=True))) for _ in range(2000)]) p_pos = float(np.mean(means > 0)) * 100 ci = np.percentile(means, [2.5, 97.5]) return { "r_amp": round(float(r_amp), 4), "mean_pnl": round(mean_pnl, 4), "n_trades": n_trades, "wr": round(wr, 1), "p_positive": round(p_pos, 1), "ci_lo": round(float(ci[0]), 4), "ci_hi": round(float(ci[1]), 4), } def main(): results_dir = Path(__file__).parent / "results" results_dir.mkdir(parents=True, exist_ok=True) print("=" * 80) print("EXP29b: ADA+DOGE TIMEFRAME SCAN (CORRECT K)") print("=" * 80) all_results = [] for asset in ASSETS: ticker = asset["ticker"] ws, K = asset["ws"], asset["K"] print(f"\n {ticker} (ws={ws}, K={K})") print(f" {'TF':>3s} {'Bars':>6s} {'r_amp':>6s} {'PnL%':>8s} " f"{'N':>4s} {'WR%':>5s} {'P%':>5s} {'CI':>20s}") print(f" {'-' * 60}") for tf in TIMEFRAMES: try: ohlcv, dates = fetch_ohlcv_ccxt(asset["symbol"], tf, "max") except Exception: print(f" {tf:>3s} fetch error") continue if ohlcv is None or len(ohlcv) < 500: print(f" {tf:>3s} {len(ohlcv) if ohlcv is not None else 0} bars (insufficient)") continue prices = ohlcv[:, 3] r = _run_tests(prices, ws, K) if r is None: print(f" {tf:>3s} {len(prices):>5d} bars — insufficient test data") continue flag = " ★" if r["mean_pnl"] > 0 and r["p_positive"] >= 90 and r["n_trades"] >= 10 else "" print(f" {tf:>3s} {len(prices):>6d} {r['r_amp']:>+5.3f} " f"{r['mean_pnl']:>+7.3f}% {r['n_trades']:>4d} " f"{r['wr']:>4.1f}% {r['p_positive']:>4.0f}% " f"[{r['ci_lo']:+.3f}, {r['ci_hi']:+.3f}]{flag}") all_results.append({"ticker": ticker, "tf": tf, "ws": ws, "K": K, "bars": len(prices), **r}) path = save_results({"results": all_results}, results_dir, "exp29b_ada_doge_tf") print(f"\nSaved: {path}") if __name__ == "__main__": main()