Skip to content

Commit c002685

Browse files
committed
개선: 수치마다 업종 내 위치를 붙여 판단 기준을 준다
답변에 남아 있던 가장 큰 구멍이다. "영업이익률 13.1%" 는 그 자체로 좋고 나쁨을 말하지 않는다. 같은 업종 회사들이 어디에 있는지를 알아야 판단이 된다. 지금까지 답변은 수치를 정확히 냈지만 그 수치가 잘한 건지 못한 건지는 말하지 못했다. 업종 분포와 백분위는 오래전부터 계산되고 있었다. 답변 표면에 오지 않아 한 번도 쓰이지 않았을 뿐이다. 신용 등급과 산업 국면 때와 정확히 같은 구조다. 본문에 세 축을 싣는다. 영업이익률, ROE, 매출 성장률 각각의 업종 내 상위 몇 퍼센트와 중앙값과 상위 10% 경계다. 표본이 작으면 백분위가 흔들리므로 몇 개 회사로 잰 값인지 함께 적어 과신을 막는다. 백분위만 있고 분포가 없으면 그 축은 건너뛴다. 기준 없는 순위는 판단이 아니다. 비용을 임계 경로에 두지 않았다. 계산이 처음 한 번 9.5 초다(실측). 그대로 붙이면 모든 첫 조회가 그만큼 늦어진다. 아는 것은 즉시 주고 느린 것은 뒤에서 재게 했다. 분석 한 턴은 같은 회사를 여러 번 조회하므로 두 번째 호출부터 붙는다. 연결 화면에서 배운 것과 같은 계약이다. 실패도 기억한다. 안 그러면 데이터 없는 회사마다 매 조회가 다시 재려 든다. 분포는 공시가 갱신될 때만 바뀌므로 오래 들고 있어도 사실이 흐려지지 않는다. 실측. 삼성전자 조회에서 "영업이익률 업종 상위 0%, 중앙값 4.1%, 상위 10% 경계 23.8% (반도체 117사 기준)" 이 나온다. 임계 경로 추가 비용은 0 초다. 1 회차 27.7 초로 기준선과 같고 2 회차부터 위치가 붙는다. 테스트 27 건. 복잡도 등급 함수 증가 없음, folderSize 통과.
1 parent 1e9c513 commit c002685

4 files changed

Lines changed: 144 additions & 4 deletions

File tree

‎src/dartlab/ai/tools/engineCall.py‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
from .creditBadge import getDcrBadge
3232
from .filingDeepLink import attachDocRef, buildPeriodToFiling
3333
from .formatting import formatMoney, formatPercent
34-
from .industryContext import getIndustryBadge
34+
from .industryContext import getIndustryBadge, getSectorPosition
3535
from .panelInsight import contextMarkdown, insightMarkdown
3636
from .types import ToolResult
3737

@@ -781,7 +781,10 @@ def _buildShowData(
781781
# 두 뱃지는 오래전부터 payload 에 실려 있었지만 본문에 없어 답변에 한 번도 쓰이지
782782
# 않았다. 모델이 읽는 것은 markdown 이다. 수치 하나에 판단 기준이 생긴다.
783783
# 맺음말 뒤에 붙이면 마무리 문장이 본문 중간에 끼므로 그 앞에 넣는다.
784-
context = contextMarkdown(badge, industryBadge)
784+
sectorPosition = getSectorPosition(company)
785+
if sectorPosition:
786+
data["sectorPosition"] = sectorPosition
787+
context = contextMarkdown(badge, industryBadge, sectorPosition)
785788
if context:
786789
body = str(data["markdown"])
787790
marker = "근거는 tableRef"

‎src/dartlab/ai/tools/industryContext.py‎

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,10 @@
1616

1717
from __future__ import annotations
1818

19+
import logging
1920
from typing import Any
2021

22+
from dartlab.ai.runtime.probeCache import SwrCache, backgroundRefresher
2123
from dartlab.core.confidence import baseScore
2224

2325
_REBOUND_TRIGGER = ("쇠퇴",)
@@ -115,4 +117,52 @@ def getIndustryBadge(company: Any) -> dict[str, Any] | None:
115117
}
116118

117119

118-
__all__ = ["getIndustryBadge"]
120+
# 업종 분포 계산은 횡단면 scan 을 두 번 돌아 5 초가 걸린다(실측 2026-08-06). 분포는 공시가
121+
# 갱신될 때만 바뀌므로 오래 들고 있어도 사실이 흐려지지 않는다. 한 번 재고 나면 같은 회사와
122+
# 같은 산업의 이어지는 질문은 공짜다.
123+
_SECTOR_CACHE = SwrCache(3600.0)
124+
125+
126+
def getSectorPosition(company: Any) -> dict[str, Any] | None:
127+
"""수치 하나를 판단으로 바꾸는 업종 내 위치.
128+
129+
"영업이익률 13.1%" 는 그 자체로 좋고 나쁨을 말하지 않는다. 같은 업종 회사들이 어디에
130+
있는지를 알아야 판단이 된다. 분포와 백분위가 이미 계산되어 있었지만 답변 표면에 오지
131+
않아 한 번도 쓰이지 않았다.
132+
133+
Args:
134+
company: Company 객체. 종목코드와 산업 매핑이 필요하다.
135+
136+
Returns:
137+
dict[str, Any] | None: 동종사 수, 분포, 백분위. 동종 3 사 미만이면 None 이다.
138+
139+
Example:
140+
`position = getSectorPosition(company)`
141+
"""
142+
stockCode = str(getattr(company, "stockCode", "") or "")
143+
if not stockCode:
144+
return None
145+
cached = _SECTOR_CACHE.peek(stockCode)
146+
if cached is not None:
147+
return cached.value or None
148+
149+
# 아직 없으면 기다리지 않고 뒤에서 잰다. 실측(2026-08-06) 첫 계산이 9.5 초인데, 그것을
150+
# 임계 경로에 두면 모든 첫 조회가 그만큼 늦어진다. 분석 한 턴은 같은 회사를 여러 번
151+
# 조회하므로 두 번째 호출부터는 붙는다. 아는 것을 즉시 주고 느린 것은 따라오게 한다.
152+
def _compute() -> dict[str, Any]:
153+
from dartlab.industry.calcs.companyCalcs import calcSectorMetrics
154+
155+
try:
156+
metrics = calcSectorMetrics(company)
157+
except Exception:
158+
logging.getLogger(__name__).debug("업종 위치 계산 실패", exc_info=True)
159+
metrics = None
160+
# 실패도 기억한다. 안 그러면 데이터 없는 회사마다 매 조회가 다시 재려 든다.
161+
_SECTOR_CACHE.put(stockCode, metrics or {})
162+
return metrics or {}
163+
164+
backgroundRefresher().submit(f"sectorPosition:{stockCode}", _compute)
165+
return None
166+
167+
168+
__all__ = ["getIndustryBadge", "getSectorPosition"]

‎src/dartlab/ai/tools/panelInsight.py‎

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -557,7 +557,58 @@ def cashFlowAnchors(summary: dict[str, Any]) -> list[str]:
557557
return notes
558558

559559

560-
def contextMarkdown(dcrBadge: dict[str, Any] | None, industryBadge: dict[str, Any] | None) -> str:
560+
_SECTOR_AXES: tuple[tuple[str, str, str], ...] = (
561+
("영업이익률", "myOpmPercentile", "opmDistribution"),
562+
("ROE", "myRoePercentile", "roeDistribution"),
563+
("매출 성장률", "myCagrPercentile", "cagrDistribution"),
564+
)
565+
566+
567+
def sectorPositionLines(position: dict[str, Any] | None) -> list[str]:
568+
"""수치를 판단으로 바꾸는 업종 내 위치를 문장으로 만든다.
569+
570+
"영업이익률 13.1%" 는 그 자체로 좋고 나쁨을 말하지 않는다. 같은 업종 회사들이 어디에
571+
있는지를 알아야 판단이 된다. 분포와 백분위는 오래전부터 계산되고 있었지만 답변 표면에
572+
오지 않아 한 번도 쓰이지 않았다.
573+
574+
표본이 작으면 백분위가 흔들린다. 몇 개 회사로 잰 값인지 함께 적어 과신을 막는다.
575+
576+
Args:
577+
position: `getSectorPosition` 결과. 없으면 빈 목록이다.
578+
579+
Returns:
580+
list[str]: 사람이 읽는 한 줄 노트 목록.
581+
582+
Example:
583+
`lines = sectorPositionLines(position)`
584+
"""
585+
if not isinstance(position, dict) or not position.get("peerCount"):
586+
return []
587+
industry = str(position.get("industryName") or position.get("industryId") or "동종 업종")
588+
peerCount = position.get("peerCount")
589+
lines: list[str] = []
590+
for label, percentileKey, distributionKey in _SECTOR_AXES:
591+
percentile = position.get(percentileKey)
592+
distribution = position.get(distributionKey)
593+
if not isinstance(percentile, (int, float)) or not isinstance(distribution, dict):
594+
continue
595+
median = distribution.get("median")
596+
top = distribution.get("p90")
597+
sampled = distribution.get("n") or peerCount
598+
parts = [f"{label} 업종 상위 {100 - float(percentile):.0f}%"]
599+
if isinstance(median, (int, float)):
600+
parts.append(f"중앙값 {float(median):.1f}%")
601+
if isinstance(top, (int, float)):
602+
parts.append(f"상위 10% 경계 {float(top):.1f}%")
603+
lines.append(f"- {', '.join(parts)} ({industry} {sampled}사 기준).")
604+
return lines
605+
606+
607+
def contextMarkdown(
608+
dcrBadge: dict[str, Any] | None,
609+
industryBadge: dict[str, Any] | None,
610+
sectorPosition: dict[str, Any] | None = None,
611+
) -> str:
561612
"""이미 계산돼 붙어 있는 신용 등급과 산업 위치를 답변 표면으로 끌어올린다.
562613
563614
두 뱃지는 오래전부터 tool 결과에 실려 있었지만 payload 안에만 있어서 실제 답변에는
@@ -600,6 +651,7 @@ def contextMarkdown(dcrBadge: dict[str, Any] | None, industryBadge: dict[str, An
600651
if peers:
601652
line += f" 같은 산업 비교 후보: {', '.join(peers)}."
602653
lines.append(line)
654+
lines.extend(sectorPositionLines(sectorPosition))
603655
if not lines:
604656
return ""
605657
return "## 회사 위치\n" + "\n".join(lines) + "\n"

‎tests/ai/test_panel_insight.py‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@
1717
observedRangeAnchors,
1818
positionNotes,
1919
profitBridge,
20+
sectorPositionLines,
2021
)
2122

2223
pytestmark = pytest.mark.unit
@@ -331,6 +332,40 @@ def testDownsideAnchorNeedsSalesAndProfit() -> None:
331332
assert observedRangeAnchors(summary) == []
332333

333334

335+
def testSectorPositionTurnsANumberIntoAJudgment() -> None:
336+
"""업종 분포와 백분위를 붙여 수치 하나에 판단 기준을 준다.
337+
338+
"영업이익률 13.1%" 는 그 자체로 좋고 나쁨을 말하지 않는다. 분포와 백분위는 오래전부터
339+
계산되고 있었지만 답변 표면에 오지 않아 한 번도 쓰이지 않았다.
340+
"""
341+
lines = sectorPositionLines(
342+
{
343+
"industryName": "반도체",
344+
"peerCount": 125,
345+
"myOpmPercentile": 96.0,
346+
"opmDistribution": {"n": 117, "median": 4.1, "p90": 23.8},
347+
}
348+
)
349+
350+
assert lines, "분포와 백분위가 있으면 위치를 말해야 한다"
351+
assert "상위 4%" in lines[0]
352+
assert "중앙값 4.1%" in lines[0]
353+
assert "117사" in lines[0], "몇 개 회사로 잰 값인지 밝혀야 과신을 막는다"
354+
355+
356+
def testSectorPositionIsSilentWithoutPeers() -> None:
357+
"""동종사가 없으면 분포를 지어내지 않는다."""
358+
assert sectorPositionLines(None) == []
359+
assert sectorPositionLines({"industryName": "반도체", "peerCount": 0}) == []
360+
361+
362+
def testSectorAxisWithoutDistributionIsSkipped() -> None:
363+
"""백분위만 있고 분포가 없으면 그 축은 건너뛴다. 기준 없는 순위는 판단이 아니다."""
364+
lines = sectorPositionLines({"industryName": "반도체", "peerCount": 40, "myRoePercentile": 80.0})
365+
366+
assert lines == []
367+
368+
334369
def testContextBlockSurfacesCreditAndIndustry() -> None:
335370
"""이미 계산된 신용 등급과 산업 국면을 본문으로 끌어올린다.
336371

0 commit comments

Comments
 (0)