fix: 하드닝 루프 8회차 — 체결 보정·고아 감지·청산 경보·실시간/차트·리스크 가드 일괄 수정
- 스윙 체결가 확인 전 executed_price NULL + fill_sweep, 진입가 resolve(ActiveTrade↔Portfolio), 0체결/부분체결 매수 장부 원복 - DT 고아 감지(근거 한정)·0체결 매도 복원·stale 점검 확대, 시간손절 -0.3% 원복 - 폴백 손절 ATR 캐시, 거래량부족-차단 신호 매수 차단, 현금 5% 유보 재적용, MDD peak/reset 수정 - KIS 서킷브레이커 청산 우회·경보, db_worker 재큐잉 순서, heartbeat·health-watch 사이드카 - 실시간 WS 재구독·41건 우선순위·다건 프레임 분할, 차트 샘플 제거·당일봉 합성, WS 서브프로토콜 인증 - 프론트: 미관리 그룹·확인 모달·차트 실시간 반영·예수금 표시 정정 - 전문가 에이전트 6종 추가(.claude/agents) - 유닛 스위트 2667 passed (소켓 차단 하), tsc OK Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Y83Za98XsNw9zuA4FTUytN
This commit is contained in:
@@ -389,6 +389,35 @@ async def _load_daily_prices(
|
||||
return pd.DataFrame(records)
|
||||
|
||||
|
||||
def _resolve_trade_price_v2(row) -> float:
|
||||
"""체결가 NULL 규약 대응: executed_price -> total_amount/executed_quantity -> order_price -> 0."""
|
||||
ep = getattr(row, "executed_price", None)
|
||||
if ep:
|
||||
return float(ep)
|
||||
amt = getattr(row, "total_amount", None)
|
||||
qty = getattr(row, "executed_quantity", None)
|
||||
if amt and qty:
|
||||
return float(amt) / float(qty)
|
||||
op = getattr(row, "order_price", None)
|
||||
return float(op) if op else 0.0
|
||||
|
||||
|
||||
# 체결 확정 상태. 운영 trade_history 는 COMPLETED 만 존재(EXECUTED 0건)하므로
|
||||
# EXECUTED 단독 필터는 성능 저하 감시를 영구히 '데이터 부족'으로 만들었다. EXECUTED 는 레거시 호환.
|
||||
_FILLED_TRADE_STATUSES = ("COMPLETED", "EXECUTED")
|
||||
|
||||
# 성능 저하 재학습을 허용하는 장외 시간대(KST): 주말 전일, 평일 20:00~익일 06:59
|
||||
_RETRAIN_SAFE_START_HOUR = 20
|
||||
_RETRAIN_SAFE_END_HOUR = 7
|
||||
|
||||
|
||||
def _is_retrain_safe_window_v2(now: datetime) -> bool:
|
||||
"""장중이 아닌(주말·야간) 시각이면 True. 인프로세스 재학습 허용 시간대."""
|
||||
if now.weekday() >= 5:
|
||||
return True
|
||||
return now.hour >= _RETRAIN_SAFE_START_HOUR or now.hour < _RETRAIN_SAFE_END_HOUR
|
||||
|
||||
|
||||
async def _load_trade_history(
|
||||
months: int = ROLLING_WINDOW_MONTHS,
|
||||
) -> pd.DataFrame:
|
||||
@@ -411,7 +440,7 @@ async def _load_trade_history(
|
||||
select(TradeHistory)
|
||||
.where(
|
||||
and_(
|
||||
TradeHistory.status == "EXECUTED",
|
||||
TradeHistory.status.in_(_FILLED_TRADE_STATUSES),
|
||||
TradeHistory.created_at >= cutoff,
|
||||
)
|
||||
)
|
||||
@@ -428,7 +457,7 @@ async def _load_trade_history(
|
||||
records.append({
|
||||
"stock_code": row.stock_code,
|
||||
"order_type": row.order_type,
|
||||
"executed_price": float(row.executed_price) if row.executed_price else 0,
|
||||
"executed_price": _resolve_trade_price_v2(row),
|
||||
"profit_loss_rate": float(row.profit_loss_rate) if row.profit_loss_rate else 0,
|
||||
"created_at": row.created_at,
|
||||
})
|
||||
@@ -489,6 +518,30 @@ async def check_performance_degradation() -> Tuple[bool, Dict[str, Any]]:
|
||||
|
||||
# ─── 메인 재학습 실행 ──────────────────────────────────────────────────────
|
||||
|
||||
def _build_training_lists_impl(
|
||||
price_df: pd.DataFrame,
|
||||
) -> Tuple[List[np.ndarray], List[np.ndarray]]:
|
||||
"""종목별 피처·라벨 구성(동기, CPU 바운드). 반드시 to_thread 로 호출한다."""
|
||||
all_X_list: List[np.ndarray] = []
|
||||
all_y_list: List[np.ndarray] = []
|
||||
for code in price_df["stock_code"].unique():
|
||||
code_df = price_df[price_df["stock_code"] == code].copy()
|
||||
if len(code_df) < 80: # 최소 80일 필요 (60일 피처 + 20일 여유)
|
||||
continue
|
||||
code_df = code_df.reset_index(drop=True)
|
||||
try:
|
||||
features = _compute_retrain_features(code_df)
|
||||
labels = _prepare_retrain_labels(code_df["close"].values.astype(float))
|
||||
X, y = _build_training_dataset(features, labels)
|
||||
if len(X) > 0:
|
||||
all_X_list.append(X)
|
||||
all_y_list.append(y)
|
||||
except Exception as e:
|
||||
warn_throttled(logger, "ml_retrain_pipeline:540", f"종목 {code} 피처 추출 실패: {e}")
|
||||
continue
|
||||
return all_X_list, all_y_list
|
||||
|
||||
|
||||
async def run_retrain(
|
||||
model_dir: Optional[Path] = None,
|
||||
force: bool = False,
|
||||
@@ -519,28 +572,10 @@ async def run_retrain(
|
||||
stock_codes = price_df["stock_code"].unique()
|
||||
logger.info(f"로드된 종목 수: {len(stock_codes)}, 총 행: {len(price_df)}")
|
||||
|
||||
# 2. 종목별 피처 + 라벨 생성
|
||||
all_X_list: List[np.ndarray] = []
|
||||
all_y_list: List[np.ndarray] = []
|
||||
|
||||
for code in stock_codes:
|
||||
code_df = price_df[price_df["stock_code"] == code].copy()
|
||||
if len(code_df) < 80: # 최소 80일 필요 (60일 피처 + 20일 여유)
|
||||
continue
|
||||
|
||||
code_df = code_df.reset_index(drop=True)
|
||||
|
||||
try:
|
||||
features = _compute_retrain_features(code_df)
|
||||
labels = _prepare_retrain_labels(code_df["close"].values.astype(float))
|
||||
X, y = _build_training_dataset(features, labels)
|
||||
|
||||
if len(X) > 0:
|
||||
all_X_list.append(X)
|
||||
all_y_list.append(y)
|
||||
except Exception as e:
|
||||
warn_throttled(logger, "ml_retrain_pipeline:540", f"종목 {code} 피처 추출 실패: {e}")
|
||||
continue
|
||||
# 2. 종목별 피처 + 라벨 생성 (CPU 바운드 — 이벤트 루프 보호를 위해 워커 스레드)
|
||||
all_X_list, all_y_list = await asyncio.to_thread(
|
||||
_build_training_lists_impl, price_df
|
||||
)
|
||||
|
||||
if not all_X_list:
|
||||
msg = "재학습 중단: 유효 학습 데이터 없음"
|
||||
@@ -617,6 +652,7 @@ async def ml_retrain_scheduler():
|
||||
|
||||
last_scheduled_retrain: Optional[date] = None
|
||||
last_degradation_check: Optional[date] = None
|
||||
retrain_pending = False
|
||||
|
||||
while True:
|
||||
try:
|
||||
@@ -637,23 +673,33 @@ async def ml_retrain_scheduler():
|
||||
except Exception as e:
|
||||
logger.error(f"주기적 재학습 실패: {e}", exc_info=True)
|
||||
|
||||
# ── 성능 저하 감지: 매일 09:30 KST (장 시작 전) ──
|
||||
# ── 성능 저하 감지: 매일 09:30 KST. 감지만 하고 재학습은 장외로 미룬다 ──
|
||||
# (인프로세스 재학습은 이벤트 루프·메모리를 점유해 손절/EOD 루프에 영향)
|
||||
if (
|
||||
now.hour >= 9
|
||||
and now.minute >= 30
|
||||
(now.hour, now.minute) >= (9, 30)
|
||||
and last_degradation_check != today
|
||||
):
|
||||
last_degradation_check = today
|
||||
try:
|
||||
degraded, details = await check_performance_degradation()
|
||||
if degraded:
|
||||
logger.warning(f"성능 저하 감지 -> 자동 재학습 트리거: {details}")
|
||||
result = await run_retrain(force=True)
|
||||
logger.info(f"성능 저하 재학습 결과: {result.get('status')}")
|
||||
retrain_pending = True
|
||||
logger.warning(
|
||||
f"ML 성능 저하 감지 -> 재학습 필요 플래그 설정 (장외에 실행): {details}"
|
||||
)
|
||||
else:
|
||||
logger.debug(f"성능 저하 미감지: {details}")
|
||||
logger.info(f"성능 저하 미감지: {details}")
|
||||
except Exception as e:
|
||||
logger.error(f"성능 저하 감지/재학습 실패: {e}", exc_info=True)
|
||||
logger.error(f"성능 저하 감지 실패: {e}", exc_info=True)
|
||||
|
||||
# ── 보류된 성능 저하 재학습: 주말·야간에만 실행 ──
|
||||
if retrain_pending and _is_retrain_safe_window_v2(now):
|
||||
retrain_pending = False
|
||||
try:
|
||||
result = await run_retrain(force=True)
|
||||
logger.info(f"성능 저하 재학습 결과: {result.get('status')}")
|
||||
except Exception as e:
|
||||
logger.error(f"성능 저하 재학습 실패: {e}", exc_info=True)
|
||||
|
||||
except asyncio.CancelledError:
|
||||
logger.info("ML 재학습 스케줄러 종료")
|
||||
|
||||
Reference in New Issue
Block a user