- 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>
160 lines
5.2 KiB
Python
160 lines
5.2 KiB
Python
"""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()
|