feat: per-asset optimal training windows + optimize-windows CLI
- AssetConfig: train_start_pct/train_end_pct (default 0-30% backward compat) - init: uses per-asset windows instead of hardcoded 30% - optimize-windows: sliding 10% window test, finds best PnL per asset - optimize-windows --apply: updates config.yaml + retrains models - config.yaml: UNI 70-80%, ATOM 0-10%, SUI 40-50% (from backtest) Backtest: per-asset best $929 vs prod 0-30% $434 = 2.14x improvement Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -37,6 +37,8 @@ assets:
|
||||
shape_confirm: false
|
||||
corr_thresh: 0.5
|
||||
timeframe: 1h
|
||||
train_start_pct: 0.70 # optimal: May-Aug 2025
|
||||
train_end_pct: 0.80
|
||||
|
||||
- ticker: ATOM-USD
|
||||
symbol: "ATOM/USDT:USDT"
|
||||
@@ -56,6 +58,8 @@ assets:
|
||||
shape_confirm: false
|
||||
corr_thresh: 0.5
|
||||
timeframe: 1h
|
||||
train_start_pct: 0.00 # optimal: Jun-Oct 2023
|
||||
train_end_pct: 0.10
|
||||
|
||||
- ticker: SUI-USD
|
||||
symbol: "SUI/USDT:USDT"
|
||||
@@ -75,6 +79,8 @@ assets:
|
||||
shape_confirm: false
|
||||
corr_thresh: 0.5
|
||||
timeframe: 1h
|
||||
train_start_pct: 0.40 # optimal: Jul-Nov 2024
|
||||
train_end_pct: 0.50
|
||||
|
||||
model:
|
||||
window_size: 64
|
||||
|
||||
+216
-4
@@ -71,10 +71,14 @@ def init():
|
||||
|
||||
model_cfg = cfg.model_for(asset_cfg)
|
||||
data = signals.prepare_windows(prices, model_cfg.window_size, model_cfg.shift)
|
||||
# Train on first 30% of windows (matches autoresearch TRAIN_RATIO=0.3)
|
||||
n_train = max(int(len(data) * 0.3), 20)
|
||||
train_data = data[:n_train]
|
||||
click.echo(f" {len(prices)} bars, {len(data)} windows, train={n_train} (ws={model_cfg.window_size})...", nl=False)
|
||||
# Per-asset training window from config (default: first 30%)
|
||||
n = len(data)
|
||||
start_idx = max(int(n * asset_cfg.train_start_pct), 0)
|
||||
end_idx = max(int(n * asset_cfg.train_end_pct), start_idx + 20)
|
||||
train_data = data[start_idx:end_idx]
|
||||
n_train = len(train_data)
|
||||
pct_label = f"{int(asset_cfg.train_start_pct*100)}-{int(asset_cfg.train_end_pct*100)}%"
|
||||
click.echo(f" {len(prices)} bars, {len(data)} windows, train={n_train} [{pct_label}] (ws={model_cfg.window_size})...", nl=False)
|
||||
|
||||
torch.manual_seed(42)
|
||||
np.random.seed(42)
|
||||
@@ -566,6 +570,214 @@ def _update_config_leverage(leverage: int):
|
||||
CONFIG_PATH.write_text(text)
|
||||
|
||||
|
||||
@main.command(name="optimize-windows")
|
||||
@click.option("--apply", is_flag=True, help="Update config.yaml and retrain models")
|
||||
def optimize_windows(apply):
|
||||
"""Find optimal training window for each asset via sliding 10% test."""
|
||||
from .core import model as model_mod, signals
|
||||
from .core.risk import calculate_pnl, compute_atr, update_trailing_stop, is_stopped
|
||||
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
|
||||
WINDOW_PCT = 0.10
|
||||
STEP_PCT = 0.05
|
||||
|
||||
click.echo("=" * 70)
|
||||
click.echo("OPTIMIZE TRAINING WINDOWS (sliding 10%)")
|
||||
click.echo("=" * 70)
|
||||
|
||||
results = {} # ticker -> {start_pct, end_pct, pnl, period}
|
||||
|
||||
for asset_cfg in cfg.assets:
|
||||
ticker = asset_cfg.ticker
|
||||
click.echo(f"\n {ticker}...", nl=False)
|
||||
|
||||
interval = asset_cfg.timeframe or cfg.timeframe
|
||||
period = "max" if interval == "1d" else "730d"
|
||||
source = cfg.exchange.data_source
|
||||
symbol = asset_cfg.symbol if source == "exchange" else ticker
|
||||
prices, dates = signals.fetch_prices(
|
||||
symbol, interval, period, cfg.exchange, source=source,
|
||||
)
|
||||
if prices is None:
|
||||
click.echo(" ERROR: no data")
|
||||
continue
|
||||
|
||||
model_cfg = cfg.model_for(asset_cfg)
|
||||
data = signals.prepare_windows(prices, model_cfg.window_size, model_cfg.shift)
|
||||
n = len(data)
|
||||
click.echo(f" {len(prices)} bars, {n} windows")
|
||||
|
||||
shift = model_cfg.shift
|
||||
K = asset_cfg.K
|
||||
ws = model_cfg.window_size
|
||||
sm = asset_cfg.stop_mult or 1.0
|
||||
ss = asset_cfg.stop_scale or cfg.risk.stop_scale
|
||||
cd = asset_cfg.cooldown_bars if asset_cfg.cooldown_bars >= 0 else shift
|
||||
cap = (cfg.total_capital or cfg.initial_capital * len(cfg.assets)) * (asset_cfg.weight or 1.0 / len(cfg.assets))
|
||||
|
||||
best_pnl = -float('inf')
|
||||
best_window = None
|
||||
|
||||
for start_pct in np.arange(0, 1.0 - WINDOW_PCT + 0.001, STEP_PCT):
|
||||
end_pct = start_pct + WINDOW_PCT
|
||||
train_start = int(n * start_pct)
|
||||
train_end = int(n * end_pct)
|
||||
train_data = data[train_start:train_end]
|
||||
if len(train_data) < 20:
|
||||
continue
|
||||
|
||||
test_data = data[:train_start] + data[train_end:]
|
||||
if len(test_data) < 10:
|
||||
continue
|
||||
|
||||
torch.manual_seed(42)
|
||||
np.random.seed(42)
|
||||
mdl = model_mod.create_model(model_cfg)
|
||||
W = np.array([d["norm_input"] for d in train_data])
|
||||
T = np.array([d["norm_target"] for d in train_data])
|
||||
model_mod.train(mdl, W, T, model_cfg.epochs, model_cfg.lr)
|
||||
|
||||
# Run backtest on test_data
|
||||
eq = cap; pos = None; cool = 0
|
||||
for d in test_data:
|
||||
pi = d["price_idx"]; cp = float(prices[pi])
|
||||
if pos:
|
||||
pos["best"], pos["stop"] = update_trailing_stop(
|
||||
cp, pos["best"], pos["stop"], pos["sd"], pos["dir"])
|
||||
stopped = is_stopped(cp, pos["stop"], pos["dir"])
|
||||
te = (pi - pos["bar"]) >= (shift - pos["k"])
|
||||
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)
|
||||
eq += pnl; pos = None
|
||||
if stopped: cool = pi + cd
|
||||
if pos is None and pi >= ws + K and pi >= cool:
|
||||
w = prices[pi-ws-K:pi-K].copy()
|
||||
mu, std = w.mean(), w.std()
|
||||
if std < 1e-10: continue
|
||||
ni = (w - mu) / std
|
||||
pred = model_mod.predict(mdl, ni)[-shift:]
|
||||
d2 = signals.get_direction(pred, K)
|
||||
if d2 and not (d2 == -1):
|
||||
atr = compute_atr(prices, pi)
|
||||
sd = max(atr * sm * ss, cp * 0.005)
|
||||
sp = cp - d2 * sd
|
||||
sz, val = calculate_position(eq, cp, sd, cfg.risk)
|
||||
pos = {"dir": d2, "entry": cp, "stop": sp, "sd": sd,
|
||||
"best": cp, "sz": sz, "val": val, "bar": pi, "k": K}
|
||||
if pos:
|
||||
lp = float(prices[-1])
|
||||
pnl, _ = calculate_pnl(pos["entry"], lp, pos["dir"],
|
||||
pos["sz"], pos["val"], commission=COMMISSION)
|
||||
eq += pnl
|
||||
|
||||
total_pnl = eq - cap
|
||||
train_first = train_data[0]["price_idx"]
|
||||
train_last = train_data[-1]["price_idx"]
|
||||
tp = f"{str(dates[train_first])[:10]}→{str(dates[train_last])[:10]}"
|
||||
|
||||
label = f"{int(start_pct*100):>2}-{int(end_pct*100)}%"
|
||||
marker = ""
|
||||
if total_pnl > best_pnl:
|
||||
best_pnl = total_pnl
|
||||
best_window = {"start": start_pct, "end": end_pct,
|
||||
"pnl": total_pnl, "period": tp}
|
||||
marker = " ◄"
|
||||
click.echo(f" {label} ({tp}) ${total_pnl:>+8.1f}{marker}")
|
||||
|
||||
if best_window:
|
||||
results[ticker] = best_window
|
||||
click.echo(f" BEST: {int(best_window['start']*100)}-{int(best_window['end']*100)}% "
|
||||
f"({best_window['period']}) ${best_window['pnl']:+.1f}")
|
||||
|
||||
# Summary
|
||||
click.echo(f"\n{'='*70}")
|
||||
click.echo("OPTIMAL WINDOWS:")
|
||||
for ticker, bw in results.items():
|
||||
s, e = int(bw['start']*100), int(bw['end']*100)
|
||||
click.echo(f" {ticker}: {s}-{e}% ({bw['period']}) ${bw['pnl']:+.1f}")
|
||||
click.echo(f" config: train_start_pct: {bw['start']:.2f}")
|
||||
click.echo(f" config: train_end_pct: {bw['end']:.2f}")
|
||||
|
||||
if apply and results:
|
||||
click.echo(f"\nApplying to config.yaml and retraining...")
|
||||
_apply_optimal_windows(cfg, results)
|
||||
click.echo("Done! Restart bot to use new models.")
|
||||
elif results:
|
||||
click.echo(f"\nRun with --apply to update config and retrain.")
|
||||
click.echo("=" * 70)
|
||||
|
||||
|
||||
def _apply_optimal_windows(cfg, results):
|
||||
"""Update config.yaml with optimal windows and retrain models."""
|
||||
import re
|
||||
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)
|
||||
click.echo(f" config.yaml updated")
|
||||
|
||||
# Retrain models with new windows
|
||||
cfg = load_config() # reload with new windows
|
||||
conn = get_db()
|
||||
init_db(conn)
|
||||
for asset_cfg in cfg.assets:
|
||||
ticker = asset_cfg.ticker
|
||||
if ticker not in results:
|
||||
continue
|
||||
click.echo(f" Retraining {ticker}...", nl=False)
|
||||
interval = asset_cfg.timeframe or cfg.timeframe
|
||||
period = "max" if interval == "1d" else "730d"
|
||||
source = cfg.exchange.data_source
|
||||
symbol = asset_cfg.symbol if source == "exchange" else ticker
|
||||
prices, dates = signals.fetch_prices(
|
||||
symbol, interval, period, cfg.exchange, source=source,
|
||||
)
|
||||
if prices is None:
|
||||
click.echo(" ERROR: no data")
|
||||
continue
|
||||
model_cfg = cfg.model_for(asset_cfg)
|
||||
data = signals.prepare_windows(prices, model_cfg.window_size, model_cfg.shift)
|
||||
n = len(data)
|
||||
start_idx = max(int(n * asset_cfg.train_start_pct), 0)
|
||||
end_idx = max(int(n * asset_cfg.train_end_pct), start_idx + 20)
|
||||
train_data = data[start_idx:end_idx]
|
||||
torch.manual_seed(42)
|
||||
np.random.seed(42)
|
||||
mdl = model_mod.create_model(model_cfg)
|
||||
W = np.array([d["norm_input"] for d in train_data])
|
||||
T = np.array([d["norm_target"] for d in train_data])
|
||||
model_mod.train(mdl, W, T, model_cfg.epochs, model_cfg.lr)
|
||||
model_mod.save_model(mdl, ticker)
|
||||
click.echo(f" done ({len(train_data)} windows [{int(asset_cfg.train_start_pct*100)}-{int(asset_cfg.train_end_pct*100)}%])")
|
||||
conn.close()
|
||||
|
||||
|
||||
@main.command()
|
||||
@click.argument("key")
|
||||
@click.argument("value")
|
||||
|
||||
@@ -34,6 +34,8 @@ class AssetConfig:
|
||||
shape_confirm: bool = True # False = skip correlation check entirely
|
||||
market_type: str = "spot" # "spot" or "futures"
|
||||
retrain_enabled: bool = True # False = frozen model (no retrain on losses)
|
||||
train_start_pct: float = 0.0 # training window start (0.0-1.0); 0+0.3 = first 30%
|
||||
train_end_pct: float = 0.3 # training window end (0.0-1.0)
|
||||
|
||||
|
||||
@dataclass
|
||||
|
||||
Reference in New Issue
Block a user