"""Exp17: Volume integration tests. Variant A: VWAP as model input (instead of Close) Variant B: Volume filter — only trade when volume > 1.5× avg Variant C: Volume-weighted stop (wider stop on high volume = conviction) Tests on ETH (2h, ws=64) and DOGE (4h, ws=48) — best performers from exp16e. """ import sys from pathlib import Path from dataclasses import dataclass from datetime import datetime, timedelta, timezone 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 remizov_trader.core import model as model_mod, signals, risk from remizov_trader.config import ModelConfig from common.metrics import save_results TOTAL_CAPITAL = 114.0 K = 2 CORR_THRESH = 0.5 TRAIN_RATIO = 0.3 SHIFT = 7 COMMISSION = 0.001 INTEREST_RATE_DAILY = 0.0002 STOP_SCALE = 0.5 # exp16e winner CORRELATED_GROUPS = [ {"BTC-USD", "ETH-USD"}, {"ADA-USD", "DOT-USD", "XRP-USD"}, ] ASSETS = [ {"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241}, {"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158}, {"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137}, {"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137}, {"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127}, {"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108}, {"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092}, ] def fetch_ohlcv(symbol, interval, period="max"): """Fetch OHLCV data.""" from remizov_trader.core.signals import _get_exchange exchange = _get_exchange(None) if period == "max": days = 1000 else: days = int(period.rstrip("d")) since = int((datetime.now(timezone.utc) - timedelta(days=days)).timestamp() * 1000) all_ohlcv = [] batch_size = 1000 now_ms = int(datetime.now(timezone.utc).timestamp() * 1000) prev_since = None while since < now_ms: try: ohlcv = exchange.fetch_ohlcv(symbol, interval, since=since, limit=batch_size) except Exception as e: print(f"ERROR: {e}") return None, None, None, None, None if not ohlcv: break all_ohlcv.extend(ohlcv) since = ohlcv[-1][0] + 1 if since == prev_since: break prev_since = since if not all_ohlcv: return None, None, None, None, None closes = np.array([c[4] for c in all_ohlcv], dtype=np.float64) highs = np.array([c[2] for c in all_ohlcv], dtype=np.float64) lows = np.array([c[3] for c in all_ohlcv], dtype=np.float64) volumes = np.array([c[5] for c in all_ohlcv], dtype=np.float64) dates = [datetime.fromtimestamp(c[0] / 1000, tz=timezone.utc).date() for c in all_ohlcv] return closes, highs, lows, volumes, dates def compute_vwap(closes, highs, lows, volumes, period=20): """Compute VWAP using typical price × volume.""" typical = (highs + lows + closes) / 3.0 vwap = np.full_like(closes, np.nan) for i in range(period, len(closes)): w = volumes[i-period:i] tp = typical[i-period:i] total_vol = w.sum() if total_vol > 0: vwap[i] = (tp * w).sum() / total_vol else: vwap[i] = closes[i] # Fill initial with close vwap[:period] = closes[:period] return vwap @dataclass class Position: ticker: str direction: int entry_price: float stop_price: float stop_dist: float best_price: float pos_size: float pos_value: float margin_locked: float borrowed: float k_used: int entry_bar: int def run_sim(asset_data, events, variant="baseline"): """Run simulation with volume variant. variant: 'baseline' — standard (Close input, no filter) 'vwap' — VWAP as model input 'vol_filter' — only trade when volume > 1.5x rolling avg 'vol_stop' — wider stop on high volume (conviction trade) """ free_usdc = TOTAL_CAPITAL open_positions = {} trades = [] last_stop_date = {} peak_equity = TOTAL_CAPITAL max_drawdown = 0.0 per_asset = {} skipped_vol = 0 tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24} for date, ticker, window in events: ad = asset_data[ticker] prices = ad["prices"] # always Close for stop/entry model_prices = ad.get("vwap", prices) if variant == "vwap" else prices volumes = ad["volumes"] price_idx = window["price_idx"] current_price = float(prices[price_idx]) ws = ad["ws"] leverage = ad["leverage"] weight = ad["weight"] bar_h = tf_hours.get(ad["tf"], 4) # Check position if ticker in open_positions: pos = open_positions[ticker] closed = False check_from = max(pos.entry_bar + 1, price_idx - SHIFT + 1) for bar_idx in range(check_from, price_idx + 1): if bar_idx >= len(prices): break bar_price = float(prices[bar_idx]) bars_since = bar_idx - pos.entry_bar pos.best_price, pos.stop_price = risk.update_trailing_stop( bar_price, pos.best_price, pos.stop_price, pos.stop_dist, pos.direction) stopped = risk.is_stopped(bar_price, pos.stop_price, pos.direction) if stopped: pnl_gross = pos.pos_size * (pos.stop_price - pos.entry_price) * pos.direction commission_cost = pos.pos_value * COMMISSION * 2 hold_hours = bars_since * bar_h trade_interest = pos.borrowed * INTEREST_RATE_DAILY * hold_hours / 24 pnl_net = pnl_gross - commission_cost - trade_interest free_usdc += pos.margin_locked + pnl_net del open_positions[ticker] trades.append({"ticker": ticker, "pnl_net": pnl_net, "equity_at_entry": pos.margin_locked}) per_asset[ticker] = per_asset.get(ticker, 0) + pnl_net if stopped: exit_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date last_stop_date[ticker] = exit_date total_eq = free_usdc + sum(p.margin_locked for p in open_positions.values()) peak_equity = max(peak_equity, total_eq) dd = (peak_equity - total_eq) / peak_equity if peak_equity > 0 else 0 max_drawdown = max(max_drawdown, dd) closed = True break if closed: continue # New signal if ticker not in open_positions and price_idx >= ws + K: # Cooldown if ticker in last_stop_date: from datetime import date as d days_since = (d.fromisoformat(date[:10]) - d.fromisoformat(last_stop_date[ticker][:10])).days candles_since = days_since * 24 // bar_h if candles_since < SHIFT: continue # Volume filter (variant B) if variant == "vol_filter": vol_window = 50 if price_idx >= vol_window: avg_vol = volumes[price_idx-vol_window:price_idx].mean() current_vol = volumes[price_idx] if avg_vol > 0 and current_vol < avg_vol * 1.5: skipped_vol += 1 continue # Use model_prices for prediction input w = model_prices[price_idx - ws - K:price_idx - K].copy() mu, std = w.mean(), w.std() if std < 1e-10: continue norm_input = (w - mu) / std pred = model_mod.predict(ad["model"], norm_input) pred_new = pred[-SHIFT:] # Shape confirmation: always use Close prices with Close normalization confirm = prices[price_idx - K:price_idx].copy() w_close = prices[price_idx - ws - K:price_idx - K] mu_close, std_close = float(w_close.mean()), float(w_close.std()) if std_close < 1e-10: continue corr, confirmed = signals.check_shape_confirmation( pred_new, confirm, mu_close, std_close, K, CORR_THRESH) if not confirmed: continue direction = signals.get_direction(pred_new, K) if direction is None or direction == -1: continue # Correlation filter skip_corr = False for g in CORRELATED_GROUPS: if ticker not in g: continue for other in g: if other != ticker and other in open_positions: if open_positions[other].direction == direction: skip_corr = True if skip_corr: continue total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values()) pos_value = total_equity * weight * leverage if pos_value < 5.0: continue margin_needed = pos_value / leverage if free_usdc < margin_needed: margin_needed = free_usdc * 0.95 pos_value = margin_needed * leverage if pos_value < 5.0: continue pos_size = pos_value / current_price borrowed = pos_value - margin_needed k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K) atr = risk.compute_atr(prices, price_idx) # Volume-weighted stop (variant C) scale = STOP_SCALE if variant == "vol_stop" and price_idx >= 50: avg_vol = volumes[price_idx-50:price_idx].mean() vol_ratio = volumes[price_idx] / avg_vol if avg_vol > 0 else 1.0 if vol_ratio > 2.0: scale *= 1.5 # wider stop on high volume (conviction) elif vol_ratio < 0.5: scale *= 0.7 # tighter stop on low volume (less conviction) stop_dist = max(atr * stop_mult * scale, current_price * 0.005) free_usdc -= margin_needed open_positions[ticker] = Position( ticker=ticker, direction=direction, entry_price=current_price, stop_price=current_price - direction * stop_dist, stop_dist=stop_dist, best_price=current_price, pos_size=pos_size, pos_value=pos_value, margin_locked=margin_needed, borrowed=borrowed, k_used=k_adj, entry_bar=price_idx, ) # Close remaining for ticker, pos in list(open_positions.items()): ad = asset_data[ticker] last_price = float(ad["prices"][-1]) pnl_gross = pos.pos_size * (last_price - pos.entry_price) * pos.direction bars_held = ad["test_data"][-1]["price_idx"] - pos.entry_bar bar_hours = tf_hours.get(ad["tf"], 4) trade_interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_hours / 24 pnl_net = pnl_gross - pos.pos_value * COMMISSION * 2 - trade_interest free_usdc += pos.margin_locked + pnl_net per_asset[ticker] = per_asset.get(ticker, 0) + pnl_net trades.append({"ticker": ticker, "pnl_net": pnl_net, "equity_at_entry": pos.margin_locked}) final = free_usdc wins = [t for t in trades if t["pnl_net"] > 0] if len(trades) > 1: from datetime import date as d first = d.fromisoformat(events[0][0][:10]) last = d.fromisoformat(events[-1][0][:10]) years = max((last - first).days / 365.25, 0.1) returns = np.array([t["pnl_net"] / t["equity_at_entry"] for t in trades if t["equity_at_entry"] > 0]) tpy = len(trades) / years sharpe = float(np.mean(returns) / np.std(returns) * np.sqrt(tpy)) if np.std(returns) > 0 else 0 months = years * 12 else: sharpe, months = 0, 1 return { "variant": variant, "sharpe": round(sharpe, 2), "total_pnl": round(final - TOTAL_CAPITAL, 2), "total_ret": round((final - TOTAL_CAPITAL) / TOTAL_CAPITAL * 100, 1), "trades": len(trades), "wr": round(len(wins) / len(trades) * 100, 1) if trades else 0, "max_dd": round(max_drawdown * 100, 1), "monthly_pnl": round((final - TOTAL_CAPITAL) / months, 2) if months > 0 else 0, "skipped_vol": skipped_vol, "per_asset": {k: round(v, 2) for k, v in sorted(per_asset.items(), key=lambda x: -x[1])}, } def main(): print(f"{'='*80}") print("EXP17: VOLUME INTEGRATION TESTS") print(f"{'='*80}\n") asset_data = {} for a in ASSETS: ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"] ws = a["ws"] print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True) closes, highs, lows, volumes, dates = fetch_ohlcv(symbol, tf) if closes is None or len(closes) < ws + K + SHIFT + 30: print("not enough data") continue # Compute VWAP vwap = compute_vwap(closes, highs, lows, volumes) # Train model on Close (baseline) — same model for all variants data_close = signals.prepare_windows(closes, ws, SHIFT) if len(data_close) < 30: continue n_train = max(int(len(data_close) * TRAIN_RATIO), 20) model_cfg = ModelConfig(window_size=ws, n_steps=20, total_time=0.5, shift=SHIFT, epochs=200, finetune_epochs=50, lr=0.003) torch.manual_seed(42) np.random.seed(42) mdl_close = model_mod.create_model(model_cfg) train_close = data_close[:n_train] model_mod.train(mdl_close, np.array([d["norm_input"] for d in train_close]), np.array([d["norm_target"] for d in train_close]), 200, 0.003) # Train model on VWAP (variant A) data_vwap = signals.prepare_windows(vwap, ws, SHIFT) torch.manual_seed(42) np.random.seed(42) mdl_vwap = model_mod.create_model(model_cfg) train_vwap = data_vwap[:n_train] model_mod.train(mdl_vwap, np.array([d["norm_input"] for d in train_vwap]), np.array([d["norm_target"] for d in train_vwap]), 200, 0.003) asset_data[ticker] = { "prices": closes, "highs": highs, "lows": lows, "volumes": volumes, "vwap": vwap, "dates": dates, "tf": tf, "model": mdl_close, "model_vwap": mdl_vwap, "test_data": data_close[n_train:], "ws": ws, "leverage": a["leverage"], "weight": a["weight"], } print(f"{len(closes)} bars, {len(data_close[n_train:])} test") # Build events events = [] for ticker, ad in asset_data.items(): for d in ad["test_data"]: events.append((str(ad["dates"][d["price_idx"]]), ticker, d)) events.sort(key=lambda x: x[0]) # Run variants variants = ["baseline", "vol_filter", "vol_stop"] print(f"\n{'='*80}") print("RESULTS") print(f"{'='*80}\n") print(f" {'Variant':<15s} | {'Sharpe':>6s} | {'PnL':>8s} | {'DD%':>5s} | " f"{'WR%':>5s} | {'Trds':>5s} | {'$/mo':>7s} | {'Skip':>5s}") print(f" {'-'*75}") all_results = [] for v in variants: r = run_sim(asset_data, events, variant=v) all_results.append(r) print(f" {v:<15s} | {r['sharpe']:>6.2f} | ${r['total_pnl']:>+7.2f} | " f"{r['max_dd']:>4.1f}% | {r['wr']:>4.1f}% | {r['trades']:>5d} | " f"${r['monthly_pnl']:>+6.2f} | {r['skipped_vol']:>5d}") for t, pnl in r["per_asset"].items(): print(f" {t}: ${pnl:>+7.2f}") # VWAP variant — needs separate model print(f"\n --- VWAP variant (separate model trained on VWAP) ---") # Swap models for VWAP test for ticker, ad in asset_data.items(): ad["model"], ad["_orig_model"] = ad["model_vwap"], ad["model"] r = run_sim(asset_data, events, variant="vwap") all_results.append(r) print(f" {'vwap':<15s} | {r['sharpe']:>6.2f} | ${r['total_pnl']:>+7.2f} | " f"{r['max_dd']:>4.1f}% | {r['wr']:>4.1f}% | {r['trades']:>5d} | " f"${r['monthly_pnl']:>+6.2f} | {r['skipped_vol']:>5d}") for t, pnl in r["per_asset"].items(): print(f" {t}: ${pnl:>+7.2f}") # Restore models for ticker, ad in asset_data.items(): ad["model"] = ad.pop("_orig_model") path = save_results({"results": all_results}, Path(__file__).parent / "results", "exp17_volume") print(f"\n Saved: {path}") if __name__ == "__main__": main()