Files
stock_chart_site/backend/app/fetch/symbols_seed.py
Claude 6ab3679331 feat(seed): KRX live 실패 시 정적 주요종목 fallback (156개)
배경: 토요일/봇차단 등으로 KRX 가 LOGOUT/JSONDecodeError 를 주면
pykrx 가 빈 리스트만 돌려줘서 SEED 10 종목 외엔 검색이 안 되는
회귀가 있었다 (기아/네이버/엔비디아 같은 비-seed 검색 실패).

해결: 시총/거래대금 상위 + 친숙도 기준으로 KOSPI 104 / KOSDAQ 52
= 156 개를 정적 스냅샷 (app/seed/krx_static.py) 으로 묶었다.
seed_symbols() 가 KRX 라이브 fetch 결과가 0건이면 자동으로 이
스냅샷에서 upsert. KRX 가 정상 돌아오면 다음 호출이 라이브 데이터로
자연 덮어쓰여진다. 응답에 static_fallback_used 필드 노출.

수록 항목은 KRX 공시 종목코드 + 현재 등록명 (공개 사실).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-28 01:15:58 +09:00

159 lines
6.2 KiB
Python

"""KRX 전 종목 리스트를 symbols 테이블에 시드한다.
검색 UX 가 KRX 전체 종목명을 대상으로 동작해야 하므로 전 종목을 미리 적재한다.
10 개 SEED_TICKERS 는 is_seed=TRUE 로 마크.
"""
from __future__ import annotations
import logging
from dataclasses import dataclass
from sqlalchemy import text
from app.db.connection import get_engine
from app.seed.krx_static import KRX_STATIC_MAJORS
from app.seed.seed_tickers import SEED_CODES, SEED_TICKERS
logger = logging.getLogger(__name__)
@dataclass
class SeedReport:
inserted: int
updated: int
seed_marked: int
markets: dict[str, int]
static_fallback_used: bool = False
def _fetch_market_listing(market: str) -> list[tuple[str, str]]:
"""pykrx 로 한 시장의 (code, name) 목록을 가져온다.
pykrx 가 외부 KRX 서버에 의존하므로 호출 측에서 예외 처리한다.
"""
from pykrx import stock as krx # local import: heavy import
tickers = krx.get_market_ticker_list(market=market)
out: list[tuple[str, str]] = []
for code in tickers:
name = krx.get_market_ticker_name(code) or ""
if not name:
continue
out.append((code, name))
return out
def _upsert_seed_tickers() -> int:
"""SEED 10종목 강제 upsert. 네트워크 불필요 → KRX 실패와 무관하게 항상 성공.
별도 트랜잭션이라 KRX 시드가 나중에 실패해도 살아남는다.
"""
engine = get_engine()
with engine.begin() as conn:
for t in SEED_TICKERS:
conn.execute(
text(
"""
INSERT INTO symbols (code, name, market, is_seed)
VALUES (:code, :name, :market, TRUE)
ON CONFLICT (code) DO UPDATE
SET name = EXCLUDED.name,
market = EXCLUDED.market,
is_seed = TRUE
"""
),
{"code": t.code, "name": t.name, "market": t.market},
)
return len(SEED_TICKERS)
def seed_symbols() -> SeedReport:
"""KOSPI + KOSDAQ 전 종목을 upsert. SEED 10 종목은 is_seed=TRUE.
순서:
1) SEED_TICKERS 먼저 별도 트랜잭션으로 강제 upsert (KRX 실패와 무관하게 검색 가능)
2) KRX 리스팅 fetch (네트워크 의존) → 별도 트랜잭션으로 일괄 upsert.
시장별 fetch 실패 시 해당 시장만 스킵하고 나머지 진행.
"""
# 1) SEED_TICKERS — 항상 보장
try:
_upsert_seed_tickers()
seed_marked = len(SEED_TICKERS)
logger.info("seed_symbols: seed-tickers upserted (%d)", seed_marked)
except Exception as e: # noqa: BLE001
# logger.exception 은 Python 3.11 의 traceback 포매터가 pykrx 소스의 한글 주석
# 'df = 가...' 바이트를 만나면 UnicodeDecodeError 를 던지는 버그가 있어, 그 예외가
# try 밖으로 escape 해서 500 을 만든다. 그래서 traceback 안 찍는다.
logger.error("seed_symbols: seed-tickers upsert failed: %s", repr(e)[:300])
seed_marked = 0
# 2) KRX 전 종목 — fetch 실패해도 부분 성공 허용
market_counts: dict[str, int] = {}
all_rows: list[tuple[str, str, str]] = []
for market in ("KOSPI", "KOSDAQ"):
try:
listing = _fetch_market_listing(market)
market_counts[market] = len(listing)
for code, name in listing:
all_rows.append((code, name, market))
logger.info("seed_symbols: KRX %s fetched (%d)", market, len(listing))
except Exception as e: # noqa: BLE001
logger.error("seed_symbols: KRX %s fetch failed — skip market: %s", market, repr(e)[:300])
market_counts[market] = 0
# 2b) KRX 가 0건만 줬으면 정적 스냅샷 (krx_static.KRX_STATIC_MAJORS) 으로 fallback.
# KRX 가 LOGOUT/JSONDecode 로 막혀도 주요 종목 검색은 동작하게 만든다.
# KRX 가 정상으로 돌아오면 다음 호출에서 all_rows 가 채워져 자동으로 덮어쓰여진다.
static_fallback_used = False
if not all_rows:
logger.warning(
"seed_symbols: KRX live fetch empty — fallback to static snapshot (%d majors)",
len(KRX_STATIC_MAJORS),
)
all_rows = list(KRX_STATIC_MAJORS)
static_fallback_used = True
# market_counts 도 fallback 으로 채워 응답에 반영
for _c, _n, m in KRX_STATIC_MAJORS:
market_counts[m] = market_counts.get(m, 0) + 1
inserted = updated = 0
if all_rows:
engine = get_engine()
try:
with engine.begin() as conn:
for code, name, market in all_rows:
is_seed = code in SEED_CODES
res = conn.execute(
text(
"""
INSERT INTO symbols (code, name, market, is_seed)
VALUES (:code, :name, :market, :is_seed)
ON CONFLICT (code) DO UPDATE
SET name = EXCLUDED.name,
market = EXCLUDED.market,
is_seed = symbols.is_seed OR EXCLUDED.is_seed
RETURNING (xmax = 0) AS inserted
"""
),
{"code": code, "name": name, "market": market, "is_seed": is_seed},
)
row = res.first()
if row and row[0]:
inserted += 1
else:
updated += 1
except Exception as e: # noqa: BLE001
logger.error("seed_symbols: KRX bulk upsert failed (transaction rolled back): %s", repr(e)[:300])
logger.info(
"seed_symbols done: inserted=%d updated=%d seed_marked=%d markets=%s static_fallback=%s",
inserted, updated, seed_marked, market_counts, static_fallback_used,
)
return SeedReport(
inserted=inserted,
updated=updated,
seed_marked=seed_marked,
markets=market_counts,
static_fallback_used=static_fallback_used,
)