feat(home+search): KOSPI/KOSDAQ 인덱스 카드 + 검색결과 미니 sparkline
- Sparkline 컴포넌트를 PriceHero 내부에서 web/components/Sparkline.tsx 로 분리·재사용 - /api/markets/indices: macro_daily 의 kospi/kosdaq N일 시계열 + 최신값/전일대비 - 홈 IndicesPanel: 두 인덱스 카드(현재값/등락/우측 sparkline) - /api/symbols/search?with_sparkline=true: 결과 한 번에 최근 30 종가 batch 조회 - SearchBox 결과 행에 mini sparkline + 현재가/등락률 인라인 표시 Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
@@ -118,6 +118,60 @@ def movers(
|
||||
}
|
||||
|
||||
|
||||
@router.get("/indices")
|
||||
def indices(days: int = Query(default=60, ge=2, le=400)) -> dict:
|
||||
"""KOSPI / KOSDAQ 지수 N일 종가 시계열.
|
||||
|
||||
macro_daily 에 yfinance 가 채우는 'kospi','kosdaq' key 를 그대로 읽음.
|
||||
채워져 있지 않으면 series 가 빈 배열로 반환되어 프런트가 '데이터 준비 중' 안내.
|
||||
"""
|
||||
sql = text(
|
||||
"""
|
||||
SELECT date, key, value
|
||||
FROM macro_daily
|
||||
WHERE key IN ('kospi','kosdaq')
|
||||
AND date >= (CURRENT_DATE - (:d || ' day')::interval)
|
||||
ORDER BY date ASC
|
||||
"""
|
||||
)
|
||||
eng = get_engine()
|
||||
with eng.connect() as conn:
|
||||
rows = conn.execute(sql, {"d": days}).all()
|
||||
|
||||
series: dict[str, list[dict]] = {"kospi": [], "kosdaq": []}
|
||||
for r in rows:
|
||||
d, k, v = r[0], r[1], r[2]
|
||||
if v is None:
|
||||
continue
|
||||
series.setdefault(k, []).append({"date": str(d), "value": float(v)})
|
||||
|
||||
def _summary(pts: list[dict]) -> dict:
|
||||
if not pts:
|
||||
return {"latest": None, "prev": None, "pct_change": None}
|
||||
latest = pts[-1]["value"]
|
||||
prev = pts[-2]["value"] if len(pts) >= 2 else None
|
||||
pct = ((latest - prev) / prev * 100) if (prev and prev > 0) else None
|
||||
return {"latest": latest, "prev": prev, "pct_change": pct}
|
||||
|
||||
return {
|
||||
"days": days,
|
||||
"indices": [
|
||||
{
|
||||
"key": "kospi",
|
||||
"name": "KOSPI",
|
||||
"points": series["kospi"],
|
||||
**_summary(series["kospi"]),
|
||||
},
|
||||
{
|
||||
"key": "kosdaq",
|
||||
"name": "KOSDAQ",
|
||||
"points": series["kosdaq"],
|
||||
**_summary(series["kosdaq"]),
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/related/{code}")
|
||||
def related(code: str, limit: int = Query(default=8, ge=1, le=30)) -> dict:
|
||||
"""같은 market 에서 등락률 절대값 기준 가까운 종목 N 개.
|
||||
|
||||
@@ -14,6 +14,10 @@ def search_symbols(
|
||||
q: str = Query(..., min_length=1, max_length=40, description="종목명 또는 코드 prefix/부분 일치"),
|
||||
limit: int = Query(default=20, ge=1, le=100),
|
||||
seed_only: bool = Query(default=False, description="true 면 학습/배치 대상 10종목만"),
|
||||
with_sparkline: bool = Query(
|
||||
default=False,
|
||||
description="true 면 각 결과에 최근 30 종가 + 전일대비 동봉 (검색 결과 미니차트용)",
|
||||
),
|
||||
) -> dict:
|
||||
"""이름은 trigram + ILIKE, 코드는 prefix 매치.
|
||||
|
||||
@@ -21,6 +25,11 @@ def search_symbols(
|
||||
1) 코드가 정확히 같으면 가장 위
|
||||
2) 이름 prefix 매치
|
||||
3) 이름 부분 매치 (trigram similarity)
|
||||
|
||||
with_sparkline=true 시:
|
||||
- 매치된 코드들에 대해 ohlcv_daily 최근 30 거래일 종가 한 번에 조회
|
||||
- items[*].sparkline (list[float]) + items[*].close + items[*].pct_change 채움
|
||||
- 데이터 없는 종목은 sparkline=[], close=None
|
||||
"""
|
||||
q_norm = q.strip()
|
||||
if not q_norm:
|
||||
@@ -61,19 +70,51 @@ def search_symbols(
|
||||
"lim": limit,
|
||||
},
|
||||
).all()
|
||||
|
||||
codes = [r[0] for r in rows]
|
||||
spark_by_code: dict[str, list[float]] = {c: [] for c in codes}
|
||||
if with_sparkline and codes:
|
||||
# 최근 30 거래일 종가 — 종목별로 ORDER BY date ASC.
|
||||
spark_rows = conn.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT code, date, close FROM (
|
||||
SELECT code, date, close,
|
||||
ROW_NUMBER() OVER (PARTITION BY code ORDER BY date DESC) AS rn
|
||||
FROM ohlcv_daily
|
||||
WHERE code = ANY(:codes) AND close IS NOT NULL
|
||||
) t
|
||||
WHERE rn <= 30
|
||||
ORDER BY code, date ASC
|
||||
"""
|
||||
),
|
||||
{"codes": codes},
|
||||
).all()
|
||||
for code, _d, close in spark_rows:
|
||||
spark_by_code.setdefault(code, []).append(float(close))
|
||||
|
||||
def _item(r) -> dict:
|
||||
code = r[0]
|
||||
pts = spark_by_code.get(code, []) if with_sparkline else None
|
||||
out: dict[str, object] = {
|
||||
"code": code,
|
||||
"name": r[1],
|
||||
"market": r[2],
|
||||
"sector": r[3],
|
||||
"is_seed": bool(r[4]),
|
||||
}
|
||||
if with_sparkline:
|
||||
out["sparkline"] = pts or []
|
||||
out["close"] = pts[-1] if pts else None
|
||||
out["pct_change"] = (
|
||||
(pts[-1] - pts[-2]) / pts[-2] * 100 if (pts and len(pts) >= 2 and pts[-2]) else None
|
||||
)
|
||||
return out
|
||||
|
||||
return {
|
||||
"q": q_norm,
|
||||
"count": len(rows),
|
||||
"items": [
|
||||
{
|
||||
"code": r[0],
|
||||
"name": r[1],
|
||||
"market": r[2],
|
||||
"sector": r[3],
|
||||
"is_seed": bool(r[4]),
|
||||
}
|
||||
for r in rows
|
||||
],
|
||||
"items": [_item(r) for r in rows],
|
||||
}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user