feat(phase-5): FastAPI 엔드포인트 (검색/차트/예측/메트릭/뉴스)
- GET /api/symbols/search?q=...&seed_only= : trigram + prefix + ILIKE 합산 정렬
- GET /api/symbols/{code} : 메타
- GET /api/chart/{code}?days=N&include_* : OHLCV + 일별 감성 + 외인기관거래대금
- POST /api/predict/{code}?horizons=1,3,5 : on-demand 앙상블 예측 + DB 적재
(user_triggered=TRUE)
- GET /api/predict/{code}/latest : 최신 base_date 의 예측 묶음 + base_close
(UI 가 차트 마지막 점에 이어 붙임)
- GET /api/metrics/{code}?window_days=N : 종목 단위 hit_rate / mae (model, horizon 별)
- GET /api/metrics?window_days=N : 전체 누적
- GET /api/news/{code}?source=&limit= : 최신순 뉴스/공시 목록 (감성 점수 포함)
main.py 에 6개 라우터 모두 include.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
116
backend/app/api/chart.py
Normal file
116
backend/app/api/chart.py
Normal file
@@ -0,0 +1,116 @@
|
||||
"""차트 데이터 API: OHLCV + 보조 데이터 (감성, 거시).
|
||||
|
||||
UI: /code 페이지 첫 로드 시 호출 → lightweight-charts 캔들 데이터로 사용.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, timedelta
|
||||
|
||||
from fastapi import APIRouter, HTTPException, Query
|
||||
from sqlalchemy import text
|
||||
|
||||
from app.db.connection import get_engine
|
||||
|
||||
router = APIRouter(prefix="/api/chart", tags=["chart"])
|
||||
|
||||
|
||||
@router.get("/{code}")
|
||||
def get_chart(
|
||||
code: str,
|
||||
days: int = Query(default=180, ge=10, le=3650),
|
||||
include_sentiment: bool = Query(default=True),
|
||||
include_trading_value: bool = Query(default=True),
|
||||
) -> dict:
|
||||
eng = get_engine()
|
||||
end = date.today()
|
||||
start = end - timedelta(days=days)
|
||||
with eng.connect() as conn:
|
||||
symbol = conn.execute(
|
||||
text("SELECT code, name, market FROM symbols WHERE code = :c"),
|
||||
{"c": code},
|
||||
).first()
|
||||
if not symbol:
|
||||
raise HTTPException(status_code=404, detail=f"unknown code: {code}")
|
||||
|
||||
ohlcv_rows = conn.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT date, open, high, low, close, volume
|
||||
FROM ohlcv_daily
|
||||
WHERE code = :c AND date BETWEEN :s AND :e
|
||||
ORDER BY date
|
||||
"""
|
||||
),
|
||||
{"c": code, "s": start, "e": end},
|
||||
).all()
|
||||
ohlcv = [
|
||||
{
|
||||
"date": str(r[0]),
|
||||
"open": float(r[1]) if r[1] is not None else None,
|
||||
"high": float(r[2]) if r[2] is not None else None,
|
||||
"low": float(r[3]) if r[3] is not None else None,
|
||||
"close": float(r[4]) if r[4] is not None else None,
|
||||
"volume": int(r[5]) if r[5] is not None else None,
|
||||
}
|
||||
for r in ohlcv_rows
|
||||
]
|
||||
|
||||
sentiment: list[dict] = []
|
||||
if include_sentiment:
|
||||
try:
|
||||
s_rows = conn.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT date, n_articles, mean_score, weighted_score
|
||||
FROM v_sentiment_daily
|
||||
WHERE code = :c AND date BETWEEN :s AND :e
|
||||
ORDER BY date
|
||||
"""
|
||||
),
|
||||
{"c": code, "s": start, "e": end},
|
||||
).all()
|
||||
sentiment = [
|
||||
{
|
||||
"date": str(r[0]),
|
||||
"n_articles": int(r[1]) if r[1] is not None else 0,
|
||||
"mean_score": float(r[2]) if r[2] is not None else None,
|
||||
"weighted_score": float(r[3]) if r[3] is not None else None,
|
||||
}
|
||||
for r in s_rows
|
||||
]
|
||||
except Exception: # noqa: BLE001
|
||||
# v_sentiment_daily 뷰 아직 없을 수 있음 (마이그레이션 미실행)
|
||||
sentiment = []
|
||||
|
||||
trading: list[dict] = []
|
||||
if include_trading_value:
|
||||
tv_rows = conn.execute(
|
||||
text(
|
||||
"""
|
||||
SELECT date, foreign_net, institution_net, individual_net
|
||||
FROM trading_value_daily
|
||||
WHERE code = :c AND date BETWEEN :s AND :e
|
||||
ORDER BY date
|
||||
"""
|
||||
),
|
||||
{"c": code, "s": start, "e": end},
|
||||
).all()
|
||||
trading = [
|
||||
{
|
||||
"date": str(r[0]),
|
||||
"foreign_net": float(r[1]) if r[1] is not None else None,
|
||||
"institution_net": float(r[2]) if r[2] is not None else None,
|
||||
"individual_net": float(r[3]) if r[3] is not None else None,
|
||||
}
|
||||
for r in tv_rows
|
||||
]
|
||||
|
||||
return {
|
||||
"code": symbol[0],
|
||||
"name": symbol[1],
|
||||
"market": symbol[2],
|
||||
"range": {"from": str(start), "to": str(end)},
|
||||
"ohlcv": ohlcv,
|
||||
"sentiment": sentiment,
|
||||
"trading_value": trading,
|
||||
}
|
||||
Reference in New Issue
Block a user