Files
DeepStock/Bithumb.py
dsyoon d18629ec8e init
2023-01-21 19:46:24 +09:00

483 lines
19 KiB
Python

import pybithumb
from hts.HTS import HTS
import pandas as pd
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import StandardScaler, MinMaxScaler
import plotly.graph_objects as go
from plotly import subplots
import plotly.io as po
from math import nan
import csv
import os
from hts.BuySellChecker import BuySellChecker
from datetime import datetime
from stock.analysis.AnalyzerSqlite import AnalyzerSqlite
class Bithumb(HTS):
RESOURCE_PATH = None
buySellChecker = None
analyzerSqlite = None
def __init__(self, RESOURCE_PATH):
super().__init__(RESOURCE_PATH)
self.RESOURCE_PATH = RESOURCE_PATH
con_key = "946dd0b0e6f8ad411144cd33f09518d3" # 본인의 Connect Key를 입력한다.
sec_key = "56b2a3cdd9fe3a82aa3f38c97c161125" # 본인의 Secret Key를 입력한다.
# bithumb api에 연결한 클라스 객체를 선언한다.
self.bithumb = pybithumb.Bithumb(con_key, sec_key)
self.buySellChecker = BuySellChecker()
self.analyzerSqlite = AnalyzerSqlite()
return
def bull_market(self, df, ticker):
m5 = df['close'].rolling(5).mean()
last_m5 = m5[-2]
price = pybithumb.get_current_price(ticker)
if price > last_m5:
return True
return False
def append(self, df, stock):
for i in range(len(df)):
stock['PRICE'].append(
{
"ymd": df.index[i].strftime('%Y.%m.%d'),
"close": df['close'][i],
"diff": 0,
"open": df['open'][i],
"high": df['high'][i],
"low": df['low'][i],
"volume": df['volume'][i],
"avg3": -1,
"avg4": -1,
"avg5": -1,
"avg6": -1,
"avg10": -1,
"avg12": -1,
"avg20": -1,
"avg36": -1,
"avg40": -1,
"avg48": -1,
"avg60": -1,
"avg120": -1,
"avg200": -1,
"avg240": -1,
"avg300": -1,
"disparity_avg5": -1,
"disparity_avg10": -1,
"disparity_avg20": -1,
"disparity_avg60": -1,
"disparity_avg120": -1,
"bolingerband_upper": -1,
"bolingerband_lower": -1,
"bolingerband_middle": -1,
"envelope_upper": -1,
"envelope_lower": -1,
"envelope_middle": -1,
"ichimokucloud_changeLine": -1,
"ichimokucloud_baseLine": -1,
"ichimokucloud_leadingSpan1": -1,
"ichimokucloud_leadingSpan2": -1,
"stochastic_fast_k": -1,
"stochastic_slow_k": -1,
"stochastic_slow_d": -1,
"rsi": -1,
"rsis": -1,
"macd": -1,
"macds": -1,
"macdo": -1,
})
return
def analyze (self, stock, days=120):
stock["PRICE"] = sorted(stock["PRICE"], key=lambda x: x['ymd'])
self.analyzerSqlite.get_moving_average(stock["PRICE"])
# 이동 평균을 이용한 이격도 계산
self.analyzerSqlite.get_disparity(stock["PRICE"])
self.analyzerSqlite.ichimokuCloud.analyze(stock)
self.analyzerSqlite.stochastic.analyze(stock)
self.analyzerSqlite.bolingerBand.analyze(stock)
self.analyzerSqlite.envelope.analyze(stock)
self.analyzerSqlite.rsi.analyze(stock)
self.analyzerSqlite.macd.analyze(stock)
result = {
"ymd": [],
"open": [],
"close": [],
"high": [],
"low": [],
"avg3": [],
"avg4": [],
"avg5": [],
"avg6": [],
"avg10": [],
"avg12": [],
"avg20": [],
"avg36": [],
"avg40": [],
"avg48": [],
"avg60": [],
"avg120": [],
"avg200": [],
"avg240": [],
"avg300": [],
"disparity_avg5": [],
"disparity_avg20": [],
"disparity_avg60": [],
"disparity_avg120": [],
"disparity": [],
"disparity_type": [],
"envelope_upper": [],
"envelope_lower": [],
"envelope_middle": [],
"rsi": [],
"rsis": [],
"macd": [],
"macds": [],
"slow_k": [],
"slow_d": [],
"buy": [],
"sell": [],
}
for item in stock['PRICE']:
result["ymd"].append(item['ymd'])
result["open"].append(item['open'])
result["close"].append(item['close'])
result["high"].append(item['high'])
result["low"].append(item['low'])
result["avg3"].append(item['avg3'])
result["avg4"].append(item['avg4'])
result["avg5"].append(item['avg5'])
result["avg6"].append(item['avg6'])
result["avg10"].append(item['avg10'])
result["avg12"].append(item['avg12'])
result["avg20"].append(item['avg20'])
result["avg36"].append(item['avg36'])
result["avg40"].append(item['avg40'])
result["avg48"].append(item['avg48'])
result["avg60"].append(item['avg60'])
result["avg120"].append(item['avg120'])
result["avg200"].append(item['avg200'])
result["avg240"].append(item['avg240'])
result["avg300"].append(item['avg300'])
result["disparity_avg5"].append(item['disparity_avg5'])
result["disparity_avg20"].append(item['disparity_avg20'])
result["disparity_avg60"].append(item['disparity_avg60'])
result["disparity_avg120"].append(item['disparity_avg120'])
result['disparity'].append(max(item['disparity_avg5'], item['disparity_avg20'], item['disparity_avg60']) - min(item['disparity_avg5'], item['disparity_avg20'], item['disparity_avg60']))
if item['disparity_avg60'] < item['disparity_avg20'] < item['disparity_avg5']:
result['disparity_type'].append(1)
elif item['disparity_avg5'] < item['disparity_avg20'] < item['disparity_avg60']:
result['disparity_type'].append(-1)
else:
result['disparity_type'].append(0)
result["envelope_upper"].append(item['envelope_upper'])
result["envelope_lower"].append(item['envelope_lower'])
result["envelope_middle"].append(item['envelope_middle'])
result["rsi"].append(item['rsi'])
result["rsis"].append(item['rsis'])
result["macd"].append(item['macd'])
result["macds"].append(item['macds'])
result["slow_k"].append(item['stochastic_slow_k'])
result["slow_d"].append(item['stochastic_slow_d'])
result["buy"].append(-1)
result["sell"].append(-1)
data = pd.DataFrame(result)
df_final_time = pd.DatetimeIndex(result['ymd'])
data.index = df_final_time
data = data.astype(
{
'open': 'int',
'high': 'int',
'low': 'int',
'close': 'int',
'avg3': 'float',
'avg4': 'float',
'avg5': 'float',
'avg6': 'float',
'avg10': 'float',
'avg12': 'float',
'avg20': 'float',
'avg36': 'float',
'avg40': 'float',
'avg48': 'float',
'avg60': 'float',
'avg120': 'float',
'avg200': 'float',
'avg240': 'float',
'avg300': 'float',
'disparity_avg5': 'float',
'disparity_avg20': 'float',
'disparity_avg60': 'float',
'disparity_avg120': 'float',
'buy': 'int',
'sell': 'int',
'slow_k': 'float',
'slow_d': 'float',
'macd': 'float',
'macds': 'float',
'envelope_upper': 'float',
'envelope_lower': 'float',
'envelope_middle': 'float',
'rsi': 'float',
'rsis': 'float'
}
)
scaler = StandardScaler()
low_df = pd.DataFrame(data['low'])
low_df.index = [c for c in range(len(low_df))]
low_std = scaler.fit_transform(data['low'].values.reshape(-1, 1))
low_std = pd.DataFrame(low_std, columns=['low_std'])
min_df = pd.DataFrame({'open': data['open'].to_list(), 'close': data['close'].to_list()})
min_df['min_std'] = min_df.min(axis=1)
min_df.index = [c for c in range(len(min_df))]
min_std = scaler.fit_transform(min_df['min_std'].values.reshape(-1, 1))
min_std = pd.DataFrame(min_std, columns=['min_std'])
line_fitter = LinearRegression()
size = len(data["close"])
gradients_low = []
gradients_avg5 = []
gradients_avg20 = []
gradients_avg60 = []
for i in range(size):
coef_low = -999
coef_avg5 = -999
coef_avg20 = -999
coef_avg60 = -999
if i > 0:
l = days if i >= days else i
x = pd.DataFrame([c for c in range(i - l, i + 1)])
y = pd.DataFrame(low_std.values.tolist()[i - l:i + 1])
line_fitter.fit(x.values.reshape(-1, 1), y)
coef_low = line_fitter.coef_[0][0]
l = 5 if i >= 5 else i
x = pd.DataFrame([c for c in range(i - l, i + 1)])
y = pd.DataFrame(min_std.values.tolist()[i - l:i + 1])
line_fitter.fit(x.values.reshape(-1, 1), y)
coef_avg5 = line_fitter.coef_[0][0]
l = 20 if i >= 20 else i
x = pd.DataFrame([c for c in range(i - l, i + 1)])
y = pd.DataFrame(min_std.values.tolist()[i - l:i + 1])
line_fitter.fit(x.values.reshape(-1, 1), y)
coef_avg20 = line_fitter.coef_[0][0]
l = 60 if i >= 60 else i
x = pd.DataFrame([c for c in range(i - l, i + 1)])
y = pd.DataFrame(min_std.values.tolist()[i - l:i + 1])
line_fitter.fit(x.values.reshape(-1, 1), y)
coef_avg60 = line_fitter.coef_[0][0]
gradients_low.append(coef_low)
gradients_avg5.append(coef_avg5)
gradients_avg20.append(coef_avg20)
gradients_avg60.append(coef_avg60)
gradients_low_df = pd.DataFrame(gradients_low, columns=['gradients_low'])
gradients_avg5_df = pd.DataFrame(gradients_avg5, columns=['gradients_avg5'])
gradients_avg20_df = pd.DataFrame(gradients_avg20, columns=['gradients_avg20'])
gradients_avg60_df = pd.DataFrame(gradients_avg60, columns=['gradients_avg60'])
gradients_low_df.index = df_final_time
gradients_avg5_df.index = df_final_time
gradients_avg20_df.index = df_final_time
gradients_avg60_df.index = df_final_time
data = data.merge(gradients_low_df, left_index=True, right_index=True)
data = data.merge(gradients_avg5_df, left_index=True, right_index=True)
data = data.merge(gradients_avg20_df, left_index=True, right_index=True)
data = data.merge(gradients_avg60_df, left_index=True, right_index=True)
return data
def writeFile(self, dirName, ticker, data, bsLine, today):
if bsLine is None:
return
# 어제 데이터는 지운다.
buy_line = bsLine['buy']
buy_weight_line = bsLine['buy_weight']
sell_line = bsLine['sell']
buy_size = []
buy_colors = []
for i in range(len(buy_line)):
if buy_line[i] < 0:
buy_colors.append("#ffffff")
buy_line[i] = nan
buy_size.append(0)
else:
buy_colors.append("#B2028C")
buy_size.append(10 + (0.1 * buy_weight_line[i]))
sell_colors = []
for i in range(len(sell_line)):
if sell_line[i] < 0:
sell_colors.append("#ffffff")
sell_line[i] = nan
else:
sell_colors.append("#00ced1")
# 그래프를 설정한다.
buy_check = go.Scatter(x=data['ymd'], y=buy_line, mode='markers', name="buy", marker=dict(size=buy_size, color=buy_colors, line_width=0))
sell_check = go.Scatter(x=data['ymd'], y=sell_line, mode='markers', name="sell", marker=dict(size=14, color=sell_colors, line_width=0))
envelope_upper = go.Scatter(x=data['ymd'], y=data["envelope_upper"], name="upper", line_color='#000000')
envelope_middle = go.Scatter(x=data['ymd'], y=data["envelope_middle"], name="upper", line_color='#927786')
envelope_lower = go.Scatter(x=data['ymd'], y=data["envelope_lower"], name="lower", line_color='#000000')
avg5 = go.Scatter(x=data['ymd'], y=data["avg5"], name="avg5", line_color='#6C2507')
avg20 = go.Scatter(x=data['ymd'], y=data["avg20"], name="avg20", line_color='#f84c43')
avg60 = go.Scatter(x=data['ymd'], y=data["avg60"], name="avg60", line_color='#f89543')
candle_stick = go.Candlestick(x=data['ymd'], open=data['open'], high=data['high'], low=data['low'], close=data['close'], increasing_line_color='red', decreasing_line_color='blue', showlegend=False)
macd_line = go.Scatter(x=data['ymd'], y=data["macd"], line=dict(color='red', width=2), name='macd')
macd_s_line = go.Scatter(x=data['ymd'], y=data["macds"], line=dict(dash='dashdot', color='black', width=2), name='macds')
# fast_k_line = go.Scatter(x=hts['date'], y=hts["fast_k"], mode='lines', name='fast_k')
slow_k_line = go.Scatter(x=data['ymd'], y=data["slow_k"], line=dict(color='red', width=2), name='slow_k')
slow_d_line = go.Scatter(x=data['ymd'], y=data["slow_d"], line=dict(dash='dashdot', color='black', width=2), name='slow_d')
rsi_line = go.Scatter(x=data['ymd'], y=data["rsi"], line=dict(color='red', width=2), name='rsi')
rsis_line = go.Scatter(x=data['ymd'], y=data["rsis"], line=dict(dash='dashdot', color='black', width=2), name='rsis')
disparity_avg5 = go.Scatter(x=data['ymd'], y=data["disparity_avg5"], name="disparity_avg5", line_color='#8F8203')
disparity_avg20 = go.Scatter(x=data['ymd'], y=data["disparity_avg20"], name="disparity_avg20", line_color='#ff00ff')
disparity_avg60 = go.Scatter(x=data['ymd'], y=data["disparity_avg60"], name="disparity_avg60", line_color='#1469F4')
candle_data = [candle_stick, avg5, avg20, avg60, envelope_upper, envelope_middle, envelope_lower, buy_check, sell_check]
disparity_data = [disparity_avg5, disparity_avg20, disparity_avg60]
macd_data = [macd_line, macd_s_line]
stochastic_data = [slow_k_line, slow_d_line]
rsi_data = [rsi_line, rsis_line]
# 그래프를 그린다.
"""
fig = go.Figure(data=candle_data)
fig.update_layout(title=stock_code + "_" + given_day)
fig.show()
"""
fig = subplots.make_subplots(
rows=5, cols=1,
subplot_titles=("MACD", "RSI", "스토캐스틱", '이격도', '캔들'),
#specs=[[{}], [{}], [{}], [{}], [{}], [{}]],
shared_xaxes=True, horizontal_spacing=0.03, vertical_spacing=0.01,
row_heights=[200, 200, 200, 200, 750]
)
for trace in macd_data:
fig.append_trace(trace, 1, 1)
for trace in rsi_data:
fig.append_trace(trace, 2, 1)
for trace in stochastic_data:
fig.append_trace(trace, 3, 1)
for trace in disparity_data:
fig.append_trace(trace, 4, 1)
for trace in candle_data:
fig.append_trace(trace, 5, 1)
df = pd.DataFrame(bsLine)
df = df.fillna(-1)
buy_count = len(df.loc[df["buy"] > 0])
sell_count = len(df.loc[df["sell"] > 0])
fig.update_layout(height=1700, title="_" + str(buy_count)+","+str(sell_count))
fig['layout'].update()
fileName = "%s/%s_%s.html" % (dirName, ticker, today)
po.write_html(fig, file=fileName, auto_open=False)
return
def getBalance(self, ticker):
tmp = self.bithumb.get_balance(ticker)
return tmp[2]
def exist_buy(self, ticker, log_filename):
log_file = open('data.csv', 'r', )
reader = csv.reader(log_file)
for line in reader:
if line[2] == ticker:
log_file.close()
return True
log_file.close()
return False
def buyRealTime(self, ticker, isRealTime=False):
stock = {"CODE": ticker, "NAME": ticker, "PRICE": []}
df = pybithumb.get_ohlcv(ticker)
close = pybithumb.get_current_price(ticker)
size = len(df)
df['close'][size-1] = close
if close < df['low'][size-1]:
df['low'][size - 1] = close
if df['high'][size-1] < close:
df['high'][size - 1] = close
self.append(df, stock)
analyzed_day = 120
data = self.analyze(stock, analyzed_day)
# 분석일 데이터만 활용한다 (이전 데이터는 제거)
data.drop(data.index[:len(data) - analyzed_day], inplace=True)
bsLine, data = self.buySellChecker.checkWithEnvelope(data, analyzed_day, isRealTime=isRealTime)
# 그래프를 그린다.
if len(data.index) > 10:
today = datetime.today().strftime('%Y%m%d')
log_filename = os.path.join(RESOURCE_PATH, 'analysis', 'bithumb', today + '.log')
if not isRealTime and self.exist_buy(ticker, log_filename):
if max(bsLine['buy'][len(bsLine['buy']) - 2:]) > 100:
balance = self.getBalance(ticker)
count = int(balance * (bsLine['buy_weight'][len(bsLine['buy_weight'])-1]/100))
order = self.bithumb.buy_limit_order(ticker, bsLine['buy'][len(bsLine['buy'])-1], count)
# order: ('bid', 'BTC', 'C0101000000322993432', 'KRW')
with open(log_filename, 'a', newline='', encoding='utf-8') as log_file:
wr = csv.writer(log_file)
wr.writerow([datetime.now().strftime('%Y-%m-%d %H:%M:%S'), order[0], order[1], order[2], order[3]])
else:
dirName = os.path.join(RESOURCE_PATH, 'analysis', 'bithumb')
self.writeFile(dirName, ticker, data, bsLine, datetime.now().strftime('%Y%m%d %H%M%S'))
return
if __name__ == "__main__":
PROJECT_HOME = os.getcwd()
RESOURCE_PATH = os.path.join(PROJECT_HOME, "resources")
if not os.path.exists(os.path.join(RESOURCE_PATH, 'analysis', 'bithumb')):
os.mkdir(os.path.join(RESOURCE_PATH, 'analysis', 'bithumb'))
dirName = os.path.join(RESOURCE_PATH, 'analysis', 'bithumb')
if not os.path.exists(dirName):
os.mkdir(dirName)
bithumb = Bithumb(RESOURCE_PATH)
tickers = ['XRP', 'BTC', 'SOL']
while True:
for ticker in tickers:
print(ticker, datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
bithumb.buyRealTime(ticker, isRealTime=False)