Skip to content

Commit db4a9c4

Browse files
committed
수정: 부르면 늘 죽던 재무 차트 다섯을 계약 호출로 되살린다
`viz.charts` 의 재무 템플릿 차트 다섯이 회사 자료와 무관하게 항상 죽었다. 매출 추세, 현금흐름, 재무상태표, 수익성, 배당이다. 원인은 `company.IS` 와 `company.BS` 와 `company.CF` 와 `company.dividend` 를 속성 으로 읽은 것이다. 그 이름들은 공개 계약에서 빠져 지금은 존재하지 않는다. `getattr(..., None)` 이 늘 None 을 돌려주니 곧바로 데이터가 없다는 예외로 갔다. 차트마다 같은 네 줄이 복붙돼 있어서 다섯 자리가 똑같이 죽었다. 재무제표 셋은 `_statementFrame` 한 자리로 모으고 `c.panel(축)` 으로 부른다. panel 이 주는 항목 열과 기간 열이 기존 추출기가 기대하던 형태 그대로다. 배당은 사정이 다르다. 옛 구현은 연도별 표를 기대했는데 지금 남은 공급원은 `capital` 축의 현재 시점 한 행(DPS, 배당수익률)뿐이다. 연도별 시계열은 계약 표면에 아직 없다. 없는 것을 지어내지 않고 있는 것만 그리도록 바꾸고, 그 사실을 docstring 에 적었다. 쓰지 않는 배당성향 가지는 걷어냈다. 삼성전자 실측. 다섯 차트가 각각 trace 4, 3, 2, 3, 2 개로 그려진다. 계약 호출만으로 그려지는지 검사하는 가드를 다섯 차트 전부에 붙였다.
1 parent a78d0b5 commit db4a9c4

2 files changed

Lines changed: 90 additions & 41 deletions

File tree

‎src/dartlab/viz/charts/__init__.py‎

Lines changed: 44 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,22 @@ def waterfall(
275275
# ── 재무 템플릿 차트 ──
276276

277277

278+
def _statementFrame(company: Any, axis: str, label: str) -> pl.DataFrame:
279+
"""공개 계약 `panel` 로 재무제표 한 장을 얻는다. 없으면 ValueError.
280+
281+
예전에는 `company.IS` 처럼 속성으로 읽었다. 그 이름들은 공개 계약에서 빠졌고 지금은
282+
존재하지 않는다. `getattr(..., None)` 이 늘 None 을 돌려주니 아래 차트 다섯이 전부
283+
"데이터가 없습니다" 로 죽고 있었다. 회사에 자료가 있고 없고와 무관하게 항상 그랬다.
284+
"""
285+
try:
286+
df = company.panel(axis)
287+
except (AttributeError, KeyError, TypeError, ValueError) as exc:
288+
raise ValueError(f"{axis} ({label}) 데이터가 없습니다.") from exc
289+
if df is None or getattr(df, "height", 0) == 0:
290+
raise ValueError(f"{axis} ({label}) 데이터가 없습니다.")
291+
return df
292+
293+
278294
def _extractAccountSeries(df: pl.DataFrame, keyword: str) -> dict[str, float | None]:
279295
"""재무제표에서 항목 키워드로 연도별 값 추출."""
280296
labelCol = "항목" if "항목" in df.columns else None
@@ -298,9 +314,7 @@ def revenue(company: Any, *, nYears: int = 5) -> Any:
298314
go = _ensurePlotly()
299315
from plotly.subplots import make_subplots
300316

301-
isDf = getattr(company, "IS", None)
302-
if isDf is None:
303-
raise ValueError("IS (손익계산서) 데이터가 없습니다.")
317+
isDf = _statementFrame(company, "IS", "손익계산서")
304318

305319
rev = _extractAccountSeries(isDf, "매출액")
306320
oi = _extractAccountSeries(isDf, "영업이익")
@@ -352,9 +366,7 @@ def cashflow(company: Any, *, nYears: int = 5) -> Any:
352366
"""영업CF/투자CF/재무CF 패턴 차트."""
353367
go = _ensurePlotly()
354368

355-
cf_df = getattr(company, "CF", None)
356-
if cf_df is None:
357-
raise ValueError("CF (현금흐름표) 데이터가 없습니다.")
369+
cf_df = _statementFrame(company, "CF", "현금흐름표")
358370

359371
op = _extractAccountSeries(cf_df, "영업활동")
360372
inv = _extractAccountSeries(cf_df, "투자활동")
@@ -380,50 +392,45 @@ def cashflow(company: Any, *, nYears: int = 5) -> Any:
380392

381393

382394
def dividend(company: Any) -> Any:
383-
"""DPS + 배당수익률 + 배당성향 차트."""
395+
"""DPS 와 배당수익률 차트 (현재 시점).
396+
397+
옛 구현은 `company.dividend` 속성에서 연도별 표를 기대했다. 그 이름은 공개 계약에서
398+
빠졌고, 지금 남은 배당 공급원은 `capital` 축의 현재 시점 한 행이다 (DPS · 배당수익률).
399+
연도별 시계열은 계약 표면에 아직 없다. 없는 것을 지어내지 않고 있는 것만 그린다.
400+
"""
384401
go = _ensurePlotly()
385402
from plotly.subplots import make_subplots
386403

387-
div_df = getattr(company, "dividend", None)
388-
if div_df is None:
389-
raise ValueError("dividend (배당) 데이터가 없습니다.")
390-
391-
if "year" not in div_df.columns:
392-
raise ValueError("year 컬럼이 없습니다.")
393-
394-
df = div_df.sort("year")
404+
try:
405+
df = company.capital()
406+
except (AttributeError, KeyError, TypeError, ValueError) as exc:
407+
raise ValueError("배당 데이터가 없습니다.") from exc
408+
if df is None or getattr(df, "height", 0) == 0:
409+
raise ValueError("배당 데이터가 없습니다.")
410+
411+
row = df.row(0, named=True)
412+
dps = row.get("DPS")
413+
dividendYield = row.get("배당수익률")
414+
if dps is None and dividendYield is None:
415+
raise ValueError("배당 데이터가 없습니다.")
395416

396417
fig = make_subplots(specs=[[{"secondary_y": True}]])
397418

398-
if "dps" in df.columns:
399-
fig.add_trace(
400-
go.Bar(x=df["year"].to_list(), y=df["dps"].to_list(), name="DPS(원)", marker_color=COLORS[2], opacity=0.7)
401-
)
419+
if dps is not None:
420+
fig.add_trace(go.Bar(x=["현재"], y=[dps], name="DPS(원)", marker_color=COLORS[2], opacity=0.7))
402421

403-
if "dividendYield" in df.columns:
422+
if dividendYield is not None:
404423
fig.add_trace(
405424
go.Scatter(
406-
x=df["year"].to_list(),
407-
y=df["dividendYield"].to_list(),
425+
x=["현재"],
426+
y=[dividendYield],
408427
name="배당수익률(%)",
409428
mode="lines+markers",
410429
line=dict(color=COLORS[0], width=2),
411430
),
412431
secondary_y=True,
413432
)
414433

415-
if "payoutRatio" in df.columns:
416-
fig.add_trace(
417-
go.Scatter(
418-
x=df["year"].to_list(),
419-
y=df["payoutRatio"].to_list(),
420-
name="배당성향(%)",
421-
mode="lines+markers",
422-
line=dict(color=COLORS[1], width=2, dash="dot"),
423-
),
424-
secondary_y=True,
425-
)
426-
427434
fig.update_layout(title=f"{company.corpName} 배당 분석")
428435
fig.update_yaxes(title_text="DPS (원)", secondary_y=False)
429436
fig.update_yaxes(title_text="(%)", secondary_y=True)
@@ -436,9 +443,7 @@ def balanceSheet(company: Any, *, nYears: int = 5) -> Any:
436443
"""자산/부채/자본 구성 누적 바 차트."""
437444
go = _ensurePlotly()
438445

439-
bs_df = getattr(company, "BS", None)
440-
if bs_df is None:
441-
raise ValueError("BS (재무상태표) 데이터가 없습니다.")
446+
bs_df = _statementFrame(company, "BS", "재무상태표")
442447

443448
ca = _extractAccountSeries(bs_df, "유동자산")
444449
nca = _extractAccountSeries(bs_df, "비유동자산")
@@ -465,10 +470,8 @@ def profitability(company: Any, *, nYears: int = 5) -> Any:
465470
"""영업이익률·순이익률·ROE 추세 라인 차트."""
466471
go = _ensurePlotly()
467472

468-
bs_df = getattr(company, "BS", None)
469-
isDf = getattr(company, "IS", None)
470-
if bs_df is None or isDf is None:
471-
raise ValueError("BS, IS 데이터가 필요합니다.")
473+
bs_df = _statementFrame(company, "BS", "재무상태표")
474+
isDf = _statementFrame(company, "IS", "손익계산서")
472475

473476
ratios = _ratioTable(bs_df, isDf)
474477
if ratios.height == 0:

‎tests/viz/test_engine.py‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -400,3 +400,49 @@ def test_extract_mixed_valid_invalid():
400400
cleaned, specs = extractVizSpecs(stdout)
401401
assert len(specs) == 1
402402
assert specs[0]["ok"] is True
403+
404+
405+
# ── 재무 템플릿 차트: 계약 호출만으로 그려지는가 ──
406+
407+
_IS_ROWS = {"항목": ["매출액", "영업이익", "당기순이익"], "2024": [100.0, 20.0, 15.0], "2025": [120.0, 25.0, 18.0]}
408+
_BS_ROWS = {
409+
"항목": ["자산총계", "부채총계", "자본총계", "유동자산", "비유동자산"],
410+
"2024": [200.0, 80.0, 120.0, 90.0, 110.0],
411+
"2025": [220.0, 85.0, 135.0, 95.0, 125.0],
412+
}
413+
_CF_ROWS = {"항목": ["영업활동", "투자활동", "재무활동"], "2024": [30.0, -10.0, -5.0], "2025": [35.0, -12.0, -6.0]}
414+
_CAPITAL_ROWS = {"stockCode": ["999999"], "DPS": [372.0], "배당수익률": [0.3]}
415+
416+
417+
class _ContractCompany:
418+
"""공개 계약(`panel` · `capital`) 만 구현한 Company 대역."""
419+
420+
corpName = "테스트기업"
421+
stockCode = "999999"
422+
423+
def panel(self, axis):
424+
import polars as pl
425+
426+
rows = {"IS": _IS_ROWS, "BS": _BS_ROWS, "CF": _CF_ROWS}.get(axis)
427+
return pl.DataFrame(rows) if rows else None
428+
429+
def capital(self):
430+
import polars as pl
431+
432+
return pl.DataFrame(_CAPITAL_ROWS)
433+
434+
435+
@pytest.mark.parametrize("name", ["revenue", "cashflow", "balanceSheet", "profitability", "dividend"])
436+
def test_financeCharts_buildFromContractCallsOnly(name):
437+
"""재무 템플릿 차트가 공개 계약 호출만으로 그려진다.
438+
439+
예전에는 `company.IS` · `company.BS` · `company.CF` · `company.dividend` 속성을 읽었다.
440+
그 이름들은 계약에서 빠져 존재하지 않으므로, 다섯 차트가 회사 자료와 무관하게 늘
441+
데이터가 없다는 예외로 죽고 있었다.
442+
"""
443+
pytest.importorskip("plotly")
444+
from dartlab.viz import charts
445+
446+
fig = getattr(charts, name)(_ContractCompany())
447+
448+
assert getattr(fig, "data", None), f"{name} 차트에 trace 가 없다"

0 commit comments

Comments
 (0)