컴퓨터/Python
upbit 이동평균
풍경소리^^
2021. 5. 26. 18:19
# https://www.youtube.com/watch?v=5vofEMqMyGk&list=PLU9-uwewPMe3KKFMiIm41D5Nzx_fx2PUJ&index=3
# https://wikidocs.net/book/1665 # 파이썬을 이용한 비트코인 자동매매
# 과거 데이터로 전략을 테스트 해보는 것
# https://github.com/sharebook-kr/book-cryptocurrency/tree/master/ch07
# import pyupbit
# import pprint
#
# f = open("uptxt.txt")
# lines = f.readlines()
# access = lines[0].strip()
# secret = lines[1].strip()
# f.close()
#
# upbit = pyupbit.Upbit(access, secret) # 인스턴스 만들기
#
# print(upbit.get_balances())
# print(upbit.get_balance("KRW-XRP"))
# print(upbit.get_balance("KRW"))
import pyupbit
import numpy as np
import time
buy_per = 1
ticker = "KRW-ETC"
buy_price = []
def bull_market(ticker):
df = pyupbit.get_ohlcv(ticker, "minute1", count=60*24)
ma5 = df['close'].rolling(window=5).mean()
price = pyupbit.get_current_price(ticker)
last_ma5 = ma5[-1]
if price > last_ma5:
return True
else:
return False
# tickers = pyupbit.get_tickers()
# for ticker in tickers:
# is_bull = bull_market(ticker)
# if is_bull:
# print(ticker, " 상승장")
# else:
# print(ticker, " 하락장")
buy_price = []
def buy(ticker):
buy_price.append(pyupbit.get_current_price(ticker))
print("buy : ", buy_price[-1])
def sell(ticker):
# print("sell : ", pyupbit.get_current_price(market), "구매가격 : ", buy_price, "손익 : ", pyupbit.get_current_price(market) - buy_price)
print("sell : ", pyupbit.get_current_price(ticker))
state = False
while True:
is_bull = bull_market(ticker)
curr = pyupbit.get_current_price(ticker)
if state == False and is_bull == True:
print("-" * 80)
buy(ticker)
# buy_price.append(pyupbit.get_current_price(ticker))
state = True
# print("상승장")
elif state == True and is_bull == False:
print("-" * 80)
print("현재가 : ", curr, " , 구입가 : ", buy_price.pop())
sell(ticker)
state = False
print("=" * 80)
time.sleep(60)
#
# df = pyupbit.get_ohlcv(ticker, "minute1", count=60*24)
# df = pyupbit.get_ohlcv("KRW-ETC", "minute3", count=60/3*24)
# df = pyupbit.get_ohlcv("KRW-ETC", "minute10", count=60/10*24)
# print(df)
# print(df.columns)
# buy_price = []
# state = False
# while True:
#
# # 변동폭 * k 계산, (고가 - 저가) * k값
# # df['range'] = (df['high'] - df['low']) * 0.5
# range = df['open'][0] * buy_per / 100
#
# df_curr = pyupbit.get_ohlcv(ticker, "minute1", count=60 * 24)
# df_buy_target = df['open'][0] + range
#
# df_last5 = pyupbit.get_ohlcv(ticker, "minute5", count=1)
# df_last5_high = df_last5['high'][-1]
#
# curr = pyupbit.get_current_price(ticker)
#
# if state == False and curr > df_buy_target:
# if df_curr['close'][-2] < df_curr['close'][-1] and df_curr['close'][-1] < curr:
# print("-" * 80)
# print("현재가 : ", curr, ", 시작가 : ", df['open'][0], ", 변동폭 : ", range, ", 목표가 : ", df_buy_target)
# print("2분전 종가 : ", df_curr['close'][-2], " , 1분전 종가 : ", df_curr['close'][-1], " , 현재가 : ", curr)
# buy(ticker)
# # buy_price.append(pyupbit.get_current_price(ticker))
# state = True
#
# elif state == True:
# if df_curr['close'][-1] > curr or buy_price[-1] > curr:
# print("-" * 80)
# print("1분전 종가 : ", df_curr['close'][-1], " , 현재가 : ", curr, " , 구입가 : ", buy_price.pop())
# sell(ticker)
# state = False
# print("=" * 80)
# # elif df['close'][-1] < (df_last5_high - range):
# elif df['close'][-1] < (df_last5_high - range) or curr < (df_last5_high - range):
# print("-" * 80)
# print("5분전 고가 : ", df_last5_high, " , 변동폭 : ", range, " , 1분전 종가 : ", df_curr['close'][-1], " , 현재가 : ", curr, " , 구입가 : ", buy_price.pop())
# sell(ticker)
# state = False
# print("=" * 80)
#
# time.sleep(10)
# # 매매대상
# df['target'] = df['close'].shift(1)
# # target(매수가), range 컬럼을 한칸씩 밑으로 내림 (.shift(1))
# df['target'] = df['open'] + df['range'].shift(1)
# df['target'] = df['open'] + range
#
#
# fee = 0.0005
# ror(수익율), np.where(조건문, 참일 때 값, 거짓일때 값)
# df['ror'] = np.where(df['high'] > df['target'], # 매수가 진행된 상황
# df['close'] / df['target'] - fee, # 종가(판매가격)/ 목표가(매입가격) = 수익률
# 1) # 목표가에 도달하지 않았으므로 매매가 이루어지지 않아서 금액은 그대로
#
# 누적 곱 계산(cumprod) → 누적 수익률
# df['hpr'] = df['ror'].cumprod()
#
# 하락최대값 Draw Down 계산 (누적 최대 값과 현재 hpr 차이/ 누적 최대값 * 100)
# df['dd'] = (df['hpr'].cummax() - df['hpr']) / df['hpr'].cummax() * 100
#
# MDD 계산
# print("MDD(%): ", df['dd'].max())
# print("잔액 : ",1000000*df['hpr'].iloc[-1])
# print(df)
# df.to_excel("dd_bit.xlsx")