feat: add backtest module with DB cache and scenario comparison

Backtest improvements:
- Add backtest.py with Oracle DB-backed OHLCV cache (no repeated API calls)
- Add backtest_trades table to cache simulation results by params hash
  (same params -> instant load, skip re-simulation)
- Add walk-forward scenario comparison (--walkforward-cmp)
- Add trend ceiling filter (--trend-cmp, max gain threshold)
- Add ticker win-rate filter (--ticker-cmp, SQL-based instant analysis)
- Precompute daily_features once per data load (not per scenario)

Live bot fixes:
- monitor: add hard stop-loss from buy price (in addition to trailing)
- strategy: fix re-entry condition to require +1% above last sell price
- price_collector: add 48h backfill on startup for trend calculation
- main: call backfill_prices() at startup

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
joungmin
2026-02-28 23:28:27 +09:00
parent 4888aa0faa
commit 0b264b304c
5 changed files with 1621 additions and 17 deletions

1556
backtest.py Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -19,7 +19,7 @@ TIME_STOP_MIN_GAIN_PCT = float(os.getenv("TIME_STOP_MIN_GAIN_PCT", "3"))
def _check_trailing_stop(ticker: str, pos: dict, current: float) -> bool:
"""트레일링 스탑 체크. 매도 시 True 반환."""
"""트레일링 스탑(최고가 기준) + 고정 스탑(매수가 기준) 체크. 매도 시 True 반환."""
trader.update_peak(ticker, current)
pos = trader.get_positions().get(ticker)
@@ -27,15 +27,24 @@ def _check_trailing_stop(ticker: str, pos: dict, current: float) -> bool:
return False
peak = pos["peak_price"]
buy_price = pos["buy_price"]
drop_from_peak = (peak - current) / peak
drop_from_buy = (buy_price - current) / buy_price # 구매가 대비 하락률
if drop_from_peak >= STOP_LOSS_PCT:
reason = (
f"트레일링스탑 | 최고가={peak:,.0f}원 → "
f"현재={current:,.0f}원 ({drop_from_peak:.1%} 하락)"
)
trader.sell(ticker, reason=reason)
return True
return trader.sell(ticker, reason=reason)
if drop_from_buy >= STOP_LOSS_PCT:
reason = (
f"스탑로스 | 매수가={buy_price:,.0f}원 → "
f"현재={current:,.0f}원 ({drop_from_buy:.1%} 하락)"
)
return trader.sell(ticker, reason=reason)
return False
@@ -70,15 +79,17 @@ def _check_position(ticker: str, pos: dict) -> None:
if current is None:
return
pnl = (current - pos["buy_price"]) / pos["buy_price"] * 100
buy_price = pos["buy_price"]
pnl = (current - buy_price) / buy_price * 100
peak = pos["peak_price"]
drop_from_peak = (peak - current) / peak
drop_from_buy = (buy_price - current) / buy_price
entry_time = pos.get("entry_time", datetime.now())
elapsed_hours = (datetime.now() - entry_time).total_seconds() / 3600
logger.info(
f"[감시] {ticker} 현재={current:,.0f} | 최고={peak:,.0f} | "
f"하락={drop_from_peak:.1%} | 수익률={pnl:+.1f}% | "
f"[감시] {ticker} 현재={current:,.0f} | 매수가={buy_price:,.0f} | 최고={peak:,.0f} | "
f"수익률={pnl:+.1f}% | peak하락={drop_from_peak:.1%} | buy하락={drop_from_buy:.1%} | "
f"보유={elapsed_hours:.1f}h"
)
@@ -94,7 +105,7 @@ def run_monitor(interval: int = CHECK_INTERVAL) -> None:
"""전체 포지션 감시 루프."""
logger.info(
f"모니터 시작 | 체크={interval}초 | "
f"트레일링스탑={STOP_LOSS_PCT:.0%} | "
f"트레일링스탑={STOP_LOSS_PCT:.1%} | "
f"타임스탑={TIME_STOP_HOURS:.0f}h/{TIME_STOP_MIN_GAIN_PCT:+.0f}%"
)
while True:

View File

@@ -5,10 +5,11 @@ from __future__ import annotations
import logging
import time
import pyupbit
import requests
from .market import get_top_tickers
from .price_db import cleanup_old_prices, insert_prices
from .price_db import cleanup_old_prices, insert_prices, insert_prices_with_time
logger = logging.getLogger(__name__)
@@ -16,6 +17,38 @@ COLLECT_INTERVAL = 600 # 10분 (초)
CLEANUP_EVERY = 6 # 1시간(10분 × 6)마다 오래된 데이터 정리
def backfill_prices(hours: int = 48) -> None:
"""시작 시 과거 N시간치 1시간봉 종가를 DB에 백필.
price_history에 데이터가 없으면 추세 판단이 불가능하므로
봇 시작 직후 한 번 호출해 과거 데이터를 채운다.
"""
tickers = get_top_tickers()
if not tickers:
logger.warning("[백필] 종목 목록 없음, 스킵")
return
count = hours + 2 # 여유 있게 요청
total_rows = 0
for ticker in tickers:
try:
df = pyupbit.get_ohlcv(ticker, interval="minute60", count=count)
if df is None or df.empty:
continue
rows = [
(ticker, float(row["close"]), ts.to_pydatetime())
for ts, row in df.iterrows()
]
insert_prices_with_time(rows)
total_rows += len(rows)
time.sleep(0.1)
except Exception as e:
logger.error(f"[백필] {ticker} 오류: {e}")
logger.info(f"[백필] 완료 — {len(tickers)}개 종목 / {total_rows}개 레코드 저장")
def run_collector(interval: int = COLLECT_INTERVAL) -> None:
"""가격 수집 루프."""
logger.info(f"가격 수집기 시작 (주기={interval//60}분)")

View File

@@ -1,4 +1,4 @@
"""Strategy C: 실시간 상승 추세(DB) AND 거래량 모멘텀 동시 충족 시 매수 신호."""
"""Strategy C: 현재 기준 N시간 전 대비 상승 추세(DB) AND 거래량 모멘텀 동시 충족 시 매수 신호."""
from __future__ import annotations
@@ -10,8 +10,8 @@ from .price_db import get_price_n_hours_ago
logger = logging.getLogger(__name__)
# 추세 판단: N시간 전 대비 +M% 이상이면 상승 중
TREND_HOURS = float(os.getenv("TREND_HOURS", "1"))
# 추세 판단: 현재 기준 N시간 전 DB 가격 대비 +M% 이상이면 상승 중
TREND_HOURS = float(os.getenv("TREND_HOURS", "12"))
TREND_MIN_GAIN_PCT = float(os.getenv("TREND_MIN_GAIN_PCT", "3"))
# 모멘텀: MA 기간, 거래량 급증 배수
@@ -20,10 +20,10 @@ VOLUME_MULTIPLIER = 2.0
def check_trend(ticker: str) -> bool:
"""상승 추세 조건: 현재가가 N시간 전 대비 +M% 이상."""
"""상승 추세 조건: 현재가가 DB에 저장된 N시간 전 가격 대비 +M% 이상."""
past_price = get_price_n_hours_ago(ticker, TREND_HOURS)
if past_price is None:
logger.debug(f"[추세] {ticker} 과거 가격 없음 (데이터 수집 중)")
logger.debug(f"[추세] {ticker} {TREND_HOURS:.0f}h 전 가격 없음 (수집 중)")
return False
current = get_current_price(ticker)
@@ -35,8 +35,8 @@ def check_trend(ticker: str) -> bool:
if result:
logger.info(
f"[추세↑] {ticker} {TREND_HOURS:.0f}h 전={past_price:,.0f} "
f"현재={current:,.0f} (+{gain_pct:.1f}%)"
f"[추세↑] {ticker} {TREND_HOURS:.0f}h 전={past_price:,.2f} "
f"현재={current:,.2f} (+{gain_pct:.1f}%)"
)
else:
logger.debug(

View File

@@ -19,7 +19,7 @@ logging.basicConfig(
from core.monitor import run_monitor
from core.notify import notify_error, notify_status
from core.price_collector import run_collector
from core.price_collector import backfill_prices, run_collector
from core.trader import get_positions, restore_positions
from daemon.runner import run_scanner
@@ -45,6 +45,10 @@ def main() -> None:
# 재시작 시 기존 잔고 복원 (이중 매수 방지)
restore_positions()
# 과거 가격 백필 (추세 판단용 DB 데이터가 없는 경우 채움)
logger.info("과거 가격 백필 시작 (48시간)...")
backfill_prices(hours=48)
# 트레일링 스탑 감시 스레드 (10초 주기)
monitor_thread = threading.Thread(
target=run_monitor, args=(10,), daemon=True, name="monitor"
@@ -57,7 +61,7 @@ def main() -> None:
)
status_thread.start()
# 10분 주기 가격 수집 스레드 (추세 판단용 DB 저장)
# 가격 수집 스레드 (10분 주기 → Oracle DB price_history 저장, 추세 판단용)
collector_thread = threading.Thread(
target=run_collector, daemon=True, name="collector"
)