[Sprint-3] Complete WBS-2.1, 3.2, 4.1, 5.1 - Fundamental V2, Engine V2, Performance Ledger, and CI/CD

This commit is contained in:
2026-06-13 15:38:28 +09:00
parent 0748c224da
commit 08f4fa2293
5 changed files with 473 additions and 358 deletions
@@ -1,106 +1,89 @@
"""build_operational_t20_outcome_ledger_v1.py — ALPHA_FEEDBACK_LOOP_V2
매수/매도 결정 20거래일 후의 실제 수익률을 추적하여 레저(Ledger)를 구축한다.
성과 인텔리전스(Phase 4)의 핵심 데이터 소스로 활용됨.
로직:
1. alpha_history 시트에서 과거 결정(Decision) 데이터를 읽음.
2. 현재 가격(Close)을 T+20 가격으로 가정하여 실현 수익률 계산.
3. outcome_ledger.json 생성.
"""
from __future__ import annotations
import argparse
import json
from datetime import date, timedelta
from datetime import datetime, timedelta
from pathlib import Path
from typing import Any
ROOT = Path(__file__).resolve().parents[1]
DEFAULT_HISTORY = ROOT / "Temp" / "proposal_evaluation_history.json"
DEFAULT_OUT = ROOT / "Temp" / "operational_t20_outcome_ledger_v1.json"
TEMP = ROOT / "Temp"
DEFAULT_JSON = ROOT / "GatherTradingData.json"
DEFAULT_OUT = TEMP / "outcome_ledger_v1.json"
# T+20 성숙 판정: 20 영업일 ≈ 28 캘린더일 (보수적 기준)
T20_CALENDAR_DAYS = 28
def _load(path: Path) -> Any:
if not path.exists(): return {}
try: return json.loads(path.read_text(encoding="utf-8"))
except: return {}
def _f(v: Any, default: float = 0.0) -> float:
try: return float(v)
except: return default
def _load(path: Path) -> dict[str, Any]:
if not path.exists():
return {}
try:
obj = json.loads(path.read_text(encoding="utf-8"))
except Exception:
return {}
return obj if isinstance(obj, dict) else {}
def _is_matured(r: dict) -> bool:
"""proposal_date + 28 캘린더일 <= today 이면 T+20 성숙 판정."""
pd = r.get("proposal_date") or r.get("entry_date") or ""
if not pd:
return False
try:
entry = date.fromisoformat(str(pd)[:10])
return (date.today() - entry).days >= T20_CALENDAR_DAYS
except Exception:
return False
def main() -> int:
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--history", default=str(DEFAULT_HISTORY))
ap.add_argument("--json", default=str(DEFAULT_JSON))
ap.add_argument("--out", default=str(DEFAULT_OUT))
args = ap.parse_args()
hist_path = Path(args.history) if Path(args.history).is_absolute() else ROOT / args.history
hist = _load(hist_path)
records = hist.get("records") if isinstance(hist.get("records"), list) else []
payload = _load(Path(args.json))
data = payload.get("data", {})
# alpha_history: 과거 예측 데이터
alpha_history = data.get("alpha_history", [])
# data_feed: 현재 가격 데이터 (T+20 프록시)
df_rows = data.get("data_feed", [])
current_prices = {str(r.get("Ticker")): _f(r.get("Close")) for r in df_rows if r.get("Ticker")}
# [T3/SG1] 운영(비-REPLAY) 레코드만 추출, T+20 성숙 확인
operational = [
r for r in records
if isinstance(r, dict)
and str(r.get("validation_status") or "").upper() != "REPLAY_BACKFILL"
]
# T+20 평가 완료 OR 20 캘린더일 이상 경과한 행 → matured
t20 = [
r for r in operational
if str(r.get("t20_evaluation_status") or "").startswith("EVALUATED_")
or _is_matured(r)
]
# INCONCLUSIVE는 통계에서 제외 (match_rate 분자/분모 모두)
decisive = [r for r in t20 if r.get("t20_outcome") in ("MATCHED", "MISMATCHED")]
matched = sum(1 for r in decisive if r.get("t20_outcome") == "MATCHED")
mismatched = sum(1 for r in decisive if r.get("t20_outcome") == "MISMATCHED")
rate = round((matched / len(decisive)) * 100.0, 2) if decisive else 0.0
ledger_rows = []
for h in alpha_history:
ticker = str(h.get("ticker"))
entry_price = _f(h.get("close_at_record"))
current_price = current_prices.get(ticker, 0.0)
if entry_price > 0 and current_price > 0:
return_pct = round((current_price - entry_price) / entry_price * 100, 2)
verdict = h.get("synthesis_verdict")
# 예측 적중 여부 (간단 로직: BUY면 +, EXIT면 -)
is_correct = False
if "BUY" in str(verdict) and return_pct > 0: is_correct = True
if "EXIT" in str(verdict) and return_pct < 0: is_correct = True
ledger_rows.append({
"date": h.get("date"),
"ticker": ticker,
"verdict": verdict,
"entry_price": entry_price,
"exit_price": current_price,
"return_pct": return_pct,
"is_correct": is_correct
})
win_rate = round(sum(1 for r in ledger_rows if r["is_correct"]) / len(ledger_rows) * 100, 2) if ledger_rows else 0
result = {
"formula_id": "OPERATIONAL_T20_OUTCOME_LEDGER_V1",
"evaluated_count": len(t20),
"decisive_count": len(decisive),
"matched_count": matched,
"mismatched_count": mismatched,
"pass_rate_pct": rate,
# [SG1] n<30 → WATCH_PENDING_SAMPLE (공허PASS 금지)
"gate": (
"PASS" if len(decisive) >= 30 and rate >= 60.0
else "WATCH_PENDING_SAMPLE"
),
"operational_total": len(operational),
"maturity_threshold_days": T20_CALENDAR_DAYS,
"rows": [
{
"proposal_id": r.get("proposal_id"),
"ticker": r.get("ticker"),
"name": r.get("name"),
"proposal_date": r.get("proposal_date"),
"t20_evaluation_status": r.get("t20_evaluation_status"),
"t20_outcome": r.get("t20_outcome"),
"t20_return_pct": r.get("t20_return_pct"),
"validation_status": r.get("validation_status"),
"matured": _is_matured(r),
}
for r in t20[:500]
],
"formula_id": "ALPHA_FEEDBACK_LOOP_V2",
"as_of_date": datetime.now().strftime("%Y-%m-%d"),
"total_cases": len(ledger_rows),
"win_rate_pct": win_rate,
"ledger": ledger_rows
}
out = Path(args.out)
if not out.is_absolute():
out = ROOT / out
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
print(json.dumps(result, ensure_ascii=False, indent=2))
Path(args.out).parent.mkdir(parents=True, exist_ok=True)
Path(args.out).write_text(json.dumps(result, ensure_ascii=False, indent=2), encoding="utf-8")
print(f"Outcome Ledger Built. Total Cases: {len(ledger_rows)}, Win Rate: {win_rate}%")
return 0
if __name__ == "__main__":
raise SystemExit(main())
main()