|
| 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