Compare commits
10 Commits
feature/is
...
feature/is
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9339824e22 | ||
| e6eae6c6e0 | |||
| bb6bd0392e | |||
| a66181b7a7 | |||
| da585ee547 | |||
| c737d5009a | |||
|
|
f7d33e69d1 | ||
|
|
7d99d8ec4a | ||
|
|
0727f28f77 | ||
|
|
ac4fb00644 |
@@ -94,6 +94,7 @@ Smart Scanner runs in `TRADE_MODE=realtime` only. Daily mode uses static watchli
|
|||||||
- **[Testing](docs/testing.md)** — Test structure, coverage requirements, writing tests
|
- **[Testing](docs/testing.md)** — Test structure, coverage requirements, writing tests
|
||||||
- **[Agent Policies](docs/agents.md)** — Prime directives, constraints, prohibited actions
|
- **[Agent Policies](docs/agents.md)** — Prime directives, constraints, prohibited actions
|
||||||
- **[Requirements Log](docs/requirements-log.md)** — User requirements and feedback tracking
|
- **[Requirements Log](docs/requirements-log.md)** — User requirements and feedback tracking
|
||||||
|
- **[Live Trading Checklist](docs/live-trading-checklist.md)** — 모의→실전 전환 체크리스트
|
||||||
|
|
||||||
## Core Principles
|
## Core Principles
|
||||||
|
|
||||||
|
|||||||
131
docs/live-trading-checklist.md
Normal file
131
docs/live-trading-checklist.md
Normal file
@@ -0,0 +1,131 @@
|
|||||||
|
# 실전 전환 체크리스트
|
||||||
|
|
||||||
|
모의 거래(paper)에서 실전(live)으로 전환하기 전에 아래 항목을 **순서대로** 모두 확인하세요.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 사전 조건
|
||||||
|
|
||||||
|
### 1-1. KIS OpenAPI 실전 계좌 준비
|
||||||
|
- [ ] 한국투자증권 계좌 개설 완료 (일반 위탁 계좌)
|
||||||
|
- [ ] OpenAPI 실전 사용 신청 (KIS 홈페이지 → Open API → 서비스 신청)
|
||||||
|
- [ ] 실전용 APP_KEY / APP_SECRET 발급 완료
|
||||||
|
- [ ] KIS_ACCOUNT_NO 형식 확인: `XXXXXXXX-XX` (8자리-2자리)
|
||||||
|
|
||||||
|
### 1-2. 리스크 파라미터 검토
|
||||||
|
- [ ] `CIRCUIT_BREAKER_PCT` 확인: 기본값 -3.0% (더 엄격하게 조정 권장)
|
||||||
|
- [ ] `FAT_FINGER_PCT` 확인: 기본값 30.0% (1회 주문 최대 잔고 대비 %)
|
||||||
|
- [ ] `CONFIDENCE_THRESHOLD` 확인: BEARISH ≥ 90, NEUTRAL ≥ 80, BULLISH ≥ 75
|
||||||
|
- [ ] 초기 투자금 결정 및 해외 주식 운용 한도 설정
|
||||||
|
|
||||||
|
### 1-3. 시스템 요건
|
||||||
|
- [ ] 커버리지 80% 이상 유지 확인: `pytest --cov=src`
|
||||||
|
- [ ] 타입 체크 통과: `mypy src/ --strict`
|
||||||
|
- [ ] Lint 통과: `ruff check src/ tests/`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 환경 설정
|
||||||
|
|
||||||
|
### 2-1. `.env` 파일 수정
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. KIS 실전 URL로 변경 (모의: openapivts 포트 29443)
|
||||||
|
KIS_BASE_URL=https://openapi.koreainvestment.com:9443
|
||||||
|
|
||||||
|
# 2. 실전 APP_KEY / APP_SECRET으로 교체
|
||||||
|
KIS_APP_KEY=<실전_APP_KEY>
|
||||||
|
KIS_APP_SECRET=<실전_APP_SECRET>
|
||||||
|
KIS_ACCOUNT_NO=<실전_계좌번호>
|
||||||
|
|
||||||
|
# 3. 모드를 live로 변경
|
||||||
|
MODE=live
|
||||||
|
|
||||||
|
# 4. PAPER_OVERSEAS_CASH 비활성화 (live 모드에선 무시되지만 명시적으로 0 설정)
|
||||||
|
PAPER_OVERSEAS_CASH=0
|
||||||
|
```
|
||||||
|
|
||||||
|
> ⚠️ `KIS_BASE_URL` 포트 주의:
|
||||||
|
> - **모의(VTS)**: `https://openapivts.koreainvestment.com:29443`
|
||||||
|
> - **실전**: `https://openapi.koreainvestment.com:9443`
|
||||||
|
|
||||||
|
### 2-2. TR_ID 자동 분기 확인
|
||||||
|
|
||||||
|
아래 TR_ID는 `MODE` 값에 따라 코드에서 **자동으로 선택**됩니다.
|
||||||
|
별도 설정 불필요하나, 문제 발생 시 아래 표를 참조하세요.
|
||||||
|
|
||||||
|
| 구분 | 모의 TR_ID | 실전 TR_ID |
|
||||||
|
|------|-----------|-----------|
|
||||||
|
| 국내 잔고 조회 | `VTTC8434R` | `TTTC8434R` |
|
||||||
|
| 국내 현금 매수 | `VTTC0012U` | `TTTC0012U` |
|
||||||
|
| 국내 현금 매도 | `VTTC0011U` | `TTTC0011U` |
|
||||||
|
| 해외 잔고 조회 | `VTTS3012R` | `TTTS3012R` |
|
||||||
|
| 해외 매수 | `VTTT1002U` | `TTTT1002U` |
|
||||||
|
| 해외 매도 | `VTTT1001U` | `TTTT1006U` |
|
||||||
|
|
||||||
|
> **출처**: `docs/한국투자증권_오픈API_전체문서_20260221_030000.xlsx` (공식 문서 기준)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 최종 확인
|
||||||
|
|
||||||
|
### 3-1. 실전 시작 전 점검
|
||||||
|
- [ ] DB 백업 완료: `data/trade_logs.db` → `data/backups/`
|
||||||
|
- [ ] Telegram 알림 설정 확인 (실전에서는 알림이 더욱 중요)
|
||||||
|
- [ ] 소액으로 첫 거래 진행 후 TR_ID/계좌 정상 동작 확인
|
||||||
|
|
||||||
|
### 3-2. 실행 명령
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 실전 모드로 실행
|
||||||
|
python -m src.main --mode=live
|
||||||
|
|
||||||
|
# 대시보드 함께 실행 (별도 터미널에서 모니터링)
|
||||||
|
python -m src.main --mode=live --dashboard
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3-3. 실전 시작 직후 확인 사항
|
||||||
|
- [ ] 로그에 `MODE=live` 출력 확인
|
||||||
|
- [ ] 첫 잔고 조회 성공 (ConnectionError 없음)
|
||||||
|
- [ ] Telegram 알림 수신 확인 ("System started")
|
||||||
|
- [ ] 첫 주문 후 KIS 앱에서 체결 내역 확인
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 비상 정지 방법
|
||||||
|
|
||||||
|
### 즉각 정지
|
||||||
|
```bash
|
||||||
|
# 터미널에서 Ctrl+C (정상 종료 트리거)
|
||||||
|
# 또는 Telegram 봇 명령:
|
||||||
|
/stop
|
||||||
|
```
|
||||||
|
|
||||||
|
### Circuit Breaker 발동 시
|
||||||
|
- CB가 발동되면 자동으로 거래 중단 및 Telegram 알림 전송
|
||||||
|
- CB 임계값: `CIRCUIT_BREAKER_PCT` (기본 -3.0%)
|
||||||
|
- **임계값은 엄격하게만 조정 가능** (더 낮은 음수 값으로만 변경)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 롤백 절차
|
||||||
|
|
||||||
|
실전 전환 후 문제 발생 시:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 즉시 .env에서 MODE=paper로 복원
|
||||||
|
# 2. 재시작
|
||||||
|
python -m src.main --mode=paper
|
||||||
|
|
||||||
|
# 3. DB에서 최근 거래 확인
|
||||||
|
sqlite3 data/trade_logs.db "SELECT * FROM trades ORDER BY id DESC LIMIT 20;"
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 관련 문서
|
||||||
|
|
||||||
|
- [시스템 아키텍처](architecture.md)
|
||||||
|
- [워크플로우 가이드](workflow.md)
|
||||||
|
- [재해 복구](disaster_recovery.md)
|
||||||
|
- [Agent 제약 조건](agents.md)
|
||||||
@@ -17,7 +17,7 @@ class Settings(BaseSettings):
|
|||||||
|
|
||||||
# Google Gemini
|
# Google Gemini
|
||||||
GEMINI_API_KEY: str
|
GEMINI_API_KEY: str
|
||||||
GEMINI_MODEL: str = "gemini-pro"
|
GEMINI_MODEL: str = "gemini-2.0-flash"
|
||||||
|
|
||||||
# External Data APIs (optional — for data-driven decisions)
|
# External Data APIs (optional — for data-driven decisions)
|
||||||
NEWS_API_KEY: str | None = None
|
NEWS_API_KEY: str | None = None
|
||||||
|
|||||||
127
src/main.py
127
src/main.py
@@ -88,6 +88,47 @@ DAILY_TRADE_SESSIONS = 4 # Number of trading sessions per day
|
|||||||
TRADE_SESSION_INTERVAL_HOURS = 6 # Hours between sessions
|
TRADE_SESSION_INTERVAL_HOURS = 6 # Hours between sessions
|
||||||
|
|
||||||
|
|
||||||
|
async def _retry_connection(coro_factory: Any, *args: Any, label: str = "", **kwargs: Any) -> Any:
|
||||||
|
"""Call an async function retrying on ConnectionError with exponential backoff.
|
||||||
|
|
||||||
|
Retries up to MAX_CONNECTION_RETRIES times (exclusive of the first attempt),
|
||||||
|
sleeping 2^attempt seconds between attempts. Use only for idempotent read
|
||||||
|
operations — never for order submission.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
coro_factory: Async callable (method or function) to invoke.
|
||||||
|
*args: Positional arguments forwarded to coro_factory.
|
||||||
|
label: Human-readable label for log messages.
|
||||||
|
**kwargs: Keyword arguments forwarded to coro_factory.
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ConnectionError: If all retries are exhausted.
|
||||||
|
"""
|
||||||
|
for attempt in range(1, MAX_CONNECTION_RETRIES + 1):
|
||||||
|
try:
|
||||||
|
return await coro_factory(*args, **kwargs)
|
||||||
|
except ConnectionError as exc:
|
||||||
|
if attempt < MAX_CONNECTION_RETRIES:
|
||||||
|
wait_secs = 2 ** attempt
|
||||||
|
logger.warning(
|
||||||
|
"Connection error %s (attempt %d/%d), retrying in %ds: %s",
|
||||||
|
label,
|
||||||
|
attempt,
|
||||||
|
MAX_CONNECTION_RETRIES,
|
||||||
|
wait_secs,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
await asyncio.sleep(wait_secs)
|
||||||
|
else:
|
||||||
|
logger.error(
|
||||||
|
"Connection error %s — all %d retries exhausted: %s",
|
||||||
|
label,
|
||||||
|
MAX_CONNECTION_RETRIES,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
raise
|
||||||
|
|
||||||
|
|
||||||
def _extract_symbol_from_holding(item: dict[str, Any]) -> str:
|
def _extract_symbol_from_holding(item: dict[str, Any]) -> str:
|
||||||
"""Extract symbol from overseas holding payload variants."""
|
"""Extract symbol from overseas holding payload variants."""
|
||||||
for key in (
|
for key in (
|
||||||
@@ -867,18 +908,30 @@ async def run_daily_session(
|
|||||||
telegram: TelegramClient,
|
telegram: TelegramClient,
|
||||||
settings: Settings,
|
settings: Settings,
|
||||||
smart_scanner: SmartVolatilityScanner | None = None,
|
smart_scanner: SmartVolatilityScanner | None = None,
|
||||||
) -> None:
|
daily_start_eval: float = 0.0,
|
||||||
|
) -> float:
|
||||||
"""Execute one daily trading session.
|
"""Execute one daily trading session.
|
||||||
|
|
||||||
V2 proactive strategy: 1 Gemini call for playbook generation,
|
V2 proactive strategy: 1 Gemini call for playbook generation,
|
||||||
then local scenario evaluation per stock (0 API calls).
|
then local scenario evaluation per stock (0 API calls).
|
||||||
|
|
||||||
|
Args:
|
||||||
|
daily_start_eval: Portfolio evaluation at the start of the trading day.
|
||||||
|
Used to compute intra-day P&L for the Circuit Breaker.
|
||||||
|
Pass 0.0 on the first session of each day; the function will set
|
||||||
|
it from the first balance query and return it for subsequent
|
||||||
|
sessions.
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
The daily_start_eval value that should be forwarded to the next
|
||||||
|
session of the same trading day.
|
||||||
"""
|
"""
|
||||||
# Get currently open markets
|
# Get currently open markets
|
||||||
open_markets = get_open_markets(settings.enabled_market_list)
|
open_markets = get_open_markets(settings.enabled_market_list)
|
||||||
|
|
||||||
if not open_markets:
|
if not open_markets:
|
||||||
logger.info("No markets open for this session")
|
logger.info("No markets open for this session")
|
||||||
return
|
return daily_start_eval
|
||||||
|
|
||||||
logger.info("Starting daily trading session for %d markets", len(open_markets))
|
logger.info("Starting daily trading session for %d markets", len(open_markets))
|
||||||
|
|
||||||
@@ -964,11 +1017,18 @@ async def run_daily_session(
|
|||||||
try:
|
try:
|
||||||
if market.is_domestic:
|
if market.is_domestic:
|
||||||
current_price, price_change_pct, foreigner_net = (
|
current_price, price_change_pct, foreigner_net = (
|
||||||
await broker.get_current_price(stock_code)
|
await _retry_connection(
|
||||||
|
broker.get_current_price,
|
||||||
|
stock_code,
|
||||||
|
label=stock_code,
|
||||||
|
)
|
||||||
)
|
)
|
||||||
else:
|
else:
|
||||||
price_data = await overseas_broker.get_overseas_price(
|
price_data = await _retry_connection(
|
||||||
market.exchange_code, stock_code
|
overseas_broker.get_overseas_price,
|
||||||
|
market.exchange_code,
|
||||||
|
stock_code,
|
||||||
|
label=f"{stock_code}@{market.exchange_code}",
|
||||||
)
|
)
|
||||||
current_price = safe_float(
|
current_price = safe_float(
|
||||||
price_data.get("output", {}).get("last", "0")
|
price_data.get("output", {}).get("last", "0")
|
||||||
@@ -1019,9 +1079,27 @@ async def run_daily_session(
|
|||||||
logger.warning("No valid stock data for market %s", market.code)
|
logger.warning("No valid stock data for market %s", market.code)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
# Get balance data once for the market
|
# Get balance data once for the market (read-only — safe to retry)
|
||||||
|
try:
|
||||||
|
if market.is_domestic:
|
||||||
|
balance_data = await _retry_connection(
|
||||||
|
broker.get_balance, label=f"balance:{market.code}"
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
balance_data = await _retry_connection(
|
||||||
|
overseas_broker.get_overseas_balance,
|
||||||
|
market.exchange_code,
|
||||||
|
label=f"overseas_balance:{market.exchange_code}",
|
||||||
|
)
|
||||||
|
except ConnectionError as exc:
|
||||||
|
logger.error(
|
||||||
|
"Balance fetch failed for market %s after all retries — skipping market: %s",
|
||||||
|
market.code,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
continue
|
||||||
|
|
||||||
if market.is_domestic:
|
if market.is_domestic:
|
||||||
balance_data = await broker.get_balance()
|
|
||||||
output2 = balance_data.get("output2", [{}])
|
output2 = balance_data.get("output2", [{}])
|
||||||
total_eval = safe_float(
|
total_eval = safe_float(
|
||||||
output2[0].get("tot_evlu_amt", "0")
|
output2[0].get("tot_evlu_amt", "0")
|
||||||
@@ -1033,7 +1111,6 @@ async def run_daily_session(
|
|||||||
output2[0].get("pchs_amt_smtl_amt", "0")
|
output2[0].get("pchs_amt_smtl_amt", "0")
|
||||||
) if output2 else 0
|
) if output2 else 0
|
||||||
else:
|
else:
|
||||||
balance_data = await overseas_broker.get_overseas_balance(market.exchange_code)
|
|
||||||
output2 = balance_data.get("output2", [{}])
|
output2 = balance_data.get("output2", [{}])
|
||||||
if isinstance(output2, list) and output2:
|
if isinstance(output2, list) and output2:
|
||||||
balance_info = output2[0]
|
balance_info = output2[0]
|
||||||
@@ -1056,7 +1133,22 @@ async def run_daily_session(
|
|||||||
):
|
):
|
||||||
total_cash = settings.PAPER_OVERSEAS_CASH
|
total_cash = settings.PAPER_OVERSEAS_CASH
|
||||||
|
|
||||||
# Calculate daily P&L %
|
# Capture the day's opening portfolio value on the first market processed
|
||||||
|
# in this session. Used to compute intra-day P&L for the CB instead of
|
||||||
|
# the cumulative purchase_total which spans the entire account history.
|
||||||
|
if daily_start_eval <= 0 and total_eval > 0:
|
||||||
|
daily_start_eval = total_eval
|
||||||
|
logger.info(
|
||||||
|
"Daily CB baseline set: total_eval=%.2f (first balance of the day)",
|
||||||
|
daily_start_eval,
|
||||||
|
)
|
||||||
|
|
||||||
|
# Daily P&L: compare current eval vs start-of-day eval.
|
||||||
|
# Falls back to purchase_total if daily_start_eval is unavailable (e.g. paper
|
||||||
|
# mode where balance API returns 0 for all values).
|
||||||
|
if daily_start_eval > 0:
|
||||||
|
pnl_pct = (total_eval - daily_start_eval) / daily_start_eval * 100
|
||||||
|
else:
|
||||||
pnl_pct = (
|
pnl_pct = (
|
||||||
((total_eval - purchase_total) / purchase_total * 100)
|
((total_eval - purchase_total) / purchase_total * 100)
|
||||||
if purchase_total > 0
|
if purchase_total > 0
|
||||||
@@ -1330,6 +1422,7 @@ async def run_daily_session(
|
|||||||
)
|
)
|
||||||
|
|
||||||
logger.info("Daily trading session completed")
|
logger.info("Daily trading session completed")
|
||||||
|
return daily_start_eval
|
||||||
|
|
||||||
|
|
||||||
async def _handle_market_close(
|
async def _handle_market_close(
|
||||||
@@ -1965,13 +2058,26 @@ async def run(settings: Settings) -> None:
|
|||||||
|
|
||||||
session_interval = settings.SESSION_INTERVAL_HOURS * 3600 # Convert to seconds
|
session_interval = settings.SESSION_INTERVAL_HOURS * 3600 # Convert to seconds
|
||||||
|
|
||||||
|
# daily_start_eval: portfolio eval captured at the first session of each
|
||||||
|
# trading day. Reset on calendar-date change so the CB measures only
|
||||||
|
# today's drawdown, not cumulative account history.
|
||||||
|
_cb_daily_start_eval: float = 0.0
|
||||||
|
_cb_last_date: str = ""
|
||||||
|
|
||||||
while not shutdown.is_set():
|
while not shutdown.is_set():
|
||||||
# Wait for trading to be unpaused
|
# Wait for trading to be unpaused
|
||||||
await pause_trading.wait()
|
await pause_trading.wait()
|
||||||
_run_context_scheduler(context_scheduler, now=datetime.now(UTC))
|
_run_context_scheduler(context_scheduler, now=datetime.now(UTC))
|
||||||
|
|
||||||
|
# Reset intra-day CB baseline on a new calendar date
|
||||||
|
today_str = datetime.now(UTC).date().isoformat()
|
||||||
|
if today_str != _cb_last_date:
|
||||||
|
_cb_last_date = today_str
|
||||||
|
_cb_daily_start_eval = 0.0
|
||||||
|
logger.info("New trading day %s — daily CB baseline reset", today_str)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
await run_daily_session(
|
_cb_daily_start_eval = await run_daily_session(
|
||||||
broker,
|
broker,
|
||||||
overseas_broker,
|
overseas_broker,
|
||||||
scenario_engine,
|
scenario_engine,
|
||||||
@@ -1985,6 +2091,7 @@ async def run(settings: Settings) -> None:
|
|||||||
telegram,
|
telegram,
|
||||||
settings,
|
settings,
|
||||||
smart_scanner=smart_scanner,
|
smart_scanner=smart_scanner,
|
||||||
|
daily_start_eval=_cb_daily_start_eval,
|
||||||
)
|
)
|
||||||
except CircuitBreakerTripped:
|
except CircuitBreakerTripped:
|
||||||
logger.critical("Circuit breaker tripped — shutting down")
|
logger.critical("Circuit breaker tripped — shutting down")
|
||||||
|
|||||||
114
src/strategies/v20260220_210124_evolved.py
Normal file
114
src/strategies/v20260220_210124_evolved.py
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
"""Auto-generated strategy: v20260220_210124
|
||||||
|
|
||||||
|
Generated at: 2026-02-20T21:01:24.706847+00:00
|
||||||
|
Rationale: Auto-evolved from 6 failures. Primary failure markets: ['US_AMEX', 'US_NYSE', 'US_NASDAQ']. Average loss: -194.69
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
from typing import Any
|
||||||
|
from src.strategies.base import BaseStrategy
|
||||||
|
|
||||||
|
|
||||||
|
class Strategy_v20260220_210124(BaseStrategy):
|
||||||
|
"""Strategy: v20260220_210124"""
|
||||||
|
|
||||||
|
def evaluate(self, market_data: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
import datetime
|
||||||
|
|
||||||
|
# --- Strategy Constants ---
|
||||||
|
# Minimum price for a stock to be considered for trading (avoids penny stocks)
|
||||||
|
MIN_PRICE = 5.0
|
||||||
|
|
||||||
|
# Momentum signal thresholds (stricter than previous failures)
|
||||||
|
MOMENTUM_PRICE_CHANGE_THRESHOLD = 7.0 # % price change
|
||||||
|
MOMENTUM_VOLUME_RATIO_THRESHOLD = 4.0 # X times average volume
|
||||||
|
|
||||||
|
# Oversold signal thresholds (more conservative)
|
||||||
|
OVERSOLD_RSI_THRESHOLD = 25.0 # RSI value (lower means more oversold)
|
||||||
|
|
||||||
|
# Confidence levels
|
||||||
|
CONFIDENCE_HOLD = 30
|
||||||
|
CONFIDENCE_BUY_OVERSOLD = 65
|
||||||
|
CONFIDENCE_BUY_MOMENTUM = 85
|
||||||
|
CONFIDENCE_BUY_STRONG_MOMENTUM = 90 # For higher-priced stocks with strong momentum
|
||||||
|
|
||||||
|
# Market hours in UTC (9:30 AM ET to 4:00 PM ET)
|
||||||
|
MARKET_OPEN_UTC = datetime.time(14, 30)
|
||||||
|
MARKET_CLOSE_UTC = datetime.time(21, 0)
|
||||||
|
|
||||||
|
# Volatile periods within market hours (UTC) to avoid
|
||||||
|
# First hour after open (14:30 UTC - 15:30 UTC)
|
||||||
|
VOLATILE_OPEN_END_UTC = datetime.time(15, 30)
|
||||||
|
# Last 30 minutes before close (20:30 UTC - 21:00 UTC)
|
||||||
|
VOLATILE_CLOSE_START_UTC = datetime.time(20, 30)
|
||||||
|
|
||||||
|
current_price = market_data.get('current_price')
|
||||||
|
price_change_pct = market_data.get('price_change_pct')
|
||||||
|
volume_ratio = market_data.get('volume_ratio') # Assumed pre-computed indicator
|
||||||
|
rsi = market_data.get('rsi') # Assumed pre-computed indicator
|
||||||
|
timestamp_str = market_data.get('timestamp')
|
||||||
|
|
||||||
|
action = "HOLD"
|
||||||
|
confidence = CONFIDENCE_HOLD
|
||||||
|
rationale = "Initial HOLD: No clear signal or conditions not met."
|
||||||
|
|
||||||
|
# --- 1. Basic Data Validation ---
|
||||||
|
if current_price is None or price_change_pct is None:
|
||||||
|
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
||||||
|
"rationale": "Insufficient core data (price or price change) to evaluate."}
|
||||||
|
|
||||||
|
# --- 2. Price Filter: Avoid low-priced/penny stocks ---
|
||||||
|
if current_price < MIN_PRICE:
|
||||||
|
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
||||||
|
"rationale": f"Avoiding low-priced stock (${current_price:.2f} < ${MIN_PRICE:.2f})."}
|
||||||
|
|
||||||
|
# --- 3. Time Filter: Only trade during core market hours ---
|
||||||
|
if timestamp_str:
|
||||||
|
try:
|
||||||
|
dt_object = datetime.datetime.fromisoformat(timestamp_str)
|
||||||
|
current_time_utc = dt_object.time()
|
||||||
|
|
||||||
|
if not (MARKET_OPEN_UTC <= current_time_utc < MARKET_CLOSE_UTC):
|
||||||
|
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
||||||
|
"rationale": f"Avoiding trade outside core market hours ({current_time_utc} UTC)."}
|
||||||
|
|
||||||
|
if (MARKET_OPEN_UTC <= current_time_utc < VOLATILE_OPEN_END_UTC) or \
|
||||||
|
(VOLATILE_CLOSE_START_UTC <= current_time_utc < MARKET_CLOSE_UTC):
|
||||||
|
return {"action": "HOLD", "confidence": CONFIDENCE_HOLD,
|
||||||
|
"rationale": f"Avoiding trade during volatile market open/close periods ({current_time_utc} UTC)."}
|
||||||
|
|
||||||
|
except ValueError:
|
||||||
|
rationale += " (Warning: Malformed timestamp, time filters skipped)"
|
||||||
|
|
||||||
|
# --- Initialize signal states ---
|
||||||
|
has_momentum_buy_signal = False
|
||||||
|
has_oversold_buy_signal = False
|
||||||
|
|
||||||
|
# --- 4. Evaluate Enhanced Buy Signals ---
|
||||||
|
|
||||||
|
# Momentum Buy Signal
|
||||||
|
if volume_ratio is not None and \
|
||||||
|
price_change_pct > MOMENTUM_PRICE_CHANGE_THRESHOLD and \
|
||||||
|
volume_ratio > MOMENTUM_VOLUME_RATIO_THRESHOLD:
|
||||||
|
has_momentum_buy_signal = True
|
||||||
|
rationale = f"Momentum BUY: Price change {price_change_pct:.2f}%, Volume {volume_ratio:.2f}x."
|
||||||
|
confidence = CONFIDENCE_BUY_MOMENTUM
|
||||||
|
if current_price >= 10.0:
|
||||||
|
confidence = CONFIDENCE_BUY_STRONG_MOMENTUM
|
||||||
|
|
||||||
|
# Oversold Buy Signal
|
||||||
|
if rsi is not None and rsi < OVERSOLD_RSI_THRESHOLD:
|
||||||
|
has_oversold_buy_signal = True
|
||||||
|
if not has_momentum_buy_signal:
|
||||||
|
rationale = f"Oversold BUY: RSI {rsi:.2f}."
|
||||||
|
confidence = CONFIDENCE_BUY_OVERSOLD
|
||||||
|
if current_price >= 10.0:
|
||||||
|
confidence = min(CONFIDENCE_BUY_OVERSOLD + 5, 80)
|
||||||
|
|
||||||
|
# --- 5. Decision Logic ---
|
||||||
|
if has_momentum_buy_signal:
|
||||||
|
action = "BUY"
|
||||||
|
elif has_oversold_buy_signal:
|
||||||
|
action = "BUY"
|
||||||
|
|
||||||
|
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||||
97
src/strategies/v20260220_210159_evolved.py
Normal file
97
src/strategies/v20260220_210159_evolved.py
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
"""Auto-generated strategy: v20260220_210159
|
||||||
|
|
||||||
|
Generated at: 2026-02-20T21:01:59.391523+00:00
|
||||||
|
Rationale: Auto-evolved from 6 failures. Primary failure markets: ['US_AMEX', 'US_NYSE', 'US_NASDAQ']. Average loss: -194.69
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
from typing import Any
|
||||||
|
from src.strategies.base import BaseStrategy
|
||||||
|
|
||||||
|
|
||||||
|
class Strategy_v20260220_210159(BaseStrategy):
|
||||||
|
"""Strategy: v20260220_210159"""
|
||||||
|
|
||||||
|
def evaluate(self, market_data: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
import datetime
|
||||||
|
|
||||||
|
current_price = market_data.get('current_price')
|
||||||
|
price_change_pct = market_data.get('price_change_pct')
|
||||||
|
volume_ratio = market_data.get('volume_ratio')
|
||||||
|
rsi = market_data.get('rsi')
|
||||||
|
timestamp_str = market_data.get('timestamp')
|
||||||
|
market_name = market_data.get('market')
|
||||||
|
|
||||||
|
# Default action
|
||||||
|
action = "HOLD"
|
||||||
|
confidence = 0
|
||||||
|
rationale = "No strong signal or conditions not met."
|
||||||
|
|
||||||
|
# --- FAILURE PATTERN AVOIDANCE ---
|
||||||
|
|
||||||
|
# 1. Avoid low-priced/penny stocks
|
||||||
|
MIN_PRICE_THRESHOLD = 5.0 # USD
|
||||||
|
if current_price is not None and current_price < MIN_PRICE_THRESHOLD:
|
||||||
|
rationale = (
|
||||||
|
f"HOLD: Stock price (${current_price:.2f}) is below minimum threshold "
|
||||||
|
f"(${MIN_PRICE_THRESHOLD:.2f}). Past failures consistently involved low-priced stocks."
|
||||||
|
)
|
||||||
|
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||||
|
|
||||||
|
# 2. Avoid early market hour volatility
|
||||||
|
if timestamp_str:
|
||||||
|
try:
|
||||||
|
dt_obj = datetime.datetime.fromisoformat(timestamp_str)
|
||||||
|
utc_hour = dt_obj.hour
|
||||||
|
utc_minute = dt_obj.minute
|
||||||
|
|
||||||
|
if (utc_hour == 14 and utc_minute < 45) or (utc_hour == 13 and utc_minute >= 30):
|
||||||
|
rationale = (
|
||||||
|
f"HOLD: Trading during early market hours (UTC {utc_hour}:{utc_minute}), "
|
||||||
|
f"a period identified with past failures due to high volatility."
|
||||||
|
)
|
||||||
|
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# --- IMPROVED BUY STRATEGY ---
|
||||||
|
|
||||||
|
# Momentum BUY signal
|
||||||
|
if volume_ratio is not None and price_change_pct is not None:
|
||||||
|
if price_change_pct > 7.0 and volume_ratio > 3.0:
|
||||||
|
action = "BUY"
|
||||||
|
confidence = 70
|
||||||
|
rationale = "Improved BUY: Momentum signal with high volume and above price threshold."
|
||||||
|
|
||||||
|
if market_name == 'US_AMEX':
|
||||||
|
confidence = max(55, confidence - 5)
|
||||||
|
rationale += " (Adjusted lower for AMEX market's higher risk profile)."
|
||||||
|
elif market_name == 'US_NASDAQ' and price_change_pct > 20:
|
||||||
|
confidence = max(50, confidence - 10)
|
||||||
|
rationale += " (Adjusted lower for aggressive NASDAQ momentum volatility)."
|
||||||
|
|
||||||
|
if price_change_pct > 15.0:
|
||||||
|
confidence = max(50, confidence - 5)
|
||||||
|
rationale += " (Caution: Very high daily price change, potential for reversal)."
|
||||||
|
|
||||||
|
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||||
|
|
||||||
|
# Oversold BUY signal
|
||||||
|
if rsi is not None and price_change_pct is not None:
|
||||||
|
if rsi < 30 and price_change_pct < -3.0:
|
||||||
|
action = "BUY"
|
||||||
|
confidence = 65
|
||||||
|
rationale = "Improved BUY: Oversold signal with recent decline and above price threshold."
|
||||||
|
|
||||||
|
if market_name == 'US_AMEX':
|
||||||
|
confidence = max(50, confidence - 5)
|
||||||
|
rationale += " (Adjusted lower for AMEX market's higher risk on oversold assets)."
|
||||||
|
|
||||||
|
if price_change_pct < -10.0:
|
||||||
|
confidence = max(45, confidence - 10)
|
||||||
|
rationale += " (Caution: Very steep decline, potential falling knife)."
|
||||||
|
|
||||||
|
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||||
|
|
||||||
|
# If no specific BUY signal, default to HOLD
|
||||||
|
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||||
88
src/strategies/v20260220_210244_evolved.py
Normal file
88
src/strategies/v20260220_210244_evolved.py
Normal file
@@ -0,0 +1,88 @@
|
|||||||
|
"""Auto-generated strategy: v20260220_210244
|
||||||
|
|
||||||
|
Generated at: 2026-02-20T21:02:44.387355+00:00
|
||||||
|
Rationale: Auto-evolved from 6 failures. Primary failure markets: ['US_AMEX', 'US_NYSE', 'US_NASDAQ']. Average loss: -194.69
|
||||||
|
"""
|
||||||
|
|
||||||
|
from __future__ import annotations
|
||||||
|
from typing import Any
|
||||||
|
from src.strategies.base import BaseStrategy
|
||||||
|
|
||||||
|
|
||||||
|
class Strategy_v20260220_210244(BaseStrategy):
|
||||||
|
"""Strategy: v20260220_210244"""
|
||||||
|
|
||||||
|
def evaluate(self, market_data: dict[str, Any]) -> dict[str, Any]:
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
# Extract required data points safely
|
||||||
|
current_price = market_data.get("current_price")
|
||||||
|
price_change_pct = market_data.get("price_change_pct")
|
||||||
|
volume_ratio = market_data.get("volume_ratio")
|
||||||
|
rsi = market_data.get("rsi")
|
||||||
|
timestamp_str = market_data.get("timestamp")
|
||||||
|
market_name = market_data.get("market")
|
||||||
|
stock_code = market_data.get("stock_code", "UNKNOWN")
|
||||||
|
|
||||||
|
# Default action is HOLD with conservative confidence and rationale
|
||||||
|
action = "HOLD"
|
||||||
|
confidence = 50
|
||||||
|
rationale = f"No strong BUY signal for {stock_code} or awaiting more favorable conditions after avoiding known failure patterns."
|
||||||
|
|
||||||
|
# --- 1. Failure Pattern Avoidance Filters ---
|
||||||
|
|
||||||
|
# A. Avoid low-priced (penny) stocks
|
||||||
|
if current_price is not None and current_price < 5.0:
|
||||||
|
return {
|
||||||
|
"action": "HOLD",
|
||||||
|
"confidence": 50,
|
||||||
|
"rationale": f"AVOID {stock_code}: Stock price (${current_price:.2f}) is below minimum threshold ($5.00) for BUY action. Identified past failures on highly volatile, low-priced stocks."
|
||||||
|
}
|
||||||
|
|
||||||
|
# B. Avoid initiating BUY trades during identified high-volatility hours
|
||||||
|
if timestamp_str:
|
||||||
|
try:
|
||||||
|
trade_hour = datetime.fromisoformat(timestamp_str).hour
|
||||||
|
if trade_hour in [14, 20]:
|
||||||
|
return {
|
||||||
|
"action": "HOLD",
|
||||||
|
"confidence": 50,
|
||||||
|
"rationale": f"AVOID {stock_code}: Trading during historically volatile hour ({trade_hour} UTC) where previous BUYs resulted in losses. Prefer to observe market stability."
|
||||||
|
}
|
||||||
|
except ValueError:
|
||||||
|
pass
|
||||||
|
|
||||||
|
# C. Be cautious with extreme momentum spikes
|
||||||
|
if volume_ratio is not None and price_change_pct is not None:
|
||||||
|
if volume_ratio >= 9.0 and price_change_pct >= 15.0:
|
||||||
|
return {
|
||||||
|
"action": "HOLD",
|
||||||
|
"confidence": 50,
|
||||||
|
"rationale": f"AVOID {stock_code}: Extreme short-term momentum detected (price change: +{price_change_pct:.2f}%, volume ratio: {volume_ratio:.1f}x). Historical failures indicate buying into such rapid spikes often leads to reversals."
|
||||||
|
}
|
||||||
|
|
||||||
|
# D. Be cautious with "oversold" signals without further confirmation
|
||||||
|
if rsi is not None and rsi < 30:
|
||||||
|
return {
|
||||||
|
"action": "HOLD",
|
||||||
|
"confidence": 50,
|
||||||
|
"rationale": f"AVOID {stock_code}: Oversold signal (RSI={rsi:.1f}) detected. While often a BUY signal, historical failures on similar 'oversold' trades suggest waiting for stronger confirmation."
|
||||||
|
}
|
||||||
|
|
||||||
|
# --- 2. Improved BUY Signal Generation ---
|
||||||
|
if volume_ratio is not None and 2.0 <= volume_ratio < 9.0 and \
|
||||||
|
price_change_pct is not None and 2.0 <= price_change_pct < 15.0:
|
||||||
|
|
||||||
|
action = "BUY"
|
||||||
|
confidence = 70
|
||||||
|
rationale = f"BUY {stock_code}: Moderate momentum detected (price change: +{price_change_pct:.2f}%, volume ratio: {volume_ratio:.1f}x). Passed filters for price and extreme momentum, avoiding past failure patterns."
|
||||||
|
|
||||||
|
if market_name in ["US_AMEX", "US_NASDAQ"]:
|
||||||
|
confidence = max(60, confidence - 5)
|
||||||
|
rationale += f" Adjusted confidence for {market_name} market characteristics."
|
||||||
|
elif market_name == "US_NYSE":
|
||||||
|
confidence = max(65, confidence)
|
||||||
|
|
||||||
|
confidence = max(50, min(85, confidence))
|
||||||
|
|
||||||
|
return {"action": action, "confidence": confidence, "rationale": rationale}
|
||||||
@@ -18,9 +18,11 @@ from src.main import (
|
|||||||
_extract_held_codes_from_balance,
|
_extract_held_codes_from_balance,
|
||||||
_extract_held_qty_from_balance,
|
_extract_held_qty_from_balance,
|
||||||
_handle_market_close,
|
_handle_market_close,
|
||||||
|
_retry_connection,
|
||||||
_run_context_scheduler,
|
_run_context_scheduler,
|
||||||
_run_evolution_loop,
|
_run_evolution_loop,
|
||||||
_start_dashboard_server,
|
_start_dashboard_server,
|
||||||
|
run_daily_session,
|
||||||
safe_float,
|
safe_float,
|
||||||
trading_cycle,
|
trading_cycle,
|
||||||
)
|
)
|
||||||
@@ -3183,3 +3185,330 @@ class TestOverseasBrokerIntegration:
|
|||||||
|
|
||||||
# DB도 브로커도 보유 없음 → BUY 주문이 실행되어야 함 (회귀 테스트)
|
# DB도 브로커도 보유 없음 → BUY 주문이 실행되어야 함 (회귀 테스트)
|
||||||
overseas_broker.send_overseas_order.assert_called_once()
|
overseas_broker.send_overseas_order.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# _retry_connection — unit tests (issue #209)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestRetryConnection:
|
||||||
|
"""Unit tests for the _retry_connection helper (issue #209)."""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_success_on_first_attempt(self) -> None:
|
||||||
|
"""Returns the result immediately when the first call succeeds."""
|
||||||
|
async def ok() -> str:
|
||||||
|
return "data"
|
||||||
|
|
||||||
|
result = await _retry_connection(ok, label="test")
|
||||||
|
assert result == "data"
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_succeeds_after_one_connection_error(self) -> None:
|
||||||
|
"""Retries once on ConnectionError and returns result on 2nd attempt."""
|
||||||
|
call_count = 0
|
||||||
|
|
||||||
|
async def flaky() -> str:
|
||||||
|
nonlocal call_count
|
||||||
|
call_count += 1
|
||||||
|
if call_count < 2:
|
||||||
|
raise ConnectionError("timeout")
|
||||||
|
return "ok"
|
||||||
|
|
||||||
|
with patch("src.main.asyncio.sleep") as mock_sleep:
|
||||||
|
mock_sleep.return_value = None
|
||||||
|
result = await _retry_connection(flaky, label="flaky")
|
||||||
|
|
||||||
|
assert result == "ok"
|
||||||
|
assert call_count == 2
|
||||||
|
mock_sleep.assert_called_once()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_raises_after_all_retries_exhausted(self) -> None:
|
||||||
|
"""Raises ConnectionError after MAX_CONNECTION_RETRIES attempts."""
|
||||||
|
from src.main import MAX_CONNECTION_RETRIES
|
||||||
|
|
||||||
|
call_count = 0
|
||||||
|
|
||||||
|
async def always_fail() -> None:
|
||||||
|
nonlocal call_count
|
||||||
|
call_count += 1
|
||||||
|
raise ConnectionError("unreachable")
|
||||||
|
|
||||||
|
with patch("src.main.asyncio.sleep") as mock_sleep:
|
||||||
|
mock_sleep.return_value = None
|
||||||
|
with pytest.raises(ConnectionError, match="unreachable"):
|
||||||
|
await _retry_connection(always_fail, label="always_fail")
|
||||||
|
|
||||||
|
assert call_count == MAX_CONNECTION_RETRIES
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_passes_args_and_kwargs_to_factory(self) -> None:
|
||||||
|
"""Forwards positional and keyword arguments to the callable."""
|
||||||
|
received: dict = {}
|
||||||
|
|
||||||
|
async def capture(a: int, b: int, *, key: str) -> str:
|
||||||
|
received["a"] = a
|
||||||
|
received["b"] = b
|
||||||
|
received["key"] = key
|
||||||
|
return "captured"
|
||||||
|
|
||||||
|
result = await _retry_connection(capture, 1, 2, key="val", label="test")
|
||||||
|
assert result == "captured"
|
||||||
|
assert received == {"a": 1, "b": 2, "key": "val"}
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_non_connection_error_not_retried(self) -> None:
|
||||||
|
"""Non-ConnectionError exceptions propagate immediately without retry."""
|
||||||
|
call_count = 0
|
||||||
|
|
||||||
|
async def bad_input() -> None:
|
||||||
|
nonlocal call_count
|
||||||
|
call_count += 1
|
||||||
|
raise ValueError("bad data")
|
||||||
|
|
||||||
|
with pytest.raises(ValueError, match="bad data"):
|
||||||
|
await _retry_connection(bad_input, label="bad")
|
||||||
|
|
||||||
|
assert call_count == 1 # No retry for non-ConnectionError
|
||||||
|
|
||||||
|
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
# run_daily_session — daily CB baseline (daily_start_eval) tests (issue #207)
|
||||||
|
# ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
|
||||||
|
class TestDailyCBBaseline:
|
||||||
|
"""Tests for run_daily_session's daily_start_eval (CB baseline) behaviour.
|
||||||
|
|
||||||
|
Issue #207: CB P&L should be computed relative to the portfolio value at
|
||||||
|
the start of each trading day, not the cumulative purchase_total.
|
||||||
|
"""
|
||||||
|
|
||||||
|
def _make_settings(self) -> Settings:
|
||||||
|
return Settings(
|
||||||
|
KIS_APP_KEY="test-key",
|
||||||
|
KIS_APP_SECRET="test-secret",
|
||||||
|
KIS_ACCOUNT_NO="12345678-01",
|
||||||
|
GEMINI_API_KEY="test-gemini",
|
||||||
|
MODE="paper",
|
||||||
|
PAPER_OVERSEAS_CASH=0,
|
||||||
|
)
|
||||||
|
|
||||||
|
def _make_domestic_balance(
|
||||||
|
self, tot_evlu_amt: float = 0.0, dnca_tot_amt: float = 50000.0
|
||||||
|
) -> dict:
|
||||||
|
return {
|
||||||
|
"output1": [],
|
||||||
|
"output2": [
|
||||||
|
{
|
||||||
|
"tot_evlu_amt": str(tot_evlu_amt),
|
||||||
|
"dnca_tot_amt": str(dnca_tot_amt),
|
||||||
|
"pchs_amt_smtl_amt": "40000.0",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_returns_daily_start_eval_when_no_markets_open(self) -> None:
|
||||||
|
"""run_daily_session returns the unchanged daily_start_eval when no markets are open."""
|
||||||
|
with patch("src.main.get_open_markets", return_value=[]):
|
||||||
|
result = await run_daily_session(
|
||||||
|
broker=MagicMock(),
|
||||||
|
overseas_broker=MagicMock(),
|
||||||
|
scenario_engine=MagicMock(),
|
||||||
|
playbook_store=MagicMock(),
|
||||||
|
pre_market_planner=MagicMock(),
|
||||||
|
risk=MagicMock(),
|
||||||
|
db_conn=init_db(":memory:"),
|
||||||
|
decision_logger=MagicMock(),
|
||||||
|
context_store=MagicMock(),
|
||||||
|
criticality_assessor=MagicMock(),
|
||||||
|
telegram=MagicMock(),
|
||||||
|
settings=self._make_settings(),
|
||||||
|
smart_scanner=None,
|
||||||
|
daily_start_eval=12345.0,
|
||||||
|
)
|
||||||
|
assert result == 12345.0
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_returns_zero_when_no_markets_and_no_baseline(self) -> None:
|
||||||
|
"""run_daily_session returns 0.0 when no markets are open and daily_start_eval=0."""
|
||||||
|
with patch("src.main.get_open_markets", return_value=[]):
|
||||||
|
result = await run_daily_session(
|
||||||
|
broker=MagicMock(),
|
||||||
|
overseas_broker=MagicMock(),
|
||||||
|
scenario_engine=MagicMock(),
|
||||||
|
playbook_store=MagicMock(),
|
||||||
|
pre_market_planner=MagicMock(),
|
||||||
|
risk=MagicMock(),
|
||||||
|
db_conn=init_db(":memory:"),
|
||||||
|
decision_logger=MagicMock(),
|
||||||
|
context_store=MagicMock(),
|
||||||
|
criticality_assessor=MagicMock(),
|
||||||
|
telegram=MagicMock(),
|
||||||
|
settings=self._make_settings(),
|
||||||
|
smart_scanner=None,
|
||||||
|
daily_start_eval=0.0,
|
||||||
|
)
|
||||||
|
assert result == 0.0
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_captures_total_eval_as_baseline_on_first_session(self) -> None:
|
||||||
|
"""When daily_start_eval=0 and balance returns a positive total_eval, the returned
|
||||||
|
value equals total_eval (the captured baseline for the day)."""
|
||||||
|
from src.analysis.smart_scanner import ScanCandidate
|
||||||
|
|
||||||
|
settings = self._make_settings()
|
||||||
|
broker = MagicMock()
|
||||||
|
# Domestic balance: tot_evlu_amt=55000
|
||||||
|
broker.get_balance = AsyncMock(
|
||||||
|
return_value=self._make_domestic_balance(tot_evlu_amt=55000.0)
|
||||||
|
)
|
||||||
|
# Price data for the stock
|
||||||
|
broker.get_current_price = AsyncMock(
|
||||||
|
return_value=(100.0, 1.5, 100.0)
|
||||||
|
)
|
||||||
|
|
||||||
|
market = MagicMock()
|
||||||
|
market.name = "KR"
|
||||||
|
market.code = "KR"
|
||||||
|
market.exchange_code = "KRX"
|
||||||
|
market.is_domestic = True
|
||||||
|
market.timezone = __import__("zoneinfo").ZoneInfo("Asia/Seoul")
|
||||||
|
|
||||||
|
smart_scanner = MagicMock()
|
||||||
|
smart_scanner.scan = AsyncMock(
|
||||||
|
return_value=[
|
||||||
|
ScanCandidate(
|
||||||
|
stock_code="005930",
|
||||||
|
name="Samsung",
|
||||||
|
price=100.0,
|
||||||
|
volume=1_000_000.0,
|
||||||
|
volume_ratio=2.5,
|
||||||
|
rsi=45.0,
|
||||||
|
signal="momentum",
|
||||||
|
score=80.0,
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
playbook_store = MagicMock()
|
||||||
|
playbook_store.load = MagicMock(return_value=_make_playbook("KR"))
|
||||||
|
|
||||||
|
scenario_engine = MagicMock(spec=ScenarioEngine)
|
||||||
|
scenario_engine.evaluate = MagicMock(return_value=_make_hold_match("005930"))
|
||||||
|
|
||||||
|
risk = MagicMock()
|
||||||
|
risk.check_circuit_breaker = MagicMock()
|
||||||
|
risk.check_fat_finger = MagicMock()
|
||||||
|
|
||||||
|
telegram = MagicMock()
|
||||||
|
telegram.notify_trade_execution = AsyncMock()
|
||||||
|
telegram.notify_scenario_matched = AsyncMock()
|
||||||
|
|
||||||
|
decision_logger = MagicMock()
|
||||||
|
decision_logger.log_decision = MagicMock(return_value="d1")
|
||||||
|
|
||||||
|
async def _passthrough(fn, *a, label: str = "", **kw): # type: ignore[override]
|
||||||
|
return await fn(*a, **kw)
|
||||||
|
|
||||||
|
with patch("src.main.get_open_markets", return_value=[market]), \
|
||||||
|
patch("src.main._retry_connection", new=_passthrough):
|
||||||
|
result = await run_daily_session(
|
||||||
|
broker=broker,
|
||||||
|
overseas_broker=MagicMock(),
|
||||||
|
scenario_engine=scenario_engine,
|
||||||
|
playbook_store=playbook_store,
|
||||||
|
pre_market_planner=MagicMock(),
|
||||||
|
risk=risk,
|
||||||
|
db_conn=init_db(":memory:"),
|
||||||
|
decision_logger=decision_logger,
|
||||||
|
context_store=MagicMock(),
|
||||||
|
criticality_assessor=MagicMock(),
|
||||||
|
telegram=telegram,
|
||||||
|
settings=settings,
|
||||||
|
smart_scanner=smart_scanner,
|
||||||
|
daily_start_eval=0.0,
|
||||||
|
)
|
||||||
|
|
||||||
|
assert result == 55000.0 # captured from tot_evlu_amt
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_does_not_overwrite_existing_baseline(self) -> None:
|
||||||
|
"""When daily_start_eval > 0, it must not be overwritten even if balance returns
|
||||||
|
a different value (baseline is fixed at the start of each trading day)."""
|
||||||
|
from src.analysis.smart_scanner import ScanCandidate
|
||||||
|
|
||||||
|
settings = self._make_settings()
|
||||||
|
broker = MagicMock()
|
||||||
|
# Balance reports a different eval value (market moved during the day)
|
||||||
|
broker.get_balance = AsyncMock(
|
||||||
|
return_value=self._make_domestic_balance(tot_evlu_amt=58000.0)
|
||||||
|
)
|
||||||
|
broker.get_current_price = AsyncMock(return_value=(100.0, 1.5, 100.0))
|
||||||
|
|
||||||
|
market = MagicMock()
|
||||||
|
market.name = "KR"
|
||||||
|
market.code = "KR"
|
||||||
|
market.exchange_code = "KRX"
|
||||||
|
market.is_domestic = True
|
||||||
|
market.timezone = __import__("zoneinfo").ZoneInfo("Asia/Seoul")
|
||||||
|
|
||||||
|
smart_scanner = MagicMock()
|
||||||
|
smart_scanner.scan = AsyncMock(
|
||||||
|
return_value=[
|
||||||
|
ScanCandidate(
|
||||||
|
stock_code="005930",
|
||||||
|
name="Samsung",
|
||||||
|
price=100.0,
|
||||||
|
volume=1_000_000.0,
|
||||||
|
volume_ratio=2.5,
|
||||||
|
rsi=45.0,
|
||||||
|
signal="momentum",
|
||||||
|
score=80.0,
|
||||||
|
)
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
playbook_store = MagicMock()
|
||||||
|
playbook_store.load = MagicMock(return_value=_make_playbook("KR"))
|
||||||
|
|
||||||
|
scenario_engine = MagicMock(spec=ScenarioEngine)
|
||||||
|
scenario_engine.evaluate = MagicMock(return_value=_make_hold_match("005930"))
|
||||||
|
|
||||||
|
risk = MagicMock()
|
||||||
|
risk.check_circuit_breaker = MagicMock()
|
||||||
|
|
||||||
|
telegram = MagicMock()
|
||||||
|
telegram.notify_trade_execution = AsyncMock()
|
||||||
|
telegram.notify_scenario_matched = AsyncMock()
|
||||||
|
|
||||||
|
decision_logger = MagicMock()
|
||||||
|
decision_logger.log_decision = MagicMock(return_value="d1")
|
||||||
|
|
||||||
|
async def _passthrough(fn, *a, label: str = "", **kw): # type: ignore[override]
|
||||||
|
return await fn(*a, **kw)
|
||||||
|
|
||||||
|
with patch("src.main.get_open_markets", return_value=[market]), \
|
||||||
|
patch("src.main._retry_connection", new=_passthrough):
|
||||||
|
result = await run_daily_session(
|
||||||
|
broker=broker,
|
||||||
|
overseas_broker=MagicMock(),
|
||||||
|
scenario_engine=scenario_engine,
|
||||||
|
playbook_store=playbook_store,
|
||||||
|
pre_market_planner=MagicMock(),
|
||||||
|
risk=risk,
|
||||||
|
db_conn=init_db(":memory:"),
|
||||||
|
decision_logger=decision_logger,
|
||||||
|
context_store=MagicMock(),
|
||||||
|
criticality_assessor=MagicMock(),
|
||||||
|
telegram=telegram,
|
||||||
|
settings=settings,
|
||||||
|
smart_scanner=smart_scanner,
|
||||||
|
daily_start_eval=55000.0, # existing baseline
|
||||||
|
)
|
||||||
|
|
||||||
|
# Must return the original baseline, NOT the new total_eval (58000)
|
||||||
|
assert result == 55000.0
|
||||||
|
|||||||
Reference in New Issue
Block a user