"""Verification: emulator runner PnL vs grid_realistic.py PnL. Run with: python -m pytest tests/test_emulator_vs_realistic.py -v -s Requires: /tmp/ohlcv_cache/ with cached OHLCV data. """ import os import sys import pickle import pytest import numpy as np import torch sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) from remizov_trader.emulator.runner import run_single_coin, load_cached_ohlcv from remizov_trader.emulator.matching import FillModel from remizov_trader.core import model as model_mod, signals, risk from remizov_trader.config import ModelConfig, RiskConfig CACHE_DIR = "/tmp/ohlcv_cache" CAP = 59.0 WS = 64; K = 2; SHIFT = 14; EPOCHS = 300; LR = 0.005; SM = 4.0 COMM = 0.00055 CONFIGS = [ ("DOGE/USDT:USDT", "DOGE", 1, 20), ("APT/USDT:USDT", "APT", 1, 12), ("LINK/USDT:USDT", "LINK", 1, 20), ] def _has_cache(): if not os.path.isdir(CACHE_DIR): return False for sym, _, _, _ in CONFIGS: safe = sym.replace("/", "_").replace(":", "_") if not os.path.exists(f"{CACHE_DIR}/{safe}_4h.pkl"): return False return True # ── Reference: grid_realistic.py logic (copied for comparison) ── def _true_atr(highs, lows, prices, idx, period=14): if idx < period + 1: return float(prices[idx]) * 0.02 trs = [] for i in range(idx - period, idx): hl = float(highs[i]) - float(lows[i]) hc = abs(float(highs[i]) - float(prices[i - 1])) lc = abs(float(lows[i]) - float(prices[i - 1])) trs.append(max(hl, hc, lc)) return float(np.mean(trs)) def _run_reference(prices, highs, lows, mdl, delay, hold, cap): """Realistic backtest from grid_realistic.py — the reference implementation.""" SPREAD = 0.0003 STOP_SLIP = 0.002 FUND_RATE = 0.0001 FUND_INTERVAL = 2 RCFG = RiskConfig(per_trade=0.05, max_position_pct=0.40, max_open_positions=3, leverage=1) data = signals.prepare_windows(prices, WS, SHIFT) n = len(data); n_train = max(int(n * 0.30), 20) test_data = data[n_train:] if not test_data: return None eq = cap; pos = None; cool = 0; pending = None pnls = []; trades = 0; wins = 0; stops = 0 ah = hold if hold > 0 else (SHIFT - K) for d in test_data: pi = d["price_idx"]; cp = float(prices[pi]) if pending and pi >= pending["ea"]: ei = pending["ea"]; ep = float(prices[ei]) atr_val = _true_atr(highs, lows, prices, ei) ep += pending["d"] * ep * SPREAD sd = max(atr_val * SM, ep * 0.005); sp = ep - pending["d"] * sd sz, val = risk.calculate_position(eq, ep, sd, RCFG) pos = {"d": pending["d"], "e": ep, "s": sp, "sd": sd, "b": ep, "sz": sz, "v": val, "bar": ei, "lc": ei} pending = None if pos: sf = pos.get("lc", pos["bar"]) + 1 for bi in range(sf, pi + 1): h, l = float(highs[bi]), float(lows[bi]); c = float(prices[bi]) if (bi - pos["bar"]) > 0 and (bi - pos["bar"]) % FUND_INTERVAL == 0: eq -= pos["v"] * FUND_RATE adv = l if pos["d"] == 1 else h if risk.is_stopped(adv, pos["s"], pos["d"]): exit_p = pos["s"] * (1 - pos["d"] * STOP_SLIP) pnl, _ = risk.calculate_pnl(pos["e"], exit_p, pos["d"], pos["sz"], pos["v"], commission=COMM) eq += pnl; pnls.append(pnl); trades += 1; stops += 1 if pnl > 0: wins += 1 pos = None; cool = bi + 3; break fav = h if pos["d"] == 1 else l pos["b"], pos["s"] = risk.update_trailing_stop( fav, pos["b"], pos["s"], pos["sd"], pos["d"]) if bi - pos["bar"] >= ah: exit_p = c * (1 - pos["d"] * SPREAD) pnl, _ = risk.calculate_pnl(pos["e"], exit_p, pos["d"], pos["sz"], pos["v"], commission=COMM) eq += pnl; pnls.append(pnl); trades += 1 if pnl > 0: wins += 1 pos = None; break if pos: pos["lc"] = pi if pos is None and pending is None and pi >= WS + K and pi >= cool: w = prices[pi-WS-K:pi-K].copy(); mu, std = w.mean(), w.std() if std < 1e-10: continue pred = model_mod.predict(mdl, (w - mu) / std)[-SHIFT:] d2 = signals.get_direction(pred, K) if d2: if delay == 0: atr_val = _true_atr(highs, lows, prices, pi) ep = cp + d2 * cp * SPREAD sd = max(atr_val * SM, ep * 0.005) sp = ep - d2 * sd; sz, val = risk.calculate_position(eq, ep, sd, RCFG) pos = {"d": d2, "e": ep, "s": sp, "sd": sd, "b": ep, "sz": sz, "v": val, "bar": pi, "lc": pi} else: pending = {"d": d2, "ea": min(pi + delay, len(prices) - 1)} if pos: lp = float(prices[-1]) * (1 - pos["d"] * SPREAD) pnl, _ = risk.calculate_pnl(pos["e"], lp, pos["d"], pos["sz"], pos["v"], commission=COMM) eq += pnl; pnls.append(pnl); trades += 1 if pnl > 0: wins += 1 return {"pnl": eq - cap, "trades": trades, "wr": wins / trades * 100 if trades else 0, "stops": stops} # ── Tests ── @pytest.mark.skipif(not _has_cache(), reason="No OHLCV cache at /tmp/ohlcv_cache") class TestEmulatorVsRealistic: """Compare emulator runner PnL with reference grid_realistic.py implementation.""" @pytest.fixture(autouse=True) def _setup(self): """Train models once for all tests.""" self.models = {} for sym, coin, delay, hold in CONFIGS: ohlcv, _ = load_cached_ohlcv(CACHE_DIR, sym) prices = ohlcv[:, 3] data = signals.prepare_windows(prices, WS, SHIFT) n_train = max(int(len(data) * 0.30), 20) mcfg = ModelConfig(window_size=WS, n_steps=20, total_time=0.5, shift=SHIFT, epochs=EPOCHS, finetune_epochs=50, lr=LR) torch.manual_seed(42); np.random.seed(42) mdl = model_mod.create_model(mcfg) W = np.array([d["norm_input"] for d in data[:n_train]]) T = np.array([d["norm_target"] for d in data[:n_train]]) model_mod.train(mdl, W, T, EPOCHS, LR) self.models[sym] = mdl @pytest.mark.parametrize("sym,coin,delay,hold", CONFIGS) def test_emulator_pnl_direction(self, sym, coin, delay, hold): """Emulator PnL should have the same sign as reference.""" ohlcv, _ = load_cached_ohlcv(CACHE_DIR, sym) prices = ohlcv[:, 3]; highs = ohlcv[:, 1]; lows = ohlcv[:, 2] ref = _run_reference(prices, highs, lows, self.models[sym], delay, hold, CAP) fm = FillModel(spread=0.0003, stop_slippage=0.002, commission=COMM, funding_rate=0.0001) emu = run_single_coin(sym, ohlcv, delay, hold, CAP, fm) print(f"\n{coin}: ref=${ref['pnl']:+.2f} ({ref['trades']}tr) " f"emu=${emu['pnl']:+.2f} ({emu['trades']}tr)") # Same sign (both profitable or both losing) if abs(ref["pnl"]) > 1.0: # skip near-zero assert (ref["pnl"] > 0) == (emu["pnl"] > 0), \ f"PnL sign mismatch: ref={ref['pnl']:.2f} emu={emu['pnl']:.2f}" @pytest.mark.parametrize("sym,coin,delay,hold", CONFIGS) def test_trade_count_similar(self, sym, coin, delay, hold): """Emulator should produce similar number of trades.""" ohlcv, _ = load_cached_ohlcv(CACHE_DIR, sym) prices = ohlcv[:, 3]; highs = ohlcv[:, 1]; lows = ohlcv[:, 2] ref = _run_reference(prices, highs, lows, self.models[sym], delay, hold, CAP) fm = FillModel(spread=0.0003, stop_slippage=0.002, commission=COMM, funding_rate=0.0001) emu = run_single_coin(sym, ohlcv, delay, hold, CAP, fm) if ref["trades"] > 0: ratio = emu["trades"] / ref["trades"] print(f"\n{coin}: ref={ref['trades']} trades, emu={emu['trades']} " f"(ratio={ratio:.2f})") # Should be within 50% (emulator may differ due to # different ATR calculation and equity path) assert 0.5 <= ratio <= 2.0, \ f"Trade count too different: ref={ref['trades']} emu={emu['trades']}"