[Backtest] 자산배분 - GoldenButterfly


영구 포트폴리오는 주식, 국채, 금, 현금을 각각 25%씩 투자하는 전략입니다. 이 비율을 변형하여 전략의 안정성을 크게 떨어뜨리지 않으면서 수익성을 개선하는 전략이 있습니다. 미국 기준으로 주식 20%, 소형 가치주 20%, 장기 국채 20%, 금 20%, 현금(단기 국채) 20% 비율로 투자하는 Goldenbutterfly (황금나비) 전략입니다.

import pandas as pd
import pandas_datareader.data as web
import datetime
import backtrader as bt
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
import pyfolio as pf
import quantstats
import math
plt.rcParams["figure.figsize"] = (10, 6) # (w, h)

금 ETF인 GLD가 2004-11-18 데이터부터 있으므로, 그 시점부터 시작합니다.

# VTI (미국 주식), VBR (미국 소형 가치주), TLT (미국 장기 국채), GLD (금), SHY (단기 국채)

start = '2004-11-18'
end = '2021-04-23'

vti = web.DataReader('VTI', 'yahoo', start, end)['Adj Close'].to_frame("vti_Close")
vbr = web.DataReader('VBR', 'yahoo', start, end)['Adj Close'].to_frame("vbr_Close")
tlt = web.DataReader('VUSTX', 'yahoo', start, end)['Adj Close'].to_frame("tlt_Close")
gld = web.DataReader('GLD', 'yahoo', start, end)['Adj Close'].to_frame("gld_Close")
shy = web.DataReader('SHY', 'yahoo', start, end)['Adj Close'].to_frame("shy_Close")
gld.head()
gld_Close
Date
2004-11-1844.380001
2004-11-1944.779999
2004-11-2244.950001
2004-11-2344.750000
2004-11-2445.049999

일단 모델 포트폴리오로, 매일 20% 비중을 맞추는 것으로 생각하고 만듭니다. 거래비용은 생략합니다.

vti_return = vti.pct_change(periods=1)
vbr_return = vbr.pct_change(periods=1)
tlt_return = tlt.pct_change(periods=1)
gld_return = gld.pct_change(periods=1)
shy_return = shy.pct_change(periods=1)

df_return = pd.concat([vti_return, vbr_return, tlt_return, gld_return, shy_return], axis=1)

df_return.head()
vti_Closevbr_Closetlt_Closegld_Closeshy_Close
Date
2004-11-17NaNNaNNaNNaNNaN
2004-11-180.001563-0.0008840.003448NaN-0.000122
2004-11-19-0.012137-0.012212-0.0068730.009013-0.001590
2004-11-220.0065820.0121840.0043250.0037960.000244
2004-11-230.0003490.003363-0.000861-0.004449-0.000122
df_return['GB_return'] = (df_return['vti_Close']+df_return['vbr_Close']+df_return['tlt_Close']+df_return['gld_Close']+df_return['shy_Close'])/5
df_return.head()
vti_Closevbr_Closetlt_Closegld_Closeshy_CloseGB_return
Date
2004-11-17NaNNaNNaNNaNNaNNaN
2004-11-180.001563-0.0008840.003448NaN-0.000122NaN
2004-11-19-0.012137-0.012212-0.0068730.009013-0.001590-0.004760
2004-11-220.0065820.0121840.0043250.0037960.0002440.005426
2004-11-230.0003490.003363-0.000861-0.004449-0.000122-0.000344
quantstats.reports.plots(df_return['GB_return'], mode='basic')

output_8_0

output_8_1

매일 리밸런싱을 한 결과 연 복리 수익률 7.88%, 샤프 비율 0.89, MDD -22.37% 정도입니다. 연 변동성 9.0%로 적당한 수익에 괜찮은 방어력을 보여주고 있습니다. 영구 포트폴리오보다는 샤프 비율이 낮아도 이 정도면 충분히 괜찮은 전략입니다.

quantstats.reports.metrics(df_return['GB_return'], mode='full')
                           Strategy
-------------------------  ----------
Start Period               2004-11-17
End Period                 2021-04-23
Risk-Free Rate             0.0%
Time in Market             100.0%

Cumulative Return          247.86%
CAGR%                      7.88%
Sharpe                     0.89
Sortino                    1.26
Max Drawdown               -22.37%
Longest DD Days            482
Volatility (ann.)          9.0%
Calmar                     0.35
Skew                       -0.4
Kurtosis                   10.9

Expected Daily %           0.03%
Expected Monthly %         0.63%
Expected Yearly %          7.17%
Kelly Criterion            8.37%
Risk of Ruin               0.0%
Daily Value-at-Risk        -0.9%
Expected Shortfall (cVaR)  -0.9%

Payoff Ratio               0.96
Profit Factor              1.18
Common Sense Ratio         1.15
CPC Index                  0.62
Tail Ratio                 0.98
Outlier Win Ratio          3.76
Outlier Loss Ratio         3.86

MTD                        3.19%
3M                         1.0%
6M                         6.95%
YTD                        2.14%
1Y                         20.64%
3Y (ann.)                  10.56%
5Y (ann.)                  8.85%
10Y (ann.)                 7.21%
All-time (ann.)            7.88%

Best Day                   4.71%
Worst Day                  -5.32%
Best Month                 7.34%
Worst Month                -11.21%
Best Year                  17.95%
Worst Year                 -7.06%

Avg. Drawdown              -1.16%
Avg. Drawdown Days         21
Recovery Factor            11.08
Ulcer Index                inf

Avg. Up Month              1.87%
Avg. Down Month            -1.47%
Win Days %                 55.13%
Win Month %                63.64%
Win Quarter %              76.12%
Win Year %                 83.33%

위에서 한 것처럼 그냥 만들어도 되지만, 백테스트에 많이 쓰이는 Backtrader 패키지를 한번 사용해 보겠습니다. Input 형식을 맞추어야 합니다.

vti = vti.rename({'vti_Close':'Close'}, axis='columns')
vbr = vbr.rename({'vbr_Close':'Close'}, axis='columns')
tlt = tlt.rename({'tlt_Close':'Close'}, axis='columns')
gld = gld.rename({'gld_Close':'Close'}, axis='columns')
shy = shy.rename({'shy_Close':'Close'}, axis='columns')

for column in ['Open', 'High', "Low"]:
    vti[column] = vti["Close"]
    vbr[column] = vbr["Close"]
    tlt[column] = tlt["Close"]
    gld[column] = gld["Close"]
    shy[column] = shy["Close"]
gld.head()
CloseOpenHighLow
Date
2004-11-1844.38000144.38000144.38000144.380001
2004-11-1944.77999944.77999944.77999944.779999
2004-11-2244.95000144.95000144.95000144.950001
2004-11-2344.75000044.75000044.75000044.750000
2004-11-2445.04999945.04999945.04999945.049999

20% 비중을 맞추어 매수하고 20 거래일마다 리밸런싱하는 전략입니다. 20 거래일은 현실 기준으로 약 1개월입니다.

class AssetAllocation_GB(bt.Strategy):
    params = (
        ('assetclass',0.20),
    )
    def __init__(self):
        self.VTI = self.datas[0]
        self.VBR = self.datas[1]
        self.TLT = self.datas[2]
        self.GLD = self.datas[3]
        self.SHY = self.datas[4]
        self.counter = 0
        
    def next(self):
        if  self.counter % 20 == 0:
            self.order_target_percent(self.VTI, target=self.params.assetclass)
            self.order_target_percent(self.VBR, target=self.params.assetclass)
            self.order_target_percent(self.TLT, target=self.params.assetclass)
            self.order_target_percent(self.GLD, target=self.params.assetclass)
            self.order_target_percent(self.SHY, target=self.params.assetclass)
        self.counter += 1
cerebro = bt.Cerebro()

cerebro.broker.setcash(1000000)

VTI = bt.feeds.PandasData(dataname = vti)
VBR = bt.feeds.PandasData(dataname = vbr)
TLT = bt.feeds.PandasData(dataname = tlt)
GLD = bt.feeds.PandasData(dataname = gld)
SHY = bt.feeds.PandasData(dataname = shy)

cerebro.adddata(VTI)
cerebro.adddata(VBR)
cerebro.adddata(TLT)
cerebro.adddata(GLD)
cerebro.adddata(SHY)

cerebro.addstrategy(AssetAllocation_GB)

cerebro.addanalyzer(bt.analyzers.PyFolio, _name = 'PyFolio')

results = cerebro.run()
strat = results[0]

portfolio_stats = strat.analyzers.getbyname('PyFolio')
returns, positions, transactions, gross_lev = portfolio_stats.get_pf_items()
returns.index = returns.index.tz_convert(None)

#quantstats.reports.html(returns, output = 'Report_AssetAllocation_GoldenButterfly.html', title='AssetAllocation_GoldenButterfly')
quantstats.reports.plots(returns, mode='basic')

output_17_0

output_17_1

20 거래일마다 리밸런싱으로 바꾸니 연 복리 수익률 7.5%, 샤프 비율 0.92, MDD -20% 수준입니다. 연 변동성 8.21%로 매일 리밸런싱보다 조금 더 안정적으로 변했습니다.

quantstats.reports.metrics(returns, mode='full')
                           Strategy
-------------------------  ----------
Start Period               2004-11-17
End Period                 2021-04-23
Risk-Free Rate             0.0%
Time in Market             100.0%

Cumulative Return          228.43%
CAGR%                      7.5%
Sharpe                     0.92
Sortino                    1.31
Max Drawdown               -20.4%
Longest DD Days            483
Volatility (ann.)          8.21%
Calmar                     0.37
Skew                       -0.48
Kurtosis                   7.16

Expected Daily %           0.03%
Expected Monthly %         0.6%
Expected Yearly %          6.83%
Kelly Criterion            8.39%
Risk of Ruin               0.0%
Daily Value-at-Risk        -0.82%
Expected Shortfall (cVaR)  -0.82%

Payoff Ratio               0.96
Profit Factor              1.18
Common Sense Ratio         1.14
CPC Index                  0.62
Tail Ratio                 0.97
Outlier Win Ratio          3.67
Outlier Loss Ratio         3.86

MTD                        3.17%
3M                         1.04%
6M                         7.13%
YTD                        2.25%
1Y                         18.62%
3Y (ann.)                  9.85%
5Y (ann.)                  8.37%
10Y (ann.)                 6.82%
All-time (ann.)            7.5%

Best Day                   3.61%
Worst Day                  -4.67%
Best Month                 6.22%
Worst Month                -11.1%
Best Year                  17.13%
Worst Year                 -7.6%

Avg. Drawdown              -1.17%
Avg. Drawdown Days         22
Recovery Factor            11.2
Ulcer Index                1.01

Avg. Up Month              1.81%
Avg. Down Month            -1.41%
Win Days %                 55.24%
Win Month %                63.13%
Win Quarter %              73.13%
Win Year %                 83.33%

월간 데이터를 사용하면 훨씬 더 과거의 결과도 테스트해 볼 수 있습니다. 가장 긴 시계열의 경우 1900년 1월부터 2020년 12월까지의 데이터가 있습니다.

MonthlyReturn = pd.read_excel('MonthlyAssetClassReturn.xlsx')
MonthlyReturn.head()
Data IndexBroker Call RateCPIT-BillsS&P 500 Total returnSmall Cap StocksMSCI EAFEEEMUS 10 YRUS Corp Bond Return Index...International Small Cap Value (Global B/M Small Low)International Large Cap Value (Global B/M Big Low)International Small High Mom (Global mom Small High)International Large High Mom (Global mom Small High)Merrill High YieldWorld StocksWorld ex USABuyWritePutWriteBitcoin
01900-01-31NaN0.0133330.00250.016413NaNNaNNaN0.000000NaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
11900-02-28NaN0.0000000.00250.021138NaNNaNNaN0.011278NaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
21900-03-31NaN0.0000000.00250.011084NaNNaNNaN0.009758NaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
31900-04-30NaN0.0000000.00250.015894NaNNaNNaN-0.016107NaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
41900-05-31NaN0.0000000.0025-0.044246NaNNaNNaN0.016023NaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN

5 rows × 50 columns

시계열로 바꾸어 주는 것이 사용하기 편합니다. 1열인 Data Index가 월말 날짜이므로, 이 열을 인덱스로 잡습니다.

MonthlyReturn = MonthlyReturn.set_index('Data Index')
MonthlyReturn.head()
Broker Call RateCPIT-BillsS&P 500 Total returnSmall Cap StocksMSCI EAFEEEMUS 10 YRUS Corp Bond Return IndexGSCI...International Small Cap Value (Global B/M Small Low)International Large Cap Value (Global B/M Big Low)International Small High Mom (Global mom Small High)International Large High Mom (Global mom Small High)Merrill High YieldWorld StocksWorld ex USABuyWritePutWriteBitcoin
Data Index
1900-01-31NaN0.0133330.00250.016413NaNNaNNaN0.000000NaNNaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
1900-02-28NaN0.0000000.00250.021138NaNNaNNaN0.011278NaNNaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
1900-03-31NaN0.0000000.00250.011084NaNNaNNaN0.009758NaNNaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
1900-04-30NaN0.0000000.00250.015894NaNNaNNaN-0.016107NaNNaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN
1900-05-31NaN0.0000000.0025-0.044246NaNNaNNaN0.016023NaNNaN...NaNNaNNaNNaNNaNNaNNaNNaNNaNNaN

5 rows × 49 columns

필요한 것만 뽑아옵니다. 월간 미국 주식(S&P 500), 월간 미국 소형 가치주, 월간 미국 30년 만기 국채, 미국 단기 국채(T-Bill, 현금 대용), 금 수익률 데이터입니다. 1926년 7월부터 2020년 12월까지 94.5년 기간의 테스트가 될 것입니다.

Monthly_GB = MonthlyReturn.loc[:, ['S&P 500 Total return','Small Value','US 30 YR','GOLD','T-Bills']]
Monthly_GB = Monthly_GB.loc[Monthly_GB.index >= '1926-07-31']
Monthly_GB['Monthly_GB'] = (Monthly_GB['S&P 500 Total return']+Monthly_GB['Small Value']+Monthly_GB['US 30 YR']+Monthly_GB['GOLD']+Monthly_GB['T-Bills'])/5

월간 데이터이므로, 일간 데이터 기준인 패키지가 주는 값을 적절히 조정해야 합니다. 1년 12개월 252거래일을 가정합니다. 1926년 7월부터 94.5년 동안 샤프 비율은 0.896으로 나옵니다. 상관관계가 매우 낮은 자산만 모아 놓아서 어느 시대이든 안정적으로 나오는 것을 볼 수 있습니다. 아래 그림의 제목 하단에 있는 샤프 비율은 무시하고, 직접 계산한 값을 보아야 합니다.

quantstats.stats.sharpe(Monthly_GB['Monthly_GB'])/math.sqrt(252/12)
0.8964498650203416
quantstats.reports.plots(Monthly_GB['Monthly_GB'], mode='basic')

output_30_0

output_30_1

** 주의: quantstats 라이브러리가 월간 데이터일 경우는 일부 지표를 이상한 값으로 돌려줍니다. 연간 기준으로 보정해서 생각해야 합니다.

연 복리 수익률 8.65%, 샤프 비율은 위에서 계산한대로 0.896 (아래 결과는 무시합니다 월간 데이터라 다르게 나옵니다), MDD는 대공황 시기를 넣고도 -49% 수준입니다. 방어력도 괜찮고 더 과거로 가니 수익률이 좋아졌습니다. 소형 가치주 성과가 과거에 더 좋았던 것 때문으로 보입니다. 94.5년을 버티면 원금이 2538배가 됩니다.

quantstats.reports.metrics(Monthly_GB['Monthly_GB'], mode='full')
                           Strategy
-------------------------  -----------
Start Period               1926-07-31
End Period                 2020-12-31
Risk-Free Rate             0.0%
Time in Market             100.0%

Cumulative Return          253,758.92%
CAGR%                      8.65%
Sharpe                     4.11
Sortino                    7.35
Max Drawdown               -49.25%
Longest DD Days            2132
Volatility (ann.)          44.96%
Calmar                     0.18
Skew                       1.11
Kurtosis                   12.74

Expected Daily %           0.69%
Expected Monthly %         0.69%
Expected Yearly %          8.6%
Kelly Criterion            34.37%
Risk of Ruin               0.0%
Daily Value-at-Risk        -3.93%
Expected Shortfall (cVaR)  -3.93%

Payoff Ratio               1.16
Profit Factor              2.13
Common Sense Ratio         2.81
CPC Index                  1.6
Tail Ratio                 1.32
Outlier Win Ratio          3.56
Outlier Loss Ratio         3.89

MTD                        3.54%
3M                         6.04%
6M                         12.52%
YTD                        15.39%
1Y                         15.39%
3Y (ann.)                  9.67%
5Y (ann.)                  9.77%
10Y (ann.)                 7.95%
All-time (ann.)            8.65%

Best Day                   24.92%
Worst Day                  -12.89%
Best Month                 24.92%
Worst Month                -12.89%
Best Year                  52.03%
Worst Year                 -21.57%

Avg. Drawdown              -3.15%
Avg. Drawdown Days         129
Recovery Factor            5152.68
Ulcer Index                0.99

Avg. Up Month              2.13%
Avg. Down Month            -1.84%
Win Days %                 64.73%
Win Month %                64.73%
Win Quarter %              72.49%
Win Year %                 81.05%





© 2021.03. by JacobJinwonLee

Powered by theorydb