diff --git a/experiments/exp18_k_comparison/run.py b/experiments/exp18_k_comparison/run.py new file mode 100644 index 0000000..b3e7309 --- /dev/null +++ b/experiments/exp18_k_comparison/run.py @@ -0,0 +1,443 @@ +"""Exp18: K parameter comparison (K=2 vs K=3 vs K=4). + +K controls shape confirmation window size: +- K=2: correlation of 2 points → always ±1.0 (binary) +- K=3: correlation of 3 points → continuous [-1, +1] +- K=4: correlation of 4 points → more granular + +Also tracks stop_scale variants: 0.5 (current) and 1.0 (baseline). +Uses same realistic Bybit margin simulation as exp16. +""" +import sys +from pathlib import Path +from dataclasses import dataclass +from copy import deepcopy + +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 compute_metrics, save_results, compare_results, print_metrics + +TOTAL_CAPITAL = 114.0 +CORR_THRESH = 0.5 +TRAILING_STOP = True +TRAIN_RATIO = 0.3 +SHIFT = 7 + +INTEREST_RATE_DAILY = 0.0002 +COMMISSION = 0.001 + +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}, +] + +# Test grid: K values × stop_scale values +K_VALUES = [2, 3, 4] +STOP_SCALES = [0.5, 1.0] + + +@dataclass +class Position: + ticker: str + direction: int + entry_price: float + entry_date: str + 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 check_correlation_conflict(open_positions: dict, ticker: str, direction: int) -> bool: + for g in CORRELATED_GROUPS: + if ticker not in g: + continue + for other in g: + if other == ticker: + continue + if other in open_positions and open_positions[other].direction == direction: + return True + return False + + +def run_simulation(asset_data: dict, events: list, K: int, stop_scale: float, + ) -> dict: + """Run one simulation with given K and stop_scale. Returns results dict.""" + tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24} + + free_usdc = TOTAL_CAPITAL + open_positions: dict[str, Position] = {} + all_trades = [] + per_asset_trades: dict[str, list] = {t: [] for t in asset_data} + last_stop_date: dict[str, str] = {} + skipped_no_margin = 0 + skipped_cooldown = 0 + skipped_correlation = 0 + skipped_spot_short = 0 + skipped_low_corr = 0 + total_interest_paid = 0.0 + peak_equity = TOTAL_CAPITAL + max_drawdown = 0.0 + + # Track correlation distribution + corr_values = [] + + for date, ticker, window in events: + ad = asset_data[ticker] + prices = ad["prices"] + price_idx = window["price_idx"] + current_price = float(prices[price_idx]) + ws = ad["ws"] + leverage = ad["leverage"] + weight = ad["weight"] + + # Check open position + if ticker in open_positions: + pos = open_positions[ticker] + bar_hours = tf_hours.get(ad["tf"], 4) + + 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]) + + if TRAILING_STOP: + 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) + bars_held = bar_idx - pos.entry_bar + time_exit = bars_held >= (SHIFT - pos.k_used) + + if stopped or time_exit: + exit_price = pos.stop_price if stopped else bar_price + exit_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date + + pnl_gross = pos.pos_size * (exit_price - pos.entry_price) * pos.direction + commission_cost = pos.pos_value * COMMISSION * 2 + hold_hours = bars_held * bar_hours + trade_interest = pos.borrowed * INTEREST_RATE_DAILY * hold_hours / 24 + total_interest_paid += trade_interest + pnl_net = pnl_gross - commission_cost - trade_interest + + free_usdc += pos.margin_locked + pnl_net + del open_positions[ticker] + + trade = { + "ticker": ticker, "pnl_net": pnl_net, "pnl_gross": pnl_gross, + "commission": commission_cost, "interest": trade_interest, + "equity_at_entry": pos.margin_locked, + "exit_reason": "stop" if stopped else "time", + "bars_held": bars_held, "date": exit_date, + "entry_price": pos.entry_price, "exit_price": exit_price, + "direction": pos.direction, + } + all_trades.append(trade) + per_asset_trades[ticker].append(trade) + if stopped: + last_stop_date[ticker] = exit_date + + total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values()) + peak_equity = max(peak_equity, total_equity) + dd = (peak_equity - total_equity) / peak_equity if peak_equity > 0 else 0 + max_drawdown = max(max_drawdown, dd) + break + + # 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 + bar_h = tf_hours.get(ad["tf"], 4) + candles_since = days_since * 24 // bar_h + if candles_since < SHIFT: + skipped_cooldown += 1 + continue + + # Signal + 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(ad["model"], norm_input) + pred_new = pred[-SHIFT:] + corr, confirmed = signals.check_shape_confirmation( + pred_new, confirm, mu, std, K, CORR_THRESH) + + corr_values.append(corr) + + if not confirmed: + skipped_low_corr += 1 + continue + + direction = signals.get_direction(pred_new, K) + if direction is None: + continue + + if direction == -1: + skipped_spot_short += 1 + continue + + if check_correlation_conflict(open_positions, ticker, direction): + skipped_correlation += 1 + 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: + skipped_no_margin += 1 + 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) + stop_dist = max(atr * stop_mult * stop_scale, current_price * 0.005) + + free_usdc -= margin_needed + open_positions[ticker] = Position( + ticker=ticker, direction=direction, + entry_price=current_price, entry_date=date, + 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 positions + 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 + commission_cost = pos.pos_value * COMMISSION * 2 + last_bar = ad["test_data"][-1]["price_idx"] + bars_held = last_bar - 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 - commission_cost - trade_interest + + free_usdc += pos.margin_locked + pnl_net + trade = { + "ticker": ticker, "pnl_net": pnl_net, "pnl_gross": pnl_gross, + "commission": commission_cost, "interest": trade_interest, + "equity_at_entry": pos.margin_locked, + "exit_reason": "end", "bars_held": bars_held, + "date": str(ad["dates"][-1]), + "entry_price": pos.entry_price, "exit_price": last_price, + "direction": pos.direction, + } + all_trades.append(trade) + per_asset_trades[ticker].append(trade) + + final_equity = free_usdc + + # Correlation distribution + corr_arr = np.array(corr_values) if corr_values else np.array([0]) + unique_corrs = np.unique(np.round(corr_arr, 2)) + + # Years for Sharpe + if events: + from datetime import date as d + first = d.fromisoformat(events[0][0][:10]) + last = d.fromisoformat(events[-1][0][:10]) + years = (last - first).days / 365.25 + else: + years = 1.0 + + metrics = compute_metrics(all_trades, TOTAL_CAPITAL, years) + metrics["max_dd"] = round(max_drawdown * 100, 1) + metrics["final_equity"] = round(final_equity, 2) + metrics["skipped_low_corr"] = skipped_low_corr + metrics["skipped_cooldown"] = skipped_cooldown + metrics["skipped_correlation"] = skipped_correlation + metrics["skipped_spot_short"] = skipped_spot_short + metrics["skipped_no_margin"] = skipped_no_margin + metrics["corr_unique_values"] = len(unique_corrs) + metrics["corr_mean"] = round(float(corr_arr.mean()), 3) + metrics["corr_std"] = round(float(corr_arr.std()), 3) + metrics["corr_pct_positive"] = round(float((corr_arr > 0).sum() / len(corr_arr) * 100), 1) + metrics["years"] = round(years, 2) + + # Per-asset + asset_metrics = {} + for a in ASSETS: + t = a["ticker"] + trades = per_asset_trades.get(t, []) + if trades: + am = compute_metrics(trades, a["weight"] * TOTAL_CAPITAL, years) + asset_metrics[t] = am + + return {"metrics": metrics, "asset_metrics": asset_metrics, "trades": all_trades} + + +def main(): + results_dir = Path(__file__).parent / "results" + + print(f"{'='*80}") + print("EXP18: K PARAMETER COMPARISON (K=2 vs K=3 vs K=4)") + print(f"{'='*80}") + print(f"Capital: ${TOTAL_CAPITAL} | Stop scales: {STOP_SCALES} | K values: {K_VALUES}") + print() + + # Fetch data + train models (once, shared across all K variants) + asset_data = {} + max_k = max(K_VALUES) + + for a in ASSETS: + ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"] + ws, leverage, weight = a["ws"], a["leverage"], a["weight"] + + print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True) + try: + prices, dates = signals.fetch_prices_ccxt(symbol, tf, "max") + except Exception as e: + print(f"FETCH ERROR: {e}") + continue + if prices is None or len(prices) < ws + max_k + SHIFT + 30: + print("not enough data") + continue + + data = signals.prepare_windows(prices, ws, SHIFT) + if len(data) < 30: + print(f"only {len(data)} windows") + continue + + n_train = max(int(len(data) * TRAIN_RATIO), 20) + train_data = data[:n_train] + test_data = data[n_train:] + + 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 = model_mod.create_model(model_cfg) + windows_arr = np.array([d["norm_input"] for d in train_data]) + targets_arr = np.array([d["norm_target"] for d in train_data]) + model_mod.train(mdl, windows_arr, targets_arr, 200, 0.003) + + asset_data[ticker] = { + "prices": prices, "dates": dates, "tf": tf, + "model": mdl, "test_data": test_data, + "ws": ws, "leverage": leverage, "weight": weight, + } + print(f"{len(prices)} bars, {len(test_data)} test windows") + + if not asset_data: + print("No data!") + return + + # Build chronological event timeline (shared) + events = [] + for ticker, ad in asset_data.items(): + for d in ad["test_data"]: + price_idx = d["price_idx"] + date = str(ad["dates"][price_idx]) + events.append((date, ticker, d)) + events.sort(key=lambda x: x[0]) + + print(f"\n Events: {len(events)} | Range: {events[0][0]} -> {events[-1][0]}") + + # Run grid + all_results = {} + + for k in K_VALUES: + for ss in STOP_SCALES: + label = f"K={k}_ss={ss}" + print(f"\n{'─'*60}") + print(f" Running: {label}...") + result = run_simulation(asset_data, events, K=k, stop_scale=ss) + all_results[label] = result + m = result["metrics"] + print(f" Equity: ${m['final_equity']} | Trades: {m['trades']} | " + f"WR: {m['wr']}% | Sharpe: {m['sharpe']} | DD: {m['max_dd']}%") + print(f" Corr: {m['corr_unique_values']} unique values | " + f"mean={m['corr_mean']} std={m['corr_std']} | " + f"{m['corr_pct_positive']}% positive") + + # Comparison table + print(f"\n{'='*80}") + print("COMPARISON TABLE") + print(f"{'='*80}") + header = (f" {'Config':<15s} {'Equity':>10s} {'Return':>8s} {'Trades':>7s} " + f"{'WR':>6s} {'Sharpe':>7s} {'MaxDD':>7s} {'CorrUniq':>9s} {'CorrMean':>9s}") + print(header) + print(f" {'─'*78}") + + for label, result in all_results.items(): + m = result["metrics"] + print(f" {label:<15s} ${m['final_equity']:>9.2f} {m['total_ret']:>+7.1f}% " + f"{m['trades']:>7d} {m['wr']:>5.1f}% {m['sharpe']:>7.2f} " + f"{m['max_dd']:>6.1f}% {m['corr_unique_values']:>9d} {m['corr_mean']:>+9.3f}") + + # Per-asset breakdown for each K (at stop_scale=0.5) + print(f"\n{'='*80}") + print("PER-ASSET: K=2 vs K=3 vs K=4 (stop_scale=0.5)") + print(f"{'='*80}") + + for a in ASSETS: + ticker = a["ticker"] + print(f"\n {ticker}:") + for k in K_VALUES: + label = f"K={k}_ss=0.5" + am = all_results[label]["asset_metrics"].get(ticker, {}) + if am: + print(f" K={k}: {am['trades']}tr WR={am['wr']}% " + f"PnL=${am['total_pnl']:+.2f} Sharpe={am['sharpe']}") + else: + print(f" K={k}: no trades") + + # Save all results + save_data = { + "config": { + "k_values": K_VALUES, + "stop_scales": STOP_SCALES, + "corr_thresh": CORR_THRESH, + "assets": ASSETS, + }, + "results": {label: r["metrics"] for label, r in all_results.items()}, + } + path = save_results(save_data, results_dir, "exp18_k_comparison") + print(f"\nSaved: {path}") + + +if __name__ == "__main__": + main()