Skip to content

Commit 9b7b170

Browse files
committed
수정: 어느 회사에서도 값을 못 내던 DCF 입력 세 갈래를 잇는다
DCFValuation 도구가 모든 회사에서 "finance.timeseries 추출 실패" 로 끝났다. 입력 해석기 셋이 전부 None 을 돌려줬기 때문이다. 세 갈래 다 표면에서 빠진 이름을 보고 있었다. 재무 시계열은 `company.finance`, 발행주식수는 `sharesOutstanding` 과 `shares` 와 `totalShares`, 주가는 `currentPrice` 와 `price` 다. 여섯 이름 전부 존재하지 않는데 `getattr(..., None)` 과 넓은 except 가 그 사실을 지웠다. 살아 있는 공급원으로 잇는다. 시계열은 회사가 이미 갖고 있는 finance 빌드, 주식수는 `capital` 축의 발행주식총수, 주가는 공개 계약 `gather("price", 코드)` 의 종가 마지막 값이다. 밸류에이션 계산부의 주가 조회에도 같은 결함이 있었다. 거기서는 두 갈래가 다 죽어 있었는데, `currentPrice` 는 없는 이름이고 대체 경로가 부르던 객체는 호출할 수 없어 TypeError 로 떨어졌다. 둘 다 except 가 삼켰다. 같은 계약 호출로 바꿨다. 삼성전자 실측. 도구가 시나리오 셋(bear·base·bull)을 할인율과 성장률과 기업가치와 함께 낸다. 주가 220,000 원, 발행주식 250 억 주. 해석기 셋을 각각 붙드는 가드를 넣었다. 기존 테스트는 등록 여부와 잘못된 코드만 봐서 이 전면 정지를 못 잡았다.
1 parent 754b90c commit 9b7b170

3 files changed

Lines changed: 113 additions & 43 deletions

File tree

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

Lines changed: 47 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -53,50 +53,66 @@ def _resolveSectorParams(company: Any) -> Any:
5353

5454

5555
def _resolveSeries(company: Any) -> dict | None:
56-
"""Company → finance.timeseries dict (BS/IS/CF). 실패 시 None."""
56+
"""Company → 재무 시계열 dict (BS/IS/CF). 실패 시 None.
57+
58+
예전에는 `company.finance.timeseries` 를 읽었다. `finance` 는 표면에서 빠진 이름이라
59+
늘 None 이었고, 호출부가 그 자리에서 곧바로 "series_unavailable" 로 끝냈다. 그래서
60+
이 도구가 어느 회사에서도 결과를 못 냈다. 회사가 이미 갖고 있는 finance 빌드를 쓴다.
61+
"""
5762
if company is None:
5863
return None
64+
build = getattr(company, "_getFinanceBuild", None)
65+
if build is None:
66+
return None
5967
try:
60-
fin = getattr(company, "finance", None)
61-
if fin is not None:
62-
ts = getattr(fin, "timeseries", None)
63-
if isinstance(ts, dict) and ts:
64-
return ts
65-
except Exception: # noqa: BLE001
66-
pass
67-
return None
68+
pair = build("q")
69+
except (AttributeError, KeyError, OSError, RuntimeError, TypeError, ValueError):
70+
return None
71+
if not pair:
72+
return None
73+
series = pair[0]
74+
return series if isinstance(series, dict) and series else None
6875

6976

7077
def _resolveShares(company: Any) -> int | None:
71-
"""Company → 발행주식수. 여러 attr 후보 순차 시도."""
78+
"""Company → 발행주식수. 실패 시 None.
79+
80+
옛 구현은 `sharesOutstanding` · `shares` · `totalShares` 세 이름을 차례로 봤는데 셋 다
81+
표면에 없어서 늘 None 이었다. 지금 공급원은 `capital` 축의 발행주식총수다.
82+
"""
7283
if company is None:
7384
return None
74-
for attr in ("sharesOutstanding", "shares", "totalShares"):
75-
try:
76-
v = getattr(company, attr, None)
77-
if callable(v):
78-
v = v()
79-
if v:
80-
return int(v)
81-
except Exception: # noqa: BLE001
82-
continue
83-
return None
85+
try:
86+
df = company.capital()
87+
except (AttributeError, KeyError, OSError, RuntimeError, TypeError, ValueError):
88+
return None
89+
if df is None or getattr(df, "height", 0) == 0:
90+
return None
91+
value = df.row(0, named=True).get("발행주식총수")
92+
return int(value) if value else None
8493

8594

8695
def _resolveCurrentPrice(company: Any) -> float | None:
87-
"""Company → 현재 주가. 여러 attr 후보 순차 시도."""
96+
"""Company → 현재 주가. 실패 시 None.
97+
98+
옛 구현은 `currentPrice` · `price` 두 이름을 봤는데 둘 다 표면에 없어서 늘 None 이었다.
99+
지금 공급원은 공개 계약 `dartlab.gather("price", 종목코드)` 의 종가 마지막 값이다.
100+
"""
88101
if company is None:
89102
return None
90-
for attr in ("currentPrice", "price"):
91-
try:
92-
v = getattr(company, attr, None)
93-
if callable(v):
94-
v = v()
95-
if v:
96-
return float(v)
97-
except Exception: # noqa: BLE001
98-
continue
99-
return None
103+
code = getattr(company, "stockCode", "")
104+
if not code:
105+
return None
106+
try:
107+
import dartlab
108+
109+
rows = dartlab.gather("price", code)
110+
except (ImportError, AttributeError, KeyError, OSError, RuntimeError, TypeError, ValueError):
111+
return None
112+
if rows is None or getattr(rows, "height", 0) == 0 or "close" not in getattr(rows, "columns", []):
113+
return None
114+
last = rows["close"][-1]
115+
return float(last) if last is not None else None
100116

101117

102118
def _scenarioDict(dcf: Any, name: str) -> dict[str, Any]:

‎src/dartlab/analysis/valuation/_dFVCalcs.py‎

Lines changed: 15 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -118,19 +118,22 @@ def _getCurrentPrice(company: Any) -> float | None:
118118
float | None
119119
현재 주가 (원). 조회 실패 시 None.
120120
"""
121+
# 두 갈래가 다 죽어 있었다. `currentPrice` 는 표면에서 빠진 이름이라 늘 None 이고,
122+
# `getDefaultGather()` 가 돌려주는 객체는 호출할 수 없어 TypeError 로 떨어졌다. 둘 다
123+
# except 가 삼켜서 이 함수는 어느 회사에서도 주가를 못 냈다. 공개 계약으로 부른다.
124+
code = getattr(company, "stockCode", "")
125+
if not code:
126+
return None
121127
try:
122-
price = getattr(company, "currentPrice", None)
123-
if price:
124-
return float(price)
125-
from dartlab.core.di import getMacroProvider
126-
127-
g = getMacroProvider().getDefaultGather()
128-
p = g("price", getattr(company, "stockCode", ""))
129-
if p is not None and hasattr(p, "height") and p.height > 0:
130-
return float(p["close"][-1])
131-
except (ImportError, AttributeError, ValueError, TypeError, KeyError):
132-
pass
133-
return None
128+
import dartlab
129+
130+
rows = dartlab.gather("price", code)
131+
except (ImportError, AttributeError, ValueError, TypeError, KeyError, OSError, RuntimeError):
132+
return None
133+
if rows is None or getattr(rows, "height", 0) == 0 or "close" not in getattr(rows, "columns", []):
134+
return None
135+
last = rows["close"][-1]
136+
return float(last) if last is not None else None
134137

135138

136139
def _calcOpinion(upside: float | None) -> str:

‎tests/ai/test_dcf_valuation_tool.py‎

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -94,3 +94,54 @@ def test_dcfValuation_confidence_uses_forecast_method() -> None:
9494
from dartlab.core.confidence import baseScore
9595

9696
assert baseScore("forecast") == 30
97+
98+
99+
# ── 입력 해석기: 살아 있는 공급원을 보는가 ──
100+
101+
102+
class _ContractCompany:
103+
"""DCF 입력 세 갈래를 계약/내부 공급원으로만 제공하는 Company 대역."""
104+
105+
stockCode = "999999"
106+
corpName = "테스트기업"
107+
108+
def _getFinanceBuild(self, period: str = "q", fsDivPref: str = "CFS"):
109+
return ({"IS": {"sales": [1.0]}, "BS": {"total_assets": [2.0]}, "CF": {}}, ["2025Q4"])
110+
111+
def capital(self):
112+
import polars as pl
113+
114+
return pl.DataFrame({"stockCode": ["999999"], "발행주식총수": [1000.0]})
115+
116+
117+
def test_resolveSeries_usesFinanceBuild() -> None:
118+
"""재무 시계열은 회사의 finance 빌드에서 나온다.
119+
120+
예전에는 `company.finance.timeseries` 를 읽었다. `finance` 는 표면에서 빠진 이름이라
121+
늘 None 이었고, 호출부가 곧바로 series_unavailable 로 끝내서 이 도구가 어느 회사에서도
122+
결과를 못 냈다.
123+
"""
124+
from dartlab.ai.tools.dcfValuationTool import _resolveSeries
125+
126+
series = _resolveSeries(_ContractCompany())
127+
128+
assert series and set(series) >= {"IS", "BS"}
129+
130+
131+
def test_resolveShares_usesCapitalAxis() -> None:
132+
"""발행주식수는 `capital` 축에서 나온다 (옛 세 후보 이름은 전부 표면에 없다)."""
133+
from dartlab.ai.tools.dcfValuationTool import _resolveShares
134+
135+
assert _resolveShares(_ContractCompany()) == 1000
136+
137+
138+
def test_resolveCurrentPrice_usesGatherContract(monkeypatch) -> None:
139+
"""현재 주가는 공개 계약 `dartlab.gather("price", 코드)` 에서 나온다."""
140+
import polars as pl
141+
142+
import dartlab
143+
from dartlab.ai.tools.dcfValuationTool import _resolveCurrentPrice
144+
145+
monkeypatch.setattr(dartlab, "gather", lambda axis, code: pl.DataFrame({"close": [100.0, 220.0]}))
146+
147+
assert _resolveCurrentPrice(_ContractCompany()) == 220.0

0 commit comments

Comments
 (0)