Spaces:
Runtime error
Runtime error
Download app.py from sk20000/dynamichedge: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/spaces/sk20000/dynamichedge/resolve/main/app.py
- Command line
-
hf download hf://spaces/sk20000/dynamichedge/app.py
-
curl -L -o app.py https://huggingface.co/spaces/sk20000/dynamichedge/resolve/main/app.py
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 | |
| # ============================================================================= | |
| # [๋ฐ์ดํฐ ๋ก๋ ์์ง] | |
| # ============================================================================= | |
| 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๊ฐ ๋์ ๋(๋ถ์ ํ๋)๋ ์ ๋น์ค์ ๋๋ ค ์ต์ ๋ฐ ๋ฐฉ์ดํ๊ณ , ๋ฎ์ ๋(ํธ๋ฅธ ํ๋)๋ ์ ๋น์ค์ ์ค์ฌ ๋กฑ ๋ ธ์ถ์ ๊ทน๋ํํฉ๋๋ค.") |