feat: add kosdaq_scanner, short_term_strategy and rewrite CLAUDE.md in narrative style
This commit is contained in:
174
backend/app/services/kosdaq_scanner.py
Normal file
174
backend/app/services/kosdaq_scanner.py
Normal file
@@ -0,0 +1,174 @@
|
||||
"""
|
||||
코스닥 전종목 스캐너 (CLAUDE.md 섹션 8.1)
|
||||
|
||||
매일 장 마감 후 코스닥 전종목(~1,600종목)을 스캔하여
|
||||
RSI + 볼린저 밴드 + 거래량 복합 점수로 상위 20종목을 선별한다.
|
||||
"""
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 가격 필터 (CLAUDE.md 섹션 6.4)
|
||||
MIN_PRICE_KRW = 5_000
|
||||
|
||||
# 거래대금 상위 20% 임계값 (하위 80% 제외)
|
||||
LIQUIDITY_PERCENTILE = 0.80
|
||||
|
||||
# 스캔 결과 상위 N개
|
||||
TOP_N = 20
|
||||
|
||||
|
||||
@dataclass
|
||||
class ScanResult:
|
||||
ticker: str
|
||||
score: float
|
||||
rsi14: float
|
||||
pct_vs_bb_lower: float # (close - bb_lower) / bb_lower * 100
|
||||
volume_ratio: float # current_volume / volume_ma20
|
||||
close: float
|
||||
reason: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
class TickerData:
|
||||
"""스캐너에 필요한 종목 데이터 구조체"""
|
||||
ticker: str
|
||||
close: float
|
||||
closes: List[float] # 최근 60일 이상 종가
|
||||
volume: int
|
||||
volumes: List[int] # 최근 20일 거래량
|
||||
turnover: float # 당일 거래대금 (원)
|
||||
turnovers: List[float] # 최근 20일 거래대금
|
||||
|
||||
|
||||
class KosdaqScanner:
|
||||
"""코스닥 전종목 스캐너
|
||||
|
||||
매일 장 마감 후 scan_all()을 호출하면 조건을 충족하는 상위 20종목을
|
||||
점수 내림차순으로 반환한다.
|
||||
|
||||
스코어링 공식 (CLAUDE.md 섹션 8.1):
|
||||
score = rsi_score × 0.5 + bb_score × 0.3 + volume_score × 0.2
|
||||
|
||||
- rsi_score = max(0, (25 - rsi14) / 25) # RSI 낮을수록 ↑
|
||||
- bb_score = max(0, (0 - pct_vs_lower) / 3) # BB 하단 근접 ↑
|
||||
- volume_score = min(volume / volume_ma20, 2.0) # 거래량 급증 ↑
|
||||
"""
|
||||
|
||||
def __init__(self, min_price: int = MIN_PRICE_KRW, top_n: int = TOP_N):
|
||||
self.min_price = min_price
|
||||
self.top_n = top_n
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def scan_all(self, tickers_data: List[TickerData]) -> List[ScanResult]:
|
||||
"""코스닥 전종목 스캔 → 상위 N개 ScanResult 반환
|
||||
|
||||
Args:
|
||||
tickers_data: 외부(KIS API 등)에서 수집한 종목 데이터 리스트
|
||||
|
||||
Returns:
|
||||
점수 내림차순 정렬된 상위 TOP_N개 ScanResult
|
||||
"""
|
||||
liquidity_threshold = self._calc_liquidity_threshold(tickers_data)
|
||||
|
||||
candidates: List[ScanResult] = []
|
||||
for td in tickers_data:
|
||||
if not self._price_filter(td.close):
|
||||
continue
|
||||
if not self._liquidity_filter(td.turnover, liquidity_threshold):
|
||||
continue
|
||||
result = self._score(td)
|
||||
if result is not None:
|
||||
candidates.append(result)
|
||||
|
||||
candidates.sort(key=lambda x: x.score, reverse=True)
|
||||
return candidates[: self.top_n]
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Filters
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _price_filter(self, close: float) -> bool:
|
||||
"""CLAUDE.md 섹션 6.4: 국내 5,000원 이하 매수 금지"""
|
||||
return close >= self.min_price
|
||||
|
||||
def _liquidity_filter(self, turnover: float, threshold: float) -> bool:
|
||||
"""거래대금 상위 20% 이내 필터 (하위 80% 제외)"""
|
||||
return turnover >= threshold
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Scoring
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _score(self, td: TickerData) -> Optional[ScanResult]:
|
||||
"""RSI + 볼린저 밴드 + 거래량 복합 점수 계산
|
||||
|
||||
Returns:
|
||||
ScanResult if 최소 조건 충족, else None
|
||||
"""
|
||||
from .mean_reversion_strategy import calculate_rsi, calculate_bollinger
|
||||
|
||||
closes = td.closes
|
||||
if len(closes) < 25:
|
||||
return None
|
||||
|
||||
rsi14 = calculate_rsi(closes, 14)
|
||||
bb = calculate_bollinger(closes, 20)
|
||||
if rsi14 is None or bb is None:
|
||||
return None
|
||||
|
||||
_, _, bb_lower = bb
|
||||
if bb_lower == 0:
|
||||
return None
|
||||
|
||||
volume_ma20 = sum(td.volumes[-20:]) / 20 if len(td.volumes) >= 20 else None
|
||||
if volume_ma20 is None or volume_ma20 == 0:
|
||||
return None
|
||||
|
||||
pct_vs_lower = (td.close - bb_lower) / bb_lower * 100
|
||||
volume_ratio = td.volume / volume_ma20
|
||||
|
||||
rsi_score = max(0.0, (25.0 - rsi14) / 25.0)
|
||||
bb_score = max(0.0, (0.0 - pct_vs_lower) / 3.0)
|
||||
volume_score = min(volume_ratio, 2.0)
|
||||
|
||||
total_score = rsi_score * 0.5 + bb_score * 0.3 + volume_score * 0.2
|
||||
|
||||
if total_score <= 0:
|
||||
return None
|
||||
|
||||
reason_parts = []
|
||||
if rsi14 <= 25:
|
||||
reason_parts.append(f"RSI({rsi14:.1f})≤25")
|
||||
if pct_vs_lower <= 0:
|
||||
reason_parts.append(f"BB하단({pct_vs_lower:.1f}%)")
|
||||
if volume_ratio >= 1.5:
|
||||
reason_parts.append(f"거래량({volume_ratio:.1f}x)")
|
||||
|
||||
return ScanResult(
|
||||
ticker=td.ticker,
|
||||
score=round(total_score, 4),
|
||||
rsi14=round(rsi14, 2),
|
||||
pct_vs_bb_lower=round(pct_vs_lower, 2),
|
||||
volume_ratio=round(volume_ratio, 2),
|
||||
close=td.close,
|
||||
reason=" + ".join(reason_parts) if reason_parts else "복합점수",
|
||||
)
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Helpers
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
@staticmethod
|
||||
def _calc_liquidity_threshold(tickers_data: List[TickerData]) -> float:
|
||||
"""거래대금 상위 20% 임계값 계산 (80번째 백분위수)"""
|
||||
turnovers = sorted([td.turnover for td in tickers_data if td.turnover > 0])
|
||||
if not turnovers:
|
||||
return 0.0
|
||||
idx = int(len(turnovers) * LIQUIDITY_PERCENTILE)
|
||||
return turnovers[min(idx, len(turnovers) - 1)]
|
||||
208
backend/app/services/short_term_strategy.py
Normal file
208
backend/app/services/short_term_strategy.py
Normal file
@@ -0,0 +1,208 @@
|
||||
"""
|
||||
15분봉 단기 전략 (CLAUDE.md 섹션 8.2)
|
||||
|
||||
전체 자본의 최대 25% 이내에서 운용.
|
||||
일봉 RSI ≤ 40 관심 종목에 한해 15분봉 신호를 감지한다.
|
||||
|
||||
⚠️ 슬리피지 주의: 수수료 0.3% + 슬리피지 0.2% 포함 백테스트 필수
|
||||
"""
|
||||
import logging
|
||||
from dataclasses import dataclass
|
||||
from enum import Enum
|
||||
from typing import List, Optional
|
||||
|
||||
from .mean_reversion_strategy import calculate_rsi, calculate_bollinger
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 자본 비율 상한 (CLAUDE.md 섹션 8.2 / 8.3)
|
||||
MAX_CAPITAL_RATIO = 0.25
|
||||
|
||||
# 비용 가정 — 백테스트 시 왕복으로 적용
|
||||
COMMISSION_RATE = 0.003 # 수수료 0.3%
|
||||
SLIPPAGE_RATE = 0.002 # 슬리피지 0.2%
|
||||
TOTAL_COST_RATE = COMMISSION_RATE + SLIPPAGE_RATE
|
||||
|
||||
|
||||
class TimeFrame(str, Enum):
|
||||
M15 = "15m"
|
||||
H1 = "60m"
|
||||
|
||||
|
||||
@dataclass
|
||||
class EntrySignal:
|
||||
ticker: str
|
||||
timeframe: TimeFrame
|
||||
reason: str
|
||||
rsi: float
|
||||
close: float
|
||||
|
||||
|
||||
@dataclass
|
||||
class ExitSignal:
|
||||
action: str # "SELL_ALL"
|
||||
reason: str
|
||||
sell_pct: float # 1.0 = 전량
|
||||
|
||||
|
||||
class ShortTermStrategy:
|
||||
"""15분봉 단기 평균회귀 전략
|
||||
|
||||
진입 조건 (모두 충족 필요):
|
||||
1. 일봉 RSI(14) ≤ 40 — 관심 종목 사전 필터
|
||||
2. 15분봉 RSI(14) ≤ 30
|
||||
3. 15분봉 종가 ≤ BB 하단 × 1.01
|
||||
4. 15분봉 종가 > MA5 — Fake-out 방지
|
||||
5. 15분봉 거래량 > 거래량 MA20 × 1.3
|
||||
|
||||
청산 조건 (둘 중 하나 충족):
|
||||
- 15분봉 RSI(14) ≥ 55
|
||||
- 수익률 ≥ 1.5 × ATR_15m_pct
|
||||
|
||||
자본 제한:
|
||||
- 이 전략 배분 총액이 전체 자본 × 25% 초과 시 신규 진입 차단
|
||||
- MDD -10% 돌파 시 즉시 중단 (호출 측에서 판단)
|
||||
"""
|
||||
|
||||
TIMEFRAME = TimeFrame.M15
|
||||
DAILY_RSI_THRESHOLD = 40.0 # 일봉 사전 필터
|
||||
M15_RSI_ENTRY = 30.0 # 15분봉 진입 RSI
|
||||
M15_RSI_EXIT = 55.0 # 15분봉 청산 RSI
|
||||
VOLUME_MULTIPLIER = 1.3 # 거래량 배수
|
||||
|
||||
def __init__(self, max_capital_ratio: float = MAX_CAPITAL_RATIO):
|
||||
self.max_capital_ratio = max_capital_ratio
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Public API
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def entry_signal(
|
||||
self,
|
||||
ticker: str,
|
||||
daily_rsi: float,
|
||||
m15_closes: List[float],
|
||||
m15_volumes: List[int],
|
||||
current_volume: int,
|
||||
) -> Optional[EntrySignal]:
|
||||
"""15분봉 진입 신호 감지
|
||||
|
||||
Args:
|
||||
ticker: 종목코드
|
||||
daily_rsi: 일봉 RSI(14)
|
||||
m15_closes: 15분봉 종가 리스트 (최소 25개)
|
||||
m15_volumes: 15분봉 거래량 리스트 (최소 20개)
|
||||
current_volume: 현재 봉 거래량
|
||||
|
||||
Returns:
|
||||
EntrySignal if 모든 조건 충족, else None
|
||||
"""
|
||||
# 조건 1: 일봉 사전 필터
|
||||
if daily_rsi > self.DAILY_RSI_THRESHOLD:
|
||||
return None
|
||||
|
||||
if len(m15_closes) < 25 or len(m15_volumes) < 20:
|
||||
return None
|
||||
|
||||
close = m15_closes[-1]
|
||||
|
||||
# 조건 2: 15분봉 RSI
|
||||
rsi_15m = calculate_rsi(m15_closes, 14)
|
||||
if rsi_15m is None or rsi_15m > self.M15_RSI_ENTRY:
|
||||
return None
|
||||
|
||||
# 조건 3: BB 하단 근처
|
||||
bb = calculate_bollinger(m15_closes, 20)
|
||||
if bb is None:
|
||||
return None
|
||||
_, _, bb_lower = bb
|
||||
if close > bb_lower * 1.01:
|
||||
return None
|
||||
|
||||
# 조건 4: MA5 상향 (Fake-out 방지)
|
||||
ma5 = sum(m15_closes[-5:]) / 5
|
||||
if close <= ma5:
|
||||
return None
|
||||
|
||||
# 조건 5: 거래량 급증
|
||||
vol_ma20 = sum(m15_volumes[-20:]) / 20
|
||||
if vol_ma20 == 0 or current_volume <= vol_ma20 * self.VOLUME_MULTIPLIER:
|
||||
return None
|
||||
|
||||
return EntrySignal(
|
||||
ticker=ticker,
|
||||
timeframe=self.TIMEFRAME,
|
||||
reason=(
|
||||
f"15분봉 RSI({rsi_15m:.1f})≤30 + BB하단 + MA5돌파 "
|
||||
f"+ 거래량({current_volume / vol_ma20:.1f}x)"
|
||||
),
|
||||
rsi=round(rsi_15m, 2),
|
||||
close=close,
|
||||
)
|
||||
|
||||
def exit_signal(
|
||||
self,
|
||||
ticker: str,
|
||||
m15_closes: List[float],
|
||||
entry_price: float,
|
||||
atr_15m: Optional[float] = None,
|
||||
) -> Optional[ExitSignal]:
|
||||
"""15분봉 청산 신호
|
||||
|
||||
Args:
|
||||
ticker: 종목코드
|
||||
m15_closes: 15분봉 종가 리스트
|
||||
entry_price: 진입 가격
|
||||
atr_15m: 15분봉 ATR (None 이면 ATR 조건 스킵)
|
||||
|
||||
Returns:
|
||||
ExitSignal if 청산 조건 충족, else None
|
||||
"""
|
||||
if len(m15_closes) < 15:
|
||||
return None
|
||||
|
||||
close = m15_closes[-1]
|
||||
rsi_15m = calculate_rsi(m15_closes, 14)
|
||||
|
||||
# 청산 조건 1: RSI ≥ 55 회복
|
||||
if rsi_15m is not None and rsi_15m >= self.M15_RSI_EXIT:
|
||||
return ExitSignal(
|
||||
action="SELL_ALL",
|
||||
reason=f"15분봉 RSI({rsi_15m:.1f})≥55 회복",
|
||||
sell_pct=1.0,
|
||||
)
|
||||
|
||||
# 청산 조건 2: 수익률 ≥ 1.5 × ATR_15m_pct
|
||||
if atr_15m and entry_price > 0:
|
||||
profit_pct = (close - entry_price) / entry_price
|
||||
atr_pct = atr_15m / entry_price
|
||||
if profit_pct >= 1.5 * atr_pct:
|
||||
return ExitSignal(
|
||||
action="SELL_ALL",
|
||||
reason=(
|
||||
f"익절 수익률({profit_pct * 100:.1f}%) "
|
||||
f"≥ 1.5×ATR({atr_pct * 100:.1f}%)"
|
||||
),
|
||||
sell_pct=1.0,
|
||||
)
|
||||
|
||||
return None
|
||||
|
||||
def is_capital_available(
|
||||
self, total_assets: float, current_short_term_allocation: float
|
||||
) -> bool:
|
||||
"""단기 전략 자본 한도 초과 여부 확인
|
||||
|
||||
CLAUDE.md 섹션 8.3: 단기 전략에 최대 25% 배분.
|
||||
MDD -10% 돌파 시에는 호출 측에서 별도로 차단해야 한다.
|
||||
"""
|
||||
limit = total_assets * self.max_capital_ratio
|
||||
return current_short_term_allocation < limit
|
||||
|
||||
@staticmethod
|
||||
def net_profit_pct(gross_profit_pct: float) -> float:
|
||||
"""수수료 + 슬리피지 차감 후 순수익률 (왕복 기준)
|
||||
|
||||
백테스트 결과 검증 시 이 함수로 실질 수익률을 계산하라.
|
||||
"""
|
||||
return gross_profit_pct - TOTAL_COST_RATE * 2
|
||||
Reference in New Issue
Block a user