Files
DeepStock/hts/Simulation.py
dosangyoon 3edadf5651 init
2021-10-19 00:06:23 +09:00

183 lines
7.3 KiB
Python

import os
from datetime import datetime, timedelta
import pandas as pd
import plotly.graph_objects as go
from plotly import subplots
from BuySellChecker import BuySellChecker
class Simulation:
buySellChecker = None
def __init__(self):
self.buySellChecker = BuySellChecker()
#self.connect()
return
def getCSV(self, fileName, given_day, result):
data = pd.read_csv(fileName)
days = data.날짜
time = data.시간
open = data.시가
close = data.종가
high = data.고가
low = data.저가
vol = data.거래량
start_time = datetime.strptime(given_day + " 090000", '%Y%m%d %H%M%S')
for i in range(len(data)):
temp = datetime.strptime(str(days[i]) + " " + str(time[i]).zfill(4)+"00", '%Y%m%d %H%M%S')
if temp < start_time:
continue
if temp not in result["check"]:
result["check"].add(temp)
result["time"].append(temp)
result["open"].append(open[i])
result["close"].append(close[i])
result["high"].append(high[i])
result["low"].append(low[i])
result["vol"].append(vol[i])
return
def checkTransaction(self, data):
size = len(data["Close"])
bsLine = {}
bsLine['buy'] = [-1 for i in range(size)]
bsLine['weight'] = [-1 for i in range(size)]
bsLine['sell'] = [-1 for i in range(size)]
for i in range(6, size-5):
buy, weight, sell = self.buySellChecker.getPriceAndWeight1(data, i)
bsLine['buy'][i] = buy
bsLine['weight'][i] = weight
bsLine['sell'][i] = sell
return bsLine
def draw(self, stock_code, given_day, data, bsLine):
buy_line = bsLine['buy']
sell_line = bsLine['sell']
# 그래프 설정을 위한 변수를 생성한다.
data['Open'] = pd.to_numeric(data['Open'])
data['High'] = pd.to_numeric(data['High'])
data['Low'] = pd.to_numeric(data['Low'])
data['Close'] = pd.to_numeric(data['Close'])
data['Volume'] = pd.to_numeric(data['Volume'])
data['avg5'] = pd.to_numeric(data['avg5'])
data["fast_k"] = pd.to_numeric(data['fast_k'])
data["slow_k"] = pd.to_numeric(data['slow_k'])
data["slow_d"] = pd.to_numeric(data['slow_d'])
data["rsi"] = pd.to_numeric(data['rsi'])
data["rsis"] = pd.to_numeric(data['rsis'])
buy_colors = []
for i in range(len(buy_line)):
if buy_line[i] < 0:
buy_colors.append("#ffffff")
buy_line[i] = data["lower"][0]
else:
buy_colors.append("#ff00ff")
sell_colors = []
for i in range(len(sell_line)):
if sell_line[i] < 0:
sell_colors.append("#ffffff")
sell_line[i] = data["lower"][0]
else:
sell_colors.append("#00ced1")
# 그래프를 설정한다.
buy_check = go.Scatter(x=data['Date'], y=buy_line, mode='markers', name="buy", marker=dict(size=14, color=buy_colors, line_width=0))
sell_check = go.Scatter(x=data['Date'], y=sell_line, mode='markers', name="sell", marker=dict(size=14, color=sell_colors, line_width=0))
bolinger_upper = go.Scatter(x=data['Date'], y=data["upper"], name="upper", line_color='#8B4513')
bolinger_lower = go.Scatter(x=data['Date'], y=data["lower"], name="lower", line_color='#8B4513')
avg5 = go.Scatter(x=data['Date'], y=data["avg5"], name="avg5", line_color='#000000')
candle_stick = go.Candlestick(x=data['Date'], open=data['Open'], high=data['High'], low=data['Low'], close=data['Close'], increasing_line_color='red', decreasing_line_color='blue')
volume_line = go.Scatter(x=data['Date'], y=data["Volume"], mode='lines', name='Volume')
fast_k_line = go.Scatter(x=data['Date'], y=data["fast_k"], mode='lines', name='fast_k')
slow_k_line = go.Scatter(x=data['Date'], y=data["slow_k"], mode='lines', name='slow_k')
slow_d_line = go.Scatter(x=data['Date'], y=data["slow_d"], mode='lines', name='slow_d')
rsi_line = go.Scatter(x=data['Date'], y=data["rsi"], mode='lines', name='rsi')
rsis_line = go.Scatter(x=data['Date'], y=data["rsis"], mode='lines', name='rsis')
#candle_data = [candle_stick, bolinger_upper, bolinger_lower, buy_check, sell_check, avg1, avg2, avg5, avg10, avg20, avg30, avg40, avg50, avg60]
candle_data = [candle_stick, bolinger_upper, bolinger_lower, avg5, buy_check, sell_check]
volume_data = [volume_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=4, cols=1, subplot_titles=('캔들', "거래량", "스토캐스틱", "RSI"))
for trace in candle_data:
fig.append_trace(trace, 1, 1)
for trace in volume_data:
fig.append_trace(trace, 2, 1)
for trace in stochastic_data:
fig.append_trace(trace, 3, 1)
for trace in rsi_data:
fig.append_trace(trace, 4, 1)
#fig.update_xaxes(nticks=5)
#fig.update_layout(height=1800, title=stock_code + "_" + given_day, xaxis_rangeslider_visible=False)
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=1800, title=stock_code + "_" + given_day + "_" + str(buy_count)+","+str(sell_count))
fig.show()
return
def simulate(self, stock_code, GIVEN_DAY):
result = {"check": set(),
"time": [],
"open": [],
"close": [],
"high": [],
"low": [],
"vol": []}
# 데이터를 가지고 온다.
self.getCSV("./data/"+stock_code+"_"+GIVEN_DAY+".csv", GIVEN_DAY, result)
# 분석을 통해서 볼린저밴드 상/하단을 계산한다.
data = self.buySellChecker.analyze(result)
# 사야 할 시점과 팔아야 할 시점을 체크한다.
bsLine = self.checkTransaction(data)
# 그래프를 그린다.
self.draw(stock_code, GIVEN_DAY, data, bsLine)
return
if __name__ == "__main__":
today = datetime.today()
PROJECT_HOME = os.path.join(os.path.dirname(os.path.join(os.path.dirname(__file__))))
RESOURCE_DIR = PROJECT_HOME + "/resources/analysis/"+today.strftime("%Y%m%d")
stock_codes = ["252670", "122630"]
given_days = ['20210901','20210902','20210903','20210906','20210907','20210908','20210909','20210910','20210913',
'20210914','20210915','20210916','20210917','20210923','20210924','20210927','20210928','20210929',
'20210930','20211001', '20211005','20211006', '20211007','20211008', '20211012','20211013', '20211014', '20211018']
simulation = Simulation()
given_days = sorted(given_days, reverse=True)
for given_day in given_days:
simulation.simulate(stock_codes[0], given_day)
print ("done...")