## 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
6.6 KiB
Python
172 lines
6.6 KiB
Python
"""
|
|
연속 손실 추적 - CLAUDE.md 섹션 7.4
|
|
|
|
동일 종목에서 3회 이상 연속 손실 시 30거래일 동안 신규 진입 금지.
|
|
재시작 후에도 ban 상태 유지: DB(stock_bans 테이블) 영속화.
|
|
"""
|
|
import asyncio
|
|
import logging
|
|
from datetime import datetime, timedelta, timezone
|
|
from typing import Dict, Optional
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class ConsecutiveLossTracker:
|
|
"""종목별 연속 손실 추적 및 쿨링오프 관리"""
|
|
|
|
def __init__(self, ban_count: int = 3, ban_calendar_days: int = 42):
|
|
"""
|
|
Args:
|
|
ban_count: 연속 손실 횟수 임계값 (기본 3)
|
|
ban_calendar_days: 금지 기간 (30거래일 ≈ 42캘린더일)
|
|
"""
|
|
self.ban_count = ban_count
|
|
self.ban_calendar_days = ban_calendar_days
|
|
# {stock_code: {"consecutive_losses": int, "ban_until": datetime|None}}
|
|
self._tracker: Dict[str, dict] = {}
|
|
self._lock = asyncio.Lock() # [FIX] 동시 접근 방지용 비동기 락
|
|
|
|
def record_trade_result(self, stock_code: str, is_loss: bool):
|
|
"""매매 결과 인메모리 기록 (DB 저장은 save_to_db 별도 호출)
|
|
|
|
Args:
|
|
stock_code: 종목코드
|
|
is_loss: 손실 여부
|
|
"""
|
|
if stock_code not in self._tracker:
|
|
self._tracker[stock_code] = {"consecutive_losses": 0, "ban_until": None}
|
|
|
|
entry = self._tracker[stock_code]
|
|
if is_loss:
|
|
entry["consecutive_losses"] += 1
|
|
if entry["consecutive_losses"] >= self.ban_count:
|
|
entry["ban_until"] = datetime.now(timezone.utc) + timedelta(days=self.ban_calendar_days)
|
|
logger.warning(
|
|
f"{stock_code}: {entry['consecutive_losses']}회 연속 손실 → "
|
|
f"{entry['ban_until'].strftime('%Y-%m-%d')}까지 진입 금지"
|
|
)
|
|
else:
|
|
entry["consecutive_losses"] = 0
|
|
entry["ban_until"] = None
|
|
|
|
async def save_to_db(self, db=None, stock_code: str = None):
|
|
"""인메모리 상태를 DB에 영속화 (record_trade_result 후 호출)
|
|
|
|
NOTE: db 파라미터는 하위호환성을 위해 유지되지만 사용되지 않습니다.
|
|
실제 DB 저장은 db_worker.py의 db_task_queue를 통해 처리됩니다.
|
|
"""
|
|
if stock_code is None:
|
|
return
|
|
|
|
try:
|
|
from app.services.db_worker import enqueue_stock_ban_upsert
|
|
|
|
entry = self._tracker.get(stock_code)
|
|
if entry is None:
|
|
return
|
|
|
|
# 큐에 UPSERT 작업 등록 (db_worker가 비동기적으로 처리)
|
|
await enqueue_stock_ban_upsert(
|
|
stock_code=stock_code,
|
|
consecutive_losses=entry["consecutive_losses"],
|
|
ban_until=entry["ban_until"],
|
|
)
|
|
logger.debug(f"loss_tracker DB 저장 큐 등록: {stock_code}")
|
|
except Exception as e:
|
|
logger.error(f"loss_tracker DB 저장 큐 등록 실패 ({stock_code}): {e}")
|
|
|
|
async def load_from_db(self, db):
|
|
"""앱 시작 시 DB에서 ban 상태 복원"""
|
|
try:
|
|
from sqlalchemy import select
|
|
from app.models.models import StockBan
|
|
|
|
result = await db.execute(select(StockBan))
|
|
records = result.scalars().all()
|
|
|
|
now = datetime.now(timezone.utc)
|
|
loaded = 0
|
|
for rec in records:
|
|
# 만료된 ban은 초기화
|
|
ban_until = rec.ban_until
|
|
if ban_until and now >= ban_until:
|
|
ban_until = None
|
|
consecutive_losses = 0
|
|
else:
|
|
consecutive_losses = rec.consecutive_losses
|
|
|
|
self._tracker[rec.stock_code] = {
|
|
"consecutive_losses": consecutive_losses,
|
|
"ban_until": ban_until,
|
|
}
|
|
if ban_until:
|
|
loaded += 1
|
|
logger.info(
|
|
f"ban 복원: {rec.stock_code} → {ban_until.strftime('%Y-%m-%d')}까지 진입 금지"
|
|
)
|
|
|
|
logger.info(f"loss_tracker DB 로드 완료: {len(records)}건 중 {loaded}건 활성 ban")
|
|
except Exception as e:
|
|
logger.error(f"loss_tracker DB 로드 실패: {e}")
|
|
|
|
def is_banned(self, stock_code: str) -> bool:
|
|
"""해당 종목이 진입 금지 상태인지 확인"""
|
|
entry = self._tracker.get(stock_code)
|
|
if not entry or not entry["ban_until"]:
|
|
return False
|
|
if datetime.now(timezone.utc) >= entry["ban_until"]:
|
|
# 금지 기간 만료 → 리셋
|
|
entry["consecutive_losses"] = 0
|
|
entry["ban_until"] = None
|
|
return False
|
|
return True
|
|
|
|
async def is_banned_safe(self, stock_code: str) -> bool:
|
|
"""[v2] 비동기 락 보호 is_banned — 동시 접근이 우려되는 경로에서 사용"""
|
|
async with self._lock:
|
|
return self.is_banned(stock_code)
|
|
|
|
async def record_trade_result_safe(self, stock_code: str, is_loss: bool):
|
|
"""[v2] 비동기 락 보호 record_trade_result"""
|
|
async with self._lock:
|
|
self.record_trade_result(stock_code, is_loss)
|
|
|
|
async def get_all_bans_safe(self) -> list:
|
|
"""[v2] Lock 보호 하에 현재 활성 ban 종목 코드 목록 반환.
|
|
|
|
Returns:
|
|
ban_until이 아직 유효한 종목코드 리스트
|
|
"""
|
|
async with self._lock:
|
|
now = datetime.now(timezone.utc)
|
|
return [
|
|
code for code, entry in self._tracker.items()
|
|
if entry.get("ban_until") and now < entry["ban_until"]
|
|
]
|
|
|
|
def get_ban_info(self, stock_code: str) -> dict:
|
|
"""종목의 연속 손실 및 금지 정보 조회"""
|
|
entry = self._tracker.get(stock_code, {"consecutive_losses": 0, "ban_until": None})
|
|
return {
|
|
"stock_code": stock_code,
|
|
"consecutive_losses": entry["consecutive_losses"],
|
|
"is_banned": self.is_banned(stock_code),
|
|
"ban_until": entry["ban_until"].isoformat() if entry["ban_until"] else None,
|
|
}
|
|
|
|
|
|
# 싱글톤 인스턴스 — settings에서 ban_count 주입
|
|
def _create_loss_tracker() -> ConsecutiveLossTracker:
|
|
try:
|
|
from app.core.config import settings
|
|
return ConsecutiveLossTracker(
|
|
ban_count=settings.CONSECUTIVE_LOSS_BAN_COUNT,
|
|
ban_calendar_days=42, # 30거래일 ≈ 42캘린더일
|
|
)
|
|
except Exception:
|
|
return ConsecutiveLossTracker()
|
|
|
|
|
|
loss_tracker = _create_loss_tracker()
|