"""Walk-forward backtest with signal visualization data export. Saves every model decision (accepted + rejected) to JSON for visual analysis. """ import json import sys from datetime import datetime from pathlib import Path sys.path.insert(0, "src") import numpy as np import torch from remizov_trader.core import model as model_mod, signals, risk from remizov_trader.config import ModelConfig, RiskConfig MODEL_CFG = ModelConfig( window_size=64, n_steps=20, total_time=0.5, shift=7, epochs=200, finetune_epochs=50, lr=0.003, ) RISK_CFG = RiskConfig( per_trade=0.05, max_position_pct=0.25, max_open_positions=1, leverage=1, ) K = 2 CORR_THRESH = 0.5 INITIAL_CAPITAL = 10_000.0 TRAILING_STOP = True TRAIN_RATIO = 0.3 def run_backtest_visual(ticker: str, symbol: str, prices: np.ndarray, dates: list): """Walk-forward backtest with signal data collection.""" ws = MODEL_CFG.window_size shift = MODEL_CFG.shift data = signals.prepare_windows(prices, ws, shift) if len(data) < 30: print(f" Not enough windows: {len(data)}") return None n_train = max(int(len(data) * TRAIN_RATIO), 20) train_data = data[:n_train] test_data = data[n_train:] print(f" Windows: {len(data)} total, {n_train} train, {len(test_data)} test") # Train model torch.manual_seed(42) np.random.seed(42) mdl = model_mod.create_model(MODEL_CFG) windows = np.array([d["norm_input"] for d in train_data]) targets = np.array([d["norm_target"] for d in train_data]) loss = model_mod.train(mdl, windows, targets, MODEL_CFG.epochs, MODEL_CFG.lr) print(f" Train loss: {loss:.6f}") # Simulate + collect signals equity = INITIAL_CAPITAL trades = [] position = None signal_log = [] # every model decision for i, d in enumerate(test_data): price_idx = d["price_idx"] current_price = float(prices[price_idx]) # Check open position if position is not None: p = position if TRAILING_STOP: p["best_price"], p["stop_price"] = risk.update_trailing_stop( current_price, p["best_price"], p["stop_price"], p["stop_dist"], p["direction"], ) stopped = risk.is_stopped(current_price, p["stop_price"], p["direction"]) bars_held = price_idx - p["entry_bar"] time_exit = bars_held >= (shift - p["k_used"]) if stopped or time_exit: exit_price = p["stop_price"] if stopped else current_price pnl_net, pnl_pct = risk.calculate_pnl( p["entry_price"], exit_price, p["direction"], p["pos_size"], p["pos_value"], ) equity += pnl_net trades.append({ "pnl_net": pnl_net, "equity_at_entry": p["equity_at_entry"], }) # Link trade result to opening signal if p.get("signal_idx") is not None: signal_log[p["signal_idx"]]["pnl_net"] = round(pnl_net, 4) signal_log[p["signal_idx"]]["exit_price"] = round(exit_price, 2) signal_log[p["signal_idx"]]["exit_reason"] = "stop" if stopped else "time" position = None # New signal check (even if we don't open) if position is None and price_idx >= ws + K: w = prices[price_idx - ws - K:price_idx - K].copy() confirm = prices[price_idx - K:price_idx].copy() mu, std = w.mean(), w.std() if std < 1e-10: continue norm_input = (w - mu) / std pred = model_mod.predict(mdl, norm_input) pred_new = pred[-shift:] corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, mu, std, K, CORR_THRESH, ) # Denormalize prediction to $ prices pred_prices = (pred_new * std + mu).tolist() # Reality: what actually happened after this point reality_end = min(price_idx + shift - K, len(prices)) reality_prices = prices[price_idx:reality_end].tolist() # Date for this signal sig_date = str(dates[price_idx]) if price_idx < len(dates) else "" # Build signal record direction = None action = "skip_corr" if confirmed: direction = signals.get_direction(pred_new, K) if direction is not None: action = "open" else: action = "skip_dir" signal_record = { "idx": len(signal_log), "price_idx": int(price_idx), "date": sig_date, "ticker": ticker, "input_prices": w.tolist(), "prediction": pred_prices, "reality": reality_prices, "confirmation": confirm.tolist(), "correlation": round(float(corr), 4), "corr_thresh": CORR_THRESH, "confirmed": bool(confirmed), "direction": direction, "action": action, "entry_price": None, "stop_price": None, "pnl_net": None, "exit_price": None, "exit_reason": None, } # Open position if signal accepted if action == "open": entry_price = current_price k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K) atr = risk.compute_atr(prices, price_idx) stop_dist = max(atr * stop_mult, entry_price * 0.005) stop_price = entry_price - direction * stop_dist pos_size, pos_value = risk.calculate_position( equity, entry_price, stop_dist, RISK_CFG, ) position = { "direction": direction, "entry_price": entry_price, "stop_price": stop_price, "stop_dist": stop_dist, "best_price": entry_price, "pos_size": pos_size, "pos_value": pos_value, "entry_bar": price_idx, "k_used": k_adj, "equity_at_entry": equity, "signal_idx": len(signal_log), } signal_record["entry_price"] = round(entry_price, 2) signal_record["stop_price"] = round(stop_price, 2) signal_log.append(signal_record) # Close remaining position if position is not None: last_price = float(prices[-1]) pnl_net, pnl_pct = risk.calculate_pnl( position["entry_price"], last_price, position["direction"], position["pos_size"], position["pos_value"], ) equity += pnl_net trades.append({"pnl_net": pnl_net, "equity_at_entry": position["equity_at_entry"]}) if position.get("signal_idx") is not None: signal_log[position["signal_idx"]]["pnl_net"] = round(pnl_net, 4) signal_log[position["signal_idx"]]["exit_price"] = round(last_price, 2) signal_log[position["signal_idx"]]["exit_reason"] = "end" # Metrics if not trades: print(" No trades!") return None wins = [t for t in trades if t["pnl_net"] > 0] total_pnl = equity - INITIAL_CAPITAL first_bar = test_data[0]["price_idx"] last_bar = test_data[-1]["price_idx"] years = (last_bar - first_bar) / (365.25 * 6) if len(trades) > 1 and years > 0: # Daily returns Sharpe (proper annualization) n_days = max(int((last_bar - first_bar) / 6), 1) daily_pnl = np.zeros(n_days) for si, s in enumerate(signal_log): if s["action"] == "open" and s.get("pnl_net") is not None: day = min((s["price_idx"] - first_bar) // 6, n_days - 1) daily_pnl[day] += s["pnl_net"] daily_ret = daily_pnl / INITIAL_CAPITAL sharpe = float(np.mean(daily_ret) / np.std(daily_ret) * np.sqrt(252)) if np.std(daily_ret) > 0 else 0 else: sharpe = 0 accepted = [s for s in signal_log if s["action"] == "open"] rejected = [s for s in signal_log if s["action"] != "open"] print(f" Signals: {len(signal_log)} total, {len(accepted)} accepted, {len(rejected)} rejected") print(f" Trades: {len(trades)} | WR: {len(wins)/len(trades)*100:.1f}% | Sharpe: {sharpe:.2f}") print(f" PnL: ${total_pnl:+,.2f} ({total_pnl/INITIAL_CAPITAL*100:+.1f}%)") # Round input_prices for compact JSON for s in signal_log: s["input_prices"] = [round(p, 2) for p in s["input_prices"]] s["prediction"] = [round(p, 2) for p in s["prediction"]] s["reality"] = [round(p, 2) for p in s["reality"]] s["confirmation"] = [round(p, 2) for p in s["confirmation"]] return { "ticker": ticker, "symbol": symbol, "sharpe": round(sharpe, 2), "total_pnl": round(total_pnl, 2), "total_trades": len(trades), "win_rate": round(len(wins) / len(trades) * 100, 1), "total_signals": len(signal_log), "accepted_signals": len(accepted), "rejected_signals": len(rejected), "signals": signal_log, } def main(): assets = [ ("ETH/USDC", "ETH-USD"), ("SOL/USDC", "SOL-USD"), ("BTC/USDC", "BTC-USD"), ] out_dir = Path("data/backtest_signals") out_dir.mkdir(parents=True, exist_ok=True) for symbol, ticker in assets: print(f"\n--- {symbol} ---") print(f" Fetching 4H data from Bybit...") prices, dates = signals.fetch_prices_ccxt(symbol, "4h", "max") if prices is None: print(f" No data for {symbol}") continue print(f" Got {len(prices)} 4h bars") result = run_backtest_visual(ticker, symbol, prices, dates) if result: ts = datetime.now().strftime("%Y%m%d_%H%M%S") path = out_dir / f"{ticker}_{ts}.json" path.write_text(json.dumps(result, indent=2, default=str)) print(f" Saved: {path}") if __name__ == "__main__": main()