diff --git a/config.yaml b/config.yaml index 71821a8..71d5a9c 100644 --- a/config.yaml +++ b/config.yaml @@ -10,35 +10,74 @@ capital: risk: per_trade: 0.05 # 5% risk per trade max_position_pct: 0.40 # max 40% of equity (min $5 Bybit limit) - max_open_positions: 2 # 2 assets: ADA+DOGE only (exp26i/j) - leverage: 2 # 2x spot margin (exp12: DD ~14%, Sharpe stable) - stop_scale: 0.5 # exp16e: tighter stop = faster exit + cooldown (Sharpe 4.15) - time_exit: false # exp20/21 new data: TE=OFF +$134 vs TE=ON -$14. Hold until stop. + max_open_positions: 3 # 3 assets: UNI+ATOM+NEAR (autoresearch grid) + leverage: 1 # 1x — grid search best results all at leverage=1 + stop_scale: 1.0 # global default; per-asset overrides below + time_exit: false # grid search: hold until stop safety_stop_pct: 0.10 # 10% hard stop on exchange (flash crash protection) - min_confidence: 1.5 # exp22: |corr| × amplitude/ATR ≥ 1.5 (Sharpe 0.92→1.43, DD 20%→10.8%) + min_confidence: 0.0 # grid search best: no confidence filter assets: - - ticker: ADA-USD - symbol: ADA/USDC + # Grid search top-3 (OOS confirmed): exact params from autoresearch + - ticker: UNI-USD + symbol: UNI/USDC window_size: 64 - weight: 0.50 - leverage: 2 - K: 3 + weight: 0.34 + leverage: 1 + K: 2 + shift: 14 + epochs: 300 + lr: 0.005 + stop_mult: 1.25 # fixed ATR mult (no regime_adaptive) + stop_scale: 0.75 + cooldown_bars: 3 + min_confidence: 0.0 + shape_confirm: false + corr_thresh: 0.5 + timeframe: 4h - - ticker: DOGE-USD - symbol: DOGE/USDC - window_size: 48 - weight: 0.50 - leverage: 2 + - ticker: ATOM-USD + symbol: ATOM/USDC + window_size: 64 + weight: 0.33 + leverage: 1 + K: 3 + shift: 14 + epochs: 300 + lr: 0.005 + stop_mult: 0.75 + stop_scale: 1.0 + cooldown_bars: 3 + min_confidence: 0.0 + shape_confirm: false + corr_thresh: 0.5 + timeframe: 4h + + - ticker: NEAR-USD + symbol: NEAR/USDC + window_size: 64 + weight: 0.33 + leverage: 1 + K: 2 + shift: 16 + epochs: 300 + lr: 0.01 + stop_mult: 1.0 + stop_scale: 1.0 + cooldown_bars: -1 # -1 = use shift (16) as cooldown, matches test behavior + min_confidence: 0.0 + shape_confirm: false + corr_thresh: 0.5 + timeframe: 4h model: window_size: 64 n_steps: 20 total_time: 0.5 - shift: 7 - epochs: 200 + shift: 14 + epochs: 300 finetune_epochs: 50 - lr: 0.003 + lr: 0.005 circuit_breaker: atr_ratio_on: 3.0 # ATR14/ATR50 > 3 → pause @@ -70,5 +109,5 @@ llm: sentiment_threshold: -0.3 schedule: - timeframe: 4h # global default (per-asset overrides above) + timeframe: 4h # 4h — matches grid search test timeframe check_time: "22:00" # UTC (used for daily, ignored for interval) diff --git a/experiments/autoresearch/.gitignore b/experiments/autoresearch/.gitignore index 7b6eb91..d1bc1e6 100644 --- a/experiments/autoresearch/.gitignore +++ b/experiments/autoresearch/.gitignore @@ -1,6 +1,9 @@ runs/ +runs_wf/ best/ +best_wf/ run.log results.tsv status.json +status_wf.json __pycache__/ diff --git a/experiments/autoresearch/dashboard.html b/experiments/autoresearch/dashboard.html index 95fd643..acdab08 100644 --- a/experiments/autoresearch/dashboard.html +++ b/experiments/autoresearch/dashboard.html @@ -406,6 +406,33 @@ tr.best-row td { padding: 40px; } +/* ═══════════ Mode Tabs ═══════════ */ +.mode-tabs { + display: flex; + gap: 4px; + background: var(--bg-2); + padding: 3px; + border-radius: 8px; +} + +.mode-tab { + padding: 6px 16px; + border-radius: 6px; + font-size: 0.78rem; + font-weight: 600; + cursor: pointer; + background: transparent; + color: var(--text-1); + border: none; + font-family: var(--font); + transition: all .15s; +} + +.mode-tab.active { + background: var(--accent); + color: white; +} + /* ═══════════ Responsive ═══════════ */ @media (max-width: 900px) { main { grid-template-columns: 1fr; } @@ -419,6 +446,10 @@ tr.best-row td {

AUTORESEARCH

+
+ + +
idle
@@ -489,7 +520,7 @@ tr.best-row td {
-
All Runs
+
All Runs
@@ -521,6 +552,9 @@ let sortAsc = false; let activeChart = 'sharpe'; let activeAsset = 'all'; let chart = null; +let activeMode = 'grid'; // 'grid' or 'wf' +let wfRuns = []; +let wfBestData = null; function getRunAssets(r) { return Object.keys(r.results || {}); @@ -797,9 +831,17 @@ function getDiscoveredAssets() { return sorted; } +function getWFAssets() { + const assetSet = new Set(); + for (const r of wfRuns) { + for (const k of Object.keys(r.results || {})) assetSet.add(k); + } + return [...assetSet].sort(); +} + function renderFilterPills() { const bar = document.getElementById('filter-bar'); - const assets = getDiscoveredAssets(); + const assets = activeMode === 'wf' ? getWFAssets() : getDiscoveredAssets(); bar.querySelectorAll('.asset-pill:not([data-asset="all"])').forEach(e => e.remove()); for (const asset of assets) { const btn = document.createElement('button'); @@ -964,14 +1006,8 @@ async function fetchAll() { // ═══════════ SSE ═══════════ function connectSSE() { const evtSrc = new EventSource('/api/events'); - evtSrc.onmessage = (e) => { - // Re-fetch on any change - fetchAll(); - }; - evtSrc.onerror = () => { - evtSrc.close(); - setTimeout(connectSSE, 5000); - }; + evtSrc.onmessage = () => { if (activeMode === 'grid') fetchAll(); }; + evtSrc.onerror = () => { evtSrc.close(); setTimeout(connectSSE, 5000); }; } // ═══════════ Asset Filter ═══════════ @@ -1024,12 +1060,179 @@ document.querySelectorAll('th[data-sort]').forEach(th => { }); }); +// ═══════════ Walk-Forward Mode ═══════════ +function setMode(mode) { + activeMode = mode; + document.querySelectorAll('.mode-tab').forEach(t => + t.classList.toggle('active', t.dataset.mode === mode)); + // Update table headers for mode + const thWR = document.querySelector('th[data-sort="wr"]'); + const thDD = document.querySelector('th[data-sort="dd"]'); + if (mode === 'wf') { + thWR.textContent = 'Worst'; + thDD.textContent = 'Std'; + document.getElementById('table-title').textContent = 'Walk-Forward Runs'; + fetchWF(); + } else { + thWR.textContent = 'WR%'; + thDD.textContent = 'DD%'; + document.getElementById('table-title').textContent = 'All Runs'; + fetchAll(); + } +} + +async function fetchWF() { + try { + const [runsRes, bestRes, statusRes] = await Promise.all([ + fetch('/api/wf/runs'), fetch('/api/wf/best'), fetch('/api/wf/status') + ]); + wfRuns = await runsRes.json(); + wfBestData = await bestRes.json(); + const status = await statusRes.json(); + renderStatus(status); + renderWF(); + } catch (e) { console.error('WF fetch error:', e); } +} + +function getWFSharpe(r) { + const res = Object.values(r.results || {})[0]; + return res?.wf_sharpe || 0; +} + +function renderWF() { + renderFilterPills(); + // Header stats + const bestWF = wfRuns.reduce((best, r) => getWFSharpe(r) > getWFSharpe(best||r) ? r : best, null); + document.getElementById('hdr-runs').textContent = wfRuns.length; + if (bestWF) { + const s = getWFSharpe(bestWF); + document.getElementById('hdr-sharpe').textContent = s.toFixed(4); + document.getElementById('hdr-sharpe').style.color = sharpeColor(s); + const p = bestWF.total_pnl || 0; + document.getElementById('hdr-pnl').textContent = '$' + p.toFixed(2); + document.getElementById('hdr-pnl').style.color = p >= 0 ? 'var(--green)' : 'var(--red)'; + } + + // Update chart with WF data + if (chart) { + const labels = wfRuns.map((_, i) => i + 1); + const values = wfRuns.map(r => getWFSharpe(r)); + let best = -Infinity; + const bestLine = values.map(v => { best = Math.max(best, v); return best; }); + chart.data.labels = labels; + chart.data.datasets[0].data = values; + chart.data.datasets[0].label = 'WF Sharpe'; + chart.data.datasets[0].borderColor = '#8b5cf6'; + chart.data.datasets[1].data = bestLine; + chart.update('none'); + } + + // Asset summary for WF + const grid = document.getElementById('asset-grid'); + const assetMap = {}; + for (const r of wfRuns) { + for (const [tk, res] of Object.entries(r.results || {})) { + if (!assetMap[tk]) assetMap[tk] = {count: 0, best: -999, bestPnl: 0, bestParams: ''}; + assetMap[tk].count++; + if ((res.wf_sharpe||0) > assetMap[tk].best) { + assetMap[tk].best = res.wf_sharpe; + assetMap[tk].bestPnl = res.wf_pnl || 0; + assetMap[tk].bestParams = keyParams(r.params); + } + } + } + let summaryHtml = ''; + for (const [tk, a] of Object.entries(assetMap).sort((x,y) => y[1].best - x[1].best)) { + const cls = a.best > 0 ? 'positive' : 'negative'; + summaryHtml += `
+
${tk.replace('-USD','')}
+
WF Sharpe + ${a.best.toFixed(4)}
+
WF PnL + $${a.bestPnl.toFixed(2)}
+
Runs${a.count}
+
${a.bestParams}
+
`; + } + grid.innerHTML = summaryHtml || '
No WF runs yet
'; + + // Best card for WF + if (wfBestData) { + const res = Object.values(wfBestData.results || {})[0]; + if (res) { + let foldHtml = ''; + for (const f of (res.folds || [])) { + foldHtml += `
+ Fold ${f.fold} + ${f.sharpe.toFixed(4)} + $${f.total_pnl.toFixed(0)} + ${f.trades}t +
`; + } + document.getElementById('best-metrics').innerHTML = ` +
WF Sharpe + ${res.wf_sharpe.toFixed(4)}
+
WF PnL + $${res.wf_pnl.toFixed(2)}
+
Trades + ${res.wf_trades}
+
Worst Fold + ${res.worst_fold.toFixed(4)}
+
Sharpe Std + ${res.sharpe_std.toFixed(4)}
+
Time + ${(wfBestData.elapsed||0).toFixed(1)}s
+
+ ${foldHtml}
`; + const params = wfBestData.params || {}; + let paramsHtml = ''; + for (const [k, v] of Object.entries(params)) + paramsHtml += `
${k}${v}
`; + document.getElementById('best-params-list').innerHTML = paramsHtml; + } + } + + // WF table + const tbody = document.getElementById('runs-tbody'); + document.getElementById('runs-count').textContent = `(${wfRuns.length})`; + const sorted = wfRuns.map((r, i) => ({...r, _idx: i + 1})); + sorted.sort((a, b) => { + const va = getWFSharpe(a), vb = getWFSharpe(b); + return sortAsc ? va - vb : vb - va; + }); + let html = ''; + for (const r of sorted) { + const res = Object.values(r.results || {})[0] || {}; + const tk = Object.keys(r.results || {})[0] || ''; + const s = res.wf_sharpe || 0; + const p = res.wf_pnl || 0; + html += ` + + + + + + + + + + `; + } + tbody.innerHTML = html; +} + +function connectWFSSE() { + const evtSrc = new EventSource('/api/wf/events'); + evtSrc.onmessage = () => { if (activeMode === 'wf') fetchWF(); }; + evtSrc.onerror = () => { evtSrc.close(); setTimeout(connectWFSSE, 5000); }; +} + // ═══════════ Init ═══════════ initChart(); fetchAll(); connectSSE(); -// Fallback polling every 10s -setInterval(fetchAll, 10000); +connectWFSSE(); +setInterval(() => { if (activeMode === 'grid') fetchAll(); else fetchWF(); }, 10000); diff --git a/experiments/autoresearch/dashboard.py b/experiments/autoresearch/dashboard.py index bfd9756..f16c5ed 100644 --- a/experiments/autoresearch/dashboard.py +++ b/experiments/autoresearch/dashboard.py @@ -19,6 +19,9 @@ ROOT = Path(__file__).parent RUNS_DIR = ROOT / "runs" BEST_DIR = ROOT / "best" STATUS_FILE = ROOT / "status.json" +RUNS_WF_DIR = ROOT / "runs_wf" +BEST_WF_DIR = ROOT / "best_wf" +STATUS_WF_FILE = ROOT / "status_wf.json" HTML_FILE = ROOT / "dashboard.html" app = FastAPI(title="Autoresearch Dashboard") @@ -102,6 +105,68 @@ async def sse_events(): return StreamingResponse(event_stream(), media_type="text/event-stream") +@app.get("/api/wf/status") +async def api_wf_status(): + if STATUS_WF_FILE.exists(): + try: + return json.loads(STATUS_WF_FILE.read_text()) + except json.JSONDecodeError: + pass + return {"state": "idle", "run_number": 0, "total_planned": 0} + + +@app.get("/api/wf/runs") +async def api_wf_runs(): + if not RUNS_WF_DIR.exists(): + return [] + runs = [] + for f in sorted(RUNS_WF_DIR.glob("run_wf_*.json")): + try: + data = json.loads(f.read_text()) + data["_file"] = f.name + runs.append(data) + except (json.JSONDecodeError, OSError): + continue + return runs + + +@app.get("/api/wf/best") +async def api_wf_best(): + best_file = BEST_WF_DIR / "best_wf_sharpe.json" + if best_file.exists(): + try: + return json.loads(best_file.read_text()) + except json.JSONDecodeError: + pass + return None + + +@app.get("/api/wf/events") +async def sse_wf_events(): + async def event_stream(): + last_count = 0 + last_status = "" + while True: + count = len(list(RUNS_WF_DIR.glob("run_wf_*.json"))) if RUNS_WF_DIR.exists() else 0 + status_data = "" + if STATUS_WF_FILE.exists(): + try: + status_data = STATUS_WF_FILE.read_text() + except OSError: + pass + if count != last_count or status_data != last_status: + last_count = count + last_status = status_data + event = json.dumps({ + "runs_count": count, + "status": json.loads(status_data) if status_data else None, + "timestamp": datetime.now().isoformat(), + }) + yield f"data: {event}\n\n" + await asyncio.sleep(2) + return StreamingResponse(event_stream(), media_type="text/event-stream") + + def main(): parser = argparse.ArgumentParser() parser.add_argument("--port", type=int, default=8050) diff --git a/experiments/autoresearch/evaluate.py b/experiments/autoresearch/evaluate.py index e91473e..45deb72 100644 --- a/experiments/autoresearch/evaluate.py +++ b/experiments/autoresearch/evaluate.py @@ -409,11 +409,17 @@ def main(): parser = argparse.ArgumentParser(description="Autoresearch backtest evaluator") parser.add_argument("--ticker", default="ADA-USD", help="Asset ticker") parser.add_argument("--all", action="store_true", help="Run on all assets") + parser.add_argument("--params-json", default="", + help="JSON string with params (bypasses strategy.py)") args = parser.parse_args() - # Import strategy (the file the agent modifies) - import importlib - strategy = importlib.import_module("strategy") + # Load params: from --params-json or strategy.py + if args.params_json: + import types + strategy = types.SimpleNamespace(PARAMS=json.loads(args.params_json)) + else: + import importlib + strategy = importlib.import_module("strategy") # Load dataset dataset = load_or_fetch("default") @@ -436,6 +442,11 @@ def main(): elapsed = time.time() - t0 + # Compute portfolio metrics + sharpes = [r["sharpe"] for r in results.values()] + avg_sharpe = float(np.mean(sharpes)) if sharpes else 0.0 + total_pnl = sum(r["total_pnl"] for r in results.values()) + # Print results in fixed, grep-friendly format print("---") if len(results) == 1: @@ -445,21 +456,12 @@ def main(): for k, v in r.items(): print(f"{k + ':':18s}{v}") else: - # Multi-asset: print each + portfolio average - sharpes = [] - total_pnl = 0 - total_trades = 0 for ticker, r in results.items(): print(f"[{ticker}] sharpe={r['sharpe']:.4f} pnl=${r['total_pnl']:.2f} " f"trades={r['trades']} wr={r['wr_pct']:.1f}% dd={r['max_dd_pct']:.1f}%") - sharpes.append(r["sharpe"]) - total_pnl += r["total_pnl"] - total_trades += r["trades"] - avg_sharpe = float(np.mean(sharpes)) if sharpes else 0.0 print(f"---") print(f"avg_sharpe: {avg_sharpe:.4f}") print(f"total_pnl: {total_pnl:.2f}") - print(f"total_trades: {total_trades}") print(f"elapsed_seconds: {elapsed:.1f}") print(f"---") @@ -467,6 +469,13 @@ def main(): # Auto-save results _auto_save(results, elapsed, strategy) + # Machine-readable output for parallel runner + print("JSON_RESULT:" + json.dumps({ + "results": results, "avg_sharpe": round(avg_sharpe, 4), + "total_pnl": round(total_pnl, 2), "elapsed": round(elapsed, 1), + "params": dict(strategy.PARAMS), + }, default=str)) + # ══════════════════════════════════════════════════ # Auto-save: every run → runs/, best → best/ @@ -481,7 +490,8 @@ def _auto_save(results: dict, elapsed: float, strategy_mod) -> None: RUNS_DIR.mkdir(exist_ok=True) BEST_DIR.mkdir(exist_ok=True) - ts = datetime.now().strftime("%Y%m%d_%H%M%S") + import os + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + f"_{os.getpid()}" params = dict(strategy_mod.PARAMS) # Primary metric: avg sharpe across all evaluated assets @@ -513,10 +523,6 @@ def _auto_save(results: dict, elapsed: float, strategy_mod) -> None: if avg_sharpe > prev_best_sharpe: BEST_FILE.write_text(json.dumps(run_data, indent=2, default=str)) - # Save the winning strategy.py snapshot - strategy_path = Path(__file__).parent / "strategy.py" - shutil.copy2(strategy_path, BEST_DIR / f"strategy_{ts}.py") - shutil.copy2(strategy_path, BEST_DIR / "strategy_best.py") print(f"NEW BEST: sharpe={avg_sharpe:.4f} (was {prev_best_sharpe:.4f})") diff --git a/experiments/autoresearch/evaluate_wf.py b/experiments/autoresearch/evaluate_wf.py new file mode 100644 index 0000000..d58dab4 --- /dev/null +++ b/experiments/autoresearch/evaluate_wf.py @@ -0,0 +1,325 @@ +"""Walk-forward evaluation harness. + +Splits data into expanding-window folds, trains model per fold, +tests on the next period. Reports per-fold + aggregate metrics. + +Usage: + python evaluate_wf.py --ticker ADA-USD + python evaluate_wf.py --params-json '{"shift":24,...}' --ticker DOGE-USD +""" +import argparse +import json +import os +import sys +import time +from datetime import datetime +from pathlib import Path + +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.core.net import EnhancedRemizovNet +from common.dataset import load_or_fetch + +# Import shared components from evaluate.py +from evaluate import ( + Pos, _compute, _empty_result, + TOTAL_CAPITAL, TF_HOURS, + CVR, SPOT_IM_PCT, INTEREST_RATE_DAILY, COMMISSION_PCT, + MARKET_ORDER_BUFFER, SLIPPAGE_PCT, SAFETY_STOP_PCT, MARGIN_BUFFER, + CB_ATR_RATIO_ON, CB_ATR_RATIO_OFF, CB_MAX_DRAWDOWN, CB_COOLDOWN_BARS, +) + +MIN_TRAIN_RATIO = 0.20 +DEFAULT_N_FOLDS = 5 +RUNS_WF_DIR = Path(__file__).parent / "runs_wf" +BEST_WF_DIR = Path(__file__).parent / "best_wf" +BEST_WF_FILE = BEST_WF_DIR / "best_wf_sharpe.json" + + +def run_fold(prices, ohlcv, params, train_end, test_start, test_end): + """Train on [0..train_end), test on [test_start..test_end). Returns metrics dict.""" + ws = params["window_size"] + shift = params["shift"] + K = params["K"] + + # Prepare windows from ALL data, then split by index + data = signals.prepare_windows(prices, ws, shift) + train_data = [d for d in data if d["price_idx"] < train_end] + test_data = [d for d in data if test_start <= d["price_idx"] < test_end] + + if len(train_data) < 20 or len(test_data) < 3: + return _empty_result() + + # Train model + torch.manual_seed(42) + np.random.seed(42) + mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5, + dx=1.0 / ws, use_sde=True) + train_w = np.array([d["norm_input"] for d in train_data]) + train_t = np.array([d["norm_target"] for d in train_data]) + model_mod.train(mdl, train_w, train_t, params["epochs"], params["lr"]) + + # Backtest on test fold + signal_bars = {d["price_idx"] for d in test_data} + first_bar = test_data[0]["price_idx"] + last_bar = test_data[-1]["price_idx"] + + leverage = params["leverage"] + stop_mult = params["stop_mult"] + stop_scale = params["stop_scale"] + trailing_stop = params["trailing_stop"] + cooldown_bars = params["cooldown_bars"] + corr_thresh = params["corr_thresh"] + min_confidence = params["min_confidence"] + shape_confirm = params["shape_confirm"] + regime_adaptive = params["regime_adaptive"] + + free_usdc = TOTAL_CAPITAL + pos = None + last_stop_bar = -999 + trades_list = [] + peak_eq = TOTAL_CAPITAL + max_dd = 0.0 + cb_active = False + cb_activated_bar = -999 + + for bar in range(first_bar, last_bar + 1): + price = float(prices[bar]) + if ohlcv is not None: + bar_open = float(ohlcv[bar, 0]) + bar_high = float(ohlcv[bar, 1]) + bar_low = float(ohlcv[bar, 2]) + else: + bar_open = bar_high = bar_low = price + + if pos is not None: + stop_check = bar_low if pos.direction == 1 else bar_high + safety_price = pos.entry_price * (1.0 - SAFETY_STOP_PCT * pos.direction) + stopped = risk.is_stopped(stop_check, pos.stop_price, pos.direction) + safety_hit = (pos.direction == 1 and bar_low <= safety_price) or \ + (pos.direction == -1 and bar_high >= safety_price) + + if stopped or safety_hit: + target = safety_price if safety_hit else pos.stop_price + raw_exit = min(target, bar_open) if pos.direction == 1 else max(target, bar_open) + exit_price = raw_exit * (1 - SLIPPAGE_PCT * pos.direction) + bars_held = bar - pos.entry_bar + pnl = (pos.pos_size * (exit_price - pos.entry_price) * pos.direction + - pos.pos_value * COMMISSION_PCT * 2 + - pos.borrowed * INTEREST_RATE_DAILY * bars_held * TF_HOURS / 24) + free_usdc += pos.margin_locked + pnl + trades_list.append({"pnl_net": pnl, "bars_held": bars_held, + "equity_at_entry": pos.margin_locked, "entry_idx": bar}) + pos = None + last_stop_bar = bar + peak_eq = max(peak_eq, free_usdc) + dd = (peak_eq - free_usdc) / peak_eq if peak_eq > 0 else 0 + max_dd = max(max_dd, dd) + else: + if trailing_stop: + trail_price = bar_high if pos.direction == 1 else bar_low + pos.best_price, pos.stop_price = risk.update_trailing_stop( + trail_price, pos.best_price, pos.stop_price, + pos.stop_dist, pos.direction) + + # Circuit breaker + if bar >= 50 and pos is None: + atr14 = risk.compute_atr(prices, bar, period=14) + atr50 = risk.compute_atr(prices, bar, period=50) + atr_ratio = atr14 / atr50 if atr50 > 0 else 1.0 + current_dd = (peak_eq - free_usdc) / peak_eq if peak_eq > 0 else 0 + if not cb_active: + if atr_ratio > CB_ATR_RATIO_ON or current_dd > CB_MAX_DRAWDOWN: + cb_active = True + cb_activated_bar = bar + else: + if atr_ratio < CB_ATR_RATIO_OFF and (bar - cb_activated_bar) >= CB_COOLDOWN_BARS: + cb_active = False + + if bar not in signal_bars or pos is not None or bar < ws + K or cb_active: + continue + effective_cooldown = cooldown_bars if cooldown_bars > 0 else shift + if bar - last_stop_bar < effective_cooldown: + continue + + # Predict + w = prices[bar - ws - K: bar - K].copy() + confirm = prices[bar - K: bar].copy() + mu, std = w.mean(), w.std() + if std < 1e-10: + continue + pred = model_mod.predict(mdl, (w - mu) / std) + pred_new = pred[-shift:] + + sm = risk.regime_adaptive_params(prices, bar, K)[1] if regime_adaptive else stop_mult + + corr, confirmed = signals.check_shape_confirmation( + pred_new, confirm, mu, std, K, corr_thresh) + if shape_confirm and not confirmed: + continue + if min_confidence > 0: + atr = risk.compute_atr(prices, bar) + if atr > 0: + amp = float(np.max(pred_new * std + mu) - np.min(pred_new * std + mu)) + if abs(corr) * (amp / atr) < min_confidence: + continue + + direction = signals.get_direction(pred_new, K) + if direction is None or direction == -1: + continue + + eq = free_usdc * MARGIN_BUFFER + if eq <= 5: + continue + freeze_rate = 1 / leverage + (1 - CVR) + (1 - 1 / leverage) * SPOT_IM_PCT + MARKET_ORDER_BUFFER + pos_value = min(eq * leverage, eq / freeze_rate) + if pos_value < 5: + continue + margin = pos_value / leverage + borrowed = pos_value - margin + entry_price = price * (1 + SLIPPAGE_PCT * direction) + atr = risk.compute_atr(prices, bar) + stop_dist = max(atr * sm * stop_scale, entry_price * 0.005) + free_usdc -= margin + pos = Pos(direction=direction, entry_price=entry_price, entry_bar=bar, + stop_price=entry_price - direction * stop_dist, + stop_dist=stop_dist, best_price=entry_price, + pos_size=pos_value / entry_price, pos_value=pos_value, + margin_locked=margin, borrowed=borrowed) + + # Close open position at fold end + if pos is not None: + exit_price = float(prices[last_bar]) * (1 - SLIPPAGE_PCT * pos.direction) + bars_held = last_bar - pos.entry_bar + pnl = (pos.pos_size * (exit_price - pos.entry_price) * pos.direction + - pos.pos_value * COMMISSION_PCT * 2 + - pos.borrowed * INTEREST_RATE_DAILY * bars_held * TF_HOURS / 24) + free_usdc += pos.margin_locked + pnl + trades_list.append({"pnl_net": pnl, "bars_held": bars_held, + "equity_at_entry": pos.margin_locked, "entry_idx": pos.entry_bar}) + + result = _compute(trades_list, free_usdc, first_bar, last_bar) + result["train_bars"] = train_end + result["test_bars"] = test_end - test_start + return result + + +def run_walkforward(prices, ohlcv, params, n_folds=DEFAULT_N_FOLDS): + """Run expanding-window walk-forward over n_folds. Returns aggregated result.""" + n = len(prices) + min_train = int(n * MIN_TRAIN_RATIO) + test_total = n - min_train + fold_size = test_total // n_folds + + folds = [] + for i in range(n_folds): + train_end = min_train + i * fold_size + test_start = train_end + test_end = train_end + fold_size if i < n_folds - 1 else n + fold_result = run_fold(prices, ohlcv, params, train_end, test_start, test_end) + fold_result["fold"] = i + 1 + folds.append(fold_result) + + # Aggregate + sharpes = [f["sharpe"] for f in folds] + wf_sharpe = float(np.mean(sharpes)) if sharpes else 0.0 + wf_pnl = sum(f["total_pnl"] for f in folds) + wf_trades = sum(f["trades"] for f in folds) + + return { + "wf_sharpe": round(wf_sharpe, 4), + "wf_pnl": round(wf_pnl, 2), + "wf_trades": wf_trades, + "sharpe_std": round(float(np.std(sharpes)), 4) if sharpes else 0.0, + "worst_fold": round(min(sharpes), 4) if sharpes else 0.0, + "best_fold": round(max(sharpes), 4) if sharpes else 0.0, + "folds": folds, + } + + +def main(): + parser = argparse.ArgumentParser(description="Walk-forward evaluator") + parser.add_argument("--ticker", default="ADA-USD") + parser.add_argument("--params-json", default="") + parser.add_argument("--n-folds", type=int, default=DEFAULT_N_FOLDS) + args = parser.parse_args() + + if args.params_json: + import types + strategy = types.SimpleNamespace(PARAMS=json.loads(args.params_json)) + else: + import importlib + strategy = importlib.import_module("strategy") + + params = dict(strategy.PARAMS) + dataset = load_or_fetch("default") + t0 = time.time() + + if args.ticker not in dataset: + print(f"SKIP: {args.ticker} not in dataset") + return + + d = dataset[args.ticker] + result = run_walkforward(d["prices"], d.get("ohlcv"), params, args.n_folds) + elapsed = time.time() - t0 + + # Print summary + print(f"--- walk-forward ({args.n_folds} folds) ---") + print(f"ticker: {args.ticker}") + print(f"wf_sharpe: {result['wf_sharpe']:.4f}") + print(f"wf_pnl: {result['wf_pnl']:.2f}") + print(f"wf_trades: {result['wf_trades']}") + print(f"sharpe_std: {result['sharpe_std']:.4f}") + print(f"worst_fold: {result['worst_fold']:.4f}") + for f in result["folds"]: + print(f" fold {f['fold']}: sharpe={f['sharpe']:.4f} pnl=${f['total_pnl']:.2f} " + f"trades={f['trades']} train={f['train_bars']} test={f['test_bars']}") + print(f"elapsed: {elapsed:.1f}s") + + # Auto-save + _auto_save(args.ticker, result, elapsed, params) + + # Machine-readable output + print("JSON_RESULT:" + json.dumps({ + "results": {args.ticker: result}, + "avg_wf_sharpe": result["wf_sharpe"], + "total_pnl": result["wf_pnl"], + "elapsed": round(elapsed, 1), + "params": params, + }, default=str)) + + +def _auto_save(ticker, result, elapsed, params): + RUNS_WF_DIR.mkdir(exist_ok=True) + BEST_WF_DIR.mkdir(exist_ok=True) + + ts = datetime.now().strftime("%Y%m%d_%H%M%S") + f"_{os.getpid()}" + run_data = { + "timestamp": ts, + "params": params, + "results": {ticker: result}, + "avg_wf_sharpe": result["wf_sharpe"], + "total_pnl": result["wf_pnl"], + "elapsed": round(elapsed, 1), + } + (RUNS_WF_DIR / f"run_wf_{ts}.json").write_text( + json.dumps(run_data, indent=2, default=str)) + + prev_best = -999.0 + if BEST_WF_FILE.exists(): + try: + prev_best = json.loads(BEST_WF_FILE.read_text()).get("avg_wf_sharpe", -999.0) + except (json.JSONDecodeError, KeyError): + pass + if result["wf_sharpe"] > prev_best: + BEST_WF_FILE.write_text(json.dumps(run_data, indent=2, default=str)) + print(f"NEW WF BEST: {result['wf_sharpe']:.4f} (was {prev_best:.4f})") + + +if __name__ == "__main__": + main() diff --git a/experiments/autoresearch/runner.py b/experiments/autoresearch/runner.py index c1bfcc1..23724ec 100644 --- a/experiments/autoresearch/runner.py +++ b/experiments/autoresearch/runner.py @@ -13,13 +13,16 @@ Usage: import argparse import importlib import json +import os import subprocess import sys import time +from concurrent.futures import ProcessPoolExecutor, as_completed from copy import deepcopy from datetime import datetime from itertools import product from pathlib import Path +from threading import Lock ROOT = Path(__file__).parent STATUS_FILE = ROOT / "status.json" @@ -169,6 +172,7 @@ def build_asset_grid(ticker): grid = { "shift": [10, 14, 16, 24], "stop_mult": [0.75, 1.0, 1.25, 2.0], + "stop_scale": [0.75, 1.0, 1.5], "K": [2, 3, 5], "lr": [0.005, 0.01], "cooldown_bars": [0, 3], @@ -230,13 +234,15 @@ def get_latest_run(): return None -def run_experiment(description, params, ticker, run_num, total): - """Run a single experiment. Returns result dict or None on crash.""" - write_strategy(params) - write_status("running", run_num, total, description, ticker) +def run_experiment_worker(args_tuple): + """Run a single experiment in a worker process. + Returns (description, run_data_or_None, ticker). + """ + description, params, ticker = args_tuple t0 = time.time() - cmd = [sys.executable, "evaluate.py"] + params_json = json.dumps(params) + cmd = [sys.executable, "evaluate.py", "--params-json", params_json] if ticker: cmd += ["--ticker", ticker] @@ -245,27 +251,22 @@ def run_experiment(description, params, ticker, run_num, total): cmd, capture_output=True, text=True, timeout=600, cwd=str(ROOT)) except subprocess.TimeoutExpired: - elapsed = time.time() - t0 - print(f" TIMEOUT after {elapsed:.0f}s") - return None + return (description, None, ticker) - elapsed = time.time() - t0 - - # Parse output - stdout = result.stdout if result.returncode != 0: - print(f" CRASH (rc={result.returncode})") - err_lines = (result.stderr or result.stdout or "").strip().split("\n") - print(f" {err_lines[-1] if err_lines else 'unknown error'}") - return None + return (description, None, ticker) - # Read from auto-saved run file - run_data = get_latest_run() - if run_data is None: - print(f" WARNING: no run file found") - return None + # Parse JSON_RESULT from stdout + for line in result.stdout.split("\n"): + if line.startswith("JSON_RESULT:"): + try: + run_data = json.loads(line[len("JSON_RESULT:"):]) + run_data["timestamp"] = datetime.now().strftime("%Y%m%d_%H%M%S") + return (description, run_data, ticker) + except json.JSONDecodeError: + pass - return run_data + return (description, None, ticker) def print_result(desc, run_data, run_num, total): @@ -310,6 +311,8 @@ def main(): help="Grid search for all available assets") parser.add_argument("--ticker", default="", help="Single asset (default: all per evaluate.py)") + parser.add_argument("--workers", type=int, default=0, + help="Parallel workers (0 = number of CPUs)") args = parser.parse_args() if args.grid: @@ -318,54 +321,62 @@ def main(): experiments = build_multi_asset_grid(ASSETS) else: experiments = build_experiments(quick=args.quick) + + # Apply ticker override + if args.ticker: + experiments = [(d, p, args.ticker) for d, p, _ in experiments] + total = len(experiments) + n_workers = args.workers or os.cpu_count() or 4 print(f"{'='*60}") - print(f"AUTORESEARCH SWEEP — {total} experiments") - if args.ticker: - print(f"Ticker override: {args.ticker}") + print(f"AUTORESEARCH SWEEP — {total} experiments, {n_workers} workers") print(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") print(f"{'='*60}") best_sharpe = -999.0 best_desc = "" + completed = 0 - for i, (desc, params, exp_ticker) in enumerate(experiments, 1): - ticker = args.ticker or exp_ticker - run_data = run_experiment(desc, params, ticker, i, total) + write_status("running", 0, total, "starting...", "") - if run_data is None: - print(f"[{i:3d}/{total}] \033[91mCRASH\033[0m {desc}") - write_status("error", i, total, desc, ticker, - error="crash or timeout") - continue + with ProcessPoolExecutor(max_workers=n_workers) as pool: + futures = {pool.submit(run_experiment_worker, exp): exp + for exp in experiments} - print_result(desc, run_data, i, total) + for future in as_completed(futures): + completed += 1 + desc, run_data, ticker = future.result() - sharpe = run_data.get("avg_sharpe", 0) - if sharpe > best_sharpe: - best_sharpe = sharpe - best_desc = desc - print(f" ★ NEW BEST: {best_sharpe:.4f} ({desc})") + if run_data is None: + print(f"[{completed:4d}/{total}] \033[91mCRASH\033[0m {desc}") + write_status("error", completed, total, desc, ticker, + error="crash or timeout") + continue - write_status("running", i, total, desc, ticker, - current_result={ - "sharpe": sharpe, - "pnl": run_data.get("total_pnl", 0), - }) + print_result(desc, run_data, completed, total) + + sharpe = run_data.get("avg_sharpe", 0) + if sharpe > best_sharpe: + best_sharpe = sharpe + best_desc = desc + print(f" ★ NEW BEST: {best_sharpe:.4f} ({desc})") + + write_status("running", completed, total, desc, ticker, + current_result={ + "sharpe": sharpe, + "pnl": run_data.get("total_pnl", 0), + }) # Done write_status("finished", total, total, f"best: {best_desc}", "", current_result={"sharpe": best_sharpe}) print(f"\n{'='*60}") - print(f"DONE — {total} experiments") + print(f"DONE — {total} experiments ({n_workers} workers)") print(f"Best Sharpe: {best_sharpe:.4f} ({best_desc})") print(f"{'='*60}") - # Restore baseline - write_strategy(BASELINE) - if __name__ == "__main__": main() diff --git a/experiments/autoresearch/runner_wf.py b/experiments/autoresearch/runner_wf.py new file mode 100644 index 0000000..b2fa9fc --- /dev/null +++ b/experiments/autoresearch/runner_wf.py @@ -0,0 +1,159 @@ +"""Walk-forward grid search runner. + +Parallel runner for evaluate_wf.py. Results saved to runs_wf/ +and displayed in the Walk-Forward section of the dashboard. + +Usage: + python runner_wf.py --grid-all --workers 8 + python runner_wf.py --grid ADA-USD DOGE-USD --workers 4 + python runner_wf.py --quick --workers 2 +""" +import argparse +import json +import os +import subprocess +import sys +import time +from concurrent.futures import ProcessPoolExecutor, as_completed +from datetime import datetime +from pathlib import Path + +from runner import BASELINE, ASSETS, build_asset_grid, build_multi_asset_grid, build_experiments + +ROOT = Path(__file__).parent +STATUS_FILE = ROOT / "status_wf.json" + + +def write_status(state, run_number=0, total=0, description="", + ticker="", current_result=None, error=None): + STATUS_FILE.write_text(json.dumps({ + "state": state, + "run_number": run_number, + "total_planned": total, + "description": description, + "ticker": ticker, + "timestamp": datetime.now().isoformat(), + "current_result": current_result, + "error": error, + }, indent=2, default=str)) + + +def run_wf_worker(args_tuple): + """Run one walk-forward experiment. Returns (desc, run_data|None, ticker).""" + description, params, ticker = args_tuple + params_json = json.dumps(params) + cmd = [sys.executable, "evaluate_wf.py", + "--params-json", params_json, "--ticker", ticker] + + try: + result = subprocess.run( + cmd, capture_output=True, text=True, timeout=1200, + cwd=str(ROOT)) + except subprocess.TimeoutExpired: + return (description, None, ticker) + + if result.returncode != 0: + return (description, None, ticker) + + for line in result.stdout.split("\n"): + if line.startswith("JSON_RESULT:"): + try: + run_data = json.loads(line[len("JSON_RESULT:"):]) + run_data["timestamp"] = datetime.now().strftime("%Y%m%d_%H%M%S") + return (description, run_data, ticker) + except json.JSONDecodeError: + pass + + return (description, None, ticker) + + +def print_result(desc, run_data, run_num, total): + r = list(run_data.get("results", {}).values())[0] if run_data.get("results") else {} + wf_sharpe = r.get("wf_sharpe", 0) + wf_pnl = r.get("wf_pnl", 0) + worst = r.get("worst_fold", 0) + trades = r.get("wf_trades", 0) + elapsed = run_data.get("elapsed", 0) + + if wf_sharpe > 0.5: + color = "\033[92m" + elif wf_sharpe > 0: + color = "\033[93m" + else: + color = "\033[91m" + reset = "\033[0m" + + print(f"[{run_num:4d}/{total}] {color}wf_sharpe={wf_sharpe:7.4f}{reset} " + f"worst={worst:6.3f} pnl=${wf_pnl:8.2f} " + f"trades={trades:3d} t={elapsed:5.1f}s {desc}") + + +def main(): + parser = argparse.ArgumentParser(description="Walk-forward sweep runner") + parser.add_argument("--quick", action="store_true") + parser.add_argument("--grid", nargs="+", metavar="TICKER") + parser.add_argument("--grid-all", action="store_true") + parser.add_argument("--ticker", default="") + parser.add_argument("--workers", type=int, default=0) + args = parser.parse_args() + + if args.grid: + experiments = build_multi_asset_grid(args.grid) + elif args.grid_all: + experiments = build_multi_asset_grid(ASSETS) + else: + experiments = build_experiments(quick=args.quick) + + if args.ticker: + experiments = [(d, p, args.ticker) for d, p, _ in experiments] + + total = len(experiments) + n_workers = args.workers or os.cpu_count() or 4 + + print(f"{'='*60}") + print(f"WALK-FORWARD SWEEP — {total} experiments, {n_workers} workers") + print(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}") + print(f"{'='*60}") + + best_sharpe = -999.0 + best_desc = "" + completed = 0 + + write_status("running", 0, total, "starting...", "") + + with ProcessPoolExecutor(max_workers=n_workers) as pool: + futures = {pool.submit(run_wf_worker, exp): exp for exp in experiments} + + for future in as_completed(futures): + completed += 1 + desc, run_data, ticker = future.result() + + if run_data is None: + print(f"[{completed:4d}/{total}] \033[91mCRASH\033[0m {desc}") + write_status("error", completed, total, desc, ticker, + error="crash or timeout") + continue + + print_result(desc, run_data, completed, total) + + wf_sharpe = run_data.get("avg_wf_sharpe", 0) + if wf_sharpe > best_sharpe: + best_sharpe = wf_sharpe + best_desc = desc + print(f" ★ NEW BEST: {best_sharpe:.4f} ({desc})") + + write_status("running", completed, total, desc, ticker, + current_result={"wf_sharpe": wf_sharpe, + "pnl": run_data.get("total_pnl", 0)}) + + write_status("finished", total, total, f"best: {best_desc}", + "", current_result={"wf_sharpe": best_sharpe}) + + print(f"\n{'='*60}") + print(f"DONE — {total} experiments ({n_workers} workers)") + print(f"Best WF Sharpe: {best_sharpe:.4f} ({best_desc})") + print(f"{'='*60}") + + +if __name__ == "__main__": + main() diff --git a/experiments/autoresearch/strategy.py b/experiments/autoresearch/strategy.py index 1cc735f..6ca252e 100644 --- a/experiments/autoresearch/strategy.py +++ b/experiments/autoresearch/strategy.py @@ -11,8 +11,8 @@ PARAMS = { 'shape_confirm': False, 'regime_adaptive': False, 'leverage': 1, - 'stop_mult': 2.0, + 'stop_mult': 1.25, 'stop_scale': 1.0, 'trailing_stop': True, - 'cooldown_bars': 3, + 'cooldown_bars': 0, } diff --git a/src/remizov_trader/cli.py b/src/remizov_trader/cli.py index 4c43b3e..46a2e7b 100644 --- a/src/remizov_trader/cli.py +++ b/src/remizov_trader/cli.py @@ -52,13 +52,16 @@ def init(): model_cfg = cfg.model_for(asset_cfg) data = signals.prepare_windows(prices, model_cfg.window_size, model_cfg.shift) - click.echo(f" {len(prices)} bars, {len(data)} windows (ws={model_cfg.window_size})...", nl=False) + # Train on first 30% of windows (matches autoresearch TRAIN_RATIO=0.3) + n_train = max(int(len(data) * 0.3), 20) + train_data = data[:n_train] + click.echo(f" {len(prices)} bars, {len(data)} windows, train={n_train} (ws={model_cfg.window_size})...", nl=False) torch.manual_seed(42) np.random.seed(42) mdl = model_mod.create_model(model_cfg) - windows = np.array([d["norm_input"] for d in data]) - targets = np.array([d["norm_target"] for d in data]) + windows = np.array([d["norm_input"] for d in train_data]) + targets = np.array([d["norm_target"] for d in train_data]) model_mod.train(mdl, windows, targets, model_cfg.epochs, model_cfg.lr) model_mod.save_model(mdl, ticker) diff --git a/src/remizov_trader/config.py b/src/remizov_trader/config.py index 40c11b4..965220b 100644 --- a/src/remizov_trader/config.py +++ b/src/remizov_trader/config.py @@ -23,6 +23,15 @@ class AssetConfig: window_size: int = 0 # per-asset override; 0 = use global model.window_size weight: float = 0.0 # portfolio weight (0 = equal allocation) leverage: int = 0 # per-asset leverage; 0 = use global risk.leverage + # Per-asset model/risk overrides (0 = use global) + shift: int = 0 + epochs: int = 0 + lr: float = 0.0 + stop_mult: float = 0.0 # fixed ATR multiplier; 0 = use regime_adaptive + stop_scale: float = 0.0 # 0 = use global risk.stop_scale + cooldown_bars: int = -1 # -1 = use shift as cooldown; >=0 = explicit + min_confidence: float = -1.0 # -1 = use global; >=0 = per-asset override + shape_confirm: bool = True # False = skip correlation check entirely @dataclass @@ -106,18 +115,22 @@ class Config: llm: LLMConfig = field(default_factory=LLMConfig) def model_for(self, asset: AssetConfig) -> ModelConfig: - """Get ModelConfig with per-asset window_size override.""" + """Get ModelConfig with per-asset overrides.""" ws = asset.window_size or self.model.window_size - if ws == self.model.window_size: + shift = asset.shift or self.model.shift + epochs = asset.epochs or self.model.epochs + lr = asset.lr or self.model.lr + if (ws == self.model.window_size and shift == self.model.shift + and epochs == self.model.epochs and lr == self.model.lr): return self.model return ModelConfig( window_size=ws, n_steps=self.model.n_steps, total_time=self.model.total_time, - shift=self.model.shift, - epochs=self.model.epochs, + shift=shift, + epochs=epochs, finetune_epochs=self.model.finetune_epochs, - lr=self.model.lr, + lr=lr, ) def leverage_for(self, asset: AssetConfig) -> int: diff --git a/src/remizov_trader/core/executor.py b/src/remizov_trader/core/executor.py index ae371d7..cbcd0f7 100644 --- a/src/remizov_trader/core/executor.py +++ b/src/remizov_trader/core/executor.py @@ -243,17 +243,17 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg): from datetime import date as d days_held = (d.fromisoformat(last_date) - d.fromisoformat(entry_date)).days - # Update trailing stop - if asset_cfg.trailing_stop: + # Check stop FIRST (before trailing update, matches backtest) + stopped = risk.is_stopped(last_price, stop_price, direction) + + # Update trailing stop only if NOT stopped (matches backtest order) + if not stopped and asset_cfg.trailing_stop: best_price, stop_price = risk.update_trailing_stop( last_price, best_price, stop_price, stop_dist, direction, ) update_position(conn, pos["id"], best_price=best_price, stop_price=stop_price) - # Check stop - stopped = risk.is_stopped(last_price, stop_price, direction) - # Check time exit (use per-asset model config) — can be disabled via config time_exit = False if cfg.risk.time_exit: @@ -330,23 +330,29 @@ def _check_position(conn, pos, prices, dates, asset, asset_cfg, cfg): def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg): """Check for new trading signal. Returns log message or None.""" - # Cooldown after stop: skip `shift` candles to avoid re-entering same failed trade + # Cooldown after stop last_stop = asset.get("last_stop_date") if last_stop: from datetime import date as d model_cfg = cfg.model_for(asset_cfg) days_since_stop = (d.fromisoformat(str(dates[-1])) - d.fromisoformat(last_stop)).days tf_str = asset_cfg.timeframe or cfg.timeframe - tf_hours = int(tf_str.replace("h", "")) + tf_hours = int(tf_str.replace("h", "").replace("d", "")) if "d" not in tf_str else 24 candles_since_stop = days_since_stop * 24 // tf_hours - if candles_since_stop < model_cfg.shift: - return f"cooldown {candles_since_stop}/{model_cfg.shift} candles after stop — SKIP" + # Per-asset cooldown_bars; -1 = use shift as cooldown + cooldown = asset_cfg.cooldown_bars if asset_cfg.cooldown_bars >= 0 else model_cfg.shift + if candles_since_stop < cooldown: + return f"cooldown {candles_since_stop}/{cooldown} candles after stop — SKIP" K_base = asset_cfg.K corr_thresh_base = asset_cfg.corr_thresh - # Regime adaptive: adjust K and stop_mult based on volatility - K, stop_mult = risk.regime_adaptive_params(prices, len(prices) - 1, K_base) + # Per-asset stop_mult: fixed value skips regime_adaptive + if asset_cfg.stop_mult > 0: + K = K_base + stop_mult = asset_cfg.stop_mult + else: + K, stop_mult = risk.regime_adaptive_params(prices, len(prices) - 1, K_base) # Adaptive corr threshold: adjust based on recent win rate corr_thresh = risk.adaptive_corr_threshold( @@ -368,7 +374,7 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg): pred = model_mod.predict(mdl, sw["norm_input"]) pred_new = pred[-model_cfg.shift:] - # Shape confirmation + # Shape confirmation (can be disabled per-asset) corr, confirmed = signals.check_shape_confirmation( pred_new, sw["confirm_prices"], sw["mu"], sw["std"], K, corr_thresh, ) @@ -376,24 +382,25 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg): update_asset(conn, ticker, signals_since_retrain=asset["signals_since_retrain"] + 1) - if not confirmed: + if asset_cfg.shape_confirm and not confirmed: log_signal(conn, ticker=ticker, date=str(dates[-1]), correlation=corr, action="skip_corr", details=f"thresh={corr_thresh:.2f} K={K}") return f"corr={corr:.3f} < {corr_thresh:.2f} (adaptive) K={K} — SKIP" - # Confidence filter: |corr| × (pred_amplitude / ATR) — exp22 - if cfg.risk.min_confidence > 0: + # Confidence filter (per-asset override: -1 = use global) + effective_min_conf = asset_cfg.min_confidence if asset_cfg.min_confidence >= 0 else cfg.risk.min_confidence + if effective_min_conf > 0: atr = risk.compute_atr(prices, len(prices) - 1) if atr > 0: pred_denorm = pred_new * sw["std"] + sw["mu"] amplitude = float(np.max(pred_denorm) - np.min(pred_denorm)) confidence = abs(corr) * (amplitude / atr) - if confidence < cfg.risk.min_confidence: + if confidence < effective_min_conf: log_signal(conn, ticker=ticker, date=str(dates[-1]), correlation=corr, action="skip_confidence", - details=f"conf={confidence:.2f} < {cfg.risk.min_confidence}") - return (f"confidence={confidence:.2f} < {cfg.risk.min_confidence} " + details=f"conf={confidence:.2f} < {effective_min_conf}") + return (f"confidence={confidence:.2f} < {effective_min_conf} " f"(corr={corr:.3f}, amp/atr={amplitude/atr:.2f}) — SKIP") # Direction @@ -418,9 +425,10 @@ def _check_signal(conn, ticker, prices, dates, asset, asset_cfg, cfg): entry_price = sw["last_price"] - # Stop with regime-adaptive multiplier × stop_scale + # Stop: ATR × stop_mult × stop_scale (per-asset or global) atr = risk.compute_atr(prices, len(prices) - 1) - stop_dist = max(atr * stop_mult * cfg.risk.stop_scale, entry_price * 0.005) + effective_stop_scale = asset_cfg.stop_scale if asset_cfg.stop_scale > 0 else cfg.risk.stop_scale + stop_dist = max(atr * stop_mult * effective_stop_scale, entry_price * 0.005) stop_price = entry_price - direction * stop_dist # Position sizing: weight-based with free balance check
${r._idx}${(r.timestamp||'').replace('_',' ')}${tk.replace('-USD','')}${s.toFixed(4)}$${p.toFixed(2)}${res.wf_trades||0}${(res.worst_fold||0).toFixed(2)}${(res.sharpe_std||0).toFixed(2)}${keyParams(r.params)}