## CRITICAL 수정 (20건) - day_trading: global 선언 누락, loss_tracker 연동, ban 체크 추가 - trade_executor: BUY 체결가 order_price로 수정, remaining_pct 누적 계산 - risk_validator: get_current_price dict 파싱, MAX_POSITION_SIZE 동기화, DB 세션 누수 - risk_management/recommendations: date.today() → KST 변환 - mdd_manager: Lock 밖 executed_key 참조 수정 - correlation_filter: output → output2 키 수정 - portfolio: 해외 종목 USD/KRW 환율 적용 분리 - Sharpe Ratio 거래빈도 기반 연간화 - telegram_notifier: send_message() 공개 래퍼 추가 - position_manager: 앱 재시작 시 DB 포지션 복원 - swing exit_service: remaining_pct 조건 범위 수정 - run_backtest: original_qty 기반 remaining_pct 계산 - us_market_schedule: 2027년 미국 공휴일 추가 - Login.tsx: res.ok 검증 추가 - mean_reversion_strategy: RSI 로그 하드코딩 수정 ## HIGH 수정 (10건) - db_worker: DLQ 파일 백업 메커니즘 추가 - korea_investment_api: 만료 토큰 임의 연장 제거 - market_data: chart_cache 최대 100개 + TTL 만료 - main.py: rate_limit_store 1시간 미접근 IP 정리 - recommendations: fire-and-forget try/except 추가 - swing/scheduler: DB 세션 3개 분리 - Dashboard: wsMessages 전체 순회 - Layout: /health 엔드포인트 + 30초 폴링 - ml_ensemble: POST /train require_api_key 추가 - day_trading: record_trade_result_safe() 전환 ## 코드 정리 - 프론트엔드: isUsStock, formatTime 공통 유틸 추출 - 백엔드: dead code 제거, 중복 import 통합 - MCP: JSON 파싱 헬퍼 추출 (~60줄 감소) - 전체 ~100개 파일 한국어 주석 추가 - 테스트 13건 코드 기준 수정 (468 passed) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
172 lines
5.6 KiB
Python
172 lines
5.6 KiB
Python
"""
|
|
ML 앙상블 API 엔드포인트
|
|
|
|
- POST /train: 모델 학습
|
|
- GET /predict/{stock_code}: 개별 종목 예측
|
|
- GET /status: 모델 상태 조회
|
|
- GET /backtest: 백테스트 결과
|
|
"""
|
|
|
|
from fastapi import APIRouter, Depends, HTTPException, Query, BackgroundTasks
|
|
from app.core.security import require_api_key
|
|
import logging
|
|
import asyncio
|
|
|
|
from app.services.ml_ensemble import get_ensemble
|
|
from app.services.korea_investment_api import korea_investment_api
|
|
from app.core.config import settings
|
|
|
|
router = APIRouter()
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
@router.get("/status")
|
|
async def get_model_status():
|
|
"""앙상블 모델 상태 조회"""
|
|
ensemble = get_ensemble()
|
|
status = ensemble.get_status()
|
|
status["config"] = {
|
|
"enabled": settings.ML_ENSEMBLE_ENABLED,
|
|
"rule_weight": settings.ML_ENSEMBLE_RULE_WEIGHT,
|
|
"ml_weight": settings.ML_ENSEMBLE_ML_WEIGHT,
|
|
"buy_threshold": settings.ML_ENSEMBLE_BUY_THRESHOLD,
|
|
"confidence_min": settings.ML_ENSEMBLE_CONFIDENCE_MIN,
|
|
}
|
|
return status
|
|
|
|
|
|
@router.get("/predict/{stock_code}")
|
|
async def predict_stock(stock_code: str):
|
|
"""개별 종목 ML 앙상블 예측"""
|
|
ensemble = get_ensemble()
|
|
|
|
if not ensemble.is_trained:
|
|
raise HTTPException(
|
|
status_code=503,
|
|
detail="모델이 학습되지 않았습니다. POST /ml-ensemble/train 으로 학습을 먼저 실행하세요."
|
|
)
|
|
|
|
try:
|
|
chart_resp = await korea_investment_api.get_daily_chart(stock_code, "D")
|
|
chart_data = chart_resp.get("output", [])
|
|
|
|
if not chart_data or len(chart_data) < 61:
|
|
raise HTTPException(status_code=400, detail=f"차트 데이터 부족: {len(chart_data) if chart_data else 0}일 (최소 61일 필요)")
|
|
|
|
result = ensemble.predict(chart_data)
|
|
result["stock_code"] = stock_code
|
|
|
|
return result
|
|
|
|
except HTTPException:
|
|
raise
|
|
except Exception as e:
|
|
logger.error(f"예측 실패 ({stock_code}): {e}")
|
|
raise HTTPException(status_code=500, detail=str(e))
|
|
|
|
|
|
async def _train_task(limit: int):
|
|
"""백그라운드 학습 작업"""
|
|
import numpy as np
|
|
from app.services.feature_engineering import (
|
|
chart_data_to_dataframe, extract_features, prepare_training_data
|
|
)
|
|
from app.services.korea_investment_api import KoreaInvestmentAPI
|
|
|
|
kis_api = KoreaInvestmentAPI()
|
|
|
|
# 종목 조회
|
|
stocks = []
|
|
try:
|
|
kospi = await kis_api.get_volume_rank("J")
|
|
if kospi and kospi.get("output"):
|
|
for item in kospi["output"]:
|
|
name = item.get("hts_kor_isnm", "")
|
|
skip = ["ETF", "레버리지", "인버스", "KODEX", "선물", "TIGER", "ARIRANG"]
|
|
if not any(k in name for k in skip):
|
|
stocks.append((item["mksc_shrn_iscd"], name))
|
|
except Exception as e:
|
|
logger.error(f"종목 조회 실패: {e}")
|
|
|
|
await asyncio.sleep(3)
|
|
|
|
try:
|
|
kosdaq = await kis_api.get_volume_rank("Q")
|
|
if kosdaq and kosdaq.get("output"):
|
|
for item in kosdaq["output"]:
|
|
name = item.get("hts_kor_isnm", "")
|
|
skip = ["ETF", "레버리지", "인버스", "KODEX", "선물", "TIGER", "ARIRANG"]
|
|
if not any(k in name for k in skip):
|
|
stocks.append((item["mksc_shrn_iscd"], name))
|
|
except Exception as e:
|
|
logger.error(f"종목 조회 실패: {e}")
|
|
|
|
stocks = stocks[:limit]
|
|
logger.info(f"학습 대상: {len(stocks)}개 종목")
|
|
|
|
# 데이터 수집
|
|
all_X_tab, all_X_seq, all_y = [], [], []
|
|
for i, (code, name) in enumerate(stocks):
|
|
try:
|
|
chart_resp = await kis_api.get_daily_chart(code, "D")
|
|
chart_data = chart_resp.get("output", [])
|
|
if not chart_data or len(chart_data) < 80:
|
|
continue
|
|
|
|
df = chart_data_to_dataframe(chart_data)
|
|
feat = extract_features(df)
|
|
X_tab, X_seq, y, _ = prepare_training_data(df, feat)
|
|
if len(X_tab) > 0:
|
|
all_X_tab.append(X_tab)
|
|
all_X_seq.append(X_seq)
|
|
all_y.append(y)
|
|
logger.info(f"[{i+1}/{len(stocks)}] {code}: {len(X_tab)}개 샘플")
|
|
except Exception as e:
|
|
logger.warning(f"[{i+1}] {code} 실패: {e}")
|
|
await asyncio.sleep(3)
|
|
|
|
if not all_X_tab:
|
|
logger.error("학습 데이터 없음")
|
|
return
|
|
|
|
X_tabular = np.vstack(all_X_tab)
|
|
X_seq = np.vstack(all_X_seq)
|
|
y = np.concatenate(all_y)
|
|
|
|
logger.info(f"총 {len(X_tabular)}개 샘플로 학습 시작")
|
|
|
|
ensemble = get_ensemble()
|
|
metrics = ensemble.train(X_tabular, X_seq, y)
|
|
logger.info(f"학습 완료: {metrics}")
|
|
|
|
|
|
@router.post("/train", dependencies=[Depends(require_api_key)])
|
|
async def train_model(
|
|
background_tasks: BackgroundTasks,
|
|
limit: int = Query(50, description="학습 종목 수"),
|
|
):
|
|
"""앙상블 모델 학습 (백그라운드 실행)"""
|
|
background_tasks.add_task(_train_task, limit)
|
|
return {
|
|
"message": f"학습이 백그라운드에서 시작되었습니다 ({limit}개 종목)",
|
|
"status": "training_started",
|
|
}
|
|
|
|
|
|
@router.get("/backtest")
|
|
async def get_backtest():
|
|
"""모델 학습 메트릭 및 백테스트 결과 조회"""
|
|
ensemble = get_ensemble()
|
|
if not ensemble.is_trained:
|
|
raise HTTPException(status_code=503, detail="모델이 학습되지 않았습니다")
|
|
|
|
return {
|
|
"is_trained": True,
|
|
"metrics": ensemble.training_metrics,
|
|
"weights": {
|
|
"lgbm": ensemble.weights[0],
|
|
"lstm": ensemble.weights[1],
|
|
"rf": ensemble.weights[2],
|
|
},
|
|
}
|