dynamichedge / app.py
sk20000's picture
Update app.py
78768e8 verified
Raw History Blame Contribute Delete
11.1 kB
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๊ฐ€ ๋†’์„ ๋•Œ(๋ถ‰์€ ํŒŒ๋„)๋Š” ์ˆ ๋น„์ค‘์„ ๋Š˜๋ ค ์ต์ ˆ ๋ฐ ๋ฐฉ์–ดํ•˜๊ณ , ๋‚ฎ์„ ๋•Œ(ํ‘ธ๋ฅธ ํŒŒ๋„)๋Š” ์ˆ ๋น„์ค‘์„ ์ค„์—ฌ ๋กฑ ๋…ธ์ถœ์„ ๊ทน๋Œ€ํ™”ํ•ฉ๋‹ˆ๋‹ค.")