본문 바로가기
가상화폐 퀀트 전략

트레이딩 전략 9 : 다자 가상화폐 + 상승장 + 변동성 돌파

by TenMillionQuant 2022. 4. 11.

가상화폐 투자마법 공식 발췌 (전체코드는 아래 파일에 있습니다)

 

 

 

전편에서는 변동성돌파에 대해 알아보고 백테스팅을 진행해보았다. 이 변동성 알파에 좀 더 알파를 추가하기 위해 상승장에만 투자하는 전략을 추가해보자. 

 

 

 

트레이딩 전략 8 : 다자 가상화폐 + 변동성 돌파

가상화폐 투자마법 공식 발췌 (전체코드는 아래 파일에 있습니다) 이 책에서 가장 유명한 전략, 변동성 돌파 전략이다. 간단하게 소개하자면, 이 전략은 위 사진의 주인공이신 래리 윌리엄스

tenmillionquant.tistory.com

 

참고로 상승장에만 투자하여 나온 백테스팅 결과는 아래에 있다. 

 

 

 

# 트레이딩 전략 5 : 슈퍼상승장 + 변동성 조절

가상화폐 투자마법 공식 발췌 (전체코드는 아래 파일에 있습니다) 투자전략 : 슈퍼상승장(3,5,10,20일 이평) + 변동성 조절 투자전략 4(이동평균 + 현금비중 80% 이상) 전략에서 5일이동평균 뿐만

tenmillionquant.tistory.com

 

 

투자대상 : 비트코인(BTC), 라이트코인(LTC), 리플(XRP), 대시(DASH) 

투자기간 : 2017.06 ~ 2022.03

거래비용 : 0.2% 적용

투자전략

1. 각 화폐의 레인지 계산(전일 고가 - 전일 저가)

 

2. 각 화폐의 가격이 5일 이동평균보다 높은지 여부 파악 => 낮을 경우 그날 투자 대상에서 제외 (추가)

 

3. 매수 : 실시간 가격 > 당일 시가 + (레인지 x k) (여기서 K = 0.5 추천)

 

4. 돌파에 성공한 가상화폐에 자산의 N분의 1 투입 (만약 이 전략에 5개 가상화폐를 투입한다면 자산의 5분의 1 투입한다)

 

5.  매도  : 다음날 시가

 

이제 위 전략을 구현해보자. 

 

#필요한 데이터를 불러온다

import pybithumb
import pandas as pd
import numpy as np

# 비트코인, 라이트코인, 이더리움클래식, 리플을 가져오자
btc_df = pybithumb.get_ohlcv('BTC')
ltc_df = pybithumb.get_ohlcv('LTC')
etc_df = pybithumb.get_ohlcv('ETC')
xrp_df = pybithumb.get_ohlcv('XRP')

# 각 코인들의 5일이평선을 구해보자
btc_df['ma_5'] = btc_df['close'].rolling(window=5).mean()
ltc_df['ma_5'] = ltc_df['close'].rolling(window=5).mean()
etc_df['ma_5'] = etc_df['close'].rolling(window=5).mean()
xrp_df['ma_5'] = xrp_df['close'].rolling(window=5).mean()

# 데이터가 없는 값들은 다 삭제한다

btc_df.dropna(inplace =  True)
ltc_df.dropna(inplace =  True)
etc_df.dropna(inplace =  True)
xrp_df.dropna(inplace =  True)

 

BTC, LTC ETC, XRP중에서 시작일이 가장 최근인 가상화폐를 가지고 진행해보자.

 

start_date_list = [] # 데이터시작일 저장 리스트
end_date_list = [] # 마지막일 저장 리스트

for ticker in tickers_list:
    df = pybithumb.get_ohlcv(ticker)
    
    start_date_list.append(str(df.index[0]))
    end_date_list.append(str(df.index[-1]))
    
    print(ticker, start_date_list[-1], end_date_list[-1])
    
    # 리플 데이터가 가장 적으므로, 시작일을 리플로 기준을 잡자
ticker_df = pd.DataFrame({"tickers_list" : tickers_list, "start_date" : start_date_list, "end_date" : end_date_list})
ticker_df

 

 

 

가장 최근인 코인은 리플(XRP)이므로, 리플로 진행하자. 

 

# 시작일은 리플 시작일로 설정하고, 다른 코인도 다 그날에 시작하게 바꾸자
start_date = xrp_df.index[0]

btc_df = btc_df[btc_df.index >= start_date]
ltc_df = ltc_df[ltc_df.index >= start_date]
etc_df = eth_df[eth_df.index >= start_date]
xrp_df = xrp_df[xrp_df.index >= start_date]

# 전일 고가를 shifted_high, 전일 저가를 shifted_low에 저장한다
btc_df['shifted_high'] = btc_df['high'].shift(1)
btc_df['shifted_low'] = btc_df['low'].shift(1)
btc_df['range'] = btc_df['shifted_high'] - btc_df['shifted_low']

ltc_df['shifted_high'] = ltc_df['high'].shift(1)
ltc_df['shifted_low'] = ltc_df['low'].shift(1)
ltc_df['range'] = ltc_df['shifted_high'] - ltc_df['shifted_low']

etc_df['shifted_high'] = etc_df['high'].shift(1)
etc_df['shifted_low'] = etc_df['low'].shift(1)
etc_df['range'] = etc_df['shifted_high'] - etc_df['shifted_low']

xrp_df['shifted_high'] = xrp_df['high'].shift(1)
xrp_df['shifted_low'] = xrp_df['low'].shift(1)
xrp_df['range'] = xrp_df['shifted_high'] - xrp_df['shifted_low']

# range값이 없는 row들은 다 삭제한다

btc_df.dropna(inplace =  True)
ltc_df.dropna(inplace =  True)
etc_df.dropna(inplace =  True)
xrp_df.dropna(inplace =  True)


# 데이터 수가 다 동일한지 확인한다
len(btc_df), len(ltc_df), len(etc_df), len(xrp_df)

 

(1773, 1773, 1773, 1773)

 

이제 투자전략을 백테스팅해보자. 

 

total_capital = 100000000 # # 전체 투자금액, 처음 시드머니 1억
fee = 0.002 # 수수료 0.2%
k = 0.5

df_list = [btc_df, ltc_df, etc_df, xrp_df]
total_capital_list = []
n = 4

for i in range(len(btc_df)):
    
    # 실시간 가격 > (당일 시가 + (레인지 x k)) 인지 확인한다 .
    # 확인하는 방법은 고가가 (당일 시가 + (레인지 x k))보다 크면 돌파, 작으면 돌파 실패를 의미한다
    # 가상화폐별로 확인을 한다
    
    buy_sell_price_list = [] # 돌파하게 되면, 매수/매도하는 가격 리스트
    
    for df in df_list:
        open_price = df.iloc[i]['open'] # 당일 시가
        high_price = df.iloc[i]['high'] # 당일 고가
        close_price = df.iloc[i]['close'] # 당일 종가 : 사실 당일 종가가 다음날 시가와 동일하므로 종가를 사용한다
        ma_5_price = df.iloc[i]['ma_5'] # 5일이평선
        
        # 타겟 가격 
        target_price = open_price + df.iloc[i]['range'] * k
        
        # 만약 시초가가 5 이평선보다 크다면, 
        if open_price >= ma_5_price:

            # 만약 고가가 타겟 가격보다 크다면, 즉 장 중에 돌파 성공했다면, 
            if high_price >= target_price:
                buy_sell_price_list.append([target_price, close_price])
    
    
    # 돌파에 성공한 가상화폐에 자산의 N분의 1 투입
    
    # 임시 총자산 => 현금
    temp_total_capital = (1 - len(buy_sell_price_list) / n) * total_capital

    for buy_price, sell_price in buy_sell_price_list:

        # 자산의 N분의 1 투입
        coin_invested = total_capital * (1 / n)
        # 매도금액을 매수금액으로 나누면 수익률이나오고, 거기에 수수료를 차감 후 투자금액을 곱하면 얻게 되는 금액이 나온다
        temp_total_capital += (sell_price / buy_price) * (1 - fee * 2) * coin_invested

    total_capital = temp_total_capital

    total_capital_list.append(total_capital)
    print(btc_df.index[i], total_capital)

 

수익률과 MDD를 확인해보자. 수익률은 -95%이고 mdd도 -95%이다..코드는 문제가 없는거같고 전략의 알파가 사라져서 이지 않을까 생각한다..

 

ror_df = pd.DataFrame({ "total_capital" : total_capital_list}, index = btc_df.index)

ror_df['ror'] = ror_df['total_capital'].pct_change() + 1
ror_df['cum_ror'] = ror_df['ror'].cumprod()

# 전 고점(HWM : High Water Mark)
ror_df['highwatermark'] =  ror_df['cum_ror'].cummax()
ror_df['drawdown'] = (ror_df['cum_ror'] / ror_df['highwatermark']) - 1

# mdd를 구한다
ror_df['max_drawdown'] = ror_df['drawdown'].cummin()

print(f"수익률 : ", (ror_df.iloc[-1]['cum_ror'] - 1) * 100 )
print("mdd : ", ror_df.iloc[-1]['max_drawdown'] * 100)

import matplotlib.pyplot as plt

plt.plot(ror_df['cum_ror'])

 

수익률 :  -95.58826007517057
mdd :  -95.6525701772156

 

 

 

 

 

트레이딩 전략 9 다자 가상화폐 + 상승장 + 변동성 돌파.ipynb
0.11MB

 

 

 

댓글