import streamlit as st import yfinance as yf import FinanceDataReader as fdr import pandas as pd import numpy as np import matplotlib.pyplot as plt from datetime import datetime, timedelta import platform import warnings warnings.filterwarnings('ignore') # ============================================================================= # [환경 설정: 한글 폰트 및 마이너스 기호 처리] # ============================================================================= system_os = platform.system() if system_os == 'Darwin': plt.rc('font', family='AppleGothic') elif system_os == 'Windows': plt.rc('font', family='Malgun Gothic') else: plt.rc('font', family='NanumGothic') plt.rcParams['axes.unicode_minus'] = False st.set_page_config(page_title="Z-Score Spread Backtester", page_icon="🌊", layout="wide") # ============================================================================= # [🌟 핵심 엔진: Z-스코어 스프레드 헷지 비율 산출] # ============================================================================= def get_zscore_hedge_ratio(prices_Y, prices_X, window=20, base_ratio=1.0, min_ratio=0.5, max_ratio=1.5): """ 종목 Y와 X의 스프레드(격차)의 Z-Score(표준화 편차)를 구해 헷지 비율을 동적으로 변속합니다. - Z-Score > 0 (오버슈팅): 롱 수익 실현 & 숏 방어막 강화 (최대 max_ratio) - Z-Score < 0 (언더슈팅): 방어막 해제 & 롱 비중 극대화 (최소 min_ratio) """ # 1. 정규화된 스프레드 계산 (Y가 X대비 얼마나 잘나가는가?) spread = (prices_Y / prices_Y.iloc[0]) / (prices_X / prices_X.iloc[0]) # 2. 이동평균 및 표준편차 (볼린저 밴드 원리) rolling_mean = spread.rolling(window=window).mean() rolling_std = spread.rolling(window=window).std() # 3. Z-Score 산출 (평균에서 얼마나 벗어났는가?) z_score = (spread - rolling_mean) / rolling_std # 4. Z-Score를 헷지 비율로 매핑 (-2.0 ~ +2.0 구간을 min ~ max 비율로 선형 변환) # Z가 +2.0일 때 max_ratio, Z가 -2.0일 때 min_ratio 가 되도록 설정 scaled_ratios = np.where( z_score > 0, base_ratio + (z_score / 2.0) * (max_ratio - base_ratio), base_ratio + (z_score / 2.0) * (base_ratio - min_ratio) ) # 설정한 Min/Max 값을 벗어나지 않도록 강제 제한(Clip) ratios = pd.Series(scaled_ratios, index=prices_Y.index).clip(min_ratio, max_ratio) return ratios.ffill(), z_score.ffill(), spread # ============================================================================= # [데이터 로드 엔진] # ============================================================================= @st.cache_data(ttl=3600) def load_data(t1, t2, start, end): def fetch_single_ticker(ticker): try: data = yf.download(ticker, start=start, end=end)['Close'] if isinstance(data, pd.DataFrame): data = data.iloc[:, 0] if data is not None and not data.empty: return data.rename(ticker) except: pass try: data = fdr.DataReader(ticker, start, end)['Close'] if isinstance(data, pd.DataFrame): data = data.iloc[:, 0] if data is not None and not data.empty: return data.rename(ticker) except: pass return None s1 = fetch_single_ticker(t1) s2 = fetch_single_ticker(t2) if s1 is None or s2 is None: return None return pd.concat([s1, s2], axis=1).ffill().dropna() # ============================================================================= # [UI 및 메인 로직] # ============================================================================= st.title("🌊 Z-스코어 알파 스프레드 헌터") st.markdown("방향성(A > B)이 확실할 때, 스프레드의 **'평균 회귀(Mean Reversion)'** 성질을 이용해 파도를 타며 수익을 극대화합니다.") with st.sidebar: st.header("🔍 설정") ticker_long = st.text_input("🟢 매수(Long) 티커", value="NVDA") ticker_short = st.text_input("🔴 매도(Short) 티커", value="^IXIC") st.markdown("---") st.markdown("**⏱️ 기간 설정**") learning_months = st.slider("1. 엔진 학습 기간 (개월)", 1, 24, 6, help="이동평균선을 계산하기 위한 초기 웜업 기간") backtest_weeks = st.slider("2. 실전 백테스트 기간 (주)", 4, 260, 156, help="본격적인 시뮬레이션 기간") st.markdown("---") st.markdown("**⚙️ Z-스코어 기어 설정**") z_window = st.slider("추세 판단 기간 (일)", 10, 60, 20, help="며칠 동안의 평균을 기준으로 과열/침체를 판단할지 결정합니다.") base_r = st.number_input("기준 헷지 비율 (Base)", value=1.0, step=0.1) min_r = st.number_input("최소 헷지 (저평가 시 롱 극대화)", value=0.5, step=0.1) max_r = st.number_input("최대 헷지 (고평가 시 이익 보전)", value=1.5, step=0.1) if st.button("🚀 스프레드 백테스트 실행", type="primary", use_container_width=True): if ticker_long == ticker_short: st.error("매수 종목과 매도 종목이 같을 수 없습니다!") else: with st.spinner("파동을 계산하고 Z-스코어 헷징을 시뮬레이션 중입니다..."): end_date = datetime.today() backtest_start_date = end_date - pd.DateOffset(weeks=backtest_weeks) learning_start_date = backtest_start_date - pd.DateOffset(months=learning_months) df = load_data(ticker_long, ticker_short, learning_start_date, end_date) if df is None or df.empty or len(df) < 10: st.error("데이터 로드 실패.") else: st.success(f"✅ 데이터 로드 완료: 총 {len(df):,} 영업일") prices_Y = df[ticker_long] prices_X = df[ticker_short] # 1. Z-스코어 동적 헷지 비율 계산 dynamic_ratio, z_scores, spread = get_zscore_hedge_ratio( prices_Y, prices_X, window=z_window, base_ratio=base_r, min_ratio=min_r, max_ratio=max_r ) # 2. 일간 리밸런싱 백테스트 (전체 기간) returns = df.pct_change().dropna() adj_ratio = dynamic_ratio.shift(1).loc[returns.index] # 매일 아침 전일 헷지 비율에 맞춰 '손바꿈' 발생 strategy_returns = returns[ticker_long] - (adj_ratio * returns[ticker_short]) # 3. '백테스트 기간'만 분리하여 평가 bt_mask = strategy_returns.index >= backtest_start_date bt_strat_returns = strategy_returns[bt_mask] bt_long_returns = returns[ticker_long][bt_mask] bt_ratio = dynamic_ratio[dynamic_ratio.index >= backtest_start_date] bt_z_scores = z_scores[z_scores.index >= backtest_start_date] bt_spread = spread[spread.index >= backtest_start_date] # 자산 1.0 초기화 누적 수익률 cum_strat = (1 + bt_strat_returns).cumprod() cum_long = (1 + bt_long_returns).cumprod() tot_strat = (cum_strat.iloc[-1] - 1) * 100 tot_long = (cum_long.iloc[-1] - 1) * 100 mdd_strat = (cum_strat / cum_strat.cummax() - 1).min() * 100 mdd_long = (cum_long / cum_long.cummax() - 1).min() * 100 st.divider() st.subheader(f"🎯 Z-스코어 다이나믹 헷징 성과 ({backtest_weeks}주)") col1, col2, col3, col4 = st.columns(4) col1.metric("Z-스코어 헷징 수익률", f"{tot_strat:.2f}%") col2.metric("롱-온리 수익률", f"{tot_long:.2f}%") col3.metric("전략 MDD (최대 낙폭)", f"{mdd_strat:.2f}%", delta_color="inverse") col4.metric("현재 Z-Score (과열/침체)", f"{bt_z_scores.iloc[-1]:.2f}", delta_color="off") st.divider() tab1, tab2 = st.tabs(["📈 수익률 시각화", "🌊 엔진 작동 원리 (Z-Score & 비율)"]) with tab1: fig1, ax1 = plt.subplots(figsize=(12, 5)) ax1.plot(cum_strat.index, cum_strat, label="Z-Score Dynamic Hedging", color='dodgerblue', linewidth=2.5) ax1.plot(cum_long.index, cum_long, label=f"Long Only ({ticker_long})", color='gray', alpha=0.5) ax1.axhline(1.0, color='black', linestyle='--', alpha=0.3) ax1.set_title("실전 백테스트 누적 수익률 비교", fontsize=14) ax1.legend() ax1.grid(True, linestyle=':', alpha=0.6) st.pyplot(fig1) with tab2: fig2, (ax2, ax3) = plt.subplots(2, 1, figsize=(12, 8), sharex=True, gridspec_kw={'height_ratios': [1.5, 1]}) # 위쪽 차트: Z-Score 파동 ax2.plot(bt_z_scores.index, bt_z_scores, color='darkorange', linewidth=1.5, label='Z-Score (Overbought/Oversold)') ax2.axhline(2.0, color='red', linestyle='--', alpha=0.5, label='+2.0 (Take Profit Zone)') ax2.axhline(-2.0, color='green', linestyle='--', alpha=0.5, label='-2.0 (Buy the Dip Zone)') ax2.axhline(0, color='black', linewidth=1) ax2.fill_between(bt_z_scores.index, 0, bt_z_scores, where=(bt_z_scores > 0), color='red', alpha=0.2) ax2.fill_between(bt_z_scores.index, 0, bt_z_scores, where=(bt_z_scores < 0), color='green', alpha=0.2) ax2.set_ylabel("Z-Score") ax2.set_title(f"{ticker_long} vs {ticker_short} 상대적 스프레드 파동", fontsize=14) ax2.legend(loc='upper left') ax2.grid(True, linestyle=':', alpha=0.6) # 아래쪽 차트: 다이나믹 헷지 비율 ax3.plot(bt_ratio.index, bt_ratio, color='purple', linewidth=2, label='Dynamic Hedge Ratio') ax3.axhline(base_r, color='black', linestyle='--', alpha=0.5, label='Base (1.0)') ax3.set_ylabel("Hedge Ratio") ax3.set_ylim(min_r - 0.2, max_r + 0.2) ax3.legend(loc='upper left') ax3.grid(True, linestyle=':', alpha=0.6) st.pyplot(fig2) st.caption("※ Z-Score가 높을 때(붉은 파도)는 숏 비중을 늘려 익절 및 방어하고, 낮을 때(푸른 파도)는 숏 비중을 줄여 롱 노출을 극대화합니다.")