fix: 3 бага в optimize-windows

- regex DOTALL перехватывал train_pct других активов → line-by-line
- yaml.dump убивал комментарии в config → line-by-line сохраняет формат
- COMMISSION общий для портфеля → per-asset commission_rates

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-15 21:06:19 +10:00
co-authored by Claude Opus 4.6
parent 449512915e
commit 9833013f1d
+29 -26
View File
@@ -579,7 +579,7 @@ def optimize_windows(apply):
from .core.risk import calculate_position
cfg = load_config()
COMMISSION = 0.00055 if any(cfg.is_futures(a) for a in cfg.assets) else 0.001
commission_rates = {a.ticker: cfg.commission_for(a) for a in cfg.assets}
WINDOW_PCT = 0.10
STEP_PCT = 0.05
@@ -640,6 +640,7 @@ def optimize_windows(apply):
model_mod.train(mdl, W, T, model_cfg.epochs, model_cfg.lr)
# Run backtest on test_data
comm = commission_rates[ticker]
eq = cap; pos = None; cool = 0
for d in test_data:
pi = d["price_idx"]; cp = float(prices[pi])
@@ -651,7 +652,7 @@ def optimize_windows(apply):
if stopped or te:
ep = pos["stop"] if stopped else cp
pnl, _ = calculate_pnl(pos["entry"], ep, pos["dir"],
pos["sz"], pos["val"], commission=COMMISSION)
pos["sz"], pos["val"], commission=comm)
eq += pnl; pos = None
if stopped: cool = pi + cd
if pos is None and pi >= ws + K and pi >= cool:
@@ -671,7 +672,7 @@ def optimize_windows(apply):
if pos:
lp = float(prices[-1])
pnl, _ = calculate_pnl(pos["entry"], lp, pos["dir"],
pos["sz"], pos["val"], commission=COMMISSION)
pos["sz"], pos["val"], commission=comm)
eq += pnl
total_pnl = eq - cap
@@ -717,29 +718,31 @@ def _apply_optimal_windows(cfg, results):
from .config import CONFIG_PATH
from .core import model as model_mod, signals
# Update config.yaml
text = CONFIG_PATH.read_text()
for ticker, bw in results.items():
s_pct, e_pct = bw["start"], bw["end"]
# Find the asset block and add/update train_start_pct, train_end_pct
# Simple approach: add after ticker line if not present, or replace
ticker_pattern = re.escape(ticker)
if f"train_start_pct:" in text:
text = re.sub(r"(- ticker: " + ticker_pattern + r".*?)"
r"train_start_pct:\s*[\d.]+",
rf"\g<1>train_start_pct: {s_pct:.2f}",
text, flags=re.DOTALL)
text = re.sub(r"(- ticker: " + ticker_pattern + r".*?)"
r"train_end_pct:\s*[\d.]+",
rf"\g<1>train_end_pct: {e_pct:.2f}",
text, flags=re.DOTALL)
else:
# Add after timeframe line in each asset block
text = re.sub(
r"(- ticker: " + ticker_pattern + r".*?timeframe:\s*\S+)",
rf"\1\n train_start_pct: {s_pct:.2f}\n train_end_pct: {e_pct:.2f}",
text, flags=re.DOTALL)
CONFIG_PATH.write_text(text)
# Update config.yaml — line-by-line to preserve comments and formatting
lines = CONFIG_PATH.read_text().splitlines()
new_lines = []
current_ticker = None
for line in lines:
# Track which asset block we're in
m = re.match(r"\s*- ticker:\s*(\S+)", line)
if m:
current_ticker = m.group(1)
# Skip old train_start_pct / train_end_pct lines (will re-add)
if current_ticker in results and re.match(r"\s+train_(start|end)_pct:", line):
continue
new_lines.append(line)
# After timeframe line, insert train window params
if current_ticker in results and re.match(r"\s+timeframe:", line):
bw = results[current_ticker]
indent = " "
new_lines.append(f"{indent}train_start_pct: {bw['start']:.2f} # optimized {bw['period']}")
new_lines.append(f"{indent}train_end_pct: {bw['end']:.2f}")
CONFIG_PATH.write_text("\n".join(new_lines) + "\n")
click.echo(f" config.yaml updated")
# Retrain models with new windows