feat: add market regime filter and compound reinvestment

- Add market_regime.py: BTC/ETH/SOL/XRP weighted 2h trend score
  Bull(≥+1.5%) / Neutral / Bear(<-1%) regime detection with 10min cache
- strategy.py: dynamic TREND/VOL thresholds based on current regime
  Bull: 3%/1.5x, Neutral: 5%/2.0x, Bear: 8%/3.5x
- price_collector.py: always include leader coins in price history
- trader.py: compound reinvestment (profit added to budget, floor at initial)
- notify.py: regime info in hourly report, P&L icons (/, 💚/🔴)
- main.py: hourly status at top-of-hour, filter positions held 1h+
- backtest.py: timestop/combo comparison modes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
joungmin
2026-03-01 10:14:36 +09:00
parent 035b3e2f30
commit 83a229dd26
8 changed files with 423 additions and 46 deletions

110
core/market_regime.py Normal file
View File

@@ -0,0 +1,110 @@
"""시장 레짐(Bull/Neutral/Bear) 판단.
BTC·ETH·SOL·XRP 가중 평균 2h 추세로 레짐을 결정하고
매수 조건 파라미터(trend_pct, vol_mult)를 동적으로 반환한다.
계산된 현재가는 price_history DB에 저장해 재활용한다.
"""
from __future__ import annotations
import logging
import time
import pyupbit
from .price_db import get_price_n_hours_ago, insert_prices
logger = logging.getLogger(__name__)
# 대장 코인 가중치
LEADERS: dict[str, float] = {
"KRW-BTC": 0.40,
"KRW-ETH": 0.30,
"KRW-SOL": 0.15,
"KRW-XRP": 0.15,
}
TREND_HOURS = 2 # 2h 추세 기준
BULL_THRESHOLD = 1.5 # score ≥ 1.5% → Bull
BEAR_THRESHOLD = -1.0 # score < -1.0% → Bear
# 레짐별 매수 조건 파라미터
REGIME_PARAMS: dict[str, dict] = {
"bull": {"trend_pct": 3.0, "vol_mult": 1.5, "emoji": "🟢"},
"neutral": {"trend_pct": 5.0, "vol_mult": 2.0, "emoji": "🟡"},
"bear": {"trend_pct": 8.0, "vol_mult": 3.5, "emoji": "🔴"},
}
# 10분 캐시 (스캔 루프마다 API 호출 방지)
_cache: dict = {}
_cache_ts: float = 0.0
_CACHE_TTL = 600
def get_regime() -> dict:
"""현재 시장 레짐 반환.
Returns:
{
'name': 'bull' | 'neutral' | 'bear',
'score': float, # 가중 평균 2h 추세(%)
'trend_pct': float, # 매수 추세 임계값
'vol_mult': float, # 거래량 배수 임계값
'emoji': str,
}
"""
global _cache, _cache_ts
if _cache and (time.time() - _cache_ts) < _CACHE_TTL:
return _cache
score = 0.0
current_prices: dict[str, float] = {}
for ticker, weight in LEADERS.items():
try:
current = pyupbit.get_current_price(ticker)
if not current:
continue
current_prices[ticker] = current
# DB에서 2h 전 가격 조회 → 없으면 API 캔들로 대체
past = get_price_n_hours_ago(ticker, TREND_HOURS)
if past is None:
df = pyupbit.get_ohlcv(ticker, interval="minute60", count=4)
if df is not None and len(df) >= 3:
past = float(df["close"].iloc[-3])
if past:
trend = (current - past) / past * 100
score += trend * weight
logger.debug(f"[레짐] {ticker} {trend:+.2f}% (기여 {trend*weight:+.3f})")
except Exception as e:
logger.warning(f"[레짐] {ticker} 오류: {e}")
# 현재가 DB 저장 (다음 레짐 계산 및 추세 판단에 재활용)
if current_prices:
try:
insert_prices(current_prices)
except Exception as e:
logger.warning(f"[레짐] 가격 저장 오류: {e}")
# 레짐 결정
if score >= BULL_THRESHOLD:
name = "bull"
elif score < BEAR_THRESHOLD:
name = "bear"
else:
name = "neutral"
params = REGIME_PARAMS[name]
result = {"name": name, "score": round(score, 3), **params}
logger.info(
f"[레짐] score={score:+.3f}% → {params['emoji']} {name.upper()} "
f"(TREND≥{params['trend_pct']}% / VOL≥{params['vol_mult']}x)"
)
_cache = result
_cache_ts = time.time()
return result

View File

@@ -28,21 +28,36 @@ def _send(text: str) -> None:
logger.error(f"Telegram 알림 실패: {e}")
def notify_buy(ticker: str, price: float, amount: float, invested_krw: int) -> None:
def notify_buy(
ticker: str, price: float, amount: float, invested_krw: int,
max_budget: int = 0, per_position: int = 0,
) -> None:
budget_line = (
f"운용예산: {max_budget:,}원 (포지션당 {per_position:,}원)\n"
if max_budget else ""
)
_send(
f"📈 <b>[매수]</b> {ticker}\n"
f"가격: {price:,.0f}\n"
f"수량: {amount}\n"
f"투자금: {invested_krw:,}"
f"투자금: {invested_krw:,}\n"
f"{budget_line}"
)
def notify_sell(ticker: str, price: float, pnl_pct: float, reason: str) -> None:
emoji = "" if pnl_pct >= 0 else "🔴"
def notify_sell(
ticker: str, price: float, pnl_pct: float, reason: str,
krw_profit: float = 0.0, fee_krw: float = 0.0,
cum_profit: float = 0.0,
) -> None:
trade_emoji = "" if pnl_pct >= 0 else ""
cum_emoji = "💚" if cum_profit >= 0 else "🔴"
_send(
f"{emoji} <b>[매도]</b> {ticker}\n"
f"{trade_emoji} <b>[매도]</b> {ticker}\n"
f"가격: {price:,.0f}\n"
f"수익률: {pnl_pct:+.1f}%\n"
f"수익률: {pnl_pct:+.2f}%\n"
f"실손익: {krw_profit:+,.0f}원 (수수료 {fee_krw:,.0f}원)\n"
f"{cum_emoji} 누적손익: {cum_profit:+,.0f}\n"
f"사유: {reason}"
)
@@ -51,19 +66,50 @@ def notify_error(message: str) -> None:
_send(f"⚠️ <b>[오류]</b>\n{message}")
def notify_status(positions: dict) -> None:
"""1시간마다 포지션 현황 요약 전송."""
def notify_status(
positions: dict,
max_budget: int = 0,
per_position: int = 0,
cum_profit: float = 0.0,
) -> None:
"""정각마다 시장 레짐 + 1시간 이상 보유 포지션 현황 전송."""
from datetime import datetime
import pyupbit
from .market_regime import get_regime
now = datetime.now().strftime("%H:%M")
cum_sign = "+" if cum_profit >= 0 else ""
if not positions:
_send(f"📊 <b>[{now} 현황]</b>\n보유 포지션 없음 — 매수 신호 대기 중")
# 시장 레짐
regime = get_regime()
regime_line = (
f"{regime['emoji']} 시장: {regime['name'].upper()} "
f"(score {regime['score']:+.2f}%) "
f"| 조건 TREND≥{regime['trend_pct']}% / VOL≥{regime['vol_mult']}x\n"
)
# 1시간 이상 보유 포지션만 필터
long_positions = {
ticker: pos for ticker, pos in positions.items()
if (datetime.now() - pos["entry_time"]).total_seconds() >= 3600
}
cum_emoji = "💚" if cum_profit >= 0 else "🔴"
budget_info = (
f"💰 운용예산: {max_budget:,}원 | 포지션당: {per_position:,}\n"
f"{cum_emoji} 누적손익: {cum_sign}{cum_profit:,.0f}\n"
if max_budget else ""
)
# 포지션 없어도 레짐 정보는 전송
header = f"📊 <b>[{now} 현황]</b>\n{regime_line}{budget_info}"
if not long_positions:
_send(header + "1h+ 보유 포지션 없음")
return
lines = [f"📊 <b>[{now} 현황]</b>"]
for ticker, pos in positions.items():
lines = [header]
for ticker, pos in long_positions.items():
current = pyupbit.get_current_price(ticker)
if not current:
continue
@@ -73,9 +119,9 @@ def notify_status(positions: dict) -> None:
elapsed = (datetime.now() - pos["entry_time"]).total_seconds() / 3600
emoji = "📈" if pnl >= 0 else "📉"
lines.append(
f"\n{emoji} <b>{ticker}</b>\n"
f"{emoji} <b>{ticker}</b>\n"
f" 현재가: {current:,.0f}\n"
f" 수익률: {pnl:+.1f}%\n"
f" 수익률: {pnl:+.2f}%\n"
f" 최고가 대비: -{drop:.1f}%\n"
f" 보유: {elapsed:.1f}h"
)

View File

@@ -9,6 +9,7 @@ import pyupbit
import requests
from .market import get_top_tickers
from .market_regime import LEADERS
from .price_db import cleanup_old_prices, insert_prices, insert_prices_with_time
logger = logging.getLogger(__name__)
@@ -27,6 +28,10 @@ def backfill_prices(hours: int = 48) -> None:
if not tickers:
logger.warning("[백필] 종목 목록 없음, 스킵")
return
# 대장 코인 항상 포함
for leader in LEADERS:
if leader not in tickers:
tickers = tickers + [leader]
count = hours + 2 # 여유 있게 요청
total_rows = 0
@@ -59,6 +64,10 @@ def run_collector(interval: int = COLLECT_INTERVAL) -> None:
tickers = get_top_tickers()
if not tickers:
continue
# 대장 코인은 top20 밖이어도 항상 포함
for leader in LEADERS:
if leader not in tickers:
tickers = tickers + [leader]
resp = requests.get(
"https://api.upbit.com/v1/ticker",
params={"markets": ",".join(tickers)},

View File

@@ -206,6 +206,15 @@ def record_trade(
)
def get_cumulative_krw_profit() -> float:
"""전체 거래 누적 KRW 손익 반환 (수수료 차감 후). 데이터 없으면 0."""
with _conn() as conn:
cur = conn.cursor()
cur.execute("SELECT SUM(krw_profit) FROM trade_results WHERE krw_profit IS NOT NULL")
row = cur.fetchone()
return float(row[0]) if row and row[0] is not None else 0.0
def load_recent_wins(ticker: str, n: int = 5) -> list[bool]:
"""직전 N건 거래의 승/패 리스트 반환 (오래된 순). 없으면 빈 리스트."""
sql = """

View File

@@ -7,22 +7,23 @@ import os
import pyupbit
from .market import get_current_price, get_ohlcv
from .market_regime import get_regime
from .price_db import get_price_n_hours_ago
logger = logging.getLogger(__name__)
# 추세 판단: 현재 기준 N시간 전 DB 가격 대비 +M% 이상이면 상승 중
TREND_HOURS = float(os.getenv("TREND_HOURS", "12"))
TREND_MIN_GAIN_PCT = float(os.getenv("TREND_MIN_GAIN_PCT", "3"))
TREND_MIN_GAIN_PCT = float(os.getenv("TREND_MIN_GAIN_PCT", "5")) # 레짐이 없을 때 기본값
# 모멘텀: MA 기간, 거래량 급증 배수
MA_PERIOD = 20
VOLUME_MULTIPLIER = float(os.getenv("VOLUME_MULTIPLIER", "1.2")) # 로컬 5h 평균 대비
VOLUME_MULTIPLIER = float(os.getenv("VOLUME_MULTIPLIER", "2.0")) # 레짐이 없을 때 기본값
LOCAL_VOL_HOURS = 5 # 로컬 기준 시간 (h)
def check_trend(ticker: str) -> bool:
"""상승 추세 조건: 현재가가 DB에 저장된 N시간 전 가격 대비 +M% 이상."""
def check_trend(ticker: str, min_gain_pct: float) -> bool:
"""상승 추세 조건: 현재가가 DB에 저장된 N시간 전 가격 대비 +min_gain_pct% 이상."""
past_price = get_price_n_hours_ago(ticker, TREND_HOURS)
if past_price is None:
logger.debug(f"[추세] {ticker} {TREND_HOURS:.0f}h 전 가격 없음 (수집 중)")
@@ -33,22 +34,22 @@ def check_trend(ticker: str) -> bool:
return False
gain_pct = (current - past_price) / past_price * 100
result = gain_pct >= TREND_MIN_GAIN_PCT
result = gain_pct >= min_gain_pct
if result:
logger.info(
f"[추세↑] {ticker} {TREND_HOURS:.0f}h 전={past_price:,.2f} "
f"현재={current:,.2f} (+{gain_pct:.1f}%)"
f"현재={current:,.2f} (+{gain_pct:.1f}%{min_gain_pct}%)"
)
else:
logger.debug(
f"[추세✗] {ticker} {gain_pct:+.1f}% (기준={TREND_MIN_GAIN_PCT:+.0f}%)"
f"[추세✗] {ticker} {gain_pct:+.1f}% (기준={min_gain_pct:+.0f}%)"
)
return result
def check_momentum(ticker: str) -> bool:
"""모멘텀 조건: 현재가 > MA20(일봉) AND 최근 1h 거래량 > 로컬 5h 평균 × 1.2.
def check_momentum(ticker: str, vol_mult: float) -> bool:
"""모멘텀 조건: 현재가 > MA20(일봉) AND 최근 1h 거래량 > 로컬 5h 평균 × vol_mult.
23h 평균은 낮 시간대 고거래량이 포함돼 새벽에 항상 미달하므로,
로컬 5h 평균(같은 시간대 컨텍스트)과 비교한다.
@@ -79,24 +80,28 @@ def check_momentum(ticker: str) -> bool:
recent_vol = df_hour["volume"].iloc[-2] # 직전 완성된 1h 봉
local_avg = df_hour["volume"].iloc[-(LOCAL_VOL_HOURS + 1):-2].mean() # 이전 LOCAL_VOL_HOURS h 평균
vol_ok = local_avg > 0 and recent_vol >= local_avg * VOLUME_MULTIPLIER
vol_ok = local_avg > 0 and recent_vol >= local_avg * vol_mult
ratio = recent_vol / local_avg if local_avg > 0 else 0
if vol_ok:
logger.info(
f"[모멘텀↑] {ticker} 현재={current:,.0f} MA20={ma:,.0f} "
f"1h거래량={recent_vol:.0f} 로컬{LOCAL_VOL_HOURS}h평균={local_avg:.0f} ({ratio:.2f}x)"
f"1h거래량={recent_vol:.0f} 로컬{LOCAL_VOL_HOURS}h평균={local_avg:.0f} ({ratio:.2f}x{vol_mult}x)"
)
else:
logger.debug(
f"[모멘텀✗] {ticker} 1h거래량={recent_vol:.0f} 로컬{LOCAL_VOL_HOURS}h평균={local_avg:.0f} "
f"({ratio:.2f}x < {VOLUME_MULTIPLIER}x)"
f"({ratio:.2f}x < {vol_mult}x)"
)
return vol_ok
def should_buy(ticker: str) -> bool:
"""Strategy C: 실시간 상승 추세 AND 거래량 모멘텀 모두 충족 시 True."""
if not check_trend(ticker):
"""Strategy C + 시장 레짐: 레짐별 동적 임계값으로 추세 AND 모멘텀 판단."""
regime = get_regime()
trend_pct = regime["trend_pct"]
vol_mult = regime["vol_mult"]
if not check_trend(ticker, trend_pct):
return False
return check_momentum(ticker)
return check_momentum(ticker, vol_mult)

View File

@@ -17,15 +17,39 @@ from .price_db import (
delete_position, load_positions, upsert_position,
ensure_trade_results_table, record_trade, load_recent_wins,
ensure_sell_prices_table, upsert_sell_price, load_sell_prices,
get_cumulative_krw_profit,
)
load_dotenv()
logger = logging.getLogger(__name__)
MAX_BUDGET = int(os.getenv("MAX_BUDGET", "10000000")) # 총 운용 한도
MAX_POSITIONS = int(os.getenv("MAX_POSITIONS", "3")) # 최대 동시 보유 종목 수
PER_POSITION = MAX_BUDGET // MAX_POSITIONS # 종목당 투자금
INITIAL_BUDGET = int(os.getenv("MAX_BUDGET", "10000000")) # 초기 원금 (고정)
MAX_POSITIONS = int(os.getenv("MAX_POSITIONS", "3")) # 최대 동시 보유 종목 수
# 복리 적용 예산 (매도 후 재계산) — 수익 발생 시만 증가, 손실 시 원금 유지
MAX_BUDGET = INITIAL_BUDGET
PER_POSITION = INITIAL_BUDGET // MAX_POSITIONS
def _recalc_compound_budget() -> None:
"""누적 수익을 반영해 MAX_BUDGET / PER_POSITION 재계산.
수익이 발생한 만큼만 예산에 더함 (손실 시 원금 아래로 내려가지 않음).
매도 완료 후 호출.
"""
global MAX_BUDGET, PER_POSITION
try:
cum_profit = get_cumulative_krw_profit()
effective = INITIAL_BUDGET + max(int(cum_profit), 0)
MAX_BUDGET = effective
PER_POSITION = effective // MAX_POSITIONS
logger.info(
f"[복리] 누적수익={cum_profit:+,.0f}원 | "
f"운용예산={MAX_BUDGET:,}원 | 포지션당={PER_POSITION:,}"
)
except Exception as e:
logger.warning(f"[복리] 예산 재계산 실패 (이전 값 유지): {e}")
# Walk-forward 필터 설정
WF_WINDOW = int(float(os.getenv("WF_WINDOW", "5"))) # 이력 윈도우 크기
@@ -103,6 +127,15 @@ def get_positions() -> dict:
return _positions
def get_budget_info() -> dict:
"""현재 복리 예산 정보 반환 (main.py 등 외부에서 동적 조회용)."""
return {
"max_budget": MAX_BUDGET,
"per_position": PER_POSITION,
"initial": INITIAL_BUDGET,
}
def restore_positions() -> None:
"""시작 시 Oracle DB + Upbit 잔고를 교차 확인하여 포지션 복원.
trade_results 테이블도 이 시점에 생성 (없으면).
@@ -115,6 +148,9 @@ def restore_positions() -> None:
except Exception as e:
logger.warning(f"trade_results 테이블 생성 실패 (무시): {e}")
# 시작 시 복리 예산 복원 (이전 세션 수익 반영)
_recalc_compound_budget()
try:
ensure_sell_prices_table()
except Exception as e:
@@ -278,7 +314,8 @@ def buy(ticker: str) -> bool:
f"[매수] {ticker} @ {actual_price:,.0f}원 (실체결가) | "
f"수량={amount} | 투자금={order_krw:,}원 | trade_id={trade_id[:8]}"
)
notify_buy(ticker, actual_price, amount, order_krw)
notify_buy(ticker, actual_price, amount, order_krw,
max_budget=MAX_BUDGET, per_position=PER_POSITION)
return True
except Exception as e:
logger.error(f"매수 예외 {ticker}: {e}")
@@ -387,7 +424,12 @@ def sell(ticker: str, reason: str = "") -> bool:
f"[매도] {ticker} @ {actual_sell_price:,.4f}원 | "
f"수익률={pnl:+.1f}% | 순익={krw_profit:+,.0f}원 (수수료 {fee:,.0f}원) | 사유={reason}"
)
notify_sell(ticker, actual_sell_price, pnl, reason)
try:
cum = get_cumulative_krw_profit() + krw_profit
except Exception:
cum = 0.0
notify_sell(ticker, actual_sell_price, pnl, reason,
krw_profit=krw_profit, fee_krw=fee, cum_profit=cum)
_last_sell_prices[ticker] = actual_sell_price
try:
upsert_sell_price(ticker, actual_sell_price)
@@ -406,6 +448,8 @@ def sell(ticker: str, reason: str = "") -> bool:
delete_position(ticker)
except Exception as e:
logger.error(f"포지션 DB 삭제 실패 {ticker}: {e}")
# 복리 예산 재계산: 수익 발생분만 다음 투자에 반영
_recalc_compound_budget()
return True
except Exception as e:
logger.error(f"매도 예외 {ticker}: {e}")