다른 인스턴스/증권사 앱에서 매수돼 동기화로 들어온 포지션은 ActiveTrade 행이 없어 손절·분할익절·트레일링 관리를 전혀 받지 못했다(2026-09-22 카카오뱅크가 -13%까지 방치되다 청산). 동기화 시 보유 중인데 active 행이 없으면 평균단가를 진입가로 등록하고 손절가를 STOP_LOSS_PERCENT 기준으로 설정한다. 데이트레이딩 태깅 종목은 제외 (DT 엔진이 당일 청산 대상으로 복원해버리므로). Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
170 lines
7.5 KiB
Python
170 lines
7.5 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()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_swing_partial_exit_persists_remaining_quantity():
|
|
"""스윙 분할매도도 ActiveTrade.quantity를 갱신해야 한다(DT와 동일 패턴)."""
|
|
import inspect
|
|
from app.services.swing import exit_service as ses
|
|
src = inspect.getsource(ses)
|
|
block = src[src.index("분할 매도 후 remaining_pct 갱신"):]
|
|
block = block[:block.index("await enqueue_active_trade_upsert(_at_data)")]
|
|
assert '"quantity": quantity - sell_qty' in block, "스윙 분할매도에 잔량 갱신 누락"
|
|
|
|
|
|
def test_us_partial_exit_persists_remaining_quantity():
|
|
"""미국 스윙도 동일 — total_qty = trade.quantity 를 읽으므로 갱신이 없으면 과다매도."""
|
|
import inspect
|
|
from app.services import us_market_scheduler as us
|
|
src = inspect.getsource(us)
|
|
i = src.index('"strategy_name": "us_mean_reversion",\n "remaining_pct"')
|
|
block = src[i:i + 500]
|
|
assert '"quantity": max(0, total_qty - sell_qty)' in block, "미국 분할매도에 잔량 갱신 누락"
|
|
|
|
|
|
def test_domestic_executor_partial_exit_persists_quantity():
|
|
import inspect
|
|
from app.services import trade_executor as te
|
|
src = inspect.getsource(te)
|
|
i = src.index('"remaining_pct": new_remaining,\n "quantity"')
|
|
assert 'max(0, total_qty - quantity)' in src[i:i + 200]
|
|
|
|
|
|
def test_manual_sell_closes_active_trade():
|
|
"""수동 전량 매도는 ActiveTrade를 closed 로 만들어야 유령 행이 남지 않는다."""
|
|
import inspect
|
|
from app.api.endpoints import portfolio as pf
|
|
src = inspect.getsource(pf.sell_stock)
|
|
assert "_enq_close_at(stock_code" in src
|
|
assert '"quantity": original_holding_qty - quantity' in src
|
|
|
|
|
|
def test_sync_reconciles_active_trade_quantity():
|
|
"""동기화가 ActiveTrade 잔량을 실제 보유량으로 정합해야 드리프트가 누적되지 않는다."""
|
|
import inspect
|
|
from app.api.endpoints import portfolio as pf
|
|
src = inspect.getsource(pf.sync_portfolio)
|
|
assert "ActiveTrade 잔량 교정" in src
|
|
assert "len(_rows) != 1" in src, "스윙+DT 혼재 종목은 자동 교정 대상에서 제외해야 함"
|
|
assert "_row.status = \"closed\"" in src, "보유 없음 → closed 처리 누락"
|
|
|
|
|
|
def test_active_trade_patch_supports_quantity():
|
|
import inspect
|
|
from app.api.endpoints import portfolio as pf
|
|
assert "quantity" in pf.ActiveTradeStatusUpdateRequest.model_fields
|
|
src = inspect.getsource(pf.update_active_trade_status)
|
|
assert "active_trade.quantity = request.quantity" in src
|
|
|
|
|
|
def test_sync_seeds_active_trade_for_external_positions():
|
|
"""외부 유입 보유 종목(ActiveTrade 없음)은 동기화 시 자동 등록되어야 손절 관리를 받는다."""
|
|
import inspect
|
|
from app.api.endpoints import portfolio as pf
|
|
src = inspect.getsource(pf.sync_portfolio)
|
|
assert "외부 유입 포지션 — 동기화 시 자동 등록" in src
|
|
# 데이트레이딩 태깅 종목은 제외 (엔진이 당일 청산 대상으로 복원해버림)
|
|
assert '(_h.strategy_type or "swing") == "daytrading"' in src
|
|
# 평균단가를 진입가로, 손절가는 STOP_LOSS_PERCENT 기준
|
|
assert "_cfg.STOP_LOSS_PERCENT" in src
|
|
assert "entry_price=Decimal(str(_avg))" in src
|