"""Frozen-model backtest: load existing prod models, test on last 3 months 1h data. NO training — just load_model and predict. Uses EXACT prod params. Long+Short futures. """ import sys sys.path.insert(0, "src") import numpy as np import torch import yfinance as yf from remizov_trader.core import model as model_mod, signals, risk from remizov_trader.config import ModelConfig, RiskConfig RISK_CFG = RiskConfig( per_trade=0.05, max_position_pct=0.40, max_open_positions=3, leverage=1, ) INITIAL_CAPITAL = 177.0 TRAILING_STOP = True LONG_ONLY = False COMMISSION = 0.00055 TIME_EXIT = True TIMEFRAME = "1h" PERIOD = "90d" # Per-asset configs # Model was trained with shift=14 for both UNI and ATOM. # ATOM new config wants shift=10, but model architecture requires shift=14. # So we load with shift=14, but use new stop/K params for trading. ASSETS = [ { "symbol": "UNI/USDT", "ticker": "UNI-USD", "yf_ticker": "UNI7083-USD", # Yahoo Finance ticker for Uniswap "model_cfg": ModelConfig( window_size=64, n_steps=20, total_time=0.5, shift=14, epochs=300, lr=0.005, ), "K": 2, "shift": 14, "stop_mult": 1.25, "stop_scale": 0.75, "cooldown_bars": 3, "shape_confirm": False, "corr_thresh": 0.5, "weight": 0.34, }, { "symbol": "ATOM/USDT", "ticker": "ATOM-USD", "yf_ticker": "ATOM-USD", "model_cfg": ModelConfig( window_size=64, n_steps=20, total_time=0.5, shift=14, epochs=300, lr=0.005, ), # Trading params: new config (K=3, stop_mult=0.75) # but shift=14 for prediction (model architecture) "K": 3, "shift": 14, "stop_mult": 0.75, "stop_scale": 1.0, "cooldown_bars": 3, "shape_confirm": False, "corr_thresh": 0.5, "weight": 0.33, }, ] def fetch_prices_yf(yf_ticker: str, period: str = "90d") -> tuple: """Fetch 1h OHLC via yfinance. Returns (closes, highs, lows, dates).""" hist = yf.Ticker(yf_ticker).history(period=period, interval="1h") if hist.empty: return None, None, None, None closes = hist["Close"].dropna().values.astype(np.float64) highs = hist["High"].reindex(hist["Close"].dropna().index).values.astype(np.float64) lows = hist["Low"].reindex(hist["Close"].dropna().index).values.astype(np.float64) dates = [d.date() if hasattr(d, "date") else d for d in hist["Close"].dropna().index] return closes, highs, lows, dates def run_backtest(asset: dict, prices: np.ndarray, highs: np.ndarray = None, lows: np.ndarray = None): """Frozen-model backtest: no training, just predict. If highs/lows provided, uses them for stop checks. """ if highs is None: highs = prices if lows is None: lows = prices ws = asset["model_cfg"].window_size shift = asset["shift"] K = asset["K"] shape_confirm = asset["shape_confirm"] corr_thresh = asset["corr_thresh"] stop_mult_base = asset["stop_mult"] stop_scale = asset["stop_scale"] cooldown_bars = asset["cooldown_bars"] # Load frozen model model = model_mod.load_model(asset["ticker"], asset["model_cfg"]) if model is None: print(f" ERROR: model not found for {asset['ticker']}") return None model.eval() print(f" Loaded frozen model for {asset['ticker']}") # Simulate bar-by-bar over ALL data (no train split) capital = INITIAL_CAPITAL * asset["weight"] equity = capital trades = [] position = None equity_curve = [equity] cooldown_until = 0 start_idx = ws + K # need window_size + K bars before first signal print(f" Bars: {len(prices)}, simulation starts at bar {start_idx}") for bar in range(start_idx, len(prices)): current_price = float(prices[bar]) h, l = float(highs[bar]), float(lows[bar]) # Check position if position is not None: p = position # Check stop FIRST with adverse price (conservative) adv = l if p["direction"] == 1 else h stopped = risk.is_stopped(adv, p["stop_price"], p["direction"]) bars_held = bar - p["entry_bar"] time_exit = TIME_EXIT and bars_held >= (shift - p["k_used"]) if stopped or time_exit: exit_price = p["stop_price"] if stopped else current_price reason = "stop" if stopped else "time" pnl_net, pnl_pct = risk.calculate_pnl( p["entry_price"], exit_price, p["direction"], p["pos_size"], p["pos_value"], commission=COMMISSION, ) equity += pnl_net trades.append({ "direction": p["direction"], "entry_price": p["entry_price"], "exit_price": exit_price, "pnl_net": pnl_net, "pnl_pct": pnl_pct, "reason": reason, "equity_at_entry": p["equity_at_entry"], "entry_idx": p["entry_bar"], }) position = None if stopped: cooldown_until = bar + cooldown_bars else: # Update trailing AFTER stop check (conservative) fav = h if p["direction"] == 1 else l if TRAILING_STOP: p["best_price"], p["stop_price"] = risk.update_trailing_stop( fav, p["best_price"], p["stop_price"], p["stop_dist"], p["direction"], ) # New signal (every shift bars from start, like prepare_windows) # Actually, we check every bar — signal when no position and no cooldown if position is None and bar >= cooldown_until: w = prices[bar - ws - K:bar - K].copy() confirm = prices[bar - K:bar].copy() mu, std = w.mean(), w.std() if std < 1e-10: equity_curve.append(equity) continue norm_input = (w - mu) / std pred = model_mod.predict(model, norm_input) pred_new = pred[-shift:] if shape_confirm: corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, mu, std, K, corr_thresh, ) else: confirmed = True if confirmed: direction = signals.get_direction(pred_new, K) if direction is not None and not (LONG_ONLY and direction == -1): entry_price = current_price atr = risk.compute_atr(prices, bar) stop_dist = max(atr * stop_mult_base * stop_scale, 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": bar, "k_used": K, "equity_at_entry": equity, } equity_curve.append(equity) # Close remaining 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"], commission=COMMISSION, ) equity += pnl_net trades.append({ "direction": position["direction"], "entry_price": position["entry_price"], "exit_price": last_price, "pnl_net": pnl_net, "pnl_pct": pnl_pct, "reason": "end", "equity_at_entry": position["equity_at_entry"], "entry_idx": position["entry_bar"], }) equity_curve.append(equity) if not trades: print(" No trades!") return None # Metrics pnls = [t["pnl_net"] for t in trades] wins = [t for t in trades if t["pnl_net"] > 0] losses = [t for t in trades if t["pnl_net"] <= 0] longs = [t for t in trades if t["direction"] == 1] shorts = [t for t in trades if t["direction"] == -1] total_pnl = equity - capital total_ret = total_pnl / capital * 100 n_bars = len(prices) - start_idx bars_per_day = 24 years = n_bars / (365.25 * bars_per_day) # Sharpe if len(pnls) > 1 and years > 0: n_days = max(n_bars // bars_per_day, 1) daily_pnl = np.zeros(n_days) for t in trades: day = min((t.get("entry_idx", start_idx) - start_idx) // bars_per_day, n_days - 1) daily_pnl[day] += t["pnl_net"] daily_ret = daily_pnl / 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 # Max DD eq = np.array(equity_curve) peak = np.maximum.accumulate(eq) dd = (peak - eq) / peak max_dd = dd.max() * 100 months = years * 12 time_exits = [t for t in trades if t["reason"] == "time"] stop_exits = [t for t in trades if t["reason"] == "stop"] return { "ticker": asset["ticker"], "trades": len(trades), "wins": len(wins), "losses": len(losses), "wr": len(wins) / len(trades) * 100, "longs": len(longs), "shorts": len(shorts), "long_wr": len([t for t in longs if t["pnl_net"] > 0]) / len(longs) * 100 if longs else 0, "short_wr": len([t for t in shorts if t["pnl_net"] > 0]) / len(shorts) * 100 if shorts else 0, "total_pnl": total_pnl, "total_ret": total_ret, "sharpe": sharpe, "max_dd": max_dd, "monthly_pnl": total_pnl / months if months > 0 else 0, "months": months, "avg_pnl": np.mean(pnls), "avg_win": np.mean([t["pnl_net"] for t in wins]) if wins else 0, "avg_loss": np.mean([t["pnl_net"] for t in losses]) if losses else 0, "time_exits": len(time_exits), "stop_exits": len(stop_exits), "capital": capital, } def main(): results = [] for asset in ASSETS: print(f"\n--- {asset['symbol']} ({asset['ticker']}) ---") print(f" Params: K={asset['K']} shift={asset['shift']} " f"stop_mult={asset['stop_mult']} stop_scale={asset['stop_scale']} " f"cooldown={asset['cooldown_bars']} shape_confirm={asset['shape_confirm']}") print(f" Fetching {TIMEFRAME} data for last {PERIOD} via yfinance ({asset['yf_ticker']})...") prices, highs, lows, dates = fetch_prices_yf(asset["yf_ticker"], PERIOD) if prices is None: print(f" No data") continue print(f" Got {len(prices)} bars ({len(prices)/24:.0f} days)") r = run_backtest(asset, prices, highs, lows) if r: results.append(r) print(f"\n{'='*65}") print(f" {r['ticker']} -- FROZEN MODEL FUTURES 1H LONG+SHORT") print(f"{'='*65}") print(f" Period: ~{r['months']:.1f} months | Capital: ${r['capital']:.0f}") print(f" Trades: {r['trades']} (W:{r['wins']} L:{r['losses']} WR:{r['wr']:.1f}%)") print(f" Longs: {r['longs']} (WR:{r['long_wr']:.1f}%) | " f"Shorts: {r['shorts']} (WR:{r['short_wr']:.1f}%)") print(f" Exits: {r['time_exits']} time | {r['stop_exits']} stop") print(f" Total PnL: ${r['total_pnl']:+,.2f} ({r['total_ret']:+.1f}%)") print(f" Sharpe: {r['sharpe']:.2f}") print(f" Max DD: {r['max_dd']:.1f}%") print(f" Monthly: ${r['monthly_pnl']:+,.2f}/mo") print(f" Avg win: ${r['avg_win']:+,.2f} | Avg loss: ${r['avg_loss']:+,.2f}") print(f"{'='*65}") if results: total_pnl = sum(r["total_pnl"] for r in results) total_cap = sum(r["capital"] for r in results) total_trades = sum(r["trades"] for r in results) total_longs = sum(r["longs"] for r in results) total_shorts = sum(r["shorts"] for r in results) print(f"\n\n{'='*65}") print(f" PORTFOLIO -- FROZEN MODEL FUTURES 1H L+S | ${INITIAL_CAPITAL:.0f} capital") print(f" Commission: {COMMISSION*100:.3f}% | Time exit: {TIME_EXIT}") print(f" NO TRAINING -- using existing prod models") print(f"{'='*65}") print(f" {'Asset':<12s} {'Sharpe':>8s} {'Return':>10s} {'PnL':>10s} " f"{'Trades':>7s} {'L/S':>6s} {'WR':>6s} {'MaxDD':>7s}") print(f" {'-'*65}") for r in sorted(results, key=lambda x: x["sharpe"], reverse=True): print(f" {r['ticker']:<12s} {r['sharpe']:>8.2f} {r['total_ret']:>+9.1f}% " f"${r['total_pnl']:>+9.2f} {r['trades']:>7d} " f"{r['longs']:>2d}/{r['shorts']:<2d} {r['wr']:>5.1f}% " f"{r['max_dd']:>6.1f}%") print(f" {'-'*65}") print(f" {'TOTAL':<12s} {'':>8s} {total_pnl/total_cap*100:>+9.1f}% " f"${total_pnl:>+9.2f} {total_trades:>7d} " f"{total_longs:>2d}/{total_shorts:<2d}") print(f"{'='*65}") print(f"\n CAVEAT: frozen model = no walk-forward training.") print(f" This tests how well the CURRENT prod model handles recent data.") print(f" Backtest still overestimates (slippage=0).") if __name__ == "__main__": main()