Skip to content

Commit ec11e4c

Browse files
committed
리팩터: 판단 재료 모듈을 값·파생·기준 셋으로 나눈다
한 파일이 827 줄이 되면서 800 줄 상한을 넘겼다. 상한을 올리는 것이 아니라 실제로 성격이 다른 셋이 한 파일에 있던 것이라 나눈다. `values` 는 표에서 값을 꺼내고 읽기 좋게 만드는 원시 도구다. 판단이 없다. `derived` 는 손에 있는 시계열만으로 계산되는 파생 지표다. 증감률, 이익 변동 분해, 기간 내 위치, 현금흐름 방향, 관측 범위 산술이 여기 있다. `anchors` 는 회사 밖에서 오는 기준이다. 업종 내 위치와 판단이 뒤집히는 지점이다. 공개 이름은 그대로다. `__init__` 은 재export 파사드로만 두고 로직은 형제 모듈이 소유한다. 호출하는 쪽 import 경로는 바뀌지 않는다. 테스트 34 건 그대로 통과. folderSize 와 initThin 통과.
1 parent 2be71f7 commit ec11e4c

5 files changed

Lines changed: 904 additions & 1 deletion

File tree

‎docs/handbook/architecture/agentRuntime.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ MCP payload 예산의 기준은 우리가 감당할 크기가 아니라 소비
4949

5050
실측 사례 셋이 같은 결론을 가리킨다. 스크리닝이 도구를 56 회 부르던 것은 지침 불이행이 아니라 `scan` 이 행 본문 없이 개수만 돌려줘서 종목마다 다시 부를 수밖에 없던 것이다. 비교 기준이 답변에 없던 것은 캡슐이 덜 요구해서가 아니라 이미 계산된 신용 등급과 산업 국면이 payload 안에만 있고 본문에 없어서다. 판단이 바뀌는 조건이 빠지던 것은 반사실 추론이 어려워서인데, 관측된 마진을 주면 그 자리에서 산술이 된다.
5151

52-
`panelInsight.py` 는 이 원칙의 구현이다. 손에 이미 있는 시계열만 써서 파생 지표, 이익 변동 요인 분해, 기간 내 위치와 기저효과, 관측 범위 기준 하방 산술, 회사 위치를 본문에 함께 싣는다. 추가 조회가 없으므로 지연이 늘지 않는다.
52+
`ai/tools/panelInsight/` 가 이 원칙의 구현이다. 값을 꺼내는 원시 도구(`values`), 표에서 계산되는 파생 지표(`derived`), 회사 밖 기준과 뒤집히는 지점(`anchors`) 셋으로 나뉜다. 손에 이미 있는 시계열만 써서 파생 지표, 이익 변동 요인 분해, 기간 내 위치와 기저효과, 관측 범위 기준 하방 산술, 회사 위치를 본문에 함께 싣는다. 추가 조회가 없으므로 지연이 늘지 않는다.
5353

5454
비교 기준은 질문의 결을 따라가야 한다. 실측(2026-08-06) 에서 재무 건전성을 물은 질문이 업종 기준을 하나도 못 받고 끝났다. 모델이 안 쓴 것이 아니라 쓸 것이 없었다. 그때 붙던 업종 축은 영업이익률과 ROE 와 매출 성장률뿐이라 "부채비율 30% 가 높은 건가" 에 답할 재료가 아예 없었다. 그래서 부채비율과 유동비율을 축으로 더했다. 방향이 다른 축은 방향을 문장에 적는다. 부채비율을 "업종 상위 몇 %" 로 쓰면 정확히 반대로 읽힌다.
5555

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""재무제표 시계열에서 판단 재료를 뽑아 답변 표면에 함께 싣는다.
2+
3+
왜 필요한가. DartLab 은 모델 루프를 설치형 CLI 에 넘긴 중개상이라 답변을 직접 고쳐 쓸 수
4+
없다. 답변 품질을 올리는 유일한 정공법은 **건네주는 근거 자체를 판단 가능한 형태로 만드는
5+
것**이다. 원시 수치 표만 주면 마진과 증감률과 기저효과 판별을 모델이 매번 손으로 해야 하고,
6+
그 계산을 잘하는 모델과 못하는 모델 사이에서 답변 품질이 갈린다.
7+
8+
실측 배경(2026-08-06). 강한 모델은 손익 표만 받고도 원가율 하락이 이익 개선의 몸통임을
9+
스스로 찾아냈고 2023FY 저점이 기저효과임을 지적했다. 같은 표를 받은 약한 모델은 "영업이익
10+
5 배 성장" 으로 끝낼 수 있다. 그 차이를 모델에 맡기지 않고 표에 실어 보낸다.
11+
12+
계산은 이미 손에 있는 시계열만 쓴다. 추가 조회가 없으므로 지연이 늘지 않는다.
13+
`Panel` wide DataFrame 의 형태와 내용은 건드리지 않는다. 여기서 만드는 것은 표현 계층의
14+
병존 projection 이다.
15+
"""
16+
17+
from __future__ import annotations
18+
19+
from .anchors import balanceTripwires, contextMarkdown, sectorPositionLines
20+
from .derived import (
21+
cashFlowAnchors,
22+
cashFlowPattern,
23+
derivedRows,
24+
insightMarkdown,
25+
observedRangeAnchors,
26+
positionNotes,
27+
profitBridge,
28+
)
29+
30+
__all__ = [
31+
"balanceTripwires",
32+
"cashFlowAnchors",
33+
"cashFlowPattern",
34+
"contextMarkdown",
35+
"derivedRows",
36+
"insightMarkdown",
37+
"observedRangeAnchors",
38+
"positionNotes",
39+
"profitBridge",
40+
"sectorPositionLines",
41+
]
Lines changed: 232 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,232 @@
1+
"""수치를 판단으로 바꾸는 기준선.
2+
3+
"영업이익률 13.1%" 도 "부채비율 29.9%" 도 그 자체로 좋고 나쁨을 말하지 않는다. 같은
4+
업종 회사들이 어디에 있는지, 그리고 이 판단이 뒤집히려면 무엇이 얼마나 움직여야 하는지를
5+
알아야 판단이 된다. 둘 다 모델이 손으로 하기에는 비싼 계산이라 우리가 해서 건넨다.
6+
"""
7+
8+
from __future__ import annotations
9+
10+
from typing import Any
11+
12+
from .values import _formatAmount, _numeric, _pick, _seriesByKey, _withDerivedEquity
13+
14+
15+
def _paceNote(distance: float, step: float, direction: str, unit: str) -> str:
16+
"""남은 거리를 최근 한 기 변화폭으로 나눈다. 산술이지 전망이 아니라고 못 박는다.
17+
18+
방향을 문장에 적는다. 내려가는 지표에 "+" 를 붙이면 정확히 반대로 읽힌다.
19+
"""
20+
if step <= 0 or distance <= 0:
21+
return ""
22+
return (
23+
f" 최근 한 기 {direction} 폭 {step:.1f}%p가 이어지면 {distance / step:.0f} {unit} 뒤입니다"
24+
f"(산술이며 전망이 아닙니다)."
25+
)
26+
27+
28+
def _debtTripwire(
29+
indexed: dict[str, dict[str, Any]], periods: list[str], position: dict[str, Any] | None, unit: str
30+
) -> list[str]:
31+
"""부채비율이 업종 중앙값에 닿으려면 부채가 얼마나 늘어야 하는지 적는다."""
32+
liabilities = indexed.get("total_liabilities")
33+
equity = _pick(indexed, ("total_stockholders_equity", "total_equity"))
34+
distribution = (position or {}).get("debtRatioDistribution")
35+
if liabilities is None or equity is None or not isinstance(distribution, dict):
36+
return []
37+
median = distribution.get("median")
38+
if not isinstance(median, (int, float)):
39+
return []
40+
latest = periods[0]
41+
debtNow = _numeric(liabilities.get("values"), latest)
42+
equityNow = _numeric(equity.get("values"), latest)
43+
if debtNow is None or not equityNow:
44+
return []
45+
ratioNow = debtNow / equityNow * 100
46+
target = float(median)
47+
gap = (target / 100) * equityNow - debtNow
48+
if gap <= 0:
49+
return [
50+
f"부채비율 {ratioNow:.1f}%는 이미 업종 중앙값 {target:.1f}% 위입니다. "
51+
f"중앙값으로 돌아가려면 자본이 그대로일 때 부채가 {_formatAmount(-gap).lstrip('+')} 줄어야 합니다."
52+
]
53+
note = (
54+
f"부채비율이 업종 중앙값 {target:.1f}%에 닿으려면 자본이 그대로일 때 부채가 지금보다 "
55+
f"{_formatAmount(gap).lstrip('+')} 늘어야 합니다(현재 {ratioNow:.1f}%)."
56+
)
57+
if len(periods) >= 2:
58+
debtPrior = _numeric(liabilities.get("values"), periods[1])
59+
equityPrior = _numeric(equity.get("values"), periods[1])
60+
if debtPrior is not None and equityPrior:
61+
note += _paceNote(target - ratioNow, ratioNow - debtPrior / equityPrior * 100, "상승", unit)
62+
return [note]
63+
64+
65+
def _liquidityTripwire(indexed: dict[str, dict[str, Any]], periods: list[str], unit: str) -> list[str]:
66+
"""유동부채가 얼마나 더 늘면 유동자산으로 못 덮는지 적는다. 100%는 정의상 경계다."""
67+
assets = indexed.get("current_assets")
68+
liabilities = indexed.get("current_liabilities")
69+
if assets is None or liabilities is None:
70+
return []
71+
latest = periods[0]
72+
assetsNow = _numeric(assets.get("values"), latest)
73+
liabilitiesNow = _numeric(liabilities.get("values"), latest)
74+
if assetsNow is None or not liabilitiesNow:
75+
return []
76+
ratioNow = assetsNow / liabilitiesNow * 100
77+
if ratioNow <= 100:
78+
return [f"유동비율 {ratioNow:.1f}%로 유동자산이 이미 유동부채에 못 미칩니다."]
79+
note = (
80+
f"유동부채가 지금보다 {_formatAmount(assetsNow - liabilitiesNow).lstrip('+')} 늘면 "
81+
f"유동자산으로 덮지 못합니다(유동비율 100%). 현재 {ratioNow:.1f}%입니다."
82+
)
83+
if len(periods) >= 2:
84+
assetsPrior = _numeric(assets.get("values"), periods[1])
85+
liabilitiesPrior = _numeric(liabilities.get("values"), periods[1])
86+
if assetsPrior is not None and liabilitiesPrior:
87+
note += _paceNote(ratioNow - 100, assetsPrior / liabilitiesPrior * 100 - ratioNow, "하락", unit)
88+
return [note]
89+
90+
91+
def balanceTripwires(summary: dict[str, Any], position: dict[str, Any] | None) -> list[str]:
92+
"""재무 건전성 판단이 뒤집히는 지점을 산술로 적는다.
93+
94+
실측(2026-08-06): 업종 기준을 붙여 주니 답변이 "29.9%는 업종 하위 28%라 낮은 편" 까지
95+
갔는데, 정작 "이 판단이 틀리려면 무엇이 일어나야 하나" 는 사라졌다. 재료가 늘면서
96+
마무리 규율이 밀려난 것이다. 반증 조건이 비싼 이유는 모델이 그 산술을 손으로 해야
97+
하기 때문이다. 현금흐름에서 통한 방법을 그대로 쓴다. 산술을 우리가 해서 건넨다.
98+
99+
가정을 지어내지 않는다. 쓰는 것은 당기 재무상태표 수치와 이미 계산된 업종 중앙값,
100+
그리고 유동비율 100%라는 정의상 경계뿐이다.
101+
102+
Args:
103+
summary: `Company.panel` tool 결과의 summary. 재무상태표가 아니면 빈 목록이다.
104+
position: `getSectorPosition` 결과. 없으면 유동성 임계만 적는다.
105+
106+
Returns:
107+
list[str]: 사람이 읽는 한 줄 노트 목록.
108+
109+
Example:
110+
`notes = balanceTripwires(summary, position)`
111+
"""
112+
periods = [str(p) for p in (summary.get("periods") or [])]
113+
timeseries = [row for row in (summary.get("timeseries") or []) if isinstance(row, dict)]
114+
if not periods or not timeseries:
115+
return []
116+
indexed = _withDerivedEquity(_seriesByKey(timeseries), periods)
117+
unit = "년" if summary.get("projection") == "annual" else "분기"
118+
return _debtTripwire(indexed, periods, position, unit) + _liquidityTripwire(indexed, periods, unit)
119+
120+
121+
# (표시 이름, 백분위 키, 분포 키, 높을수록 좋은가).
122+
# 방향을 표에 박아 둔다. 부채비율은 낮을수록 안전한데 "상위 몇 %" 로 적으면 정반대로 읽힌다.
123+
_SECTOR_AXES: tuple[tuple[str, str, str, bool], ...] = (
124+
("영업이익률", "myOpmPercentile", "opmDistribution", True),
125+
("ROE", "myRoePercentile", "roeDistribution", True),
126+
("매출 성장률", "myCagrPercentile", "cagrDistribution", True),
127+
("부채비율", "myDebtRatioPercentile", "debtRatioDistribution", False),
128+
("유동비율", "myCurrentRatioPercentile", "currentRatioDistribution", True),
129+
)
130+
131+
132+
def sectorPositionLines(position: dict[str, Any] | None) -> list[str]:
133+
"""수치를 판단으로 바꾸는 업종 내 위치를 문장으로 만든다.
134+
135+
"영업이익률 13.1%" 는 그 자체로 좋고 나쁨을 말하지 않는다. 같은 업종 회사들이 어디에
136+
있는지를 알아야 판단이 된다. 분포와 백분위는 오래전부터 계산되고 있었지만 답변 표면에
137+
오지 않아 한 번도 쓰이지 않았다.
138+
139+
표본이 작으면 백분위가 흔들린다. 몇 개 회사로 잰 값인지 함께 적어 과신을 막는다.
140+
141+
Args:
142+
position: `getSectorPosition` 결과. 없으면 빈 목록이다.
143+
144+
Returns:
145+
list[str]: 사람이 읽는 한 줄 노트 목록.
146+
147+
Example:
148+
`lines = sectorPositionLines(position)`
149+
"""
150+
if not isinstance(position, dict) or not position.get("peerCount"):
151+
return []
152+
industry = str(position.get("industryName") or position.get("industryId") or "동종 업종")
153+
peerCount = position.get("peerCount")
154+
lines: list[str] = []
155+
for label, percentileKey, distributionKey, higherIsBetter in _SECTOR_AXES:
156+
percentile = position.get(percentileKey)
157+
distribution = position.get(distributionKey)
158+
if not isinstance(percentile, (int, float)) or not isinstance(distribution, dict):
159+
continue
160+
median = distribution.get("median")
161+
sampled = distribution.get("n") or peerCount
162+
if higherIsBetter:
163+
parts = [f"{label} 업종 상위 {100 - float(percentile):.0f}%"]
164+
boundary, boundaryLabel = distribution.get("p90"), "상위 10% 경계"
165+
else:
166+
# 낮은 쪽에 있을수록 안전하다는 뜻을 문장 안에 넣는다. 숫자만 주면 뒤집혀 읽힌다.
167+
parts = [f"{label} 업종 하위 {float(percentile):.0f}% (낮을수록 안전)"]
168+
boundary, boundaryLabel = distribution.get("p10"), "가장 낮은 10% 경계"
169+
if isinstance(median, (int, float)):
170+
parts.append(f"중앙값 {float(median):.1f}%")
171+
if isinstance(boundary, (int, float)):
172+
parts.append(f"{boundaryLabel} {float(boundary):.1f}%")
173+
lines.append(f"- {', '.join(parts)} ({industry} {sampled}사 기준).")
174+
return lines
175+
176+
177+
def contextMarkdown(
178+
dcrBadge: dict[str, Any] | None,
179+
industryBadge: dict[str, Any] | None,
180+
sectorPosition: dict[str, Any] | None = None,
181+
summary: dict[str, Any] | None = None,
182+
) -> str:
183+
"""이미 계산돼 붙어 있는 신용 등급과 산업 위치를 답변 표면으로 끌어올린다.
184+
185+
두 뱃지는 오래전부터 tool 결과에 실려 있었지만 payload 안에만 있어서 실제 답변에는
186+
한 번도 쓰이지 않았다. 모델이 읽고 재사용하는 것은 markdown 본문이다. 계산이 이미
187+
끝난 것을 옮겨 적기만 하므로 비용이 없고, 수치 하나에 판단 기준이 생긴다.
188+
189+
Args:
190+
dcrBadge: 신용 스코어카드 요약. 없으면 건너뛴다.
191+
industryBadge: 산업 분류와 국면과 동종 후보. 없으면 건너뛴다.
192+
193+
Returns:
194+
str: 붙일 것이 없으면 빈 문자열이다.
195+
196+
Example:
197+
`block = contextMarkdown(data.get("dcrBadge"), data.get("industryBadge"))`
198+
"""
199+
lines: list[str] = []
200+
if isinstance(dcrBadge, dict) and dcrBadge.get("grade"):
201+
parts = [f"신용 {dcrBadge.get('grade')}"]
202+
if dcrBadge.get("outlook"):
203+
parts.append(f"전망 {dcrBadge['outlook']}")
204+
pd = dcrBadge.get("pdEstimate")
205+
if isinstance(pd, (int, float)):
206+
parts.append(f"1년 부도확률 {float(pd):.2f}%")
207+
if dcrBadge.get("investmentGrade") is not None:
208+
parts.append("투자등급" if dcrBadge["investmentGrade"] else "투기등급")
209+
lines.append(f"- {', '.join(parts)}.")
210+
if isinstance(industryBadge, dict) and industryBadge.get("industryName"):
211+
parts = [str(industryBadge["industryName"])]
212+
if industryBadge.get("stageName"):
213+
parts.append(str(industryBadge["stageName"]))
214+
if industryBadge.get("phase") and industryBadge["phase"] != "unknown":
215+
parts.append(f"국면 {industryBadge['phase']}")
216+
peers = [
217+
f"{peer.get('corpName')}({peer.get('stockCode')})"
218+
for peer in (industryBadge.get("peers") or [])
219+
if isinstance(peer, dict) and peer.get("corpName")
220+
][:3]
221+
line = f"- 산업 {', '.join(parts)}."
222+
if peers:
223+
line += f" 같은 산업 비교 후보: {', '.join(peers)}."
224+
lines.append(line)
225+
lines.extend(sectorPositionLines(sectorPosition))
226+
tripwires = balanceTripwires(summary or {}, sectorPosition)
227+
if not lines and not tripwires:
228+
return ""
229+
block = "## 회사 위치\n" + "\n".join(lines) + "\n" if lines else ""
230+
if tripwires:
231+
block += "\n## 판단이 뒤집히는 지점\n" + "\n".join(f"- {note}" for note in tripwires) + "\n"
232+
return block

0 commit comments

Comments
 (0)