Files
QuantEngineByItz/tools/validate_report_numerical_sync_v1.py
kjh2064 ee3e799de1 feat: 리밸런싱 엔진 V1 + GAS 버그 수정 (2026-06-13)
주요 변경:
- tools/build_rebalance_engine_v1.py: REBALANCE_ENGINE_V1 신규
  * account_snapshot 직접 합산(_build_snap_position_map) → 소수주 분리 행 병합
  * 레짐 소스 macro.REGIME_PRELIM 최우선 (GAS 와 동일)
- src/gas_adapter_parts/gdf_06_rebalance.gs: runRebalanceSheet_() 신규
  * Logger.log / getSpreadsheet_() 로 run_all 연동 수정
- src/gas_adapter_parts/gdc_01_fetch_fundamentals.gs
  * _mergePositionRecord_(): 소수주 중복 행 합산 신규
  * parseInt → parseFloat (qty, availQty)
- src/gas_adapter_parts/gdf_01_price_metrics.gs
  * 미보유 종목 SELL_READY → WATCH_EXIT_SIGNAL
- spec/41_release_dag.yaml: build_rebalance_sheet 노드 추가 (step_count 63)
- spec/51_formula_lifecycle_registry.yaml: REBALANCE_ENGINE_V1 등록

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-13 13:20:14 +09:00

101 lines
3.1 KiB
Python

#!/usr/bin/env python3
from __future__ import annotations
import argparse
import json
import re
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
NUM_RE = re.compile(r"(?<![\w.])(?:\d{1,3}(?:,\d{3})+|\d+)(?:\.\d+)?")
SYNC_KEYS = (
("pass_100", "score_0_100"),
("pass_100", "passed_count"),
("pass_100", "failed_count"),
("execution_readiness", "min_axis_score"),
("prediction", "match_rate_pct"),
)
def _load_text(path: Path) -> str:
raw = path.read_text(encoding="utf-8")
try:
payload = json.loads(raw)
except Exception:
return raw
if isinstance(payload, dict) and isinstance(payload.get("sections"), list):
chunks: list[str] = []
for section in payload["sections"]:
if isinstance(section, dict):
chunks.append(str(section.get("markdown") or ""))
return "\n".join(chunks)
return raw
def _format_candidates(value: Any) -> set[str]:
candidates: set[str] = set()
if isinstance(value, bool) or value is None:
return candidates
if isinstance(value, int):
candidates.add(str(value))
return candidates
if isinstance(value, float):
raw = f"{value}"
candidates.add(raw)
candidates.add(f"{value:.2f}".rstrip("0").rstrip("."))
candidates.add(f"{value:.1f}".rstrip("0").rstrip("."))
candidates.add(str(int(value)) if value.is_integer() else raw)
return candidates
text = str(value).strip()
if text:
candidates.add(text)
return candidates
def _report_contains_any(report_text: str, value: Any) -> bool:
for candidate in _format_candidates(value):
if candidate and candidate in report_text:
return True
return False
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--report", default="Temp/operational_report.json")
ap.add_argument("--packet", default="Temp/final_decision_packet_active.json")
ap.add_argument("--strict", action="store_true")
args = ap.parse_args()
report_path = Path(args.report)
packet_path = Path(args.packet)
report_text = _load_text(report_path)
packet = json.loads(packet_path.read_text(encoding="utf-8"))
mismatches = []
for section_key, field_key in SYNC_KEYS:
value = (packet.get(section_key) or {}).get(field_key)
if value is None:
mismatches.append(f"missing_packet:{section_key}.{field_key}")
continue
if not _report_contains_any(report_text, value):
mismatches.append(f"{section_key}.{field_key}={value}")
result = {
"formula_id": "REPORT_NUMERICAL_SYNC_V1",
"report_number_count": len([m.group(0) for m in NUM_RE.finditer(report_text)]),
"packet_sync_field_count": len(SYNC_KEYS),
"mismatch_count": len(mismatches),
"mismatches": mismatches[:50],
"gate": "PASS" if not mismatches else "FAIL",
}
print(json.dumps(result, ensure_ascii=False, indent=2))
return 0 if not mismatches else 1
if __name__ == "__main__":
raise SystemExit(main())