- 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>
326 lines
12 KiB
Python
326 lines
12 KiB
Python
"""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()
|