Skip to content

Commit 2be71f7

Browse files
committed
개선: 재무 건전성 판단이 뒤집히는 지점을 산술로 건넨다
실측에서 잡았다. 업종 기준을 붙여 주니 답변이 "29.9% 는 업종 하위 28% 라 낮은 편" 까지 갔는데, 정작 "이 판단이 틀리려면 무엇이 일어나야 하나" 가 사라졌다. 같은 질문의 직전 답변에는 있었다. 재료가 늘면서 마무리 규율이 밀려난 것이다. 반증 조건이 비싼 이유는 모델이 그 산술을 손으로 해야 하기 때문이다. 지침을 더 쓰는 것은 이미 실패한 방법이다. 현금흐름에서 통한 방법을 그대로 쓴다. 산술을 우리가 해서 건넨다. 두 가지를 적는다. 부채비율이 업종 중앙값에 닿으려면 부채가 얼마나 늘어야 하는지, 그리고 유동부채가 얼마나 더 늘면 유동자산으로 못 덮는지다. 유동비율 100% 는 임의 시나리오가 아니라 정의상 경계다. 이미 경계를 넘은 회사는 여유가 아니라 그 사실을 적는다. 여기에 최근 한 기 변화폭을 나눠 시간 축을 준다. 정적인 비율이 기한 있는 명제가 된다. 방향을 문장에 적는다. 내려가는 지표에 "+" 를 붙이면 정확히 반대로 읽힌다. 실제로 처음 구현에서 하락 중인 유동비율에 상승 부호가 붙어 있었고 실측 출력에서 잡아 고쳤다. 연간 조회는 "년", 분기 조회는 "분기" 로 적어 기간 단위를 헷갈리지 않게 한다. 가정을 지어내지 않는다. 쓰는 것은 당기 재무상태표 수치와 이미 계산된 업종 중앙값과 정의상 경계뿐이고, 시간 축은 산술이며 전망이 아님을 문장에 명시한다. 실측. 삼성전자 조회에서 "부채비율이 업종 중앙값 50.5% 에 닿으려면 자본이 그대로일 때 부채가 지금보다 89.7 조원 늘어야 합니다. 최근 한 기 상승 폭 2.0%p 가 이어지면 10 년 뒤입니다" 와 "유동부채가 지금보다 141.3 조원 늘면 유동자산으로 덮지 못합니다" 가 나온다. 손익계산서 조회에는 아무 것도 붙지 않는다. 추가 조회 0 건, 지연 증가 없음. 테스트 7 건 신설. 방향 단어, 정의상 경계, 손익계산서 제외, 본문 도달을 각각 잠근다.
1 parent 1c8dbf5 commit 2be71f7

3 files changed

Lines changed: 230 additions & 3 deletions

File tree

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -784,7 +784,7 @@ def _buildShowData(
784784
sectorPosition = getSectorPosition(company)
785785
if sectorPosition:
786786
data["sectorPosition"] = sectorPosition
787-
context = contextMarkdown(badge, industryBadge, sectorPosition)
787+
context = contextMarkdown(badge, industryBadge, sectorPosition, summary)
788788
if context:
789789
body = str(data["markdown"])
790790
marker = "근거는 tableRef"

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

Lines changed: 113 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -557,6 +557,112 @@ def cashFlowAnchors(summary: dict[str, Any]) -> list[str]:
557557
return notes
558558

559559

560+
def _paceNote(distance: float, step: float, direction: str, unit: str) -> str:
561+
"""남은 거리를 최근 한 기 변화폭으로 나눈다. 산술이지 전망이 아니라고 못 박는다.
562+
563+
방향을 문장에 적는다. 내려가는 지표에 "+" 를 붙이면 정확히 반대로 읽힌다.
564+
"""
565+
if step <= 0 or distance <= 0:
566+
return ""
567+
return (
568+
f" 최근 한 기 {direction} 폭 {step:.1f}%p가 이어지면 {distance / step:.0f} {unit} 뒤입니다"
569+
f"(산술이며 전망이 아닙니다)."
570+
)
571+
572+
573+
def _debtTripwire(
574+
indexed: dict[str, dict[str, Any]], periods: list[str], position: dict[str, Any] | None, unit: str
575+
) -> list[str]:
576+
"""부채비율이 업종 중앙값에 닿으려면 부채가 얼마나 늘어야 하는지 적는다."""
577+
liabilities = indexed.get("total_liabilities")
578+
equity = _pick(indexed, ("total_stockholders_equity", "total_equity"))
579+
distribution = (position or {}).get("debtRatioDistribution")
580+
if liabilities is None or equity is None or not isinstance(distribution, dict):
581+
return []
582+
median = distribution.get("median")
583+
if not isinstance(median, (int, float)):
584+
return []
585+
latest = periods[0]
586+
debtNow = _numeric(liabilities.get("values"), latest)
587+
equityNow = _numeric(equity.get("values"), latest)
588+
if debtNow is None or not equityNow:
589+
return []
590+
ratioNow = debtNow / equityNow * 100
591+
target = float(median)
592+
gap = (target / 100) * equityNow - debtNow
593+
if gap <= 0:
594+
return [
595+
f"부채비율 {ratioNow:.1f}%는 이미 업종 중앙값 {target:.1f}% 위입니다. "
596+
f"중앙값으로 돌아가려면 자본이 그대로일 때 부채가 {_formatAmount(-gap).lstrip('+')} 줄어야 합니다."
597+
]
598+
note = (
599+
f"부채비율이 업종 중앙값 {target:.1f}%에 닿으려면 자본이 그대로일 때 부채가 지금보다 "
600+
f"{_formatAmount(gap).lstrip('+')} 늘어야 합니다(현재 {ratioNow:.1f}%)."
601+
)
602+
if len(periods) >= 2:
603+
debtPrior = _numeric(liabilities.get("values"), periods[1])
604+
equityPrior = _numeric(equity.get("values"), periods[1])
605+
if debtPrior is not None and equityPrior:
606+
note += _paceNote(target - ratioNow, ratioNow - debtPrior / equityPrior * 100, "상승", unit)
607+
return [note]
608+
609+
610+
def _liquidityTripwire(indexed: dict[str, dict[str, Any]], periods: list[str], unit: str) -> list[str]:
611+
"""유동부채가 얼마나 더 늘면 유동자산으로 못 덮는지 적는다. 100%는 정의상 경계다."""
612+
assets = indexed.get("current_assets")
613+
liabilities = indexed.get("current_liabilities")
614+
if assets is None or liabilities is None:
615+
return []
616+
latest = periods[0]
617+
assetsNow = _numeric(assets.get("values"), latest)
618+
liabilitiesNow = _numeric(liabilities.get("values"), latest)
619+
if assetsNow is None or not liabilitiesNow:
620+
return []
621+
ratioNow = assetsNow / liabilitiesNow * 100
622+
if ratioNow <= 100:
623+
return [f"유동비율 {ratioNow:.1f}%로 유동자산이 이미 유동부채에 못 미칩니다."]
624+
note = (
625+
f"유동부채가 지금보다 {_formatAmount(assetsNow - liabilitiesNow).lstrip('+')} 늘면 "
626+
f"유동자산으로 덮지 못합니다(유동비율 100%). 현재 {ratioNow:.1f}%입니다."
627+
)
628+
if len(periods) >= 2:
629+
assetsPrior = _numeric(assets.get("values"), periods[1])
630+
liabilitiesPrior = _numeric(liabilities.get("values"), periods[1])
631+
if assetsPrior is not None and liabilitiesPrior:
632+
note += _paceNote(ratioNow - 100, assetsPrior / liabilitiesPrior * 100 - ratioNow, "하락", unit)
633+
return [note]
634+
635+
636+
def balanceTripwires(summary: dict[str, Any], position: dict[str, Any] | None) -> list[str]:
637+
"""재무 건전성 판단이 뒤집히는 지점을 산술로 적는다.
638+
639+
실측(2026-08-06): 업종 기준을 붙여 주니 답변이 "29.9%는 업종 하위 28%라 낮은 편" 까지
640+
갔는데, 정작 "이 판단이 틀리려면 무엇이 일어나야 하나" 는 사라졌다. 재료가 늘면서
641+
마무리 규율이 밀려난 것이다. 반증 조건이 비싼 이유는 모델이 그 산술을 손으로 해야
642+
하기 때문이다. 현금흐름에서 통한 방법을 그대로 쓴다. 산술을 우리가 해서 건넨다.
643+
644+
가정을 지어내지 않는다. 쓰는 것은 당기 재무상태표 수치와 이미 계산된 업종 중앙값,
645+
그리고 유동비율 100%라는 정의상 경계뿐이다.
646+
647+
Args:
648+
summary: `Company.panel` tool 결과의 summary. 재무상태표가 아니면 빈 목록이다.
649+
position: `getSectorPosition` 결과. 없으면 유동성 임계만 적는다.
650+
651+
Returns:
652+
list[str]: 사람이 읽는 한 줄 노트 목록.
653+
654+
Example:
655+
`notes = balanceTripwires(summary, position)`
656+
"""
657+
periods = [str(p) for p in (summary.get("periods") or [])]
658+
timeseries = [row for row in (summary.get("timeseries") or []) if isinstance(row, dict)]
659+
if not periods or not timeseries:
660+
return []
661+
indexed = _withDerivedEquity(_seriesByKey(timeseries), periods)
662+
unit = "년" if summary.get("projection") == "annual" else "분기"
663+
return _debtTripwire(indexed, periods, position, unit) + _liquidityTripwire(indexed, periods, unit)
664+
665+
560666
# (표시 이름, 백분위 키, 분포 키, 높을수록 좋은가).
561667
# 방향을 표에 박아 둔다. 부채비율은 낮을수록 안전한데 "상위 몇 %" 로 적으면 정반대로 읽힌다.
562668
_SECTOR_AXES: tuple[tuple[str, str, str, bool], ...] = (
@@ -617,6 +723,7 @@ def contextMarkdown(
617723
dcrBadge: dict[str, Any] | None,
618724
industryBadge: dict[str, Any] | None,
619725
sectorPosition: dict[str, Any] | None = None,
726+
summary: dict[str, Any] | None = None,
620727
) -> str:
621728
"""이미 계산돼 붙어 있는 신용 등급과 산업 위치를 답변 표면으로 끌어올린다.
622729
@@ -661,9 +768,13 @@ def contextMarkdown(
661768
line += f" 같은 산업 비교 후보: {', '.join(peers)}."
662769
lines.append(line)
663770
lines.extend(sectorPositionLines(sectorPosition))
664-
if not lines:
771+
tripwires = balanceTripwires(summary or {}, sectorPosition)
772+
if not lines and not tripwires:
665773
return ""
666-
return "## 회사 위치\n" + "\n".join(lines) + "\n"
774+
block = "## 회사 위치\n" + "\n".join(lines) + "\n" if lines else ""
775+
if tripwires:
776+
block += "\n## 판단이 뒤집히는 지점\n" + "\n".join(f"- {note}" for note in tripwires) + "\n"
777+
return block
667778

668779

669780
def insightMarkdown(summary: dict[str, Any]) -> str:

‎tests/ai/test_panel_insight.py‎

Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
import pytest
1010

1111
from dartlab.ai.tools.panelInsight import (
12+
balanceTripwires,
1213
cashFlowAnchors,
1314
cashFlowPattern,
1415
contextMarkdown,
@@ -412,3 +413,118 @@ def testMissingValuesDoNotCrash() -> None:
412413
block = insightMarkdown(summary)
413414

414415
assert "-" in block
416+
417+
418+
def _balanceSummary(**values: dict[str, float]) -> dict[str, object]:
419+
"""재무상태표 모양의 summary. 항목 이름은 재무제표 매핑의 정본 snakeId 다."""
420+
periods = ["2025FY", "2024FY", "2023FY"]
421+
labels = {
422+
"total_assets": "자산총계",
423+
"total_liabilities": "부채총계",
424+
"total_stockholders_equity": "자본총계",
425+
"current_assets": "유동자산",
426+
"current_liabilities": "유동부채",
427+
}
428+
return {
429+
"periods": periods,
430+
"latestPeriod": periods[0],
431+
"projection": "annual",
432+
"timeseries": [
433+
{"snakeId": key, "item": labels.get(key, key), "values": series, "formatted": {}}
434+
for key, series in values.items()
435+
],
436+
"rows": [],
437+
}
438+
439+
440+
def _debtPosition(median: float) -> dict[str, object]:
441+
return {"peerCount": 117, "debtRatioDistribution": {"n": 117, "median": median, "p10": 17.0}}
442+
443+
444+
def testDebtTripwireStatesHowMuchDebtWouldReachTheSectorMedian() -> None:
445+
"""반증 조건은 산술이다. 모델이 손으로 하게 두면 비싸서 그냥 빠진다."""
446+
summary = _balanceSummary(
447+
total_liabilities={"2025FY": 100e12, "2024FY": 90e12},
448+
total_stockholders_equity={"2025FY": 400e12, "2024FY": 380e12},
449+
)
450+
451+
notes = balanceTripwires(summary, _debtPosition(50.0))
452+
453+
# 부채비율 25.0% 에서 중앙값 50.0% 에 닿으려면 부채가 400조의 절반인 200조여야 한다.
454+
assert any("100.0조원 늘어야" in note for note in notes)
455+
assert any("현재 25.0%" in note for note in notes)
456+
457+
458+
def testDebtTripwireFlipsDirectionWhenAlreadyAboveMedian() -> None:
459+
"""중앙값 위에 있으면 얼마나 늘어야 하는지가 아니라 얼마나 줄어야 하는지가 질문이다."""
460+
summary = _balanceSummary(
461+
total_liabilities={"2025FY": 300e12},
462+
total_stockholders_equity={"2025FY": 400e12},
463+
)
464+
465+
notes = balanceTripwires(summary, _debtPosition(50.0))
466+
467+
assert any("줄어야" in note for note in notes)
468+
assert not any("늘어야" in note for note in notes)
469+
470+
471+
def testLiquidityTripwireUsesTheHundredPercentDefinitionBoundary() -> None:
472+
"""유동비율 100% 는 임의 시나리오가 아니라 정의상 경계다."""
473+
summary = _balanceSummary(
474+
current_assets={"2025FY": 300e12},
475+
current_liabilities={"2025FY": 120e12},
476+
)
477+
478+
notes = balanceTripwires(summary, None)
479+
480+
assert any("180.0조원 늘면" in note and "유동비율 100%" in note for note in notes)
481+
482+
483+
def testLiquidityTripwireSaysSoWhenAlreadyBelowTheBoundary() -> None:
484+
"""이미 못 덮고 있으면 여유를 말할 것이 아니라 그 사실을 적어야 한다."""
485+
summary = _balanceSummary(
486+
current_assets={"2025FY": 80e12},
487+
current_liabilities={"2025FY": 120e12},
488+
)
489+
490+
notes = balanceTripwires(summary, None)
491+
492+
assert any("못 미칩니다" in note for note in notes)
493+
494+
495+
def testPaceNoteNamesTheDirectionItIsMoving() -> None:
496+
"""내려가는 지표에 상승이라고 적으면 정확히 반대로 읽힌다."""
497+
summary = _balanceSummary(
498+
total_liabilities={"2025FY": 100e12, "2024FY": 90e12},
499+
total_stockholders_equity={"2025FY": 400e12, "2024FY": 400e12},
500+
current_assets={"2025FY": 300e12, "2024FY": 320e12},
501+
current_liabilities={"2025FY": 120e12, "2024FY": 120e12},
502+
)
503+
504+
notes = balanceTripwires(summary, _debtPosition(50.0))
505+
joined = "\n".join(notes)
506+
507+
assert "상승 폭" in joined
508+
assert "하락 폭" in joined
509+
assert "전망이 아닙니다" in joined
510+
assert "년 뒤" in joined
511+
512+
513+
def testTripwiresAreEmptyForIncomeStatements() -> None:
514+
"""손익계산서에는 재무상태표 임계가 없다. 없는 것을 지어내지 않는다."""
515+
summary = _summary(sales={"2025FY": 300e12}, operating_profit={"2025FY": 30e12})
516+
517+
assert balanceTripwires(summary, _debtPosition(50.0)) == []
518+
519+
520+
def testTripwiresReachTheContextBlock() -> None:
521+
"""계산만 되고 본문에 안 실리면 모델은 보지 못한다. payload 안에만 있던 실패의 반복이다."""
522+
summary = _balanceSummary(
523+
current_assets={"2025FY": 300e12},
524+
current_liabilities={"2025FY": 120e12},
525+
)
526+
527+
block = contextMarkdown(None, None, None, summary)
528+
529+
assert "판단이 뒤집히는 지점" in block
530+
assert "유동비율 100%" in block

0 commit comments

Comments
 (0)