이하영

ui

No preview for this file type
No preview for this file type
No preview for this file type
No preview for this file type
......@@ -59,7 +59,7 @@ def lstm_algorithm(dataset,ai_setting):
msg += f' {ratio:.2f}% ⯆ '
print(msg, end=' ')
return ai_setting['ratio_cut']
return ai_setting['ratio_cut']>=ratio
def create_training_engine(db_name):
......@@ -78,7 +78,7 @@ def ai_filter(ai_filter_num,engine,until=datetime.datetime.today()):
if ai_filter_num == 1:
ai_setting = {
"n_steps": 100, # 시퀀스 데이터를 몇개씩 담을지 설정
"lookup_step": 30, # 단위 : 몇 일(분) 뒤의 종가를 예측 할 것 인지
"lookup_step": 1, # 단위 : 몇 일(분) 뒤의 종가를 예측 할 것 인지
"test_size": 0.2, # train 범위
"n_layers": 4, # LSTM layer 개수
"units": 50, # LSTM neurons 개수
......@@ -87,7 +87,7 @@ def ai_filter(ai_filter_num,engine,until=datetime.datetime.today()):
"optimizer": "adam", # optimizer : 최적화 알고리즘 선택
"batch_size": 64, # 각 학습 반복에 사용할 데이터 샘플 수
"epochs": 400, # 몇 번 테스트 할지
"ratio_cut": 3, # 단위:(%) lookup_step 기간 뒤 ratio_cut(%) 만큼 증가 할 것이 예측 된다면 매수
"ratio_cut": 2, # 단위:(%) lookup_step 기간 뒤 ratio_cut(%) 만큼 증가 할 것이 예측 된다면 매수
"table": "daily_craw", # 분석 시 daily_craw(일별데이터)를 이용 할지 min_craw(분별데이터)를 이용 할지
"is_used_predicted_close" : True # ratio(예상 상승률) 계산 시 예측 그래프의 close 값을 이용 할 경우 True,
# 실제 close 값을 이용할 시 False
......@@ -109,6 +109,7 @@ def ai_filter(ai_filter_num,engine,until=datetime.datetime.today()):
feature_columns = ["close", "volume", "open", "high", "low"]
filtered_list = []
for code_name in buy_list:
code_name=code_name[0]
sql = """
SELECT {} FROM `{}`
WHERE STR_TO_DATE(date, '%Y%m%d%H%i') <= '{}'
......
import pymysql
pymysql.install_as_MySQLdb()
import sys
from library.collector_api import *
import library.cf
class Collector:
def __init__(self):
def __init__(self,num=1):
self.set_simul_num(num)
self.collector_api=collector_api()
def collecting(self):
self.collector_api.code_update_check()
def set_simul_num(self,num):
library.cf.test_num=num
def set_real_num(self,num=1):
library.cf.real_num=num
if __name__=="__main__":
app=QApplication(sys.argv)
c=Collector()
......
import sys
from PyQt5.QtWidgets import *
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from sqlalchemy import create_engine
from library.cf import *
class Graph(QDialog):
def __init__(self,num=1):
QDialog.__init__(self,None)
self.setGeometry(200,200,1000,800)
self.engine1 = create_engine("mysql+pymysql://" + db_id + ":" + db_pw + "@" +
db_ip + ":" + db_port + "/simul1", encoding='utf-8')
self.engine2 = create_engine("mysql+pymysql://" + db_id + ":" + db_pw + "@" +
db_ip + ":" + db_port + "/simul2", encoding='utf-8')
self.engine3 = create_engine("mysql+pymysql://" + db_id + ":" + db_pw + "@" +
db_ip + ":" + db_port + "/simul3", encoding='utf-8')
self.engine4 = create_engine("mysql+pymysql://" + db_id + ":" + db_pw + "@" +
db_ip + ":" + db_port + "/simul4", encoding='utf-8')
date,data=self.getAlgorithm(num)
col=""
if num==1:
col="red"
elif num==2:
col="blue"
elif num==3:
col="green"
elif num==4:
col="purple"
N = len(data)
value = data
ind = np.arange(N)
width = 0.35
self.fig = plt.Figure()
ax = self.fig.add_subplot(111)
ax.bar(ind, value, width,color=col)
ax.set_xticks(ind + width / 20)
ax.set_xticklabels(date)
canvas = FigureCanvas(self.fig)
canvas.draw()
lay=QVBoxLayout()
self.setLayout(lay)
lay.addWidget(canvas)
canvas.show()
def getdata(self,engine):
query="select date, sum_valuation_profit from jango_data order by date"
result=engine.execute(query).fetchall()
date=list()
data=list()
for i in range(len(result)):
date.append(result[i][0])
data.append(int(result[i][1]))
return date,data
def getAlgorithm(self,num):
if num==1:
engine=self.engine1
elif num==2:
engine=self.engine2
elif num==3:
engine=self.engine3
elif num==4:
engine=self.engine4
else:
sys.exit()
date,data=self.getdata(engine)
return date,data
if __name__=="__main__":
app=QApplication(sys.argv)
main_dialog=Graph()
main_dialog.show()
app.exec_()
......@@ -75,7 +75,7 @@ def load_data(df,n_steps=100,lookup_step=1,test_size=0.2,shuffle=True):
last_sequence=list(sequences)+list(last_sequence)
last_sequence=np.array(pd.DataFrame(last_sequence).shift(-1).dropna())
result['last_sequence']=last_sequence
X,y=[],[]
for seq,target in sequence_data:
......
......@@ -564,28 +564,101 @@ class simulator_api:
# 다음날 매수 할 종목의 리스트를 선정하는 함수
def db_to_realtime_daily_buy_list(self,date_rows_today,date_rows_yesterday,i):
realtime_daily_buy_list=None # 다음날 매수할 종목 리스트를 저장하는 변수
realtime_daily_buy_list=list() # 다음날 매수할 종목 리스트를 저장하는 변수
if self.db_to_realtime_daily_buy_list_num in [5,6,7,8]:
self.use_ai=True
# (5,20) 골든크로스
if self.db_to_realtime_daily_buy_list_num == 1:
if self.db_to_realtime_daily_buy_list_num in [1,5]:
query=f"select * from `{date_rows_yesterday}` " \
f"where yes_clo20>yes_clo5 and clo5>clo20 and close<'{self.invest_unit}' group by code"
realtime_daily_buy_list=self.engine_daily_buy_list.execute(query).fetchall()
# (20,60) 골든크로스
elif self.db_to_realtime_daily_buy_list_num == 2:
elif self.db_to_realtime_daily_buy_list_num in [2,6]:
query = f"select * from `{date_rows_yesterday}` " \
f"where yes_clo40 > yes_clo5 and clo5 > clo40 and close < '{self.invest_unit}' group by code"
f"where yes_clo60 > yes_clo20 and clo20 > clo60 and close < '{self.invest_unit}' group by code"
realtime_daily_buy_list = self.engine_daily_buy_list.execute(query).fetchall()
"""
# RSI
elif self.db_to_realtime_daily_buy_list_num==3:
au_query=f"select "
elif self.db_to_realtime_daily_buy_list_num in [3,7]:
realtime_daily_buy_list=list()
self.sell_list=list()
date_form=datetime.datetime.strptime(date_rows_yesterday,"%Y%m%d").date()
weeks_ago=date_form-datetime.timedelta(14)
weeks_ago=weeks_ago.strftime("%Y%m%d")
query="SELECT table_name as tname FROM information_schema.tables " \
"WHERE table_schema ='daily_craw'"
name_list=self.engine_daily_craw.execute(query).fetchall()
for i in range(len(name_list)):
name=name_list[i]
name=name[0]
au_query=f"select sum(d1_diff) from `{name}` where d1_diff>0 and " \
f"{weeks_ago}<=date and date<={date_rows_yesterday} " \
f"group by code"
au=self.engine_daily_craw.execute(au_query).fetchall()
ad_query=f"select sum(d1_diff) from `{name}` where d1_diff<0 and " \
f"{weeks_ago}<=date and date<={date_rows_yesterday} " \
f"group by code"
ad=self.engine_daily_craw.execute(ad_query).fetchall()
if len(au)==0 or len(ad)==0:
continue
au=au[0][0]
ad=ad[0][0]
au=float(au/14)
ad=float(ad/14)*(-1)
rsi=float(au/(au+ad))
if rsi<0.3:
query=f"select * from `{date_rows_yesterday}` where code_name='{name}'"
val=self.engine_daily_buy_list.execute(query).fetchall()
realtime_daily_buy_list.append(val[0])
# RMI
elif self.db_to_realtime_daily_buy_list_num==4:
elif self.db_to_realtime_daily_buy_list_num in [4,8]:
realtime_daily_buy_list = list()
self.sell_list = list()
date_form = datetime.datetime.strptime(date_rows_yesterday, "%Y%m%d").date()
weeks_ago = date_form - datetime.timedelta(14)
weeks_ago = weeks_ago.strftime("%Y%m%d")
query = "SELECT table_name as tname FROM information_schema.tables " \
"WHERE table_schema ='daily_craw'"
name_list = self.engine_daily_craw.execute(query).fetchall()
for i in range(len(name_list)):
name = name_list[i]
name = name[0]
mu_query = f"select sum(dn_diff) from `{name}` where dn_diff>0 and " \
f"{weeks_ago}<=date and date<={date_rows_yesterday} " \
f"group by code"
mu = self.engine_daily_craw.execute(mu_query).fetchall()
md_query = f"select sum(dn_diff) from `{name}` where dn_diff<0 and " \
f"{weeks_ago}<=date and date<={date_rows_yesterday} " \
f"group by code"
md = self.engine_daily_craw.execute(md_query).fetchall()
if len(mu) == 0 or len(md) == 0:
continue
mu = mu[0][0]
md = md[0][0]
mu = float(mu / 14)
md = float(md / 14) * (-1)
rmi = float(mu / (mu + md))
if rmi < 0.3:
query = f"select * from `{date_rows_yesterday}` where code_name='{name}'"
val = self.engine_daily_buy_list.execute(query).fetchall()
realtime_daily_buy_list.append(val[0])
else:
logger.error("Invalid Algorithm Setting...")
"""
# 알고리즘에 의해 선택된 항목이 존재한다면 데이터베이스에 해당 항목 업데이트
if len(realtime_daily_buy_list) > 0:
df_realtime_daily_buy_list = DataFrame(realtime_daily_buy_list,
......@@ -620,10 +693,10 @@ class simulator_api:
# 딥러닝 알고리즘을 이용
if self.use_ai:
print(date_rows_today)
from ai_trader import ai_filter
ai_filter(self.ai_num, engine=self.engine_simul, until=date_rows_yesterday)
# 모의투자 / 실전투자
else:
df_realtime_daily_buy_list['check_item'] = int(0)
......@@ -851,6 +924,7 @@ class simulator_api:
def auto_trade_sell_stock(self,date,i):
# 매도할 리스트를 저장
sell_list=self.get_sell_list(i)
print(sell_list)
for j in range(len(sell_list)):
sell_code=sell_list[j][0]
......@@ -905,9 +979,16 @@ class simulator_api:
sell_list=self.engine_simul.execute(query).fetchall()
# RSI
#elif self.sell_algorithm==3:
elif self.sell_list_num==3:
query=f"select code,rate,present_price,valuation_price from all_stocks " \
f"where sell_date='0' and (clo5<clo20 or rate<='{self.losscut_point}') group by code"
sell_list=self.engine_simul.execute(query).fetchall()
# RMI
#elif self.sell_algorithm==4:
elif self.sell_list_num==4:
query=f"select code,rate, present_price,valuation_price from all_stocks " \
f"where sell_date='0' and (clo20<clo60 or rate<='{self.losscut_point}') group by code"
sell_list=self.engine_simul.execute(query).fetchall()
else:
logger.error("Invalid sell algorithm setting...")
......
......@@ -21,7 +21,7 @@ real_daily_craw_db_name = "daily_craw"
real_daily_buy_list_db_name = "daily_buy_list"
# 시뮬레이션을 돌리기 시작할 날짜
start_daily_buy_list='20190102'
start_daily_buy_list='20150101'
# api를 최대 몇 번까지 호출 하고 봇을 끌지 설정 하는 옵션
max_api_call=998
......
......@@ -293,7 +293,7 @@ class collector_api():
# 특정 종목명(code_name)의 테이블이 존재하는 경우
if self.engine_bot.dialect.has_table(self.open_api.engine_daily_craw, code_name):
query=f"select * from {code_name} where date='{oldest_row['date']}' limit 1"
query=f"select * from `{code_name}` where date='{oldest_row['date']}' limit 1"
check_row = self.open_api.engine_daily_craw.execute(query).fetchall()
# 종목명 테이블이 존재하지 않는 경우, 종목 리스트(stock_item_all) 테이블에 check_daily_crawler=4 업데이트
else:
......
......@@ -282,7 +282,6 @@ class open_api(QAxWidget):
# 국내주식 잔고전달
elif sGubun=="1":
chegyul_fail_amount=self.get_chejan_data(902)
logger.debug("미체결 수량 : "+chegyul_fail_amount)
else:
logger.debug("Invlid _receive_chejan_data")
......@@ -325,7 +324,7 @@ class open_api(QAxWidget):
def sell_chegyul_fail_check(self,code):
query = f"UPDATE all_stocks SET chegyul_check='1' WHERE code='{code}' and sell_date = '0' " \
f"ORDER BY buy_date desc LIMIT 1"
self.engine_JB.execute(query)
self.engine_bot.execute(query)
# OnReceiveChejan()이벤트가 호출될때 체결정보나 잔고정보를 얻어오는 함수
# param : nFid - 실시간 타입에 포함된 FID
......@@ -767,7 +766,7 @@ class open_api(QAxWidget):
# daily_craw의 특정 종목 테이블에서 마지막으로 저장된 날짜를 가져오는 함수
# 저장된 데이터가 없다면 '0'문자를 반환
def get_daily_craw_db_last_date(self,code_name):
query="select date from {} order by date desc limit 1"
query="select date from `{}` order by date desc limit 1"
result=self.engine_daily_craw.execute(query.format(code_name)).fetchall()
if len(result):
return result[0][0]
......@@ -895,7 +894,7 @@ class open_api(QAxWidget):
# min_craw 테이블에서 마지막에 저장한 행의 시간(분) 정보를 가져오는 함수
def get_craw_db_last_min(self,code_name):
query = f"SELECT date from {code_name} order by date desc limit 1"
query = f"SELECT date from `{code_name}` order by date desc limit 1"
result = self.engine_craw.execute(query).fetchall()
if len(result):
return result[0][0]
......
......@@ -14,7 +14,7 @@ class Trader(QMainWindow):
self.market_start_time=QTime(9,0,0) # 장시작 시간
self.market_end_time=QTime(15,30,0) # 장마감 시간
self.buy_end_time=QTime(9,30,0) # 매수를 몇 시까지 할지
self.buy_end_time=QTime(15,31,0) # 매수를 몇 시까지 할지
# 매수 함수
def auto_trade_stock(self):
......
from collector import *
from trader import *
from graph import *
class Ui(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle("Menu Page")
self.resize(820,465)
self.using_dl=QLabel("----------* Deep Learning *------------",self)
self.using_dl.setGeometry(QRect(50,20,800,30))
self.using_dl=QRadioButton("Using Deep Learning",self)
self.using_dl.clicked.connect(self.__Rdl_Clicked)
self.using_dl.setGeometry(QRect(50,70,800,30))
self.not_using_dl=QRadioButton("Not Using Deep Learning",self)
self.not_using_dl.setGeometry(QRect(50,120,800,30))
self.not_using_dl.clicked.connect(self.__Rndl_Clicked)
self.line=QLabel("----------* Algorithm *------------",self)
self.line.setGeometry(QRect(50,170,800,30))
self.input=QLabel("Selection : ",self)
self.input.setGeometry(QRect(50,200,150,40))
self.al=QLineEdit(self)
self.al.setGeometry(QRect(200,200,150,40))
self.al1=QLabel("1. Golden/Dead Cross(5,20)",self)
self.al1.setGeometry(QRect(50,250,800,30))
self.al2=QLabel("2. Golden/Dead Cross(20,60)",self)
self.al2.setGeometry(QRect(50,300,800,30))
self.al3=QLabel("3. RSI",self)
self.al3.setGeometry(QRect(50,350,800,30))
self.al4=QLabel("4. RMI",self)
self.al4.setGeometry(QRect(50,400,800,30))
# 매매 프로그램 시작
self.btn_run=QPushButton("Trade",self)
self.btn_run.setGeometry(QRect(600,50,200,70))
self.btn_run.clicked.connect(self.__bRun_Clicked)
# 매매 후 결과 화면
self.btn_report=QPushButton("Report",self)
self.btn_report.setGeometry(QRect(600,150,200,70))
self.btn_report.clicked.connect(self.__bReport_Clicked)
# 컬렉터
self.btn_collector=QPushButton("Collector",self)
self.btn_collector.setGeometry(QRect(600,250,200,70))
self.btn_collector.clicked.connect(self.__bCollector_Clicked)
# 프로그램 종료
self.btn_exit=QPushButton("Exit",self)
self.btn_exit.setGeometry(QRect(600,350,200,70))
self.btn_exit.clicked.connect(self.__bExit_Clicked)
self.option=-1
def __Rdl_Clicked(self):
if self.using_dl.isChecked():
self.option=0
def __Rndl_Clicked(self):
if self.not_using_dl.isChecked():
self.option=4
# open selection page for rpa
def __bRun_Clicked(self):
trader = Trader()
trader.run()
def __bReport_Clicked(self):
if self.al.text() not in ['1','2','3','4']:
print("error")
else:
g=Graph(int(self.al.text()))
g.exec()
g.show()
def __bCollector_Clicked(self):
algorithm_num=0
if self.al.text()=="" or self.option==-1:
print("error")
else:
algorithm_num=self.option+int(self.al.text())
c = Collector(algorithm_num)
c.collecting()
def __bExit_Clicked(self):
self.close()
sys.exit()
if __name__=="__main__":
app = QApplication(sys.argv)
ui=Ui()
ui.show()
app.exec_()
\ No newline at end of file