Coverage for train_rl_sizing.py: 100%
354 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-22 12:55 +0000
1"""Offline trainer for the RL sizing overlay (development/Problems.md #71,
2Phase 4.12, Component E) - risk/rl_sizing.py's runtime counterpart.
4Honest framing of what this actually is (read before assuming this is
5online/off-policy RL): `experience_events` (Postgres) is empty and only
6populates in observation mode, and even then the logged action would be a
7constant (main.py has never varied its own sizing action), so there is
8NO usable (state, action, reward) log to learn from off-policy. Instead
9this is a **full-information contextual bandit**: for every historical row
10already in ml/datasets/{train,validation,backtest}_dataset.csv, the reward
11of EVERY candidate sizing multiplier is computable in closed form from the
12already-known forward return (target_return_1d) - no exploration needed,
13because changing a synthetic "what if we'd sized this differently" counter-
14factual doesn't require having actually traded that way historically. This
15is the same sense in which a backtest itself is a full-information replay,
16not live exploration - it adds no new kind of lookahead risk beyond what
17`aq backtest` already carries.
19Split discipline (avoids stacking circularity, same reasoning
20train_gating.py's docstring already established for the identical
21concern): the multitask model's rank_20d head is already fit on `train`,
22so this trainer fits its policy on `validation` (early-stopped on its own
23internal held-out slice) and reports final numbers on `backtest` - never
24touches `train`.
26KNOWN SIMPLIFICATION, stated plainly rather than silently baked in: the
27per-row "base weight" this trainer scales is NOT a full replay of
28production's cross-sectional top_n/bottom_n book-construction pipeline
29(portfolio/book_construction.py) - that would require reconstructing the
30full historical daily cross-section's rank ordering, a materially larger
31undertaking that was not built. Instead, base_weight is a fixed
32nominal per-position weight (config-controlled) scaled by the SAME
33confidence formula main.py:1709 already uses for its rank-based book
34(`min(1.0, abs(predicted_rank_20d - 0.5) * 2.0)`), with predicted_rank_20d
35itself REAL - replayed through the actual exported multitask model
36(inference.run_exported_multitask_model(), the exact same interpreter
37main.py/moe/gating.py use at runtime), not synthesized. nominal_base_weight
38is calibrated so this trainer's own simulated total fees over the backtest
39split land within the same order of magnitude as the real, observed
40Backtest 1 fee total ($1,641) - see verify_cost_calibration() below and
41this module's __main__ output.
43Usage:
44 python train_rl_sizing.py --version-id <uuid> [--config-path config.json]
46Writes ml/versions/<version_id>/rl_sizing_model.json, rl_sizing_feature_schema.json,
47rl_sizing_training_metrics.json. Exits 0 (not an error) when there isn't
48enough usable data yet - "skipped" must never look like "failed" to the
49caller (aq_cli.py::_train_rl_sizing_only(), mirroring _train_topology_only()).
50"""
52from __future__ import annotations
54import argparse
55import json
56import logging
57import sys
58from datetime import datetime, timezone
59from pathlib import Path
61import numpy as np
62import pandas as pd
64from inference import run_exported_multitask_model
65from risk.rl_sizing import RL_SIZING_STATE_KEYS
67LOGGER = logging.getLogger("aether_quant.train_rl_sizing")
68ROOT = Path(__file__).resolve().parent
69ML_DIR = ROOT / "ml"
70CONFIG_PATH = ROOT / "config.json"
71DATASET_DIR = ML_DIR / "datasets"
72MULTITASK_MODEL_PATH = ML_DIR / "multitask_model.json"
73FEATURE_SCHEMA_PATH = ML_DIR / "feature_schema.json"
75DEFAULT_ACTION_SET = [0.6, 0.8, 1.0]
76DEFAULT_MIN_TRAINING_ROWS = 20000
77DEFAULT_LEARNING_RATE = 0.01
78DEFAULT_EPOCHS = 200
79DEFAULT_L2 = 0.001
80DEFAULT_ENTROPY_BONUS = 0.01
81DEFAULT_COMMISSION_BPS = 1.0
82DEFAULT_NOMINAL_BASE_WEIGHT = 0.05
85def parse_args() -> argparse.Namespace:
86 parser = argparse.ArgumentParser(description="Aether Quant offline RL sizing-policy trainer")
87 parser.add_argument("--version-id", type=str, required=True, help="Candidate model_version_id (UUID)")
88 parser.add_argument("--config-path", type=str, default=str(CONFIG_PATH))
89 parser.add_argument("--dataset-dir", type=str, default=str(DATASET_DIR))
90 parser.add_argument(
91 "--penalty-sweep",
92 type=str,
93 default=None,
94 help="Comma-separated asymmetric_penalty_weight candidates (e.g. 1.0,1.5,2.0,3.0): picked on a chronological "
95 "holdout of the validation split by UNPENALISED reward vs constant 1.0. Overrides phase_v2.rl_sizing.training.penalty_sweep.",
96 )
97 return parser.parse_args()
100def load_rl_sizing_training_config(config_path: Path = CONFIG_PATH) -> dict:
101 with Path(config_path).open("r", encoding="utf-8") as f:
102 config = json.load(f)
103 return config.get("phase_v2", {}).get("rl_sizing", {}).get("training", {})
106def rl_sizing_candidate_output_paths(version_id: str) -> dict[str, Path]:
107 """Own local helper mirroring train_topology.py's
108 topology_candidate_output_paths() / train_gating.py's
109 gating_candidate_output_paths() - kept independent since each writes
110 disjoint filenames."""
111 version_dir = ML_DIR / "versions" / version_id
112 return {
113 "version_dir": version_dir,
114 "rl_sizing_model": version_dir / "rl_sizing_model.json",
115 "rl_sizing_feature_schema": version_dir / "rl_sizing_feature_schema.json",
116 "rl_sizing_training_metrics": version_dir / "rl_sizing_training_metrics.json",
117 }
120def load_multitask_export(path: Path = MULTITASK_MODEL_PATH) -> dict | None:
121 if not path.exists():
122 return None
123 try:
124 with path.open("r", encoding="utf-8") as f:
125 return json.load(f)
126 except (OSError, ValueError):
127 return None
130# ---------------------------------------------------------------------------
131# Pure helpers - unit-tested directly (train_topology.py's own convention:
132# pure functions get real coverage, main()'s file I/O does not).
133# ---------------------------------------------------------------------------
136def compute_action_reward(
137 action: float,
138 base_weight: float,
139 direction: float,
140 forward_return: float,
141 prior_action_weight: float,
142 turnover_cost_bps: float,
143 commission_bps: float,
144 *,
145 asymmetric_penalty_weight: float = 1.0,
146) -> float:
147 """r(s, a) = a*w*dir*ret - turnover_cost - commission.
149 V5.4.1 - adds an ASYMMETRIC PENALTY when the action reduces exposure to
150 a winning trade or increases exposure to a losing trade, weighted by
151 `asymmetric_penalty_weight` (> 1.0 penalizes leaving profit on the table
152 more than taking on slightly-larger losers). This is the root-cause fix
153 for the honest negative result found three times previously (#71/Phase
154 4.12 lineage): the old symmetric reward made undersizing a winner and
155 oversizing a loser cost IDENTICALLY, so the policy's optimal strategy
156 was always "do nothing" (= constant 1.0 baseline), which it correctly
157 learned every time.
159 Never raises - all inputs are plain floats."""
160 sized_weight = action * base_weight
161 gross = sized_weight * direction * forward_return
162 weight_delta = abs(sized_weight - prior_action_weight)
163 turnover_cost = (turnover_cost_bps / 1e4) * weight_delta
164 commission_cost = (commission_bps / 1e4) if weight_delta > 1e-12 else 0.0
166 # V5.4.1 asymmetric penalty: if the trade WOULD have been profitable at
167 # full size but this action shrinks it, the foregone profit is a real
168 # cost the symmetric formula ignored. Only applies to REDUCED exposure
169 # on winning trades (direction * forward_return > 0). At
170 # asymmetric_penalty_weight=1.0 the penalty is exactly zero (backwards-
171 # compatible with the pre-V5.4.1 formula); values above 1.0 scale it.
172 opportunity_cost = 0.0
173 if forward_return != 0.0 and direction != 0.0 and asymmetric_penalty_weight > 1.0:
174 full_size_gross = base_weight * direction * forward_return
175 if full_size_gross > 0 and sized_weight < base_weight:
176 excess = asymmetric_penalty_weight - 1.0
177 opportunity_cost = (base_weight - sized_weight) * abs(forward_return) * excess
179 return gross - turnover_cost - commission_cost - opportunity_cost
182def standardize_states(states: np.ndarray) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
183 """Returns (standardized, mean, scale). scale falls back to 1.0 for a
184 zero-variance column (a constant feature must not divide-by-zero into
185 NaN/inf - it becomes a harmless always-zero standardized column)."""
186 mean = states.mean(axis=0)
187 scale = states.std(axis=0)
188 scale = np.where(scale > 1e-12, scale, 1.0)
189 return (states - mean) / scale, mean, scale
192def fit_policy(
193 standardized_states: np.ndarray,
194 rewards_by_action: np.ndarray,
195 learning_rate: float = DEFAULT_LEARNING_RATE,
196 epochs: int = DEFAULT_EPOCHS,
197 l2: float = DEFAULT_L2,
198 entropy_bonus: float = DEFAULT_ENTROPY_BONUS,
199 seed: int = 0,
200) -> dict:
201 """Exact softmax policy-gradient with a full-information baseline (the
202 expected reward under the current policy) - full-batch, plain numpy,
203 no exploration needed since every action's reward is already known for
204 every row (see this module's docstring). weights initialized to ZERO
205 so the untrained policy is exactly uniform-softmax; the tie-break in
206 risk/rl_sizing.py::_softmax_argmax_index() then prefers the LAST
207 (largest-multiplier, closest-to-no-op) action - an untrained model is
208 a strict no-op by construction, never an arbitrary one.
210 rewards_by_action: shape (n_rows, n_actions). Returns
211 {"weights": (n_actions, n_features), "bias": (n_actions,),
212 "history": [mean_expected_reward per epoch]} as plain nested lists,
213 JSON-serializable directly."""
214 _rng = np.random.default_rng(seed)
215 n_rows, n_features = standardized_states.shape
216 n_actions = rewards_by_action.shape[1]
217 weights = np.zeros((n_actions, n_features))
218 bias = np.zeros(n_actions)
219 history: list[float] = []
221 for _ in range(epochs):
222 scores = standardized_states @ weights.T + bias # (n_rows, n_actions)
223 scores = scores - scores.max(axis=1, keepdims=True) # numerical stability
224 exp_scores = np.exp(scores)
225 policy = exp_scores / exp_scores.sum(axis=1, keepdims=True) # (n_rows, n_actions)
227 expected_reward = float((policy * rewards_by_action).sum(axis=1).mean())
228 history.append(expected_reward)
230 baseline = (policy * rewards_by_action).sum(axis=1, keepdims=True) # (n_rows, 1)
231 advantage = rewards_by_action - baseline # (n_rows, n_actions)
232 # d(expected_reward)/d(scores) for a softmax policy with this
233 # full-information baseline: policy * advantage, averaged over rows.
234 grad_scores = policy * advantage / n_rows
236 # Entropy bonus (encourages non-degenerate policies early in
237 # training; decayed implicitly by leaving epochs finite - never
238 # added at inference, only shapes the fit).
239 if entropy_bonus > 0.0:
240 entropy_grad = -policy * (np.log(policy + 1e-12) + 1.0) / n_rows
241 grad_scores = grad_scores + entropy_bonus * entropy_grad
243 grad_weights = grad_scores.T @ standardized_states - l2 * weights
244 grad_bias = grad_scores.sum(axis=0)
246 # Gradient ASCENT (maximizing expected reward), not descent.
247 weights = weights + learning_rate * grad_weights
248 bias = bias + learning_rate * grad_bias
250 return {"weights": weights.tolist(), "bias": bias.tolist(), "history": history}
253def evaluate_policy_expected_reward(
254 standardized_states: np.ndarray, rewards_by_action: np.ndarray, weights: np.ndarray, bias: np.ndarray
255) -> float:
256 """Argmax (not softmax-expectation) evaluation - matches
257 risk/rl_sizing.py's real inference-time behavior (deterministic argmax,
258 never sampled), so this number is what the policy would actually earn
259 live, not an optimistic softmax-averaged estimate."""
260 scores = standardized_states @ weights.T + bias
261 best_actions = scores.argmax(axis=1)
262 return float(rewards_by_action[np.arange(len(rewards_by_action)), best_actions].mean())
265def action_distribution(standardized_states: np.ndarray, weights: np.ndarray, bias: np.ndarray, n_actions: int) -> list[int]:
266 """Histogram of argmax action choices - used to detect a degenerate
267 (constant-action) policy, this module's #1 abandon criterion."""
268 scores = standardized_states @ weights.T + bias
269 best_actions = scores.argmax(axis=1)
270 return [int((best_actions == index).sum()) for index in range(n_actions)]
273# ---------------------------------------------------------------------------
274# Dataset construction (uses the real exported multitask model - replay,
275# not synthesis)
276# ---------------------------------------------------------------------------
279def build_bandit_rows(
280 frame: pd.DataFrame,
281 multitask_export: dict,
282 model_input_names: list[str],
283 action_set: list[float],
284 turnover_cost_bps_column: str,
285 commission_bps: float,
286 nominal_base_weight: float,
287 asymmetric_penalty_weight: float = 1.0,
288 with_unpenalized: bool = False,
289) -> tuple[np.ndarray, ...]:
290 """Builds (states, rewards_by_action) arrays from one dataset split; with
291 `with_unpenalized` also the same rewards WITHOUT the asymmetric penalty as a third array - the
292 penalty shapes the policy being fit, but only real (unpenalised) P&L may judge it against the
293 constant-1.0 baseline, which pays no penalty by construction.
294 Skips rows with a missing target_return_1d, a missing state key, or a
295 failed model replay - never raises, matching every other trainer's
296 "skip the bad row, don't abort the run" convention.
298 Ticker-scoped prior_action_weight (for turnover-cost continuity) resets
299 to 0.0 at the start of each ticker's own date-sorted sequence - a
300 fresh position, not a carried-over one from a different asset."""
301 states: list[list[float]] = []
302 rewards: list[list[float]] = []
303 plain_rewards: list[list[float]] = []
305 for _, ticker_frame in frame.groupby("ticker", sort=False):
306 ticker_frame = ticker_frame.sort_values("date")
307 prior_action_weight = dict.fromkeys(action_set, 0.0)
308 for _, row in ticker_frame.iterrows():
309 forward_return = row.get("target_return_1d")
310 if pd.isna(forward_return):
311 continue
312 if any(key != "confidence" and (key not in row or pd.isna(row[key])) for key in RL_SIZING_STATE_KEYS):
313 continue
315 model_inputs = [float(row[name]) for name in model_input_names if name in row]
316 if len(model_inputs) != len(model_input_names):
317 continue
318 try:
319 prediction = run_exported_multitask_model(multitask_export, model_inputs)
320 except Exception:
321 continue
322 predicted_rank_20d = prediction.get("rank_20d")
323 if predicted_rank_20d is None:
324 continue
325 confidence = min(1.0, abs(float(predicted_rank_20d) - 0.5) * 2.0)
326 direction = 1.0 if predicted_rank_20d >= 0.5 else -1.0
327 base_weight = nominal_base_weight * confidence
328 turnover_cost_bps = float(row.get(turnover_cost_bps_column, 0.0) or 0.0)
330 state_vector = [confidence if key == "confidence" else float(row[key]) for key in RL_SIZING_STATE_KEYS]
331 row_rewards = []
332 row_plain_rewards = []
333 for action in action_set:
334 reward = compute_action_reward(
335 action, base_weight, direction, float(forward_return),
336 prior_action_weight[action], turnover_cost_bps, commission_bps,
337 asymmetric_penalty_weight=asymmetric_penalty_weight,
338 )
339 row_rewards.append(reward)
340 if with_unpenalized:
341 row_plain_rewards.append(
342 reward
343 if asymmetric_penalty_weight <= 1.0
344 else compute_action_reward(
345 action, base_weight, direction, float(forward_return),
346 prior_action_weight[action], turnover_cost_bps, commission_bps,
347 )
348 )
349 prior_action_weight[action] = action * base_weight
351 states.append(state_vector)
352 rewards.append(row_rewards)
353 plain_rewards.append(row_plain_rewards)
355 if not states:
356 empty = (np.empty((0, len(RL_SIZING_STATE_KEYS))), np.empty((0, len(action_set))))
357 return (*empty, np.empty((0, len(action_set)))) if with_unpenalized else empty
358 result = (np.asarray(states, dtype=np.float64), np.asarray(rewards, dtype=np.float64))
359 return (*result, np.asarray(plain_rewards, dtype=np.float64)) if with_unpenalized else result
362# ---------------------------------------------------------------------------
363# V5.7.0 - book-level reward. The daily/all-rows bandit above rewards a 1-day return on every row with a flat 1 bp
364# commission; the book trades a handful of names every 10 bars and holds ~20 days, and a forex order pays IB's dollar
365# minimum. This variant scores only would-be book members at the rebalance cadence on their 20-day return, net of the
366# per-class fee (minimum included) and the round-trip spread, and lets the action set include 0 (skip) and sizes above 1.
367# ---------------------------------------------------------------------------
370def fee_fraction_of_nav(security_type: str, notional_usd: float, nav: float, costs_config: dict) -> float:
371 """Round-trip commission of one position of `notional_usd` as a fraction of NAV: each side pays
372 max(rate x notional, dollar minimum) (execution.cost_model's terms, the net-edge gate's definition)."""
373 from execution.cost_model import commission_terms_for_security_type
375 if notional_usd <= 0.0 or nav <= 0.0:
376 return 0.0
377 rate_bps, min_usd = commission_terms_for_security_type(costs_config, security_type)
378 per_side = max(notional_usd * rate_bps / 1e4, min_usd)
379 return 2.0 * per_side / nav
382def compute_book_action_reward(
383 action: float,
384 base_weight: float,
385 direction: float,
386 forward_return: float,
387 *,
388 nav: float,
389 security_type: str,
390 spread_fraction: float,
391 costs_config: dict,
392) -> float:
393 """r(s, a) = a*w*dir*ret_20d - round-trip fee (dollar minimum included) - round-trip spread. Action 0 skips the
394 trade: reward exactly 0 (no fee). Never raises."""
395 sized_weight = action * base_weight
396 if sized_weight <= 0.0:
397 return 0.0
398 gross = sized_weight * direction * forward_return
399 fee = fee_fraction_of_nav(security_type, sized_weight * nav, nav, costs_config)
400 return gross - fee - spread_fraction * sized_weight
403def build_book_member_rows(
404 frame: pd.DataFrame,
405 multitask_export: dict,
406 model_input_names: list[str],
407 action_set: list[float],
408 state_keys: list[str],
409 *,
410 asset_class_by_ticker: dict[str, str],
411 pool_classes: list[str],
412 per_side: int,
413 rebalance_every: int,
414 nominal_base_weight: float,
415 nav: float,
416 costs_config: dict,
417 spread_caps: dict | None = None,
418 target_column: str = "target_return_20d",
419) -> tuple[np.ndarray, np.ndarray]:
420 """(states, rewards_by_action) for the would-be book members of `pool_classes` on every `rebalance_every`-th date:
421 the top/bottom `per_side` of the pool by the model's rank_20d, confidence from the pool's own percentile (the live
422 formula), base weight `nominal_base_weight`. Rows with a missing target / state value or a failed replay are skipped."""
423 from liquidity.market_liquidity import cap_spread_proxy
424 from portfolio.rank_signal import cross_sectional_rank_scores
426 states: list[list[float]] = []
427 rewards: list[list[float]] = []
428 pool = set(pool_classes)
429 dates = sorted(frame["date"].astype(str).unique())[:: max(1, rebalance_every)]
430 for date in dates:
431 day = frame[(frame["date"].astype(str) == date) & frame["ticker"].map(lambda t: asset_class_by_ticker.get(t) in pool)]
432 predictions: dict[str, tuple[float, pd.Series]] = {}
433 for _, row in day.iterrows():
434 inputs = [float(row[name]) for name in model_input_names if name in row and not pd.isna(row[name])]
435 if len(inputs) != len(model_input_names):
436 continue
437 try:
438 prediction = run_exported_multitask_model(multitask_export, inputs).get("rank_20d")
439 except Exception:
440 continue
441 if prediction is not None:
442 predictions[str(row["ticker"])] = (float(prediction), row)
443 if len(predictions) < 2 * per_side + 2:
444 continue
445 percentiles = cross_sectional_rank_scores({ticker: score for ticker, (score, _row) in predictions.items()})
446 ordered = sorted(percentiles, key=percentiles.get)
447 members = [(ticker, -1.0) for ticker in ordered[:per_side]] + [(ticker, 1.0) for ticker in ordered[-per_side:]]
448 for ticker, direction in members:
449 row = predictions[ticker][1]
450 forward_return = row.get(target_column)
451 if pd.isna(forward_return):
452 continue
453 confidence = min(1.0, abs(percentiles[ticker] - 0.5) * 2.0)
454 extra = {"confidence": confidence, "log_order_notional": float(np.log(max(nominal_base_weight * nav, 1.0)))}
455 values = []
456 for key in state_keys:
457 value = extra[key] if key in extra else row.get(key)
458 if value is None or pd.isna(value):
459 values = None
460 break
461 values.append(float(value))
462 if values is None:
463 continue
464 security_type = asset_class_by_ticker.get(ticker, "equity")
465 spread = cap_spread_proxy(float(row.get("liquidity_spread_proxy", 0.0) or 0.0), security_type, spread_caps) or 0.0
466 states.append(values)
467 rewards.append(
468 [
469 compute_book_action_reward(
470 action, nominal_base_weight, direction, float(forward_return), nav=nav, security_type=security_type,
471 spread_fraction=float(spread), costs_config=costs_config,
472 )
473 for action in action_set
474 ]
475 )
476 if not states:
477 return np.empty((0, len(state_keys))), np.empty((0, len(action_set)))
478 return np.asarray(states, dtype=np.float64), np.asarray(rewards, dtype=np.float64)
481def select_penalty_weight(
482 validation_frame: pd.DataFrame,
483 multitask_export: dict,
484 model_input_names: list[str],
485 action_set: list[float],
486 turnover_cost_bps_column: str,
487 commission_bps: float,
488 nominal_base_weight: float,
489 candidate_weights: list[float],
490 *,
491 holdout_fraction: float = 0.33,
492 min_fit_rows: int = 1000,
493 fit_kwargs: dict | None = None,
494) -> dict:
495 """Pick `asymmetric_penalty_weight` without touching the backtest split: fit each candidate on the
496 EARLY part of the validation split (penalised reward), score it on the LATE part by unpenalised
497 reward against constant 1.0, and take the best margin. `selected_beats_constant` says whether even
498 the best candidate cleared the constant baseline - false is the honest fourth negative, not an error.
499 Returns {"selected": weight, "selected_beats_constant": bool, "table": [...], "reason": str}."""
500 fit_kwargs = fit_kwargs or {}
501 if 1.0 not in action_set or not candidate_weights:
502 return {"selected": 1.0, "selected_beats_constant": False, "table": [], "reason": "no_baseline_action_or_no_candidates"}
503 dates = sorted(validation_frame["date"].astype(str).unique())
504 if len(dates) < 20:
505 return {"selected": 1.0, "selected_beats_constant": False, "table": [], "reason": "too_few_validation_dates"}
506 cut = dates[int(len(dates) * (1.0 - holdout_fraction))]
507 fit_frame = validation_frame[validation_frame["date"].astype(str) < cut]
508 hold_frame = validation_frame[validation_frame["date"].astype(str) >= cut]
509 hold_states, _, hold_plain = build_bandit_rows(
510 hold_frame, multitask_export, model_input_names, action_set,
511 turnover_cost_bps_column, commission_bps, nominal_base_weight, with_unpenalized=True,
512 )
513 if len(hold_states) == 0:
514 return {"selected": 1.0, "selected_beats_constant": False, "table": [], "reason": "empty_holdout"}
515 baseline = float(hold_plain[:, action_set.index(1.0)].mean())
516 table = []
517 for weight in candidate_weights:
518 fit_states, fit_rewards = build_bandit_rows(
519 fit_frame, multitask_export, model_input_names, action_set,
520 turnover_cost_bps_column, commission_bps, nominal_base_weight, asymmetric_penalty_weight=float(weight),
521 )
522 if len(fit_states) < min_fit_rows:
523 table.append({"weight": float(weight), "skipped": "too_few_fit_rows", "fit_rows": int(len(fit_states))})
524 continue
525 standardized_fit, mean, scale = standardize_states(fit_states)
526 fitted = fit_policy(standardized_fit, fit_rewards, **fit_kwargs)
527 policy_reward = evaluate_policy_expected_reward(
528 (hold_states - mean) / scale, hold_plain, np.asarray(fitted["weights"]), np.asarray(fitted["bias"])
529 )
530 table.append({
531 "weight": float(weight), "holdout_policy_reward": policy_reward,
532 "holdout_constant_reward": baseline, "margin": policy_reward - baseline, "fit_rows": int(len(fit_states)),
533 })
534 scored = [row for row in table if "margin" in row]
535 if not scored:
536 return {"selected": 1.0, "selected_beats_constant": False, "table": table, "reason": "no_candidate_had_enough_rows"}
537 best = max(scored, key=lambda row: row["margin"])
538 return {
539 "selected": best["weight"], "selected_beats_constant": best["margin"] > 0.0, "table": table, "reason": "selected_by_holdout_margin",
540 }
543def train_book_level_policy(args: argparse.Namespace, config: dict, training_config: dict) -> int:
544 """`reward_mode: "book_member_20d"` (V5.7.0): fit on the validation split's would-be book members, judge on the
545 backtest split (and the holdout when `--holdout-dataset` exists), against constant 1.0 and skip-everything. Writes
546 `rl_sizing_forex_*` artifacts when the pool is forex. The verdict is `policy_beats_constant_unpenalized` on BOTH."""
547 from risk.rl_sizing import FOREX_RL_SIZING_STATE_KEYS
549 action_set = [float(a) for a in training_config.get("action_set", [0.0, 0.6, 1.0, 1.25, 1.5])]
550 pool_classes = [str(c) for c in training_config.get("book_pool_classes", ["forex"])]
551 state_keys = list(FOREX_RL_SIZING_STATE_KEYS) if pool_classes == ["forex"] else list(RL_SIZING_STATE_KEYS)
552 prefix = "rl_sizing_forex" if pool_classes == ["forex"] else "rl_sizing"
553 nav = float(config.get("runtime", {}).get("initial_cash", 100_000) or 100_000)
554 nominal = float(training_config.get("book_nominal_weight", 0.08))
555 per_side = int(training_config.get("book_per_side", 2 if pool_classes == ["forex"] else 6))
556 cadence = int(training_config.get("book_rebalance_every", 10))
557 asset_class_by_ticker = {
558 a["ticker"]: str(a.get("asset_class") or a.get("security_type")) for a in config["phase1"]["universe"]["assets"]
559 }
560 costs_config = config.get("phase_v2", {}).get("costs", {})
561 spread_caps = config.get("phase_v2", {}).get("liquidity", {}).get("max_spread_proxy_by_type", {})
562 multitask_export = load_multitask_export()
563 dataset_dir = Path(args.dataset_dir)
564 schema_path = FEATURE_SCHEMA_PATH
565 if multitask_export is None or not (dataset_dir / "validation_dataset.csv").exists() or not schema_path.exists():
566 LOGGER.info("train_rl_sizing(book): multitask model or datasets not found - skipping.")
567 return 0
568 model_input_names = json.loads(schema_path.read_text(encoding="utf-8"))["model_input_names"]
569 common = dict(
570 asset_class_by_ticker=asset_class_by_ticker, pool_classes=pool_classes, per_side=per_side, rebalance_every=cadence,
571 nominal_base_weight=nominal, nav=nav, costs_config=costs_config, spread_caps=spread_caps,
572 )
573 splits: dict[str, tuple[np.ndarray, np.ndarray]] = {}
574 for name, filename in (("validation", "validation_dataset.csv"), ("backtest", "backtest_dataset.csv"), ("holdout", "holdout_dataset.csv")):
575 path = dataset_dir / filename
576 if not path.exists():
577 continue
578 frame = pd.read_csv(path)
579 if name == "holdout" and "split" in frame.columns:
580 frame = frame[frame["split"] == "backtest"]
581 splits[name] = build_book_member_rows(frame, multitask_export, model_input_names, action_set, state_keys, **common)
582 train_states, train_rewards = splits.get("validation", (np.empty((0, len(state_keys))), np.empty((0, len(action_set)))))
583 minimum = int(training_config.get("book_min_training_rows", 200))
584 if len(train_states) < minimum:
585 LOGGER.info("train_rl_sizing(book): only %d usable rows (need %d) - skipping.", len(train_states), minimum)
586 return 0
587 standardized, mean, scale = standardize_states(train_states)
588 fit = fit_policy(
589 standardized, train_rewards, float(training_config.get("learning_rate", DEFAULT_LEARNING_RATE)),
590 int(training_config.get("epochs", DEFAULT_EPOCHS)), float(training_config.get("l2", DEFAULT_L2)),
591 float(training_config.get("entropy_bonus", DEFAULT_ENTROPY_BONUS)),
592 )
593 weights, bias = np.asarray(fit["weights"]), np.asarray(fit["bias"])
594 one, zero = action_set.index(1.0) if 1.0 in action_set else None, action_set.index(0.0) if 0.0 in action_set else None
595 judged = {}
596 for name, (states, rewards) in splits.items():
597 if name == "validation" or len(states) == 0:
598 continue
599 standardized_eval = (states - mean) / scale
600 judged[name] = {
601 "rows": int(len(states)),
602 "policy_reward": evaluate_policy_expected_reward(standardized_eval, rewards, weights, bias),
603 "constant_1_0_reward": float(rewards[:, one].mean()) if one is not None else None,
604 "skip_all_reward": float(rewards[:, zero].mean()) if zero is not None else None,
605 "action_distribution": action_distribution(standardized_eval, weights, bias, len(action_set)),
606 }
607 judged[name]["beats_constant"] = bool(
608 judged[name]["constant_1_0_reward"] is not None and judged[name]["policy_reward"] > judged[name]["constant_1_0_reward"]
609 )
610 verdict = bool(judged) and all(entry["beats_constant"] for name, entry in judged.items() if name in ("backtest", "holdout"))
611 trained_at = datetime.now(timezone.utc).isoformat()
612 paths = rl_sizing_candidate_output_paths(args.version_id)
613 paths["version_dir"].mkdir(parents=True, exist_ok=True)
614 (paths["version_dir"] / f"{prefix}_model.json").write_text(
615 json.dumps(
616 {
617 "version_id": args.version_id, "trained_at": trained_at, "state_keys": state_keys, "actions": action_set,
618 "weights": fit["weights"], "bias": fit["bias"], "mean": mean.tolist(), "scale": scale.tolist(),
619 "pool_classes": pool_classes, "reward_mode": "book_member_20d",
620 },
621 indent=2,
622 ),
623 encoding="utf-8",
624 )
625 (paths["version_dir"] / f"{prefix}_training_metrics.json").write_text(
626 json.dumps(
627 {
628 "version_id": args.version_id, "trained_at": trained_at, "reward_mode": "book_member_20d",
629 "pool_classes": pool_classes, "training_rows": int(len(train_states)), "action_set": action_set,
630 "training_action_distribution": action_distribution(standardized, weights, bias, len(action_set)),
631 "judged": judged, "policy_beats_constant_unpenalized": verdict,
632 },
633 indent=2,
634 ),
635 encoding="utf-8",
636 )
637 LOGGER.info("train_rl_sizing(book): %s -> beats constant 1.0 on every judged split: %s", judged, verdict)
638 return 0
641def main() -> int:
642 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s")
643 args = parse_args()
645 try:
646 training_config = load_rl_sizing_training_config(Path(args.config_path))
647 if str(training_config.get("reward_mode", "daily_all_rows")) == "book_member_20d":
648 with Path(args.config_path).open("r", encoding="utf-8") as f:
649 return train_book_level_policy(args, json.load(f), training_config)
650 action_set = [float(a) for a in training_config.get("action_set", DEFAULT_ACTION_SET)]
651 min_training_rows = int(training_config.get("min_training_rows", DEFAULT_MIN_TRAINING_ROWS))
652 learning_rate = float(training_config.get("learning_rate", DEFAULT_LEARNING_RATE))
653 epochs = int(training_config.get("epochs", DEFAULT_EPOCHS))
654 l2 = float(training_config.get("l2", DEFAULT_L2))
655 entropy_bonus = float(training_config.get("entropy_bonus", DEFAULT_ENTROPY_BONUS))
656 commission_bps = float(training_config.get("commission_bps", DEFAULT_COMMISSION_BPS))
657 nominal_base_weight = float(training_config.get("nominal_base_weight", DEFAULT_NOMINAL_BASE_WEIGHT))
658 # V5.4.5 (development/Problems.md #119): V5.4.1's asymmetric
659 # penalty existed only behind this parameter - which nothing ever
660 # loaded from config or passed through, so every real training run
661 # silently used the symmetric reward (opportunity_cost exactly 0.0)
662 # while the changelog claimed the fix. Wired now; default 1.0 keeps
663 # any existing behavior byte-identical until the key is set.
664 asymmetric_penalty_weight = float(training_config.get("asymmetric_penalty_weight", 1.0))
665 turnover_cost_bps_column = "liquidity_spread_proxy"
667 multitask_export = load_multitask_export()
668 dataset_dir = Path(args.dataset_dir)
669 validation_path = dataset_dir / "validation_dataset.csv"
670 backtest_path = dataset_dir / "backtest_dataset.csv"
671 schema_path = FEATURE_SCHEMA_PATH
673 if multitask_export is None or not validation_path.exists() or not backtest_path.exists() or not schema_path.exists():
674 LOGGER.info(
675 "train_rl_sizing: multitask model or dataset/schema files not found yet - skipping, not writing artifacts."
676 )
677 return 0
679 feature_schema = json.loads(schema_path.read_text(encoding="utf-8"))
680 model_input_names = feature_schema["model_input_names"]
682 validation_frame = pd.read_csv(validation_path)
683 backtest_frame = pd.read_csv(backtest_path)
685 sweep_candidates = (
686 [float(item) for item in args.penalty_sweep.split(",") if item.strip()]
687 if args.penalty_sweep
688 else [float(item) for item in training_config.get("penalty_sweep", [])]
689 )
690 penalty_sweep_result = None
691 if sweep_candidates:
692 penalty_sweep_result = select_penalty_weight(
693 validation_frame, multitask_export, model_input_names, action_set,
694 turnover_cost_bps_column, commission_bps, nominal_base_weight, sweep_candidates,
695 fit_kwargs={"learning_rate": learning_rate, "epochs": epochs, "l2": l2, "entropy_bonus": entropy_bonus},
696 )
697 asymmetric_penalty_weight = float(penalty_sweep_result["selected"])
698 LOGGER.info(
699 "train_rl_sizing: penalty sweep selected %.2f (%s, beats constant: %s)",
700 asymmetric_penalty_weight, penalty_sweep_result["reason"], penalty_sweep_result["selected_beats_constant"],
701 )
703 train_states, train_rewards = build_bandit_rows(
704 validation_frame, multitask_export, model_input_names, action_set,
705 turnover_cost_bps_column, commission_bps, nominal_base_weight,
706 asymmetric_penalty_weight=asymmetric_penalty_weight,
707 )
708 if len(train_states) < min_training_rows:
709 LOGGER.info(
710 "train_rl_sizing: only %d usable rows (need %d) - skipping, not writing artifacts.",
711 len(train_states), min_training_rows,
712 )
713 return 0
715 standardized_train, mean, scale = standardize_states(train_states)
716 fit_result = fit_policy(standardized_train, train_rewards, learning_rate, epochs, l2, entropy_bonus)
717 weights = np.asarray(fit_result["weights"])
718 bias = np.asarray(fit_result["bias"])
720 backtest_states, backtest_rewards, backtest_plain_rewards = build_bandit_rows(
721 backtest_frame, multitask_export, model_input_names, action_set,
722 turnover_cost_bps_column, commission_bps, nominal_base_weight,
723 asymmetric_penalty_weight=asymmetric_penalty_weight, with_unpenalized=True,
724 )
725 standardized_backtest = (backtest_states - mean) / scale if len(backtest_states) else backtest_states
727 constant_policy_expected_reward = float(train_rewards[:, action_set.index(1.0)].mean()) if 1.0 in action_set else None
728 trained_at = datetime.now(timezone.utc).isoformat()
730 model_payload = {
731 "version_id": args.version_id,
732 "trained_at": trained_at,
733 "state_keys": list(RL_SIZING_STATE_KEYS),
734 "actions": action_set,
735 "weights": fit_result["weights"],
736 "bias": fit_result["bias"],
737 "mean": mean.tolist(),
738 "scale": scale.tolist(),
739 }
740 feature_schema_payload = {"state_keys": list(RL_SIZING_STATE_KEYS)}
741 training_metrics_payload = {
742 "project": "aether_quant",
743 "phase": "Phase 4.12 Component E",
744 "version_id": args.version_id,
745 "trained_at": trained_at,
746 "training_rows": int(len(train_states)),
747 "backtest_rows": int(len(backtest_states)),
748 "action_set": action_set,
749 "asymmetric_penalty_weight": asymmetric_penalty_weight,
750 "training_history_expected_reward": fit_result["history"],
751 "training_action_distribution": (
752 action_distribution(standardized_train, weights, bias, len(action_set))
753 ),
754 "backtest_action_distribution": (
755 action_distribution(standardized_backtest, weights, bias, len(action_set))
756 if len(backtest_states) else None
757 ),
758 "backtest_policy_expected_reward": (
759 evaluate_policy_expected_reward(standardized_backtest, backtest_rewards, weights, bias)
760 if len(backtest_states) else None
761 ),
762 "backtest_constant_action_1_0_expected_reward": (
763 float(backtest_rewards[:, action_set.index(1.0)].mean())
764 if len(backtest_states) and 1.0 in action_set else None
765 ),
766 "training_constant_action_1_0_expected_reward": constant_policy_expected_reward,
767 "penalty_sweep": penalty_sweep_result,
768 # Judged on REAL P&L: the penalised numbers above compare a penalty-trained policy to a
769 # baseline that pays no penalty, so they can only ever favour the baseline.
770 "backtest_policy_expected_reward_unpenalized": (
771 evaluate_policy_expected_reward(standardized_backtest, backtest_plain_rewards, weights, bias)
772 if len(backtest_states) else None
773 ),
774 "backtest_constant_action_1_0_expected_reward_unpenalized": (
775 float(backtest_plain_rewards[:, action_set.index(1.0)].mean())
776 if len(backtest_states) and 1.0 in action_set else None
777 ),
778 }
779 policy_unpenalized = training_metrics_payload["backtest_policy_expected_reward_unpenalized"]
780 constant_unpenalized = training_metrics_payload["backtest_constant_action_1_0_expected_reward_unpenalized"]
781 training_metrics_payload["policy_beats_constant_unpenalized"] = (
782 bool(policy_unpenalized > constant_unpenalized) if policy_unpenalized is not None and constant_unpenalized is not None else None
783 )
785 paths = rl_sizing_candidate_output_paths(args.version_id)
786 paths["version_dir"].mkdir(parents=True, exist_ok=True)
787 paths["rl_sizing_model"].write_text(json.dumps(model_payload, indent=2), encoding="utf-8")
788 paths["rl_sizing_feature_schema"].write_text(json.dumps(feature_schema_payload, indent=2), encoding="utf-8")
789 paths["rl_sizing_training_metrics"].write_text(json.dumps(training_metrics_payload, indent=2), encoding="utf-8")
791 LOGGER.info(
792 "train_rl_sizing: wrote artifacts for version %s (%d training rows, %d backtest rows).",
793 args.version_id, len(train_states), len(backtest_states),
794 )
795 return 0
796 except Exception as exc: # never let an unexpected failure look ambiguous to the caller
797 LOGGER.error("train_rl_sizing: unexpected failure - %s", exc)
798 return 1
801if __name__ == "__main__":
802 sys.exit(main())