feat(quant-engine): v8.9 제안서 P0-P3 로드맵 채택 — 15개 의사결정 엔진 신규 구현
suggest/quant_investment_engine_v8_9_portfolio_optimizer_canonical_refactored.yaml의
implementation_todo_v8_9(P0~P4) 전체를 spec/tool/golden case 레벨로 구현.
- P0: PORTFOLIO_TRANSITION_UTILITY_V1, SELL_LOT_PARETO_SELECTOR_V1, FORECAST_SIMULATION_ENGINE_V1
- P1: SECTOR_EXPOSURE_GRAPH_V1/LEADER_LIFECYCLE_GATE_V1, EXECUTION_CAPACITY_LADDER_V1, MODEL_GOVERNANCE_KILL_SWITCH_V1
- P2: SCENARIO_SHOCK_MATRIX_V1, TRANSITION_SET_ENUMERATOR_V1, IMMUTABLE_DECISION_LEDGER_V1, EXECUTION_PLAN_COMPILER_V1
- P3: STATE_VECTOR_CONSTRUCTOR_V1, WALK_FORWARD_BOOTSTRAP_V1, TRANSITION_SET_ENUMERATOR_V1(MRC/CVaR 확장),
REBALANCE_CADENCE_GATE_V1, WEEKLY_LEGACY_TRANSFER_PLAN_V1
기존 regime/cluster 연동 정책 수치(현금방어선, 반도체 cap)는 그대로 유지하고 신규 cap 필드만 추가.
spec/09_decision_flow.yaml과 runtime/active_artifact_manifest.yaml에 전 엔진 배선 완료.
governance/todo/v8_9_p{0,1,2,3}_adoption_plan.yaml에 각 단계 작업 추적 기록.
검증: validate_specs/validate_golden_coverage_100(100%)/validate_calibration_registry_v1/
validate_schema_model_generation_v1/validate_agents_shrink_v1 전부 PASS. golden test 53/53 PASS.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,153 @@
|
||||
#!/usr/bin/env python3
|
||||
"""TRANSITION_SET_ENUMERATOR_V1 — spec/formulas/domains/portfolio.yaml.
|
||||
|
||||
Evaluates combinations of already-vetoed candidates as a portfolio-level set,
|
||||
so individually-passing candidates that jointly breach cash floor or
|
||||
concentration caps are rejected. governance/todo/v8_9_p2_adoption_plan.yaml P2-B.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import itertools
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DEFAULT_TRANSITION_OPTIMIZER = ROOT / "Temp" / "portfolio_transition_optimizer_v1.json"
|
||||
DEFAULT_OUT = ROOT / "Temp" / "transition_set_enumerator_v1.json"
|
||||
|
||||
COMPLEXITY_PENALTY_RATE_KRW = 5000.0
|
||||
|
||||
|
||||
def _load(path: Path) -> dict:
|
||||
if not path.exists():
|
||||
return {}
|
||||
try:
|
||||
data = json.loads(path.read_text(encoding="utf-8"))
|
||||
return data if isinstance(data, dict) else {}
|
||||
except Exception:
|
||||
return {}
|
||||
|
||||
|
||||
def post_trade_mrc(transition_set: tuple[dict, ...], portfolio_total_risk_budget: float) -> float | None:
|
||||
if not portfolio_total_risk_budget:
|
||||
return None
|
||||
total = sum(c.get("marginal_risk_contribution", 0.0) for c in transition_set)
|
||||
return total / portfolio_total_risk_budget
|
||||
|
||||
|
||||
def post_trade_cvar95_krw(transition_set: tuple[dict, ...]) -> float | None:
|
||||
values = [c.get("cvar95_loss_krw") for c in transition_set]
|
||||
if any(v is None for v in values):
|
||||
return None
|
||||
return sum(values)
|
||||
|
||||
|
||||
def set_hard_constraint_pass(
|
||||
transition_set: tuple[dict, ...],
|
||||
portfolio_total_risk_budget: float = 0.0,
|
||||
mrc_cap: float = 1.0,
|
||||
cvar95_budget_krw: float | None = None,
|
||||
) -> bool:
|
||||
post_trade_cash_floor_pct = sum(c.get("post_trade_cash_floor_delta_pct", 0.0) for c in transition_set)
|
||||
post_trade_concentration_pct = sum(c.get("post_trade_concentration_delta_pct", 0.0) for c in transition_set)
|
||||
if post_trade_cash_floor_pct < 0 or post_trade_concentration_pct > 0:
|
||||
return False
|
||||
|
||||
mrc = post_trade_mrc(transition_set, portfolio_total_risk_budget)
|
||||
if mrc is not None and mrc > mrc_cap:
|
||||
return False
|
||||
|
||||
cvar95 = post_trade_cvar95_krw(transition_set)
|
||||
if cvar95 is not None and cvar95_budget_krw is not None and cvar95 < -abs(cvar95_budget_krw):
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def set_transition_utility_krw(transition_set: tuple[dict, ...]) -> float:
|
||||
total = sum(c.get("transition_utility_krw") or 0.0 for c in transition_set)
|
||||
combination_penalty = COMPLEXITY_PENALTY_RATE_KRW * (len(transition_set) - 1)
|
||||
return total - combination_penalty
|
||||
|
||||
|
||||
def enumerate_transition_sets(
|
||||
candidates: list[dict],
|
||||
max_set_size: int = 3,
|
||||
portfolio_total_risk_budget: float = 0.0,
|
||||
mrc_cap: float = 1.0,
|
||||
cvar95_budget_krw: float | None = None,
|
||||
) -> list[dict]:
|
||||
passing = [c for c in candidates if c.get("hard_constraint_pass") is True]
|
||||
evaluated_sets = []
|
||||
for size in range(1, min(max_set_size, len(passing)) + 1):
|
||||
for combo in itertools.combinations(passing, size):
|
||||
evaluated_sets.append(
|
||||
{
|
||||
"candidate_ids": [c.get("candidate_id") for c in combo],
|
||||
"set_hard_constraint_pass": set_hard_constraint_pass(
|
||||
combo, portfolio_total_risk_budget, mrc_cap, cvar95_budget_krw
|
||||
),
|
||||
"set_transition_utility_krw": set_transition_utility_krw(combo),
|
||||
"post_trade_mrc": post_trade_mrc(combo, portfolio_total_risk_budget),
|
||||
"post_trade_cvar95_krw": post_trade_cvar95_krw(combo),
|
||||
}
|
||||
)
|
||||
return evaluated_sets
|
||||
|
||||
|
||||
def select_best_set(evaluated_sets: list[dict]) -> dict | None:
|
||||
passing_sets = [s for s in evaluated_sets if s["set_hard_constraint_pass"]]
|
||||
if not passing_sets:
|
||||
return None
|
||||
return max(
|
||||
passing_sets,
|
||||
key=lambda s: (s["set_transition_utility_krw"], -len(s["candidate_ids"])),
|
||||
)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser()
|
||||
ap.add_argument("--transition-optimizer", default=str(DEFAULT_TRANSITION_OPTIMIZER))
|
||||
ap.add_argument("--max-set-size", type=int, default=3)
|
||||
ap.add_argument("--out", default=str(DEFAULT_OUT))
|
||||
args = ap.parse_args()
|
||||
|
||||
doc = _load(Path(args.transition_optimizer))
|
||||
candidates = doc.get("candidate_actions") if isinstance(doc.get("candidate_actions"), list) else []
|
||||
|
||||
if not candidates:
|
||||
result = {
|
||||
"formula_id": "TRANSITION_SET_ENUMERATOR_V1",
|
||||
"gate": "NO_TRADE",
|
||||
"selected_transition_set": [],
|
||||
"rejected_sets_count": 0,
|
||||
"source_paths": [str(Path(args.transition_optimizer))],
|
||||
}
|
||||
out = Path(args.out)
|
||||
out.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
evaluated_sets = enumerate_transition_sets(candidates, args.max_set_size)
|
||||
best = select_best_set(evaluated_sets)
|
||||
rejected_count = len(evaluated_sets) - (1 if best else 0)
|
||||
|
||||
result = {
|
||||
"formula_id": "TRANSITION_SET_ENUMERATOR_V1",
|
||||
"gate": "PASS" if best else "NO_TRADE",
|
||||
"selected_transition_set": best["candidate_ids"] if best else [],
|
||||
"set_transition_utility_krw": best["set_transition_utility_krw"] if best else None,
|
||||
"post_trade_mrc": best["post_trade_mrc"] if best else None,
|
||||
"post_trade_cvar95_krw": best["post_trade_cvar95_krw"] if best else None,
|
||||
"rejected_sets_count": rejected_count,
|
||||
"source_paths": [str(Path(args.transition_optimizer))],
|
||||
}
|
||||
out = Path(args.out)
|
||||
out.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
print(json.dumps(result, ensure_ascii=False, indent=2))
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user