Skip to content

Commit 0feab50

Browse files
committed
추가: expectation-grid P3 (연간 매출 기대 수집자, recordForecast write-end P9c, forwardTest data/ 승격 P9b, 표본 3사 라이브 봉인)
1 parent 28305e0 commit 0feab50

7 files changed

Lines changed: 407 additions & 25 deletions

File tree

‎.github/scripts/sync/buildExpectations.py‎

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,16 +20,25 @@ def main() -> int:
2020
parser = argparse.ArgumentParser(description=__doc__)
2121
parser.add_argument("--cycle", choices=["monthly", "quarterly"], default="monthly")
2222
parser.add_argument("--market", default="KR")
23+
parser.add_argument("--codes", default="", help="quarterly 대상 종목 CSV (기본 = 전상장사)")
2324
parser.add_argument("--push", action="store_true", help="HF expectations/ surface 업로드")
2425
args = parser.parse_args()
2526

26-
from dartlab.simulate.expectationCycle import buildScorecard, issueMacro, scoreDue
27+
from dartlab.simulate.expectationCycle import buildScorecard, issueMacro, issueRevenue, scoreDue
2728
from dartlab.simulate.expectationLedger import ledgerDir
2829

29-
issued = []
30+
issued: list = []
31+
skipped: dict[str, str] = {}
3032
if args.cycle == "monthly":
3133
issued = issueMacro(market=args.market, live=True)
32-
# quarterly(매출·손익·credit) 발행은 P3~P5 에서 본 진입점에 합류한다.
34+
else: # quarterly: 전상장사 매출 (순차 스트림, Company 1개씩 로드·해제)
35+
if args.codes:
36+
codes = [c.strip() for c in args.codes.split(",") if c.strip()]
37+
else:
38+
import dartlab
39+
40+
codes = dartlab.listing().get_column("종목코드").to_list()
41+
issued, skipped = issueRevenue(codes, live=True)
3342

3443
scores = scoreDue()
3544
card = buildScorecard()
@@ -38,8 +47,13 @@ def main() -> int:
3847
(outDir / "scorecard.json").write_text(json.dumps(card, ensure_ascii=False, indent=1), encoding="utf-8")
3948
print(
4049
f"[expectation-cycle] cycle={args.cycle} issued={len(issued)} scored={len(scores)} "
41-
f"errorRows={card['totals']['errorRows']} unscored={card['totals']['unscored']} dir={outDir}"
50+
f"errorRows={card['totals']['errorRows']} unscored={card['totals']['unscored']} "
51+
f"skipped={len(skipped)} dir={outDir}"
4252
)
53+
if skipped: # 발행 결손 census: 조용히 빼면 생존 편향, 반드시 남긴다
54+
(outDir / f"issueCensus_{args.cycle}.json").write_text(
55+
json.dumps(skipped, ensure_ascii=False, indent=1), encoding="utf-8"
56+
)
4357

4458
if args.push:
4559
from dartlab.pipeline.hfUpload import uploadCategoryToHf

‎.github/workflows/expectationCycle.yml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ concurrency:
3434
jobs:
3535
expectation-cycle:
3636
runs-on: ubuntu-latest
37-
timeout-minutes: 30
37+
timeout-minutes: 360 # quarterly 전상장사 순차 sweep (Company 1개씩 로드·해제) 대비
3838

3939
steps:
4040
- uses: actions/checkout@v6

‎src/dartlab/analysis/forecast/forwardTest.py‎

Lines changed: 102 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,25 @@
1-
"""Forward Test 인프라 — 매출 예측 저장 + 사후 평가."""
1+
"""Forward Test 인프라 : 매출 예측 저장 + 사후 평가.
2+
3+
저장 위치 (2026-07-03 승격, scenario-simulator 09 §10.2 P9b + expectation-grid 00 §9 A2):
4+
``~/.dartlab``(ephemeral) 폐기. ``DARTLAB_DATA_DIR`` env > ``./data`` 아래 ``forwardTests/``.
5+
"""
26

37
from __future__ import annotations
48

59
import json
610
import logging
11+
import os
712
from dataclasses import asdict, dataclass, field
813
from datetime import datetime, timezone
914
from pathlib import Path
1015

1116
log = logging.getLogger(__name__)
1217

13-
_FORWARD_TEST_DIR = Path.home() / ".dartlab" / "forward_tests"
18+
19+
def _forwardTestDir() -> Path:
20+
"""기록 루트: DARTLAB_DATA_DIR env > ./data. (옛 ~/.dartlab 저장 폐기, A2)."""
21+
root = os.environ.get("DARTLAB_DATA_DIR")
22+
return (Path(root) if root else Path("data")) / "forwardTests"
1423

1524

1625
@dataclass
@@ -109,8 +118,9 @@ def saveForecast(record: ForwardTestRecord) -> Path:
109118
AIContext:
110119
AI 답변 시 forward test 누적 후 캘리브레이션 점수 트래킹에 사용.
111120
"""
112-
_FORWARD_TEST_DIR.mkdir(parents=True, exist_ok=True)
113-
filepath = _FORWARD_TEST_DIR / f"{record.stockCode}.json"
121+
baseDir = _forwardTestDir()
122+
baseDir.mkdir(parents=True, exist_ok=True)
123+
filepath = baseDir / f"{record.stockCode}.json"
114124

115125
# 기존 기록 로드
116126
records = _loadRaw(filepath)
@@ -168,7 +178,7 @@ def loadRecords(stockCode: str) -> list[ForwardTestRecord]:
168178
AIContext:
169179
AI 답변 시 과거 예측 회수 → 사후 평가용 데이터 소스.
170180
"""
171-
filepath = _FORWARD_TEST_DIR / f"{stockCode}.json"
181+
filepath = _forwardTestDir() / f"{stockCode}.json"
172182
raw = _loadRaw(filepath)
173183
results = []
174184
for r in raw:
@@ -371,9 +381,10 @@ def evaluateCalibration(
371381

372382
if stockCodes is None:
373383
# 모든 종목 파일 스캔
374-
if not _FORWARD_TEST_DIR.exists():
384+
baseDir = _forwardTestDir()
385+
if not baseDir.exists():
375386
return None
376-
stockCodes = [f.stem for f in _FORWARD_TEST_DIR.glob("*.json")]
387+
stockCodes = [f.stem for f in baseDir.glob("*.json")]
377388

378389
predictions: list[float] = []
379390
outcomes: list[int] = []
@@ -390,6 +401,90 @@ def evaluateCalibration(
390401
return generateCalibrationReport(predictions, outcomes)
391402

392403

404+
def recordForecast(
405+
*,
406+
stockCode: str,
407+
horizon: int,
408+
projected: list[float],
409+
scenarios: dict[str, list[float]],
410+
sourcesUsed: list[str],
411+
assumptions: list[str],
412+
version: str = "v3",
413+
directionProbability: float | None = None,
414+
directionPredicted: str | None = None,
415+
) -> Path:
416+
"""예측 봉인 write-end : thin facade (새 저장 메커니즘 0, ForwardTestRecord+saveForecast 재사용).
417+
418+
Capabilities:
419+
forecast 산출물을 발행 시각(now UTC)과 함께 ForwardTestRecord 로 봉인 저장.
420+
scenario-simulator 09 §10.2 P9c 티켓의 구현 : forward-test 루프의 write-end.
421+
422+
Parameters
423+
----------
424+
stockCode : str
425+
6자리 종목코드.
426+
horizon : int
427+
예측 연 수.
428+
projected : list[float]
429+
연도별 예측 매출 (원).
430+
scenarios : dict[str, list[float]]
431+
Base/Bull/Bear 경로.
432+
sourcesUsed : list[str]
433+
사용 소스 목록.
434+
assumptions : list[str]
435+
예측 가정.
436+
version : str
437+
기록 스키마 버전 태그 (기본 "v3").
438+
directionProbability : float | None
439+
매출 방향 예측 확률 (v4 캘리브레이션용).
440+
directionPredicted : str | None
441+
"up" | "down".
442+
443+
Returns
444+
-------
445+
Path
446+
저장된 종목 JSON 경로.
447+
448+
Guide:
449+
발행 즉시 호출한다. 사후 채점은 ``evaluate``, 캘리브레이션 집계는
450+
``evaluateCalibration`` 이 닫는다 (write→evaluate→calibration 루프).
451+
452+
When:
453+
expectation-grid 수집자(issueRevenue)·forecast 파이프라인이 예측을 낼 때마다.
454+
455+
How:
456+
generateKey + now(UTC) 로 ForwardTestRecord 구성 → saveForecast 위임.
457+
458+
Raises:
459+
없음. 저장 실패는 saveForecast 의 OSError 전파.
460+
461+
Example:
462+
>>> recordForecast(stockCode="005930", horizon=3, projected=[1.0],
463+
... scenarios={}, sourcesUsed=[], assumptions=[]) # doctest: +SKIP
464+
465+
See Also:
466+
- saveForecast : 저장 본체
467+
- evaluate / evaluateCalibration : 루프의 read-end
468+
469+
Requires:
470+
쓰기 가능한 DARTLAB_DATA_DIR (기본 ./data).
471+
"""
472+
record = ForwardTestRecord(
473+
key=generateKey(stockCode, horizon, version),
474+
stockCode=stockCode,
475+
forecastDate=datetime.now(timezone.utc).isoformat(),
476+
version=version,
477+
horizon=horizon,
478+
projected=list(projected),
479+
scenarios=dict(scenarios),
480+
sourcesUsed=list(sourcesUsed),
481+
assumptions=list(assumptions),
482+
directionProbability=directionProbability,
483+
directionPredicted=directionPredicted,
484+
)
485+
return saveForecast(record)
486+
487+
393488
def _loadRaw(filepath: Path) -> list[dict]:
394489
"""JSON 파일에서 raw dict 리스트 로드."""
395490
if not filepath.exists():

‎src/dartlab/core/dataConfig.py‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,11 @@
183183
"label": "기대치 격자 원장 (발행 봉인 + 사후 채점, append-only, 시뮬레이터 검증척추)",
184184
"public": True,
185185
},
186+
"forwardTests": {
187+
"dir": "forwardTests",
188+
"label": "매출 예측 도메인 기록 (ForwardTestRecord JSON, 09 P9a/P9b 승격분)",
189+
"public": False,
190+
},
186191
# ── generated artifact (landing 빌드 시 HF 에서 fetch) ──
187192
"industryMap": {
188193
"dir": "landing/map",

0 commit comments

Comments
 (0)