diff --git a/experiments/autoresearch/.gitignore b/experiments/autoresearch/.gitignore
new file mode 100644
index 0000000..7b6eb91
--- /dev/null
+++ b/experiments/autoresearch/.gitignore
@@ -0,0 +1,6 @@
+runs/
+best/
+run.log
+results.tsv
+status.json
+__pycache__/
diff --git a/experiments/autoresearch/dashboard.html b/experiments/autoresearch/dashboard.html
new file mode 100644
index 0000000..95fd643
--- /dev/null
+++ b/experiments/autoresearch/dashboard.html
@@ -0,0 +1,1035 @@
+
+
+
+
+
+Autoresearch — Strategy Lab
+
+
+
+
+
+
+
+ AUTORESEARCH
+ idle
+
+
+
+
+
+
+
+
Performance Over Runs
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
Current Run
+
+
Waiting for runner...
+
+
+
+
+
+
+
All Runs
+
+
+
+
+ | # |
+ Time |
+ Asset |
+ Sharpe |
+ PnL |
+ Trades |
+ WR% |
+ DD% |
+ Key Params |
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/experiments/autoresearch/dashboard.py b/experiments/autoresearch/dashboard.py
new file mode 100644
index 0000000..bfd9756
--- /dev/null
+++ b/experiments/autoresearch/dashboard.py
@@ -0,0 +1,116 @@
+#!/usr/bin/env python3
+"""Real-time dashboard for autoresearch experiments.
+
+Usage:
+ python dashboard.py # start on port 8050
+ python dashboard.py --port 8080 # custom port
+"""
+import argparse
+import asyncio
+import json
+from datetime import datetime
+from pathlib import Path
+
+from fastapi import FastAPI
+from fastapi.responses import HTMLResponse, StreamingResponse
+import uvicorn
+
+ROOT = Path(__file__).parent
+RUNS_DIR = ROOT / "runs"
+BEST_DIR = ROOT / "best"
+STATUS_FILE = ROOT / "status.json"
+HTML_FILE = ROOT / "dashboard.html"
+
+app = FastAPI(title="Autoresearch Dashboard")
+
+
+@app.get("/", response_class=HTMLResponse)
+async def index():
+ """Serve the dashboard HTML."""
+ if HTML_FILE.exists():
+ return HTML_FILE.read_text()
+ return "dashboard.html not found
"
+
+
+@app.get("/api/status")
+async def api_status():
+ """Current runner status."""
+ if STATUS_FILE.exists():
+ try:
+ return json.loads(STATUS_FILE.read_text())
+ except json.JSONDecodeError:
+ pass
+ return {"state": "idle", "run_number": 0, "total_planned": 0}
+
+
+@app.get("/api/runs")
+async def api_runs():
+ """All runs sorted by timestamp."""
+ if not RUNS_DIR.exists():
+ return []
+ runs = []
+ for f in sorted(RUNS_DIR.glob("run_*.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/best")
+async def api_best():
+ """Current best result."""
+ best_file = BEST_DIR / "best_sharpe.json"
+ if best_file.exists():
+ try:
+ return json.loads(best_file.read_text())
+ except json.JSONDecodeError:
+ pass
+ return None
+
+
+@app.get("/api/events")
+async def sse_events():
+ """Server-Sent Events stream for real-time updates."""
+ async def event_stream():
+ last_count = 0
+ last_status = ""
+ while True:
+ # Check for new runs
+ count = len(list(RUNS_DIR.glob("run_*.json"))) if RUNS_DIR.exists() else 0
+ status_data = ""
+ if STATUS_FILE.exists():
+ try:
+ status_data = STATUS_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)
+ parser.add_argument("--host", default="0.0.0.0")
+ args = parser.parse_args()
+
+ print(f"Dashboard: http://localhost:{args.port}")
+ uvicorn.run(app, host=args.host, port=args.port, log_level="warning")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/experiments/autoresearch/evaluate.py b/experiments/autoresearch/evaluate.py
new file mode 100644
index 0000000..e91473e
--- /dev/null
+++ b/experiments/autoresearch/evaluate.py
@@ -0,0 +1,524 @@
+"""Autoresearch evaluation harness — DO NOT MODIFY.
+
+This is the fixed evaluation script. The agent modifies ONLY strategy.py.
+This file loads data, trains the model, runs the backtest, and prints metrics.
+
+Usage:
+ python evaluate.py # run strategy.py backtest
+ python evaluate.py --ticker ETH-USD # override asset
+ python evaluate.py --all # run on all assets
+
+The primary metric is `sharpe` (higher is better).
+"""
+import argparse
+import json
+import shutil
+import sys
+import time
+from dataclasses import dataclass
+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
+
+# ══════════════════════════════════════════════════
+# FIXED CONSTANTS — not tunable by the agent
+# ══════════════════════════════════════════════════
+TOTAL_CAPITAL = 254.0
+TRAIN_RATIO = 0.3
+TF_HOURS = 4 # 4h bars
+
+# Bybit margin simulation
+CVR = 0.90
+SPOT_IM_PCT = 0.05
+INTEREST_RATE_DAILY = 0.0002
+COMMISSION_PCT = 0.001
+MARKET_ORDER_BUFFER = 0.02
+SLIPPAGE_PCT = 0.0002 # 0.02% market order slippage
+SAFETY_STOP_PCT = 0.10 # 10% hard stop on exchange (flash crash protection)
+MARGIN_BUFFER = 0.85 # 85% of free balance (matches live 15% buffer)
+
+# Circuit breaker (matches executor.py / risk.py)
+CB_ATR_RATIO_ON = 3.0 # ATR14/ATR50 > 3.0 → block signals
+CB_ATR_RATIO_OFF = 2.0 # ATR14/ATR50 < 2.0 → resume
+CB_MAX_DRAWDOWN = 0.20 # DD > 20% → block signals
+CB_COOLDOWN_BARS = 12 # 48h at 4h bars = 12 bars
+
+
+# ══════════════════════════════════════════════════
+# Position tracking
+# ══════════════════════════════════════════════════
+@dataclass
+class Pos:
+ direction: int
+ entry_price: float
+ entry_bar: int
+ stop_price: float
+ stop_dist: float
+ best_price: float
+ pos_size: float
+ pos_value: float
+ margin_locked: float
+ borrowed: float
+
+
+# ══════════════════════════════════════════════════
+# Backtest engine
+# ══════════════════════════════════════════════════
+def run_backtest(prices, ohlcv, strategy_mod) -> dict:
+ """Run walk-forward backtest using strategy parameters.
+
+ Args:
+ prices: close prices array
+ ohlcv: OHLCV array (N,4) or None
+ strategy_mod: the strategy module (strategy.py imported)
+
+ Returns:
+ dict with metrics
+ """
+ # Extract params from strategy module
+ p = strategy_mod.PARAMS
+
+ ws = p["window_size"]
+ shift = p["shift"]
+ K = p["K"]
+ epochs = p["epochs"]
+ lr = p["lr"]
+ leverage = p["leverage"]
+ stop_mult = p["stop_mult"]
+ stop_scale = p["stop_scale"]
+ corr_thresh = p["corr_thresh"]
+ min_confidence = p["min_confidence"]
+ trailing_stop = p["trailing_stop"]
+ shape_confirm = p["shape_confirm"]
+ regime_adaptive = p["regime_adaptive"]
+ cooldown_bars = p["cooldown_bars"]
+
+ # Prepare windows and train/test split
+ data = signals.prepare_windows(prices, ws, shift)
+ n_train = max(int(len(data) * TRAIN_RATIO), 20)
+ if len(data) < n_train + 5:
+ 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_windows = np.array([d["norm_input"] for d in data[:n_train]])
+ train_targets = np.array([d["norm_target"] for d in data[:n_train]])
+ model_mod.train(mdl, train_windows, train_targets, epochs, lr)
+
+ # Test data
+ test_data = data[n_train:]
+ if not test_data:
+ return _empty_result()
+
+ test_start = test_data[0]["price_idx"]
+ last_test_bar = test_data[-1]["price_idx"]
+ signal_bars = {d["price_idx"] for d in test_data}
+
+ # Allow strategy to define custom signal logic
+ has_custom_signal = hasattr(strategy_mod, 'generate_signal')
+
+ # Walk-forward simulation
+ 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(test_start, last_test_bar + 1):
+ price = float(prices[bar])
+ # Intra-bar extremes for realistic stop checking
+ 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
+
+ # Check stop on open position
+ if pos is not None:
+ # Check stop against worst intra-bar price (low for longs)
+ 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:
+ # Exit at stop price; account for gaps (fill at open if worse)
+ target = safety_price if safety_hit else pos.stop_price
+ if pos.direction == 1:
+ raw_exit = min(target, bar_open)
+ else:
+ raw_exit = max(target, bar_open)
+ exit_price = raw_exit * (1 - SLIPPAGE_PCT * pos.direction)
+ bars_held = bar - pos.entry_bar
+ pnl_gross = pos.pos_size * (exit_price - pos.entry_price) * pos.direction
+ commission = pos.pos_value * COMMISSION_PCT * 2
+ interest = (pos.borrowed * INTEREST_RATE_DAILY
+ * bars_held * TF_HOURS / 24)
+ pnl = pnl_gross - commission - interest
+ 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,
+ })
+ pos = None
+ last_stop_bar = bar
+
+ # Track drawdown
+ 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:
+ # Update trailing stop only when not stopped (using best intra-bar price)
+ 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 (matches live executor.py) ---
+ # DD check only when no position open (free_usdc == actual equity)
+ 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:
+ bars_since_cb = bar - cb_activated_bar
+ if atr_ratio < CB_ATR_RATIO_OFF and bars_since_cb >= CB_COOLDOWN_BARS:
+ cb_active = False
+
+ # Generate signal on signal bars only
+ if bar not in signal_bars:
+ continue
+ if pos is not None:
+ continue
+ if bar < ws + K:
+ continue
+ if cb_active:
+ continue
+
+ # Cooldown after stop-out (default: shift bars, matches live)
+ 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:]
+
+ # Stop multiplier
+ if regime_adaptive:
+ _, sm = risk.regime_adaptive_params(prices, bar, K)
+ else:
+ sm = stop_mult
+
+ # Custom signal logic or default
+ if has_custom_signal:
+ signal = strategy_mod.generate_signal(
+ pred_new=pred_new, confirm=confirm, mu=mu, std=std,
+ K=K, prices=prices, bar=bar, ohlcv=ohlcv,
+ corr_thresh=corr_thresh, min_confidence=min_confidence,
+ shape_confirm=shape_confirm)
+ if signal is None:
+ continue
+ direction = signal
+ else:
+ # Default signal logic
+ corr, confirmed = signals.check_shape_confirmation(
+ pred_new, confirm, mu, std, K, corr_thresh)
+ if shape_confirm and not confirmed:
+ continue
+
+ # Confidence filter
+ atr = risk.compute_atr(prices, bar)
+ if min_confidence > 0 and atr > 0:
+ pred_denorm = pred_new * std + mu
+ amp = float(np.max(pred_denorm) - np.min(pred_denorm))
+ conf = abs(corr) * (amp / atr)
+ if conf < min_confidence:
+ continue
+
+ direction = signals.get_direction(pred_new, K)
+
+ if direction is None:
+ continue
+ if direction == -1:
+ continue # long only
+
+ # Position sizing (with live-matching 15% margin buffer)
+ eq = free_usdc * MARGIN_BUFFER # matches live: free_usdc * 0.85
+ if eq <= 5:
+ continue
+ lev = leverage
+ freeze_rate = (1 / lev + (1 - CVR) + (1 - 1 / lev) * SPOT_IM_PCT
+ + MARKET_ORDER_BUFFER)
+ pos_value = min(eq * lev, eq / freeze_rate)
+ if pos_value < 5:
+ continue
+ margin = pos_value / lev
+ borrowed = pos_value - margin
+
+ # Apply slippage on entry
+ 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 end (with slippage)
+ if pos is not None:
+ last_price = float(prices[last_test_bar])
+ exit_price = last_price * (1 - SLIPPAGE_PCT * pos.direction)
+ bars_held = last_test_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,
+ })
+
+ # Compute metrics (full test period)
+ result = _compute(trades_list, free_usdc, test_start, last_test_bar)
+
+ # Out-of-sample split: last 40% of test period is holdout
+ val_boundary = test_start + int((last_test_bar - test_start) * 0.6)
+ oos_trades = [t for t in trades_list if t["entry_idx"] >= val_boundary]
+ if oos_trades:
+ oos_pnl = sum(t["pnl_net"] for t in oos_trades)
+ oos_result = _compute(oos_trades, TOTAL_CAPITAL + oos_pnl,
+ val_boundary, last_test_bar)
+ result["sharpe_oos"] = oos_result["sharpe"]
+ result["pnl_oos"] = oos_result["total_pnl"]
+ result["trades_oos"] = oos_result["trades"]
+ else:
+ result["sharpe_oos"] = 0.0
+ result["pnl_oos"] = 0.0
+ result["trades_oos"] = 0
+
+ return result
+
+
+def _compute(trades, final_equity, test_start, last_test_bar) -> dict:
+ """Compute metrics from trade list."""
+ n = len(trades)
+ total_pnl = final_equity - TOTAL_CAPITAL
+
+ if n == 0:
+ return _empty_result()
+
+ wins = sum(1 for t in trades if t["pnl_net"] > 0)
+ losses = n - wins
+
+ # Sharpe ratio (daily returns method)
+ first_idx = min(t["entry_idx"] for t in trades)
+ last_idx = max(t["entry_idx"] + t["bars_held"] for t in trades)
+ bars_per_day = 24 // TF_HOURS # 6 for 4h, 12 for 2h
+ n_days = max((last_idx - first_idx) // bars_per_day, 1)
+ daily_pnl = np.zeros(n_days)
+ for t in trades:
+ # Distribute PnL across holding period (not lump into entry day)
+ entry_day = min((t["entry_idx"] - first_idx) // bars_per_day, n_days - 1)
+ hold_days = max(t["bars_held"] // bars_per_day, 1)
+ exit_day = min(entry_day + hold_days - 1, n_days - 1)
+ n_trade_days = max(exit_day - entry_day + 1, 1)
+ daily_amount = t["pnl_net"] / n_trade_days
+ for d in range(entry_day, exit_day + 1):
+ if 0 <= d < n_days:
+ daily_pnl[d] += daily_amount
+ daily_ret = daily_pnl / TOTAL_CAPITAL
+ sharpe = float(
+ np.mean(daily_ret) / np.std(daily_ret) * np.sqrt(365)
+ ) if np.std(daily_ret) > 0 else 0.0
+
+ # Max drawdown
+ equity_curve = np.cumsum([t["pnl_net"] for t in trades]) + TOTAL_CAPITAL
+ peak = np.maximum.accumulate(equity_curve)
+ drawdown = (peak - equity_curve) / peak
+ max_dd = float(np.max(drawdown)) * 100
+
+ # Avg win / avg loss
+ avg_win = float(np.mean([t["pnl_net"] for t in trades if t["pnl_net"] > 0])) if wins else 0
+ avg_loss = float(np.mean([t["pnl_net"] for t in trades if t["pnl_net"] <= 0])) if losses else 0
+
+ return {
+ "sharpe": round(sharpe, 4),
+ "total_pnl": round(total_pnl, 2),
+ "total_ret_pct": round(total_pnl / TOTAL_CAPITAL * 100, 1),
+ "trades": n,
+ "wins": wins,
+ "losses": losses,
+ "wr_pct": round(wins / n * 100, 1),
+ "max_dd_pct": round(max_dd, 1),
+ "avg_win": round(avg_win, 2),
+ "avg_loss": round(avg_loss, 2),
+ }
+
+
+def _empty_result() -> dict:
+ return {
+ "sharpe": 0.0, "total_pnl": 0.0, "total_ret_pct": 0.0,
+ "trades": 0, "wins": 0, "losses": 0, "wr_pct": 0.0,
+ "max_dd_pct": 0.0, "avg_win": 0.0, "avg_loss": 0.0,
+ "sharpe_oos": 0.0, "pnl_oos": 0.0, "trades_oos": 0,
+ }
+
+
+# ══════════════════════════════════════════════════
+# Main
+# ══════════════════════════════════════════════════
+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")
+ args = parser.parse_args()
+
+ # Import strategy (the file the agent modifies)
+ import importlib
+ strategy = importlib.import_module("strategy")
+
+ # Load dataset
+ dataset = load_or_fetch("default")
+
+ tickers = list(dataset.keys()) if args.all else [args.ticker]
+ results = {}
+ t0 = time.time()
+
+ for ticker in tickers:
+ if ticker not in dataset:
+ print(f"SKIP: {ticker} not in dataset")
+ continue
+
+ d = dataset[ticker]
+ prices = d["prices"]
+ ohlcv = d.get("ohlcv")
+
+ r = run_backtest(prices, ohlcv, strategy)
+ results[ticker] = r
+
+ elapsed = time.time() - t0
+
+ # Print results in fixed, grep-friendly format
+ print("---")
+ if len(results) == 1:
+ ticker = list(results.keys())[0]
+ r = results[ticker]
+ print(f"ticker: {ticker}")
+ 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"---")
+
+ # Auto-save results
+ _auto_save(results, elapsed, strategy)
+
+
+# ══════════════════════════════════════════════════
+# Auto-save: every run → runs/, best → best/
+# ══════════════════════════════════════════════════
+RUNS_DIR = Path(__file__).parent / "runs"
+BEST_DIR = Path(__file__).parent / "best"
+BEST_FILE = BEST_DIR / "best_sharpe.json"
+
+
+def _auto_save(results: dict, elapsed: float, strategy_mod) -> None:
+ """Save every run to runs/ and track best in best/."""
+ RUNS_DIR.mkdir(exist_ok=True)
+ BEST_DIR.mkdir(exist_ok=True)
+
+ ts = datetime.now().strftime("%Y%m%d_%H%M%S")
+ params = dict(strategy_mod.PARAMS)
+
+ # Primary metric: avg sharpe across all evaluated assets
+ 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())
+
+ run_data = {
+ "timestamp": ts,
+ "params": params,
+ "results": results,
+ "avg_sharpe": round(avg_sharpe, 4),
+ "total_pnl": round(total_pnl, 2),
+ "elapsed": round(elapsed, 1),
+ }
+
+ # Save every run
+ run_path = RUNS_DIR / f"run_{ts}.json"
+ run_path.write_text(json.dumps(run_data, indent=2, default=str))
+
+ # Check if this is the new best
+ prev_best_sharpe = -999.0
+ if BEST_FILE.exists():
+ try:
+ prev = json.loads(BEST_FILE.read_text())
+ prev_best_sharpe = prev.get("avg_sharpe", -999.0)
+ except (json.JSONDecodeError, KeyError):
+ pass
+
+ 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})")
+
+
+if __name__ == "__main__":
+ main()
diff --git a/experiments/autoresearch/ideas.md b/experiments/autoresearch/ideas.md
new file mode 100644
index 0000000..ee0f9bf
--- /dev/null
+++ b/experiments/autoresearch/ideas.md
@@ -0,0 +1,65 @@
+# Experiment Ideas — Autoresearch Strategy Optimization
+
+## 1. Parameter Sweeps (одномерные)
+
+| Parameter | Values to try |
+|-----------|--------------|
+| `window_size` | 32, 48, 64, 96, 128 |
+| `shift` | 3, 5, 10, 14, 16, 24, 32 |
+| `K` | 2, 3, 4, 5, 8 |
+| `epochs` | 50, 100, 200, 300, 500 |
+| `lr` | 0.001, 0.003, 0.005, 0.01, 0.03 |
+| `corr_thresh` | 0.2, 0.3, 0.4, 0.5, 0.6, 0.7 (with shape_confirm=True) |
+| `stop_mult` | 0.75, 1.0, 1.25, 1.5, 2.0, 2.5, 3.0 |
+| `stop_scale` | 0.5, 0.75, 1.0, 1.5, 2.0 |
+| `cooldown_bars` | 0, 3, 5, 7, 10, 14, 20 |
+| `min_confidence` | 0.0, 0.5, 1.0, 1.5, 2.0, 3.0 |
+| `leverage` | 1, 2, 3, 5 |
+
+## 2. Multi-dimensional Grid Search
+
+After finding best single-parameter values, combine:
+- Top-3 shift × Top-3 window_size × Top-2 K = 18 combinations
+- Best stop_mult × stop_scale × trailing_stop = ~12 combinations
+
+## 3. Feature Toggle Combinations
+
+- `shape_confirm=True` + various `corr_thresh`
+- `regime_adaptive=True` + various base params
+- `trailing_stop=True/False` + various `stop_mult`
+- All toggle combos: 2³ = 8 configs × best params
+
+## 4. Custom `generate_signal()` in strategy.py
+
+### Filters:
+- Momentum filter — enter only if prediction confirmed N bars in a row
+- Trend alignment — long only if price > SMA(N), short if price < SMA(N)
+- Volatility filter — skip trade when ATR above/below threshold
+- Prediction strength filter — enter only when |prediction| > threshold
+
+### Multi-window:
+- Two windows (long for trend + short for entry)
+- Ensemble — average signal from 2-3 models with different window_size
+- Voting from multiple models
+
+### Dynamic params:
+- Adaptive stop_mult based on current ATR
+- Dynamic leverage based on confidence
+- Adaptive cooldown based on volatility
+
+### Exit logic:
+- Time-based exit (close after N bars)
+- Prediction reversal exit (exit when model changes direction)
+
+## 5. Model hyperparams (requires evaluate.py support)
+
+- `n_steps`: 10, 20, 30, 50
+- `total_time`: 0.25, 0.5, 1.0
+- `use_sde`: True/False
+
+## 6. Meta-strategies
+
+- Bayesian-style search: analyze results.tsv, pick next point based on patterns
+- Ablation study: start with best config, remove one component at a time
+- Robustness testing: run best config 5-10 times, check Sharpe stability
+- Per-asset optimization: each asset has its own optimal params
diff --git a/experiments/autoresearch/runner.py b/experiments/autoresearch/runner.py
new file mode 100644
index 0000000..c1bfcc1
--- /dev/null
+++ b/experiments/autoresearch/runner.py
@@ -0,0 +1,371 @@
+#!/usr/bin/env python3
+"""Long-running experiment runner for autoresearch.
+
+Launches a sequence of parameter sweeps, modifies strategy.py,
+runs evaluate.py, and tracks results. Writes status.json for
+the dashboard to read.
+
+Usage:
+ python runner.py # full sweep
+ python runner.py --quick # quick test (3 experiments)
+ python runner.py --ticker DOGE-USD # single asset
+"""
+import argparse
+import importlib
+import json
+import subprocess
+import sys
+import time
+from copy import deepcopy
+from datetime import datetime
+from itertools import product
+from pathlib import Path
+
+ROOT = Path(__file__).parent
+STATUS_FILE = ROOT / "status.json"
+STRATEGY_FILE = ROOT / "strategy.py"
+RUNS_DIR = ROOT / "runs"
+
+# ══════════════════════════════════════════════════
+# Baseline parameters (known good from prior sweeps)
+# ══════════════════════════════════════════════════
+BASELINE = {
+ "window_size": 64,
+ "shift": 16,
+ "epochs": 300,
+ "lr": 0.01,
+ "K": 2,
+ "corr_thresh": 0.5,
+ "min_confidence": 0.0,
+ "shape_confirm": False,
+ "regime_adaptive": False,
+ "leverage": 1,
+ "stop_mult": 1.25,
+ "stop_scale": 1.0,
+ "trailing_stop": True,
+ "cooldown_bars": 0,
+}
+
+# ══════════════════════════════════════════════════
+# Sweep plans
+# ══════════════════════════════════════════════════
+SWEEPS_FULL = [
+ # Phase 1: single-parameter sweeps
+ ("shift", [3, 5, 10, 14, 24, 32]),
+ ("window_size", [32, 48, 96, 128]),
+ ("K", [3, 4, 5]),
+ ("epochs", [50, 100, 200, 500]),
+ ("lr", [0.001, 0.003, 0.005, 0.03]),
+ ("stop_mult", [0.75, 1.0, 1.5, 2.0, 2.5, 3.0]),
+ ("stop_scale", [0.5, 0.75, 1.5, 2.0]),
+ ("cooldown_bars", [3, 5, 7, 10, 14]),
+ ("leverage", [2, 3, 5]),
+]
+
+SWEEPS_QUICK = [
+ ("shift", [10, 14]),
+ ("K", [3]),
+]
+
+# Phase 2: feature toggles
+TOGGLE_COMBOS = [
+ {"shape_confirm": True, "corr_thresh": 0.3},
+ {"shape_confirm": True, "corr_thresh": 0.5},
+ {"shape_confirm": True, "corr_thresh": 0.7},
+ {"regime_adaptive": True},
+ {"trailing_stop": False},
+ {"shape_confirm": True, "corr_thresh": 0.4, "regime_adaptive": True},
+]
+
+TOGGLE_COMBOS_QUICK = [
+ {"shape_confirm": True, "corr_thresh": 0.5},
+]
+
+
+# Phase 2: grid search of best single-param winners
+GRID_PARAMS = {
+ "shift": [10, 14, 24],
+ "window_size": [32, 48, 96],
+ "K": [2, 3],
+}
+
+# Phase 3: per-asset runs
+ASSETS = [
+ "BTC-USD", "ETH-USD", "ADA-USD", "DOT-USD", "DOGE-USD", "SOL-USD",
+ # New top-20 coins (require data download first)
+ "XRP-USD", "AVAX-USD", "LINK-USD", "UNI-USD",
+ "ATOM-USD", "LTC-USD", "NEAR-USD", "APT-USD", "FIL-USD",
+ "ARB-USD", "OP-USD", "SUI-USD", "INJ-USD", "SEI-USD",
+]
+
+
+def build_experiments(quick=False):
+ """Generate list of (description, params, ticker) tuples.
+
+ ticker="" means use evaluate.py default (ADA-USD).
+ """
+ experiments = []
+ sweeps = SWEEPS_QUICK if quick else SWEEPS_FULL
+ toggles = TOGGLE_COMBOS_QUICK if quick else TOGGLE_COMBOS
+
+ # ── Phase 1: baseline + single-param sweeps ──
+ experiments.append(("baseline", dict(BASELINE), ""))
+
+ for param, values in sweeps:
+ for val in values:
+ if val == BASELINE.get(param):
+ continue
+ p = dict(BASELINE)
+ p[param] = val
+ experiments.append((f"{param}={val}", p, ""))
+
+ # Toggle combos
+ for combo in toggles:
+ p = dict(BASELINE)
+ p.update(combo)
+ desc = " + ".join(f"{k}={v}" for k, v in combo.items())
+ experiments.append((desc, p, ""))
+
+ if quick:
+ return experiments
+
+ # ── Phase 2: grid search of top combos ──
+ keys = list(GRID_PARAMS.keys())
+ for combo in product(*GRID_PARAMS.values()):
+ overrides = dict(zip(keys, combo))
+ # Skip if identical to baseline
+ if all(overrides[k] == BASELINE[k] for k in keys):
+ continue
+ p = dict(BASELINE)
+ p.update(overrides)
+ desc = "grid: " + " ".join(f"{k}={v}" for k, v in overrides.items())
+ experiments.append((desc, p, ""))
+
+ # ── Phase 3: per-asset sweeps (top parameters only) ──
+ per_asset_sweeps = [
+ ("shift", [10, 14, 24]),
+ ("window_size", [32, 48, 96]),
+ ("K", [3, 4]),
+ ("stop_mult", [1.0, 1.5, 2.0]),
+ ("lr", [0.003, 0.005]),
+ ]
+ for asset in ASSETS:
+ # Baseline per asset
+ experiments.append((f"{asset} baseline", dict(BASELINE), asset))
+ for param, values in per_asset_sweeps:
+ for val in values:
+ if val == BASELINE.get(param):
+ continue
+ p = dict(BASELINE)
+ p[param] = val
+ experiments.append((f"{asset} {param}={val}", p, asset))
+
+ return experiments
+
+
+def build_asset_grid(ticker):
+ """Focused grid search for a specific asset."""
+ experiments = []
+ grid = {
+ "shift": [10, 14, 16, 24],
+ "stop_mult": [0.75, 1.0, 1.25, 2.0],
+ "K": [2, 3, 5],
+ "lr": [0.005, 0.01],
+ "cooldown_bars": [0, 3],
+ }
+ label = ticker.replace("-USD", "")
+ keys = list(grid.keys())
+ for combo in product(*grid.values()):
+ overrides = dict(zip(keys, combo))
+ p = dict(BASELINE)
+ p.update(overrides)
+ desc = f"{label} grid: " + " ".join(f"{k}={v}" for k, v in overrides.items())
+ experiments.append((desc, p, ticker))
+ return experiments
+
+
+def build_multi_asset_grid(tickers):
+ """Grid search across multiple assets sequentially."""
+ experiments = []
+ for ticker in tickers:
+ experiments.extend(build_asset_grid(ticker))
+ return experiments
+
+
+def write_strategy(params):
+ """Write strategy.py with given params."""
+ lines = ['"""Strategy parameters — autogenerated."""', "", "PARAMS = {"]
+ for k, v in params.items():
+ lines.append(f" {k!r}: {v!r},")
+ lines.append("}")
+ lines.append("")
+ STRATEGY_FILE.write_text("\n".join(lines))
+
+
+def write_status(state, run_number=0, total=0, description="",
+ ticker="", current_result=None, error=None):
+ """Write status.json for dashboard."""
+ 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 get_latest_run():
+ """Read the most recent run JSON from runs/."""
+ if not RUNS_DIR.exists():
+ return None
+ runs = sorted(RUNS_DIR.glob("run_*.json"))
+ if not runs:
+ return None
+ try:
+ return json.loads(runs[-1].read_text())
+ except (json.JSONDecodeError, OSError):
+ 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)
+
+ t0 = time.time()
+ cmd = [sys.executable, "evaluate.py"]
+ if ticker:
+ cmd += ["--ticker", ticker]
+
+ try:
+ result = subprocess.run(
+ 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
+
+ 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
+
+ # 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
+
+ return run_data
+
+
+def print_result(desc, run_data, run_num, total):
+ """Print formatted result to terminal."""
+ sharpe = run_data.get("avg_sharpe", 0)
+ pnl = run_data.get("total_pnl", 0)
+ elapsed = run_data.get("elapsed", 0)
+
+ # Per-asset breakdown
+ results = run_data.get("results", {})
+ trades_total = sum(r.get("trades", 0) for r in results.values())
+
+ # Color coding via ANSI
+ if sharpe > 1.0:
+ color = "\033[92m" # green
+ elif sharpe > 0.5:
+ color = "\033[93m" # yellow
+ elif sharpe > 0:
+ color = "\033[0m" # normal
+ else:
+ color = "\033[91m" # red
+ reset = "\033[0m"
+
+ print(f"[{run_num:3d}/{total}] {color}sharpe={sharpe:7.4f}{reset} "
+ f"pnl=${pnl:8.2f} trades={trades_total:3d} "
+ f"t={elapsed:5.1f}s {desc}")
+
+ # Per-asset details if multi-asset
+ if len(results) > 1:
+ for tk, r in results.items():
+ print(f" {tk:10s} sharpe={r['sharpe']:7.4f} "
+ f"pnl=${r['total_pnl']:8.2f} trades={r['trades']}")
+
+
+def main():
+ parser = argparse.ArgumentParser(description="Autoresearch sweep runner")
+ parser.add_argument("--quick", action="store_true",
+ help="Quick test (3 experiments)")
+ parser.add_argument("--grid", nargs="+", metavar="TICKER",
+ help="Grid search for specific assets (e.g. --grid ADA-USD DOT-USD)")
+ parser.add_argument("--grid-all", action="store_true",
+ help="Grid search for all available assets")
+ parser.add_argument("--ticker", default="",
+ help="Single asset (default: all per evaluate.py)")
+ 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)
+ total = len(experiments)
+
+ print(f"{'='*60}")
+ print(f"AUTORESEARCH SWEEP — {total} experiments")
+ if args.ticker:
+ print(f"Ticker override: {args.ticker}")
+ print(f"Started: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
+ print(f"{'='*60}")
+
+ best_sharpe = -999.0
+ best_desc = ""
+
+ 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)
+
+ 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
+
+ print_result(desc, run_data, i, 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", i, 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"Best Sharpe: {best_sharpe:.4f} ({best_desc})")
+ print(f"{'='*60}")
+
+ # Restore baseline
+ write_strategy(BASELINE)
+
+
+if __name__ == "__main__":
+ main()
diff --git a/experiments/autoresearch/strategy.py b/experiments/autoresearch/strategy.py
new file mode 100644
index 0000000..1cc735f
--- /dev/null
+++ b/experiments/autoresearch/strategy.py
@@ -0,0 +1,18 @@
+"""Strategy parameters — autogenerated."""
+
+PARAMS = {
+ 'window_size': 64,
+ 'shift': 10,
+ 'epochs': 300,
+ 'lr': 0.01,
+ 'K': 3,
+ 'corr_thresh': 0.5,
+ 'min_confidence': 0.0,
+ 'shape_confirm': False,
+ 'regime_adaptive': False,
+ 'leverage': 1,
+ 'stop_mult': 2.0,
+ 'stop_scale': 1.0,
+ 'trailing_stop': True,
+ 'cooldown_bars': 3,
+}
diff --git a/experiments/common/dataset.py b/experiments/common/dataset.py
index 701f3b5..6625cc4 100644
--- a/experiments/common/dataset.py
+++ b/experiments/common/dataset.py
@@ -11,12 +11,28 @@ import numpy as np
DATA_DIR = Path(__file__).parent.parent / "data"
ASSETS = [
+ # Original 6
{"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.183},
{"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.183},
{"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},
+ # Top-20 additions (Bybit spot USDC pairs, 4h TF)
+ {"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "AVAX/USDC", "ticker": "AVAX-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "LINK/USDC", "ticker": "LINK-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "UNI/USDC", "ticker": "UNI-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "ATOM/USDC", "ticker": "ATOM-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "LTC/USDC", "ticker": "LTC-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "NEAR/USDC", "ticker": "NEAR-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "APT/USDC", "ticker": "APT-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "FIL/USDC", "ticker": "FIL-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "ARB/USDC", "ticker": "ARB-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "OP/USDC", "ticker": "OP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "SUI/USDC", "ticker": "SUI-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "INJ/USDC", "ticker": "INJ-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
+ {"symbol": "SEI/USDC", "ticker": "SEI-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.05},
]