This commit is contained in:
dosangyoon
2021-09-22 21:04:41 +09:00
parent 50a669ad1f
commit 448cd9aeb6
11 changed files with 2859 additions and 5608 deletions

View File

@@ -1,14 +1,9 @@
#import win32com.client
import os
import re
import win32com.client
from datetime import datetime
#import matplotlib.pyplot as plt
#import matplotlib.ticker as ticker
#import mplfinance as mpf
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
import pandas as pd
#import cufflinks as cf
#import plotly.graph_objects as go
import plotly.graph_objects as go
class HTS:
@@ -248,6 +243,24 @@ class HTS:
return
def write(self, day, result):
#날짜,시간,시가,고가,저가,종가,거래량
#20210909,900,2070,2070,2070,2070,0
outFp = open(day+".csv", "w")
outFp.write("날짜,시간,시가,고가,저가,종가,거래량\n")
for i in range(len(result["time"])):
outFp.write("%s,%s,%s,%s,%s,%s,%s\n"%(
result["time"][i].strftime('%Y%m%d'),
result["time"][i].strftime('%H%M'),
result["open"][i],
result["high"][i],
result["low"][i],
result["close"][i],
result["vol"][i]))
outFp.close()
return
# 주식 현재가 조회
def getRealTime(self, stock_code, day, result):
objCpCybos = win32com.client.Dispatch("CpUtil.CpCybos")
@@ -273,25 +286,32 @@ class HTS:
size = objStockChart.GetHeaderValue(3)
#print("날짜", "시간", "시가", "고가", "저가", "종가", "거래량")
start_time = datetime.strptime(day+" 093000", '%Y%m%d %H%M%S')
start_time = datetime.strptime(day + " 090000", '%Y%m%d %H%M%S')
for i in range(size-1, -1, -1):
#day = objStockChart.GetDataValue(0, i)
time = datetime.strptime(day+" "+objStockChart.GetDataValue(1, i), '%Y%m%d %H%M%S')
if time < start_time:
continue
#open = objStockChart.GetDataValue(2, i)
#high = objStockChart.GetDataValue(3, i)
#low = objStockChart.GetDataValue(4, i)
open = objStockChart.GetDataValue(2, i)
close = objStockChart.GetDataValue(5, i)
high = objStockChart.GetDataValue(3, i)
low = objStockChart.GetDataValue(4, i)
vol = objStockChart.GetDataValue(6, i)
#print(day, time, open, high, low, close, vol)
if time[i] not in result["check"]:
if len(result["check"]) == 0:
result["check"].add(start_time)
result["time"].append(start_time)
if time not in result["check"]:
result["check"].add(time)
result["time"].append(time)
result["close"].append(close)
result["vol"].append(vol)
result["open"].append(open)
result["close"].append(close)
result["high"].append(high)
result["low"].append(low)
result["vol"].append(vol)
return
def getCSV(self, fileName, day, result):
@@ -299,112 +319,171 @@ class HTS:
days = data.날짜
time = data.시간
open = data.시가
close = data.종가
high = data.고가
low = data.저가
vol = data.거래량
start_time = datetime.strptime(day + " 093000", '%Y%m%d %H%M%S')
start_time = datetime.strptime(day + " 090000", '%Y%m%d %H%M%S')
for i in range(len(data)):
temp = datetime.strptime(str(days[i]) + " " + str(time[i]), '%Y%m%d %H%M%S')
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 analyze(self, result):
y_value = result["close"]
#x_value = [i for i in range(len(y_value))]
vol = result["vol"]
df = pd.DataFrame(y_value)
point = result["time"]
df = pd.DataFrame(result["close"])
max20 = df.rolling(window=20).mean()
stddev20 = df.rolling(window=20).std()
max20 = df.rolling(window=10).mean()
stddev20 = df.rolling(window=10).std()
upper_df = max20 + (stddev20 * 2) # 상단 볼린저 밴드
lower_df = max20 - (stddev20 * 2) # 하단 볼린저 밴드
window = 60
open = y_value[:len(y_value)-window] + [y_value[len(y_value)-window] for i in range(window)] # 시가
close = [y_value[window-1] for i in range(window-1)] + y_value[window-1:] # 종가
high_df = df.rolling(window=window).max() # 고가
low_df = df.rolling(window=window).min() # 저가
size = len(result["open"])
window = 5
open = [result["open"][i] for i in range(0, size, window)]
close = [result["close"][i-1] for i in range(window-1, size, window)]
for i in range(len(open)-len(close)):
close.append(result["close"][len(result["close"])-1])
high = [max(result["high"][i:i+window]) for i in range(0, size, window)]
low = [min(result["low"][i:i+window]) for i in range(0, size, window)]
high, low, upper, lower = [], [], [], []
for i in range(len(high_df)):
upper, lower = [], []
for i in range(len(upper_df)):
if i < window:
high.append(high_df.values[window - 1][0])
low.append(low_df.values[window - 1][0])
upper.append(upper_df.values[window - 1][0])
lower.append(lower_df.values[window - 1][0])
else:
high.append(high_df.values[i][0])
low.append(low_df.values[i][0])
upper.append(upper_df.values[i][0])
lower.append(lower_df.values[i][0])
open_temp = [open[i] for i in range(len(open)) if i % window == 0]
high_temp = [high[i] for i in range(len(high)) if i % window == 0]
low_temp = [low[i] for i in range(len(low)) if i % window == 0]
close_temp = [close[i] for i in range(len(close)) if i % window == 0]
vol_temp = [vol[i] for i in range(len(vol)) if i % window == 0]
point_temp = [point[i] for i in range(len(point)) if i % window == 0]
upper_temp = [upper[i] for i in range(len(upper)) if i % window == 0]
lower_temp = [lower[i] for i in range(len(lower)) if i % window == 0]
point_temp = [result["time"][i] for i in range(size) if i % window == 0]
upper_temp = [upper[i] for i in range(size) if i % window == 0]
lower_temp = [lower[i] for i in range(size) if i % window == 0]
vol_temp = [sum(result["vol"][i:window]) for i in range(0, size, window)]
temp = {"Open": open_temp, "High": high_temp, "Low": low_temp, "Close": close_temp, "Volume": vol_temp, "Date": point_temp}
temp = {"Open": open, "High": high, "Low": low, "Close": close, "Volume": vol_temp, "Date": point_temp}
data = pd.DataFrame(temp)
df_final_time = pd.DatetimeIndex(point_temp)
data.index = df_final_time
return data, upper_temp, lower_temp
# 살 시점인지 체크
# 볼린저밴드 하단에 연속으로 같은 가격이 왔을 때,
# 해당 하단 가격 + 5원에 매수를 시도함
check = False
buy_line = [-1 for i in range(len(lower_temp))]
for i in range(3, len(lower_temp)):
for j in range(i-3, i):
if (low[j] < lower_temp[j]) and (low[i] < lower_temp[i] and low[j] == low[i]):
#buy_line[i] = low[i]
check = True
break
if check and i < len(lower_temp) - 1:
buy_line[i+1] = low[i] + 5
check = False
def buyRealTime(self, stock_code, day):
result = {"check": set(),
"time": [],
"close": [],
"vol": []}
# 팔 시점 체크
# 산 가격에 5원 위로 매도를 건다.
sell_line = [-1 for i in range(len(lower_temp))]
for i in range(len(buy_line)):
if buy_line[i] > 0:
for j in range(i+1, len(buy_line)):
# 5원 이득을 보고 판다.
if close[j] >= buy_line[i] + 5:
sell_line[j] = buy_line[i] + 5
break
return data, upper_temp, lower_temp, buy_line, sell_line
#self.getRealTime(stock_code, day, result)
self.getCSV("data_s_1.csv", day, result)
self.getCSV("data_s_2.csv", day, result)
data, upper, lower = self.analyze(result)
def draw(self, data, upper, lower, buy_line, sell_line):
# 그래프 설정을 위한 변수를 생성한다.
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'])
fig = plt.figure(figsize=(10, 10))
ax = fig.add_subplot(111)
"""
# 이동평균선 그리기
ax.plot(upper, label='upper', linewidth=1.5)
ax.plot(lower, label='lower', linewidth=1.5)
# 참고) https://pypi.org/project/mplfinance/
mc = mpf.make_marketcolors(up='red', down='blue', inherit=True)
style_final = mpf.make_mpf_style(marketcolors=mc)
mpf.plot(data, ax=ax, style=style_final)
plt.grid()
plt.show()
"""
buy_colors = []
for i in range(len(buy_line)):
if buy_line[i] < 0:
buy_colors.append("#ffffff")
buy_line[i] = 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] = 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=upper, name="upper", line_color='#8B4513')
bolinger_lower = go.Scatter(x=data['Date'], y=lower, name="lower", line_color='#8B4513')
candle_stick = go.Candlestick(x=data['Date'], open=data['Open'], high=data['High'], low=data['Low'], close=data['Close'])
fig = go.Figure(data=[candle_stick, bolinger_upper, bolinger_lower])
fig.update_layout(title="2x")
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')
# 그래프를 그린다.
fig = go.Figure(data=[candle_stick, bolinger_upper, bolinger_lower, buy_check, sell_check])
fig.update_layout(title=day + "_2x")
fig.show()
return
def simulate(self, stock_code, day):
result = {"check": set(),
"time": [],
"open": [],
"close": [],
"high": [],
"low": [],
"vol": []}
# 데이터를 가지고 온다.
self.getCSV(day+".csv", day, result)
# 가져온 만큼 데이터를 누적해서 파일로 작성한다.
self.write(day, result)
# 분석을 통해서 볼린저밴드 상/하단을 계산한다.
data, upper, lower, buy_line, sell_line = self.analyze(result)
# 그래프를 그린다.
self.draw(data, upper, lower, buy_line, sell_line)
return
def buyRealTime(self, stock_code, day):
result = {"check": set(),
"time": [],
"open": [],
"close": [],
"high": [],
"low": [],
"vol": []}
# 데이터를 가지고 온다.
self.getRealTime(stock_code, day, result)
# 가져온 만큼 데이터를 누적해서 파일로 작성한다.
self.write(day, result)
# 분석을 통해서 볼린저밴드 상/하단을 계산한다.
data, upper, lower, buy_line, sell_line = self.analyze(result)
# 그래프를 그린다.
self.draw(data, upper, lower, buy_line, sell_line)
return
@@ -417,13 +496,30 @@ if __name__ == "__main__":
stock_code = "252670"
day = datetime.today().strftime("%Y%m%d")
day = '20210917'
hts = HTS()
#hts.all_stocks()
#hts.getChartData(stock_code)
#hts.currentStock(stock_code)
hts.printStockData(stock_code, day)
#hts.printStockData(stock_code, day)
"""
day = '20210909'
hts.simulate(stock_code, day)
day = '20210910'
hts.simulate(stock_code, day)
day = '20210913'
hts.simulate(stock_code, day)
day = '20210914'
hts.simulate(stock_code, day)
day = '20210915'
hts.simulate(stock_code, day)
day = '20210916'
hts.simulate(stock_code, day)
day = '20210917'
hts.simulate(stock_code, day)
"""
hts.buyRealTime(stock_code, day)
#hts.buyRealTime(stock_code, day)
print ("done...")