feat: replace volatility breakout with DB-backed real-time trend check

- price_history table on Oracle ADB stores prices every 10 minutes
- check_trend(): current price vs N hours ago (default 1h, +3% threshold)
- check_momentum(): unchanged (MA20 + 2x volume still applies)
- Ticker list cached 5 minutes to avoid 429 rate limits
- Collector starts 30s after boot to avoid simultaneous API calls
- Configurable: TREND_HOURS, TREND_MIN_GAIN_PCT in .env

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
joungmin
2026-02-28 11:26:26 +09:00
parent 9fe3ce488e
commit 80ab004eba
6 changed files with 206 additions and 26 deletions

View File

@@ -1,36 +1,47 @@
"""Strategy C: 변동성 돌파 AND 모멘텀 동시 충족 시 매수 신호."""
"""Strategy C: 실시간 상승 추세(DB) AND 거래량 모멘텀 동시 충족 시 매수 신호."""
from __future__ import annotations
import logging
import os
from .market import get_current_price, get_ohlcv
from .price_db import get_price_n_hours_ago
logger = logging.getLogger(__name__)
# 변동성 돌파 계수 (래리 윌리엄스 기본값)
BREAKOUT_K = 0.5
# 모멘텀 이동평균 기간
# 추세 판단: N시간 전 대비 +M% 이상이면 상승 중
TREND_HOURS = float(os.getenv("TREND_HOURS", "1"))
TREND_MIN_GAIN_PCT = float(os.getenv("TREND_MIN_GAIN_PCT", "3"))
# 모멘텀: MA 기간, 거래량 급증 배수
MA_PERIOD = 20
# 거래량 급증 배수
VOLUME_MULTIPLIER = 2.0
def check_volatility_breakout(ticker: str) -> bool:
"""변동성 돌파 조건: 현재가 > 오늘 시가 + 전일 변동폭 × K."""
df = get_ohlcv(ticker, count=2)
if df is None or len(df) < 2:
def check_trend(ticker: str) -> bool:
"""상승 추세 조건: 현재가 N시간 전 대비 +M% 이상."""
past_price = get_price_n_hours_ago(ticker, TREND_HOURS)
if past_price is None:
logger.debug(f"[추세] {ticker} 과거 가격 없음 (데이터 수집 중)")
return False
prev = df.iloc[-2]
today = df.iloc[-1]
target = today["open"] + (prev["high"] - prev["low"]) * BREAKOUT_K
current = get_current_price(ticker)
if current is None:
if not current:
return False
result = current > target
gain_pct = (current - past_price) / past_price * 100
result = gain_pct >= TREND_MIN_GAIN_PCT
if result:
logger.debug(f"[변동성돌파] {ticker} 현재가={current:,.0f} 목표가={target:,.0f}")
logger.info(
f"[추세↑] {ticker} {TREND_HOURS:.0f}h 전={past_price:,.0f} "
f"현재={current:,.0f} (+{gain_pct:.1f}%)"
)
else:
logger.debug(
f"[추세✗] {ticker} {gain_pct:+.1f}% (기준={TREND_MIN_GAIN_PCT:+.0f}%)"
)
return result
@@ -41,7 +52,7 @@ def check_momentum(ticker: str) -> bool:
return False
ma = df["close"].iloc[-MA_PERIOD:].mean()
avg_vol = df["volume"].iloc[:-1].mean() # 오늘 제외한 20일 평균
avg_vol = df["volume"].iloc[:-1].mean()
today_vol = df["volume"].iloc[-1]
current = get_current_price(ticker)
@@ -54,16 +65,14 @@ def check_momentum(ticker: str) -> bool:
if result:
logger.debug(
f"[모멘텀] {ticker} 현재={current:,.0f} MA20={ma:,.0f} "
f"오늘거래량={today_vol:.1f} 평균={avg_vol:.1f}"
f"[모멘텀] {ticker} 현재={current:,.0f} MA20={ma:,.0f} "
f"거래량={today_vol:.0f} 평균={avg_vol:.0f}"
)
return result
def should_buy(ticker: str) -> bool:
"""Strategy C: 변동성 돌파 AND 모멘텀 모두 충족 시 True."""
vb = check_volatility_breakout(ticker)
if not vb:
"""Strategy C: 실시간 상승 추세 AND 거래량 모멘텀 모두 충족 시 True."""
if not check_trend(ticker):
return False
mo = check_momentum(ticker)
return vb and mo
return check_momentum(ticker)