Compare commits
13 Commits
feature/is
...
feature/is
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
df12be1305 | ||
| 6a6d3bd631 | |||
|
|
7aa5fedc12 | ||
|
|
3e777a5ab8 | ||
| 6f93258983 | |||
|
|
82167c5b8a | ||
| f87c4dc2f0 | |||
|
|
8af5f564c3 | ||
| 06e4fc5597 | |||
|
|
b697b6d515 | ||
| 42db5b3cc1 | |||
|
|
f252a84d65 | ||
| adc5211fd2 |
@@ -23,7 +23,7 @@ if [ -z "${APP_CMD:-}" ]; then
|
||||
|
||||
dashboard_port="${DASHBOARD_PORT:-8080}"
|
||||
|
||||
APP_CMD="DASHBOARD_PORT=$dashboard_port $PYTHON_BIN -m src.main --mode=paper --dashboard"
|
||||
APP_CMD="DASHBOARD_PORT=$dashboard_port $PYTHON_BIN -m src.main --mode=live --dashboard"
|
||||
fi
|
||||
|
||||
mkdir -p "$LOG_DIR"
|
||||
|
||||
@@ -121,6 +121,7 @@ class OverseasBroker:
|
||||
tr_id = self._broker._settings.OVERSEAS_RANKING_VOLUME_TR_ID
|
||||
path = self._broker._settings.OVERSEAS_RANKING_VOLUME_PATH
|
||||
params: dict[str, str] = {
|
||||
"KEYB": "", # NEXT KEY BUFF — Required, 공백
|
||||
"AUTH": "",
|
||||
"EXCD": ranking_excd,
|
||||
"MIXN": "0",
|
||||
@@ -130,10 +131,11 @@ class OverseasBroker:
|
||||
tr_id = self._broker._settings.OVERSEAS_RANKING_FLUCT_TR_ID
|
||||
path = self._broker._settings.OVERSEAS_RANKING_FLUCT_PATH
|
||||
params = {
|
||||
"KEYB": "", # NEXT KEY BUFF — Required, 공백
|
||||
"AUTH": "",
|
||||
"EXCD": ranking_excd,
|
||||
"NDAY": "0",
|
||||
"GUBN": "0", # 0=전체(상승+하락), 1=상승만 — 변동성 스캐너는 전체 필요
|
||||
"GUBN": "1", # 0=하락율, 1=상승율 — 변동성 스캐너는 급등 종목 우선
|
||||
"VOL_RANG": "0",
|
||||
}
|
||||
|
||||
@@ -220,6 +222,59 @@ class OverseasBroker:
|
||||
f"Network error fetching overseas balance: {exc}"
|
||||
) from exc
|
||||
|
||||
async def get_overseas_buying_power(
|
||||
self,
|
||||
exchange_code: str,
|
||||
stock_code: str,
|
||||
price: float,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Fetch overseas buying power for a specific stock and price.
|
||||
|
||||
Args:
|
||||
exchange_code: Exchange code (e.g., "NASD", "NYSE")
|
||||
stock_code: Stock ticker symbol
|
||||
price: Current stock price (used for quantity calculation)
|
||||
|
||||
Returns:
|
||||
API response; key field: output.ord_psbl_frcr_amt (주문가능외화금액)
|
||||
|
||||
Raises:
|
||||
ConnectionError: On network or API errors
|
||||
"""
|
||||
await self._broker._rate_limiter.acquire()
|
||||
session = self._broker._get_session()
|
||||
|
||||
# TR_ID: 실전 TTTS3007R, 모의 VTTS3007R
|
||||
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 매수가능금액조회' 시트
|
||||
ps_tr_id = (
|
||||
"TTTS3007R" if self._broker._settings.MODE == "live" else "VTTS3007R"
|
||||
)
|
||||
headers = await self._broker._auth_headers(ps_tr_id)
|
||||
params = {
|
||||
"CANO": self._broker._account_no,
|
||||
"ACNT_PRDT_CD": self._broker._product_cd,
|
||||
"OVRS_EXCG_CD": exchange_code,
|
||||
"OVRS_ORD_UNPR": f"{price:.2f}",
|
||||
"ITEM_CD": stock_code,
|
||||
}
|
||||
url = (
|
||||
f"{self._broker._base_url}/uapi/overseas-stock/v1/trading/inquire-psamount"
|
||||
)
|
||||
|
||||
try:
|
||||
async with session.get(url, headers=headers, params=params) as resp:
|
||||
if resp.status != 200:
|
||||
text = await resp.text()
|
||||
raise ConnectionError(
|
||||
f"get_overseas_buying_power failed ({resp.status}): {text}"
|
||||
)
|
||||
return await resp.json()
|
||||
except (TimeoutError, aiohttp.ClientError) as exc:
|
||||
raise ConnectionError(
|
||||
f"Network error fetching overseas buying power: {exc}"
|
||||
) from exc
|
||||
|
||||
async def send_overseas_order(
|
||||
self,
|
||||
exchange_code: str,
|
||||
|
||||
@@ -254,10 +254,11 @@ def get_open_position(
|
||||
"""Return open position if latest trade is BUY, else None."""
|
||||
cursor = conn.execute(
|
||||
"""
|
||||
SELECT action, decision_id, price, quantity
|
||||
SELECT action, decision_id, price, quantity, timestamp
|
||||
FROM trades
|
||||
WHERE stock_code = ?
|
||||
AND market = ?
|
||||
AND action IN ('BUY', 'SELL')
|
||||
ORDER BY timestamp DESC
|
||||
LIMIT 1
|
||||
""",
|
||||
@@ -266,7 +267,7 @@ def get_open_position(
|
||||
row = cursor.fetchone()
|
||||
if not row or row[0] != "BUY":
|
||||
return None
|
||||
return {"decision_id": row[1], "price": row[2], "quantity": row[3]}
|
||||
return {"decision_id": row[1], "price": row[2], "quantity": row[3], "timestamp": row[4]}
|
||||
|
||||
|
||||
def get_recent_symbols(
|
||||
|
||||
107
src/main.py
107
src/main.py
@@ -508,9 +508,43 @@ async def trading_cycle(
|
||||
balance_info = {}
|
||||
|
||||
total_eval = safe_float(balance_info.get("frcr_evlu_tota", "0") or "0")
|
||||
total_cash = safe_float(balance_info.get("frcr_dncl_amt_2", "0") or "0")
|
||||
purchase_total = safe_float(balance_info.get("frcr_buy_amt_smtl", "0") or "0")
|
||||
|
||||
# Resolve current price first (needed for buying power API)
|
||||
current_price = safe_float(price_data.get("output", {}).get("last", "0"))
|
||||
if current_price <= 0:
|
||||
market_candidates_lookup = scan_candidates.get(market.code, {})
|
||||
cand_lookup = market_candidates_lookup.get(stock_code)
|
||||
if cand_lookup and cand_lookup.price > 0:
|
||||
logger.debug(
|
||||
"Price API returned 0 for %s; using scanner candidate price %.4f",
|
||||
stock_code,
|
||||
cand_lookup.price,
|
||||
)
|
||||
current_price = cand_lookup.price
|
||||
foreigner_net = 0.0 # Not available for overseas
|
||||
price_change_pct = safe_float(price_data.get("output", {}).get("rate", "0"))
|
||||
|
||||
# Fetch available foreign currency cash via inquire-psamount (TTTS3007R/VTTS3007R).
|
||||
# TTTS3012R output2 does not include a cash/deposit field — frcr_dncl_amt_2 does not exist.
|
||||
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 매수가능금액조회' 시트
|
||||
total_cash = 0.0
|
||||
if current_price > 0:
|
||||
try:
|
||||
ps_data = await overseas_broker.get_overseas_buying_power(
|
||||
market.exchange_code, stock_code, current_price
|
||||
)
|
||||
total_cash = safe_float(
|
||||
ps_data.get("output", {}).get("ord_psbl_frcr_amt", "0") or "0"
|
||||
)
|
||||
except ConnectionError as exc:
|
||||
logger.warning(
|
||||
"Could not fetch overseas buying power for %s/%s: %s",
|
||||
market.exchange_code,
|
||||
stock_code,
|
||||
exc,
|
||||
)
|
||||
|
||||
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
||||
# Only activate in paper mode — live mode must use real balance from KIS.
|
||||
if (
|
||||
@@ -526,34 +560,6 @@ async def trading_cycle(
|
||||
)
|
||||
total_cash = settings.PAPER_OVERSEAS_CASH
|
||||
|
||||
current_price = safe_float(price_data.get("output", {}).get("last", "0"))
|
||||
# Fallback: if price API returns 0, use scanner candidate price
|
||||
if current_price <= 0:
|
||||
market_candidates_lookup = scan_candidates.get(market.code, {})
|
||||
cand_lookup = market_candidates_lookup.get(stock_code)
|
||||
if cand_lookup and cand_lookup.price > 0:
|
||||
logger.debug(
|
||||
"Price API returned 0 for %s; using scanner candidate price %.4f",
|
||||
stock_code,
|
||||
cand_lookup.price,
|
||||
)
|
||||
current_price = cand_lookup.price
|
||||
foreigner_net = 0.0 # Not available for overseas
|
||||
price_change_pct = safe_float(price_data.get("output", {}).get("rate", "0"))
|
||||
|
||||
# Price API may return 0/empty for certain VTS exchange codes.
|
||||
# Fall back to the scanner candidate's price so order sizing still works.
|
||||
if current_price <= 0:
|
||||
market_candidates_lookup = scan_candidates.get(market.code, {})
|
||||
cand_lookup = market_candidates_lookup.get(stock_code)
|
||||
if cand_lookup and cand_lookup.price > 0:
|
||||
current_price = cand_lookup.price
|
||||
logger.debug(
|
||||
"Price API returned 0 for %s; using scanner price %.4f",
|
||||
stock_code,
|
||||
current_price,
|
||||
)
|
||||
|
||||
# Calculate daily P&L %
|
||||
pnl_pct = (
|
||||
((total_eval - purchase_total) / purchase_total * 100)
|
||||
@@ -576,6 +582,22 @@ async def trading_cycle(
|
||||
market_data["rsi"] = candidate.rsi
|
||||
market_data["volume_ratio"] = candidate.volume_ratio
|
||||
|
||||
# Enrich market_data with holding info for SELL/HOLD scenario conditions
|
||||
open_pos = get_open_position(db_conn, stock_code, market.code)
|
||||
if open_pos and current_price > 0:
|
||||
entry_price = safe_float(open_pos.get("price"), 0.0)
|
||||
if entry_price > 0:
|
||||
market_data["unrealized_pnl_pct"] = (
|
||||
(current_price - entry_price) / entry_price * 100
|
||||
)
|
||||
entry_ts = open_pos.get("timestamp")
|
||||
if entry_ts:
|
||||
try:
|
||||
entry_date = datetime.fromisoformat(entry_ts).date()
|
||||
market_data["holding_days"] = (datetime.now(UTC).date() - entry_date).days
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
# 1.3. Record L7 real-time context (market-scoped keys)
|
||||
timeframe = datetime.now(UTC).isoformat()
|
||||
context_store.set_context(
|
||||
@@ -1643,10 +1665,35 @@ async def run_daily_session(
|
||||
balance_info = {}
|
||||
|
||||
total_eval = safe_float(balance_info.get("frcr_evlu_tota", "0") or "0")
|
||||
total_cash = safe_float(balance_info.get("frcr_dncl_amt_2", "0") or "0")
|
||||
purchase_total = safe_float(
|
||||
balance_info.get("frcr_buy_amt_smtl", "0") or "0"
|
||||
)
|
||||
|
||||
# Fetch available foreign currency cash via inquire-psamount (TTTS3007R/VTTS3007R).
|
||||
# TTTS3012R output2 does not include a cash/deposit field — frcr_dncl_amt_2 does not exist.
|
||||
# Use the first stock with a valid price as the reference for the buying power query.
|
||||
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 매수가능금액조회' 시트
|
||||
total_cash = 0.0
|
||||
ref_stock = next(
|
||||
(s for s in stocks_data if s.get("current_price", 0) > 0), None
|
||||
)
|
||||
if ref_stock:
|
||||
try:
|
||||
ps_data = await overseas_broker.get_overseas_buying_power(
|
||||
market.exchange_code,
|
||||
ref_stock["stock_code"],
|
||||
ref_stock["current_price"],
|
||||
)
|
||||
total_cash = safe_float(
|
||||
ps_data.get("output", {}).get("ord_psbl_frcr_amt", "0") or "0"
|
||||
)
|
||||
except ConnectionError as exc:
|
||||
logger.warning(
|
||||
"Could not fetch overseas buying power for %s: %s",
|
||||
market.exchange_code,
|
||||
exc,
|
||||
)
|
||||
|
||||
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
||||
# Only activate in paper mode — live mode must use real balance from KIS.
|
||||
if (
|
||||
|
||||
@@ -1,114 +0,0 @@
|
||||
"""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}
|
||||
@@ -1,97 +0,0 @@
|
||||
"""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}
|
||||
@@ -1,88 +0,0 @@
|
||||
"""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}
|
||||
@@ -903,12 +903,14 @@ class TestOverseasBalanceParsing:
|
||||
"output2": [
|
||||
{
|
||||
"frcr_evlu_tota": "10000.00",
|
||||
"frcr_dncl_amt_2": "5000.00",
|
||||
"frcr_buy_amt_smtl": "4500.00",
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "5000.00"}}
|
||||
)
|
||||
return broker
|
||||
|
||||
@pytest.fixture
|
||||
@@ -922,11 +924,13 @@ class TestOverseasBalanceParsing:
|
||||
return_value={
|
||||
"output2": {
|
||||
"frcr_evlu_tota": "10000.00",
|
||||
"frcr_dncl_amt_2": "5000.00",
|
||||
"frcr_buy_amt_smtl": "4500.00",
|
||||
}
|
||||
}
|
||||
)
|
||||
broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "5000.00"}}
|
||||
)
|
||||
return broker
|
||||
|
||||
@pytest.fixture
|
||||
@@ -937,6 +941,9 @@ class TestOverseasBalanceParsing:
|
||||
return_value={"output": {"last": "150.50"}}
|
||||
)
|
||||
broker.get_overseas_balance = AsyncMock(return_value={"output2": []})
|
||||
broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "0.00"}}
|
||||
)
|
||||
return broker
|
||||
|
||||
@pytest.fixture
|
||||
@@ -951,12 +958,15 @@ class TestOverseasBalanceParsing:
|
||||
"output2": [
|
||||
{
|
||||
"frcr_evlu_tota": "10000.00",
|
||||
"frcr_dncl_amt_2": "5000.00",
|
||||
"frcr_buy_amt_smtl": "4500.00",
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
# get_overseas_buying_power not called when price=0, but mock for safety
|
||||
broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "5000.00"}}
|
||||
)
|
||||
return broker
|
||||
|
||||
@pytest.fixture
|
||||
@@ -1186,12 +1196,14 @@ class TestOverseasBalanceParsing:
|
||||
"output2": [
|
||||
{
|
||||
"frcr_evlu_tota": "100000.00",
|
||||
"frcr_dncl_amt_2": "50000.00",
|
||||
"frcr_buy_amt_smtl": "50000.00",
|
||||
}
|
||||
]
|
||||
}
|
||||
)
|
||||
broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "50000.00"}}
|
||||
)
|
||||
broker.send_overseas_order = AsyncMock(return_value={"msg1": "주문접수"})
|
||||
return broker
|
||||
|
||||
@@ -1291,12 +1303,14 @@ class TestOverseasBalanceParsing:
|
||||
"output2": [
|
||||
{
|
||||
"frcr_evlu_tota": "100000.00",
|
||||
"frcr_dncl_amt_2": "50000.00",
|
||||
"frcr_buy_amt_smtl": "50000.00",
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "50000.00"}}
|
||||
)
|
||||
overseas_broker.send_overseas_order = AsyncMock(
|
||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
||||
)
|
||||
@@ -1355,9 +1369,12 @@ class TestOverseasBalanceParsing:
|
||||
overseas_broker.get_overseas_balance = AsyncMock(
|
||||
return_value={
|
||||
"output1": [],
|
||||
"output2": [{"frcr_evlu_tota": "0", "frcr_dncl_amt_2": "10000", "frcr_buy_amt_smtl": "0"}],
|
||||
"output2": [{"frcr_evlu_tota": "0", "frcr_buy_amt_smtl": "0"}],
|
||||
}
|
||||
)
|
||||
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "10000"}}
|
||||
)
|
||||
overseas_broker.get_overseas_price = AsyncMock(
|
||||
return_value={"output": {"last": "50.1234", "rate": "0"}}
|
||||
)
|
||||
@@ -1413,9 +1430,12 @@ class TestOverseasBalanceParsing:
|
||||
overseas_broker.get_overseas_balance = AsyncMock(
|
||||
return_value={
|
||||
"output1": [],
|
||||
"output2": [{"frcr_evlu_tota": "0", "frcr_dncl_amt_2": "10000", "frcr_buy_amt_smtl": "0"}],
|
||||
"output2": [{"frcr_evlu_tota": "0", "frcr_buy_amt_smtl": "0"}],
|
||||
}
|
||||
)
|
||||
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "10000"}}
|
||||
)
|
||||
overseas_broker.get_overseas_price = AsyncMock(
|
||||
return_value={"output": {"last": "0.5678", "rate": "0"}}
|
||||
)
|
||||
@@ -2781,9 +2801,11 @@ class TestBuyCooldown:
|
||||
)
|
||||
broker.get_overseas_balance = AsyncMock(return_value={
|
||||
"output1": [],
|
||||
"output2": [{"frcr_dncl_amt_2": "50000", "frcr_evlu_tota": "50000",
|
||||
"frcr_buy_amt_smtl": "0"}],
|
||||
"output2": [{"frcr_evlu_tota": "50000", "frcr_buy_amt_smtl": "0"}],
|
||||
})
|
||||
broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "50000"}}
|
||||
)
|
||||
broker.send_overseas_order = AsyncMock(
|
||||
return_value={"rt_cd": "1", "msg1": "모의투자 주문가능금액이 부족합니다."}
|
||||
)
|
||||
@@ -2896,9 +2918,11 @@ class TestBuyCooldown:
|
||||
)
|
||||
overseas_broker.get_overseas_balance = AsyncMock(return_value={
|
||||
"output1": [],
|
||||
"output2": [{"frcr_dncl_amt_2": "50000", "frcr_evlu_tota": "50000",
|
||||
"frcr_buy_amt_smtl": "0"}],
|
||||
"output2": [{"frcr_evlu_tota": "50000", "frcr_buy_amt_smtl": "0"}],
|
||||
})
|
||||
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "50000"}}
|
||||
)
|
||||
overseas_broker.send_overseas_order = AsyncMock(
|
||||
return_value={"rt_cd": "1", "msg1": "기타 오류 메시지"}
|
||||
)
|
||||
@@ -3293,9 +3317,12 @@ async def test_buy_suppressed_when_open_position_exists() -> None:
|
||||
overseas_broker.get_overseas_balance = AsyncMock(
|
||||
return_value={
|
||||
"output1": [],
|
||||
"output2": [{"frcr_dncl_amt_2": "10000", "frcr_evlu_tota": "10000", "frcr_buy_amt_smtl": "0"}],
|
||||
"output2": [{"frcr_evlu_tota": "10000", "frcr_buy_amt_smtl": "0"}],
|
||||
}
|
||||
)
|
||||
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "10000"}}
|
||||
)
|
||||
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "OK"})
|
||||
|
||||
engine = MagicMock(spec=ScenarioEngine)
|
||||
@@ -3357,9 +3384,12 @@ async def test_buy_proceeds_when_no_open_position() -> None:
|
||||
overseas_broker.get_overseas_balance = AsyncMock(
|
||||
return_value={
|
||||
"output1": [],
|
||||
"output2": [{"frcr_dncl_amt_2": "50000", "frcr_evlu_tota": "50000", "frcr_buy_amt_smtl": "0"}],
|
||||
"output2": [{"frcr_evlu_tota": "50000", "frcr_buy_amt_smtl": "0"}],
|
||||
}
|
||||
)
|
||||
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "50000"}}
|
||||
)
|
||||
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "OK"})
|
||||
|
||||
engine = MagicMock(spec=ScenarioEngine)
|
||||
@@ -3460,13 +3490,15 @@ class TestOverseasBrokerIntegration:
|
||||
"output1": [{"ovrs_pdno": "AAPL", "ovrs_cblc_qty": "10"}],
|
||||
"output2": [
|
||||
{
|
||||
"frcr_dncl_amt_2": "50000.00",
|
||||
"frcr_evlu_tota": "60000.00",
|
||||
"frcr_buy_amt_smtl": "50000.00",
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "50000.00"}}
|
||||
)
|
||||
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "주문접수"})
|
||||
|
||||
engine = MagicMock(spec=ScenarioEngine)
|
||||
@@ -3534,13 +3566,15 @@ class TestOverseasBrokerIntegration:
|
||||
"output1": [],
|
||||
"output2": [
|
||||
{
|
||||
"frcr_dncl_amt_2": "50000.00",
|
||||
"frcr_evlu_tota": "50000.00",
|
||||
"frcr_buy_amt_smtl": "0.00",
|
||||
}
|
||||
],
|
||||
}
|
||||
)
|
||||
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "50000.00"}}
|
||||
)
|
||||
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "주문접수"})
|
||||
|
||||
engine = MagicMock(spec=ScenarioEngine)
|
||||
@@ -3963,7 +3997,6 @@ class TestSyncPositionsFromBroker:
|
||||
"output2": [
|
||||
{
|
||||
"frcr_evlu_tota": "50000",
|
||||
"frcr_dncl_amt_2": "10000",
|
||||
"frcr_buy_amt_smtl": "40000",
|
||||
}
|
||||
],
|
||||
@@ -4131,7 +4164,7 @@ class TestSyncPositionsFromBroker:
|
||||
|
||||
balance = {
|
||||
"output1": [{"ovrs_pdno": "AAPL", "ovrs_cblc_qty": "10", "pchs_avg_pric": "170.0"}],
|
||||
"output2": [{"frcr_evlu_tota": "50000", "frcr_dncl_amt_2": "10000", "frcr_buy_amt_smtl": "40000"}],
|
||||
"output2": [{"frcr_evlu_tota": "50000", "frcr_buy_amt_smtl": "40000"}],
|
||||
}
|
||||
broker = MagicMock()
|
||||
overseas_broker = MagicMock()
|
||||
@@ -4789,6 +4822,9 @@ class TestOverseasGhostPositionClose:
|
||||
return_value={"output": {"last": str(current_price), "rate": "0.0"}}
|
||||
)
|
||||
ob.get_overseas_balance = AsyncMock(return_value=balance_data)
|
||||
ob.get_overseas_buying_power = AsyncMock(
|
||||
return_value={"output": {"ord_psbl_frcr_amt": "0.00"}}
|
||||
)
|
||||
ob.send_overseas_order = AsyncMock(return_value=sell_result)
|
||||
return ob
|
||||
|
||||
@@ -4811,7 +4847,7 @@ class TestOverseasGhostPositionClose:
|
||||
"output1": [
|
||||
{"ovrs_pdno": stock_code, "ord_psbl_qty": "5", "ovrs_cblc_qty": "5"}
|
||||
],
|
||||
"output2": [{"tot_evlu_amt": "10000", "frcr_dncl_amt_2": "10000"}],
|
||||
"output2": [{"tot_evlu_amt": "10000"}],
|
||||
}
|
||||
sell_result = {"rt_cd": "1", "msg1": "모의투자 잔고내역이 없습니다"}
|
||||
|
||||
@@ -4887,7 +4923,7 @@ class TestOverseasGhostPositionClose:
|
||||
current_price = 250.0
|
||||
balance_data = {
|
||||
"output1": [{"ovrs_pdno": stock_code, "ord_psbl_qty": "5", "ovrs_cblc_qty": "5"}],
|
||||
"output2": [{"tot_evlu_amt": "100000", "frcr_dncl_amt_2": "100000"}],
|
||||
"output2": [{"tot_evlu_amt": "100000"}],
|
||||
}
|
||||
sell_result = {"rt_cd": "1", "msg1": "일시적 오류가 발생했습니다"}
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ def mock_settings() -> Settings:
|
||||
KIS_APP_SECRET="test_secret",
|
||||
KIS_ACCOUNT_NO="12345678-01",
|
||||
GEMINI_API_KEY="test_gemini_key",
|
||||
MODE="paper", # Explicitly set to avoid .env MODE=live override
|
||||
)
|
||||
|
||||
|
||||
@@ -122,9 +123,10 @@ class TestFetchOverseasRankings:
|
||||
params = call_args[1]["params"]
|
||||
|
||||
assert "/uapi/overseas-stock/v1/ranking/updown-rate" in url
|
||||
assert params["KEYB"] == "" # Required by KIS API spec
|
||||
assert params["EXCD"] == "NAS"
|
||||
assert params["NDAY"] == "0"
|
||||
assert params["GUBN"] == "0" # 0=전체(상승+하락), 변동성 스캐너에 필요
|
||||
assert params["GUBN"] == "1" # 1=상승율 — 변동성 스캐너는 급등 종목 우선
|
||||
assert params["VOL_RANG"] == "0"
|
||||
|
||||
overseas_broker._broker._auth_headers.assert_called_with("HHDFS76290000")
|
||||
@@ -157,6 +159,7 @@ class TestFetchOverseasRankings:
|
||||
params = call_args[1]["params"]
|
||||
|
||||
assert "/uapi/overseas-stock/v1/ranking/volume-surge" in url
|
||||
assert params["KEYB"] == "" # Required by KIS API spec
|
||||
assert params["EXCD"] == "NYS"
|
||||
assert params["MIXN"] == "0"
|
||||
assert params["VOL_RANG"] == "0"
|
||||
|
||||
Reference in New Issue
Block a user