Files
remizov-trader/experiments/autoresearch/evaluate.py
T
anorandClaude Opus 4.6 6e37be51a9 feat: прод на UNI/ATOM/NEAR — точные параметры из grid search
- config.yaml: 3 актива с per-asset shift, K, lr, stop_mult, stop_scale, cooldown
- config.py: per-asset overrides (shift, epochs, lr, stop_mult, stop_scale, cooldown_bars, min_confidence, shape_confirm)
- executor.py: per-asset stop_mult (вместо regime_adaptive), shape_confirm флаг, per-asset cooldown_bars, trailing stop порядок (check→trail)
- cli.py: train на 30% данных (TRAIN_RATIO=0.3, как в тесте)
- walk-forward: evaluate_wf.py + runner_wf.py
- dashboard: WF таб с отдельными заголовками/pills/данными
- runner.py: параллельный grid search (ProcessPoolExecutor, --workers)
- evaluate.py: OHLCV стопы, OOS holdout, Sharpe sqrt(365)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-12 22:36:43 +10:00

531 lines
20 KiB
Python

"""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")
parser.add_argument("--params-json", default="",
help="JSON string with params (bypasses strategy.py)")
args = parser.parse_args()
# 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")
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
# 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:
ticker = list(results.keys())[0]
r = results[ticker]
print(f"ticker: {ticker}")
for k, v in r.items():
print(f"{k + ':':18s}{v}")
else:
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}%")
print(f"---")
print(f"avg_sharpe: {avg_sharpe:.4f}")
print(f"total_pnl: {total_pnl:.2f}")
print(f"elapsed_seconds: {elapsed:.1f}")
print(f"---")
# 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/
# ══════════════════════════════════════════════════
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)
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
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))
print(f"NEW BEST: sharpe={avg_sharpe:.4f} (was {prev_best_sharpe:.4f})")
if __name__ == "__main__":
main()