perf: распараллелить A/B тесты на ProcessPoolExecutor

- ProcessPoolExecutor с N_WORKERS = cpu_count()-1 (7 воркеров)
- Модель передаётся через state_dict (picklable)
- torch.set_num_threads(1) в воркерах для избежания thread contention
- Ensemble обучение параллельно (_worker_ensemble_single)
- Время выполнения ~24 мин vs ~90+ мин последовательно

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-08 13:13:17 +10:00
co-authored by Claude Opus 4.6
parent c6e8f08164
commit ca26ff34f5
+185 -130
View File
@@ -19,8 +19,10 @@ import json
import os
import time
import warnings
from concurrent.futures import ProcessPoolExecutor, as_completed
from copy import deepcopy
from datetime import date, datetime
from multiprocessing import cpu_count
import numpy as np
import torch
@@ -31,6 +33,8 @@ from models import EnhancedRemizovNet
warnings.filterwarnings("ignore")
N_WORKERS = max(1, cpu_count() - 1) # leave 1 core free
# -- Base Config (same as final_backtest.py) ---------------------------------
WINDOW_SIZE = 64
@@ -498,111 +502,161 @@ def print_comparison(results: list[dict], asset: str):
f"${r['final_equity']:>9,.0f}")
# -- Main: Sequential A/B Testing -------------------------------------------
# -- Parallel worker ---------------------------------------------------------
def main():
t0 = time.time()
def _worker_backtest(args):
"""Worker for ProcessPoolExecutor. Recreates model from state_dict."""
label, prices, dates, data, cfg, impr, state_dict, grid_size = args
print("=" * 100)
print("IMPROVEMENT A/B TESTING")
print("=" * 100)
torch.set_num_threads(1) # avoid thread contention in workers
all_metrics = {} # asset -> list of metrics dicts
best_per_asset = {} # asset -> best improvement name
if state_dict is not None:
model = create_model(grid_size=grid_size)
model.load_state_dict(state_dict)
impr = {**impr, "pretrained_model": model}
for asset, cfg in ASSET_CONFIGS.items():
time.sleep(2)
try:
prices, dates = fetch_asset(asset)
except Exception as e:
print(f"\n {asset}: FETCH ERROR ({e})")
continue
r = run_backtest(prices, dates, data, cfg, impr)
return calc_metrics(r["trades"], label)
data = prepare_data(prices)
n = len(data)
print(f"\n{'=' * 100}")
print(f" {asset}: {n} windows, K={cfg['K']}, corr>{cfg['corr_thresh']}")
print(f"{'=' * 100}")
def _worker_ensemble_single(args):
"""Train one ensemble member and return predictions."""
seed, data, grid_size, train_size = args
results = []
torch.set_num_threads(1)
torch.manual_seed(seed * 42)
np.random.seed(seed * 42)
# Train ONE model per asset (fixed seed), share across all tests
print(f"\n Training base model (seed=42)...", end=" ", flush=True)
torch.manual_seed(42)
np.random.seed(42)
base_model = create_model()
train_size = 80
windows = np.array([d["norm_input"] for d in data[:train_size]])
targets = np.array([d["norm_target"] for d in data[:train_size]])
train_model(base_model, windows, targets, EPOCHS)
print("done")
model = create_model(grid_size=grid_size)
windows = np.array([d["norm_input"] for d in data[:train_size]])
targets = np.array([d["norm_target"] for d in data[:train_size]])
train_model(model, windows, targets, EPOCHS)
# Helper: run with shared model
def run_test(label, impr=None):
if impr is None:
impr = {}
impr_copy = {**impr, "pretrained_model": base_model}
print(f" Running {label}...", end=" ", flush=True)
r = run_backtest(prices, dates, data, cfg, impr_copy)
m = calc_metrics(r["trades"], label)
results.append(m)
print(f"done ({m['n_trades']} trades)")
n = len(data)
preds = {}
retrain_ctr = 0
for i in range(train_size, n):
preds[i] = predict(model, data[i]["norm_input"])
retrain_ctr += 1
if retrain_ctr >= 10:
ws = np.array([dd["norm_input"] for dd in data[:i + 1]])
ts = np.array([dd["norm_target"] for dd in data[:i + 1]])
train_model(model, ws, ts, FINETUNE_EPOCHS)
retrain_ctr = 0
# ── BASELINE ──
run_test("BASELINE")
return preds
# ── A: Adaptive Stop (ATR) ──
run_test("A: ATR stop", {"adaptive_stop": True})
# ── A2: Trailing Stop ──
run_test("A2: Trailing stop", {"trailing_stop": True})
def compute_ensemble_parallel(data, n_models=3, train_size=80):
"""Train N models in parallel, average predictions."""
args = [(seed, data, WINDOW_SIZE, train_size) for seed in range(n_models)]
# ── B: Kelly Position Sizing ──
run_test("B: Kelly sizing", {"kelly": True})
with ProcessPoolExecutor(max_workers=min(n_models, N_WORKERS)) as pool:
all_preds = list(pool.map(_worker_ensemble_single, args))
# ── D: Ensemble (3 models) ──
print(f" Running D: Ensemble (3 models)...", end=" ", flush=True)
ens_preds = compute_ensemble_preds(data, n_models=3)
r = run_backtest(prices, dates, data, cfg, {"ensemble_preds": ens_preds})
m = calc_metrics(r["trades"], "D: Ensemble x3")
results.append(m)
print(f"done ({m['n_trades']} trades)")
# Average
n = len(data)
ensemble = {}
for i in range(n):
member_preds = [p[i] for p in all_preds if i in p]
if member_preds:
ensemble[i] = np.mean(member_preds, axis=0)
else:
ensemble[i] = None
return ensemble
# ── E: Volatility Filter ──
run_test("E: Vol filter (MA20>50)", {"vol_filter": True})
# ── F: Higher Correlation Threshold ──
for thresh in [0.7, 0.8, 0.9]:
if thresh <= cfg["corr_thresh"]:
continue
run_test(f"F: corr>{thresh}", {"corr_override": thresh})
# -- Main: Parallel A/B Testing ---------------------------------------------
# ── G: Leverage 2x ──
run_test("G: 2x leverage", {"leverage": 2.0})
def run_asset_tests(asset, cfg, prices, dates):
"""Run all tests for one asset. Returns list of metrics."""
data = prepare_data(prices)
n = len(data)
# Print comparison
print_comparison(results, asset)
# Find best (by Sharpe, minimum 5 trades)
valid = [r for r in results if r["n_trades"] >= 5]
if valid:
best = max(valid, key=lambda r: r["sharpe"])
print(f"\n BEST for {asset}: {best['label']} "
f"(Sharpe={best['sharpe']}, Return={best['total_return']:+.1f}%)")
best_per_asset[asset] = best["label"]
all_metrics[asset] = results
# ================================================================
# PHASE 2: COMBINATIONS of best improvements
# ================================================================
print(f"\n\n{'=' * 100}")
print("PHASE 2: COMBINATIONS")
print(f"\n{'=' * 100}")
print(f" {asset}: {n} windows, K={cfg['K']}, corr>{cfg['corr_thresh']}")
print(f"{'=' * 100}")
# Define promising combos based on individual results
# Train base model (sequential — must happen first)
print(f"\n Training base model (seed=42)...", end=" ", flush=True)
torch.manual_seed(42)
np.random.seed(42)
base_model = create_model()
train_size = 80
windows = np.array([d["norm_input"] for d in data[:train_size]])
targets = np.array([d["norm_target"] for d in data[:train_size]])
train_model(base_model, windows, targets, EPOCHS)
sd = base_model.state_dict()
print("done")
# Define all tests
tests = [
("BASELINE", {}),
("A: ATR stop", {"adaptive_stop": True}),
("A2: Trailing stop", {"trailing_stop": True}),
("B: Kelly sizing", {"kelly": True}),
("E: Vol filter (MA20>50)", {"vol_filter": True}),
("G: 2x leverage", {"leverage": 2.0}),
]
# Add F tests (higher corr thresholds)
for thresh in [0.7, 0.8, 0.9]:
if thresh > cfg["corr_thresh"]:
tests.append((f"F: corr>{thresh}", {"corr_override": thresh}))
# Run all tests in parallel
print(f" Running {len(tests)} tests in parallel ({N_WORKERS} workers)...",
end=" ", flush=True)
worker_args = [
(label, prices, dates, data, cfg, impr, sd, WINDOW_SIZE)
for label, impr in tests
]
with ProcessPoolExecutor(max_workers=N_WORKERS) as pool:
results = list(pool.map(_worker_backtest, worker_args))
print("done")
# Ensemble (parallel model training)
print(f" Running D: Ensemble (3 models, parallel)...", end=" ", flush=True)
ens_preds = compute_ensemble_parallel(data, n_models=3)
r = run_backtest(prices, dates, data, cfg, {"ensemble_preds": ens_preds})
m = calc_metrics(r["trades"], "D: Ensemble x3")
results.append(m)
print(f"done ({m['n_trades']} trades)")
# Print
print_comparison(results, asset)
valid = [r for r in results if r["n_trades"] >= 5]
if valid:
best = max(valid, key=lambda r: r["sharpe"])
print(f"\n BEST for {asset}: {best['label']} "
f"(Sharpe={best['sharpe']}, Return={best['total_return']:+.1f}%)")
return results
def run_asset_combos(asset, cfg, prices, dates):
"""Run combination tests for one asset. Returns list of metrics."""
data = prepare_data(prices)
print(f"\n{'=' * 100}")
print(f" {asset}: COMBINATIONS")
print(f"{'=' * 100}")
torch.manual_seed(42)
np.random.seed(42)
base_model = create_model()
train_size = 80
windows = np.array([d["norm_input"] for d in data[:train_size]])
targets = np.array([d["norm_target"] for d in data[:train_size]])
train_model(base_model, windows, targets, EPOCHS)
sd = base_model.state_dict()
combos = [
("BASELINE", {}),
("ATR + Kelly", {"adaptive_stop": True, "kelly": True}),
("ATR + Trailing", {"adaptive_stop": True, "trailing_stop": True}),
("ATR + Vol filter", {"adaptive_stop": True, "vol_filter": True}),
@@ -613,54 +667,59 @@ def main():
("ATR+Kelly+Vol+2x", {"adaptive_stop": True, "kelly": True, "vol_filter": True, "leverage": 2.0}),
]
print(f" Running {len(combos)} combos in parallel...", end=" ", flush=True)
worker_args = [
(label, prices, dates, data, cfg, impr, sd, WINDOW_SIZE)
for label, impr in combos
]
with ProcessPoolExecutor(max_workers=N_WORKERS) as pool:
results = list(pool.map(_worker_backtest, worker_args))
print("done")
print_comparison(results, asset)
valid = [r for r in results if r["n_trades"] >= 5]
if valid:
best = max(valid, key=lambda r: r["sharpe"])
print(f"\n BEST COMBO for {asset}: {best['label']} "
f"(Sharpe={best['sharpe']}, Return={best['total_return']:+.1f}%)")
return results
def main():
t0 = time.time()
print("=" * 100)
print(f"IMPROVEMENT A/B TESTING (parallel, {N_WORKERS} workers)")
print("=" * 100)
all_metrics = {}
# Phase 1: Individual improvements
for asset, cfg in ASSET_CONFIGS.items():
time.sleep(2)
try:
prices, dates = fetch_asset(asset)
except Exception as e:
print(f"\n {asset}: FETCH ERROR ({e})")
continue
all_metrics[asset] = run_asset_tests(asset, cfg, prices, dates)
# Phase 2: Combinations
print(f"\n\n{'=' * 100}")
print("PHASE 2: COMBINATIONS")
print(f"{'=' * 100}")
for asset, cfg in ASSET_CONFIGS.items():
time.sleep(2)
try:
prices, dates = fetch_asset(asset)
except Exception as e:
continue
run_asset_combos(asset, cfg, prices, dates)
data = prepare_data(prices)
print(f"\n{'=' * 100}")
print(f" {asset}: COMBINATIONS")
print(f"{'=' * 100}")
# Train shared model (same seed as Phase 1)
torch.manual_seed(42)
np.random.seed(42)
base_model = create_model()
train_size = 80
windows = np.array([d["norm_input"] for d in data[:train_size]])
targets = np.array([d["norm_target"] for d in data[:train_size]])
train_model(base_model, windows, targets, EPOCHS)
results = []
# Baseline for reference
r = run_backtest(prices, dates, data, cfg,
{"pretrained_model": base_model})
results.append(calc_metrics(r["trades"], "BASELINE"))
for name, impr in combos:
print(f" Running {name}...", end=" ", flush=True)
impr_copy = {**impr, "pretrained_model": base_model}
r = run_backtest(prices, dates, data, cfg, impr_copy)
m = calc_metrics(r["trades"], name)
results.append(m)
print(f"done ({m['n_trades']} trades)")
print_comparison(results, asset)
valid = [r for r in results if r["n_trades"] >= 5]
if valid:
best = max(valid, key=lambda r: r["sharpe"])
print(f"\n BEST COMBO for {asset}: {best['label']} "
f"(Sharpe={best['sharpe']}, Return={best['total_return']:+.1f}%)")
# ================================================================
# FINAL SUMMARY
# ================================================================
# Final summary
elapsed = time.time() - t0
print(f"\n\n{'=' * 100}")
print(f"FINAL SUMMARY ({elapsed:.0f}s)")
@@ -699,11 +758,7 @@ def main():
"timestamp": datetime.now().isoformat(),
"elapsed_seconds": elapsed,
"results": {
asset: [
{k: v for k, v in m.items()
if k not in ("trades",)}
for m in metrics
]
asset: metrics
for asset, metrics in all_metrics.items()
},
}, f, indent=2, default=str)