Files
auto-stock/backend/tests/test_bugfixes_20260923.py
shuim f32bf412f3 fix: 로그 분석으로 찾은 버그 4건 (과다매도·수량 0 오염·LSTM 무력화·sync 충돌)
1) DT 분할매도가 ActiveTrade.quantity를 갱신하지 않아 재기동 복원 시 원래 수량이 되살아남
   → 잔량 4주인데 7주 매도되어 같은 종목 스윙 보유분 3주까지 청산됨(2026-09-23 LG씨엔에스).
2) reflect_sell이 '전략 포지션 잔량'을 Portfolio 행 잔량으로 사용 → DT 전량청산이 스윙
   보유분까지 0으로 만듦. 행 잔량은 항상 (행 수량 - 매도 수량)으로 계산.
3) LSTM 체크포인트에 numpy 배열이 들어가 weights_only=True 로드가 매번 실패 → 앙상블에서
   LSTM이 조용히 빠진 채 예측 중이었음. 저장을 list로 바꾸고, 기존 파일은 MODEL_DIR 내부일
   때만 완화 재시도.
4) 수동 매도(행 삭제)와 sync 동시 실행 시 StaleDataError로 sync 전체 실패 → 전량 매도는
   행 삭제 대신 수량 0, sync는 충돌 시 실패 기록 없이 다음 주기 재시도.
   추가로 비강제 sync는 락 점유 중이면 30초 대기 없이 캐시 반환.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-23 10:24:45 +09:00

101 lines
4.2 KiB
Python

"""2026-09-23 로그 기반 버그 수정 회귀 테스트."""
from decimal import Decimal
from pathlib import Path
from unittest.mock import AsyncMock, patch
import numpy as np
import pytest
from app.api.endpoints.portfolio import portfolio_cache
from app.models.models import Portfolio
from app.services import portfolio_cache_bridge as bridge
@pytest.fixture(autouse=True)
def _reset():
portfolio_cache.holdings = []
portfolio_cache.summary = {"available_cash": 0, "total_value": 0, "total_investment": 0,
"total_assets": 0, "total_profit_loss": 0,
"total_profit_loss_rate": 0, "total_stocks": 0}
portfolio_cache.recent_sells = {}
yield
@pytest.mark.asyncio
async def test_dt_full_exit_does_not_zero_swing_shares():
"""DT 전량청산(잔량 0)이 같은 종목의 스윙 보유분까지 0으로 만들면 안 된다.
2026-09-23: LG씨엔에스 스윙 8 + DT 7 = 15주. DT 전량청산 7주에
remaining_qty=0이 전달돼 Portfolio 행 전체가 0이 됐음(실제 잔고 8주).
"""
portfolio_cache.holdings = [Portfolio(
stock_code="064400", stock_name="LG씨엔에스", quantity=15,
average_price=Decimal("70400"), current_price=Decimal("70300"),
strategy_type="swing",
)]
q = AsyncMock()
with patch("app.services.db_worker.enqueue_portfolio_upsert", q):
await bridge.reflect_sell("064400", 7, 70300.0, remaining_qty=0)
assert portfolio_cache.holdings[0].quantity == 8, "스윙 보유분이 남아야 함"
assert q.await_args.args[0]["quantity"] == 8
def test_lstm_checkpoint_roundtrip_with_weights_only():
"""LSTM 체크포인트가 weights_only=True 로 로드 가능해야 한다(앙상블 무력화 방지)."""
torch = pytest.importorskip("torch")
from app.services.ml_ensemble import LSTMPredictor
p = LSTMPredictor(input_size=4)
if p.model is None:
pytest.skip("torch 모델 초기화 불가")
p.seq_mean = np.array([1.0, 2.0, 3.0, 4.0], dtype=np.float32)
p.seq_std = np.array([1.0, 1.0, 1.0, 1.0], dtype=np.float32)
import tempfile
with tempfile.TemporaryDirectory() as d:
path = Path(d) / "lstm.pt"
p.save(path)
ckpt = torch.load(path, map_location="cpu", weights_only=True) # 여기서 예외 없어야 함
assert ckpt["seq_mean"] == [1.0, 2.0, 3.0, 4.0]
p2 = LSTMPredictor(input_size=4)
assert p2.load(path) is True
assert isinstance(p2.seq_mean, np.ndarray)
np.testing.assert_allclose(p2.seq_mean, p.seq_mean)
@pytest.mark.asyncio
async def test_dt_partial_exit_updates_active_trade_quantity():
"""DT 분할매도 후 ActiveTrade.quantity가 줄어야 재기동 복원 시 과다 매도가 없다.
2026-09-23: 7주 중 3주 분할매도 후에도 DB는 7주 → 재기동 복원이 7주로 되살아나
잔량 4주인데 7주 매도(스윙 3주 침범).
"""
from app.services.daytrading import exit_service as es
from app.services.daytrading.position_manager import day_trading_state
day_trading_state.positions["064400"] = {
"stock_name": "LG씨엔에스", "strategy": "day_trade", "entry_price": 70800.0,
"stop_loss": 69000.0, "target_price": 73000.0, "quantity": 7,
"highest_price": 71200.0, "entry_time": es._kst_now(), "reason": "", "order_id": "",
}
upserts = []
async def _capture_at(data):
upserts.append(data)
with patch("app.services.trade_executor.safe_place_order",
AsyncMock(return_value={"rt_cd": "0", "output": {"ODNO": "1"}})), \
patch.object(es, "enqueue_trade_history", AsyncMock()), \
patch("app.services.db_worker.enqueue_active_trade_upsert", _capture_at), \
patch("app.services.portfolio_cache_bridge.reflect_sell", AsyncMock()):
out = await es._execute_exit("064400", day_trading_state.positions["064400"],
71200.0, reason="목표가 달성", sell_pct=0.5)
assert out is not None
assert day_trading_state.positions["064400"]["quantity"] == 4 # 인메모리
at = [u for u in upserts if u.get("stock_code") == "064400"]
assert at and at[-1]["quantity"] == 4, f"ActiveTrade 잔량 갱신 누락: {upserts}"
day_trading_state.positions.clear()