이하영

면담확인서

......@@ -26,6 +26,12 @@ class Simulator_Api:
self.buy_algorithm=1
self.sell_algorithm=1
# 투자에서 사용할 변수 설정
self.per_invest=1000000 # 한 항목 당 구매할 금액
self.sell_point=10 # 매도 수익률
self.limit_money=1000000 # 최소로 남겨놓을 금액
# 특정 데이터베이스 내에 특정 테이블이 존재하는지 확인하는 함수
def is_table_exist(self,db_name,table_name):
query="select 1 from information_schema.tables where table_schema='%s' and table_name='%s'"
......
from sqlalchemy import *
from Open_Api import *
from collections import OrderedDict
from pandas import DataFrame
from open_api import *
from daily_info import *
from stock_info import *
from Daily_Info import *
from Stock_Info import *
import config
class CollectorApi():
class Collector_Api():
def __init__(self):
self.open_api=OpenApi()
self.open_api=Open_Api()
self.engine_bot=self.open_api.engine_bot
self.set_variable()
# 변수 설정
def set_variable(self):
self.open_api.sort="collector"
self.stock_info=StockInfo(config.real_bot,config.real_stockInfo,config.real_dailyInofo)
self.daily_info=DailyInfo()
def update_code(self):
print("update code")
query = "select code_update,jango_data_db_check, possessed_item, today_profit, final_chegyul_check, " \
"db_to_buy_list,today_buy_list, daily_crawler , min_crawler, daily_buy_list " \
"from setting_data limit 1"
result=self.engine_bot.execute(query).fetchall()
self.open_api.use="collector"
self.stock_info=Stock_Info(config.real_bot_name,config.real_dailyInfo_name,config.real_stockInfo_name)
self.daily_info=Daily_Info()
print(result)
def code_update_check(self):
query="select code_update,balance_to_db,posses_stocks,today_profit,contract_check,db_to_daily_info," \
"today_buy_list,stock_info,min_info,daily_info from setting_data"
result=self.engine_bot.execute(query).fetchall()
if result[0][0]!=self.open_api.today():
self.open_api.check_balance()
# 오늘 날짜에 종목리스트가 업데이트 되지 않았다면 업데이트를 실행
if result[0][0]!=self.open_api.today:
self.open_api.get_balance()
self.get_code_list()
# 계좌정보 업데이트
if result[0][1]!=self.open_api.today or result[0][2]!=self.open_api.today:
self.check_balance()
self.open_api.set_per_invest()
# 현재 보유종목 테이블 업데이트
if result[0][2]!=self.open_api.today:
self.open_api.get_posses_item()
self.open_api.setting_data_posses_stock()
if result[0][3]!=self.open_api.today:
self.update_today_profit_list()
if result[0][7]!=self.open_api.today:
self.check_daily_info()
# 코스피, 코스닥 리스트 확인 및 데이터베이스 업데이트
def get_code_list(self):
self.stock_info.get_item_kospi()
self.stock_info.get_item_kosdaq()
stock_data=OrderedDict(
kospi=self.stock_info.kospi_list,
kosdaq=self.stock_info.kosdaq_list
)
for s_type,data in stock_data.items():
stock_data[s_type]=self.create_stock_table(data,s_type)
stock_all=stock_data['kospi'].append(stock_data['kosdaq'],ignore_index=True)
self.create_stock_table(stock_all,"all")
query="update setting_data set code_update='%s'"
self.engine_bot.execute(query%(self.open_api.today))
# kospi, kosdaq 주식 종목을 저장하는 테이블 생성
def create_stock_table(self,data,type):
checking=['kospi','kosdaq']
stock_df=DataFrame()
stock_df['code']=data['code']
stock_list=list()
# 주식 code를 이용하여 실제 kiwoom 증권에서 사용하는 주식이름으로 변경
for kind in data.itertuples():
kiwoom_name=self.open_api.dynamicCall("GetMasterCodeName(QString)",kind.code).strip()
stock_list.append(kiwoom_name)
stock_df['code_name']=stock_list
stock_df['check_item']=0
if type in checking:
stock_df=stock_df[stock_df['code_name'].map(len)>0]
if type=="all":
stock_df['check_stock']="0"
stock_df['check_min']="0"
# 데이터 타입을 설정
# code, code_name 칼럼은 Text. check_item 칼럼은 Integer
dtypes=dict(zip(list(stock_df.columns),[Text]*len(stock_df.columns)))
dtypes['check_item']=Integer
table_name='stock_'+str(type)
stock_df.to_sql(table_name,self.open_api.engine_daily,if_exists='replace',dtype=dtypes)
return stock_df
def check_balance(self):
self.open_api.reset_opw00018_output()
# 예수금 상세현황 요청
self.open_api.set_input_value("계좌번호",self.open_api.account_no)
self.open_api.set_input_value("비밀번호입력매체구분",00)
self.open_api.set_input_value("조회구분",1)
self.open_api.comm_rq_data("opw00001_req","opw00001",0,"2000")
# 계좌평가 잔고내역 요청
self.open_api.set_input_value("계좌번호",self.open_api.account_no)
self.open_api.comm_rq_data("opw00018_req","opw00018",0,"2000")
while self.open_api.remained_data:
self.open_api.set_input_value("계좌번호",self.open_api.account_no)
self.open_api.comm_rq_data("opw00018_req","opw00018",2,"2000")
# 일자별 실현손익 요청
self.open_api.set_input_value("계좌번호",self.open_api.account_no)
self.open_api.set_input_value("시작일자","20170101")
self.open_api.set_input_value("종료일자",self.open_api.today)
self.open_api.comm_rq_data("opt10074_req","opt10074",0,"0329")
while self.open_api.remained_data:
self.open_api.set_input_value("계좌번호", self.open_api.account_no)
self.open_api.set_input_value("시작일자", "20170101")
self.open_api.set_input_value("종료일자", self.open_api.today)
self.open_api.set_input_value("구분","0")
self.open_api.comm_rq_data("opt10074_req", "opt10074", 2, "0329")
self.create_balance_table()
# balance_data 테이블 생성
def create_balance_table(self):
self.total_invest=int(self.open_api.deposit)+int(self.open_api.total_purchase)
balance_data={'id':[],'date':[],'total_asset':[],'today_profit':[],"total_profit":[],
'total_invest':[],'deposit':[],'total_purchase':[],'total_evaluation':[],'today_invest':[],
'today_rate':[],'estimated_asset':[]}
balance_cols=['date','today_earning_rate','total_asset','deposit',
'today_profit','total_profit','today_invest','total_invest',
'total_purchase','today_evaluation','today_sell_count',
'today_rate','estimated_asset','sell_point','per_invest','limit_money',
'today_buy_count','today_sell_count','total_posses_count','today_buy_price','today_sell_price'
]
balance=DataFrame(balance_data,columns=balance_cols,index=balance_data['id'])
balance.loc[0,'date']=self.open_api.today
balance.loc[0,'today_profit']=self.open_api.today_profit
balance.loc[0,'total_profit']=self.open_api.total_profit
balance.loc[0,'total_invest']=self.open_api.total_invest
balance.loc[0,'deposit']=self.open_api.deposit
balance.loc[0,'total_purchase']=self.open_api.total_purchase
balance.loc[0,'total_evaluation']=self.open_api.total_evaluated_price
balance.loc[0,'today_invest']=self.open_api.total_valuation
balance.loc[0,'today_rate']=float(self.open_api.earning_rate/self.open_api.mod_classify)
balance.loc[0,'estimate_asset']=self.open_api.estimated_deposit
balance.loc[0,'sell_point']=self.open_api.simul_api.sell_point
balance.loc[0,'per_invest']=self.open_api.per_invest
balance.loc[0,'limit_money']=self.open_api.simul_api.limit_money
# balance_data 테이블 생성
balance.to_sql('balance_data', self.engine_bot, if_exists='append')
query = "select date from balance_data"
rows = self.engine_bot.execute(query).fetchall()
for i in range(len(rows)):
# today_earning_rate
query = "update balance_data " \
"set " \
"today_earning_rate =round(today_profit / total_invest * '%s',2) WHERE date='%s'"
self.engine_bot.execute(query % (100, rows[i][0]))
# today_buy_count
query = "UPDATE balance_data " \
"SET " \
"today_buy_count=" \
"(select count(*) " \
"from " \
"(select code from transaction_history where buy_date like '%s' group by code )) " \
"WHERE date='%s'"
self.engine_bot.execute(query % (rows[i][0] + "%%", rows[i][0]))
# today_sell_count
query="UPDATE balance_data " \
"SET " \
"today_sell_count=" \
"(select count(*) " \
"from " \
"(select code from transaction_history" \
"where buy_date like '%s' and sell_date is not null group by code) temp) " \
"WHERE date='%s'"
self.engine_bot.execute(query % (rows[i][0] + "%%", rows[i][0]))
# today_sell_price
query="UPDATE balance_data " \
"SET" \
"today_sell_price=" \
"(select sum(*) " \
"from " \
"(select sell_price from transaction_history " \
"where sell_date like '%s')" \
"where date='%s'"
self.engine_bot.execute(query%(rows[i][0])+"%%",rows[i][0])
# today_buy_price
query="UPDATE balance_data " \
"SET" \
"today_sell_price=" \
"(select sum(*) " \
"from " \
"(select purchase_price from transaction_history " \
"where sell_date like '%s')" \
"where date='%s'"
self.engine_bot.execute(query%(rows[i][0])+"%%",rows[i][0])
# total_posses_count
query="UPDATE balance_data " \
"SET" \
"total_posses_count=" \
"(select count(*) " \
"from" \
"transaction_history where sell_date is Null)" \
"where date='%s'"
self.engine_bot.execute(query%(rows[i][0]))
sql = "UPDATE setting_data SET balance_to_db='%s' limit 1"
self.engine_bot.execute(sql % (self.open_api.today))
def is_table_exist(self,db_name,table_name):
query="select 1 from information_schema.tables where table_schema='{}' and table_name='{}'"
result=self.open_api.engine_minute.execute(query.format(db_name,table_name)).fetchall()
if len(result)==1:
return True
else:
return False
def update_today_profit_list(self):
self.open_api.reset_opt10073_output()
self.open_api.set_input_value("계좌번호",self.open_api.account_no)
self.open_api.set_input_value("시작일자",self.open_api.today)
self.open_api.set_input_value("종료일자",self.open_api.today)
self.open_api.comm_rq_data("opt10073_req","opt10073",0,"0328")
while self.open_api.remained_data:
self.open_api.set_input_value("계좌번호",self.open_api.account_no)
self.open_api.comm_rq_data("opt10073_req","opt10073",2,"0328")
today_profit_item_temp = {'date': [], 'code': [], 'code_name': [], 'amount': [], 'today_profit': [],
'earning_rate': []}
today_profit_item = DataFrame(today_profit_item_temp,
columns=['date', 'code', 'code_name', 'amount', 'today_profit',
'earning_rate'])
item_count = len(self.open_api.opt10073_output['multi'])
for i in range(item_count):
row = self.open_api.opt10073_output['multi'][i]
today_profit_item.loc[i, 'date'] = row[0]
today_profit_item.loc[i, 'code'] = row[1]
today_profit_item.loc[i, 'code_name'] = row[2]
today_profit_item.loc[i, 'amount'] = int(row[3])
today_profit_item.loc[i, 'today_profit'] = float(row[4])
today_profit_item.loc[i, 'earning_rate'] = float(row[5])
if len(today_profit_item) > 0:
today_profit_item.to_sql('today_profit_list', self.engine_bot, if_exists='append')
query = "UPDATE setting_data SET today_profit='%s' limit 1"
self.engine_bot.execute(query % (self.open_api.today))
def check_daily_info(self):
self.update_daily_info()
query="update setting_data set daily_info='%s'"
self.engine_bot.execute(query%(self.open_api.today))
def update_daily_info(self):
query="select code,code_name,check_stock from stock_all"
code_list=self.open_api.engine_daily.execute(query).fetchall()
num=len(code_list)
query="update stock_all set check_stock='%s' where code='%s'"
for i in range(num):
if int(code_list[i][2] in (1,3)):
continue
code=code_list[i][0]
code_name=code_list[i][1]
check_item_sort=self.set_minute_info_table(code,code_name)
self.open_api.engine_daily.execute(query%(check_item_sort,code))
def set_minute_info_table(self,code,code_name):
df=self.open_api.
def set_db_minute_info(self):
print("Make Minute Info Database")
query="select code,code_name from stock_all"
target=self.open_api.engine_dInfo.execute(query).fetchall()
print(target)
app = QApplication(sys.argv)
c=CollectorApi()
c.update_code()
\ No newline at end of file
app=QApplication(sys.argv)
c=Collector_Api()
c.get_code_list()
\ No newline at end of file
......
from sqlalchemy import *
from open_api import *
from daily_info import *
from stock_info import *
import config
class CollectorApi():
def __init__(self):
self.open_api=OpenApi()
self.engine_bot=self.open_api.engine_bot
def set_variable(self):
self.open_api.sort="collector"
self.stock_info=StockInfo(config.real_bot,config.real_stockInfo,config.real_dailyInofo)
self.daily_info=DailyInfo()
def update_code(self):
print("update code")
query = "select code_update,jango_data_db_check, possessed_item, today_profit, final_chegyul_check, " \
"db_to_buy_list,today_buy_list, daily_crawler , min_crawler, daily_buy_list " \
"from setting_data limit 1"
result=self.engine_bot.execute(query).fetchall()
print(result)
if result[0][0]!=self.open_api.today():
self.open_api.check_balance()
self.get_code_list()
def set_db_minute_info(self):
print("Make Minute Info Database")
query="select code,code_name from stock_all"
target=self.open_api.engine_dInfo.execute(query).fetchall()
print(target)
app = QApplication(sys.argv)
c=CollectorApi()
c.update_code()
\ No newline at end of file
import datetime
from sqlalchemy import *
import pandas as pd
from pandas import DataFrame
import config
class DailyInfo():
class Daily_Info():
def __init__(self):
self.date_setting()
self.engine_setting()
self.create_stocks()
self.set_variable()
# 날짜 정보 설정
def date_setting(self):
def set_variable(self):
self.today=datetime.datetime.today().strftime("%Y%m%d")
self.today_time=datetime.datetime.today().strftime("%Y%m%d%H%M")
self.start_date=config.start_buying
# 데이터베이스 엔진 설정
def engine_setting(self):
self.engine_daily=create_engine(
"mysql+pymysql://" + config.db_id + ":" + config.db_pw + "@" + config.db_ip + ":" + config.db_port +
"/daily_info", encoding='utf-8')
......@@ -25,6 +19,13 @@ class DailyInfo():
"mysql+pymysql://" + config.db_id + ":" + config.db_pw + "@" + config.db_ip + ":" + config.db_port +
"/stock_info", encoding='utf-8')
# 지정한 날짜부터 현재까지의 날짜 리스트를 반환
# 모든 지정한 날짜에 대해 정확한 값을 반환하기 위해
# 한국에서 가장 오래된 상장기업 중 하나인 'CJ대한통운' 테이블을 활용한다
def set_date_rows(self):
query="select date from 'CJ대한통운' where date>=%s group by date"
self.date_rows=self.engine_stock.execute(query%self.start_date)
# date에 해당하는 이름을 가진 테이블이 daily_info 데이터베이스 안에 존재하는지 확인하는 함수
def is_date_table_exist(self,date):
query = "select 1 from information_schema.tables where table_schema ='daily_info' and table_name = '%s'"
......@@ -34,19 +35,21 @@ class DailyInfo():
else:
return True
# 날짜에 해당하는 테이블 생성
def create_daily_table(self):
print("setting daily_info database!!")
self.get_date_list()
self.set_date_rows()
self.get_all_stock_list()
for date in self.date_list:
for date in self.date_rows:
if not self.is_date_table_exist(date):
print(date,"테이블이 존재하지 않습니다. 테이블을 생성합니다")
daily_list=list()
for i in range(len(self.all_list)):
code_name=self.all_list.loc[i][0]
code=self.all_list.loc[i][1]
for i in range(len(self.stock_all)):
code_name=self.stock_all.loc[i][0]
code=self.stock_all.loc[i][1]
if self.is_stock_table_exist(code,code_name):
query="select * from {} where date='{}' group by date"
......@@ -75,70 +78,10 @@ class DailyInfo():
])
df.to_sql(name=date,con=self.engine_daily,if_exists='replace')
# 지정한 날짜부터 현재까지의 날짜 리스트를 반환
# 모든 지정한 날짜에 대해 정확한 값을 반환하기 위해
# 한국에서 가장 오래된 상장기업 중 하나인 'CJ대한통운' 테이블을 활용한다
def get_date_list(self):
query="select date from 'CJ대한통운' where date>=%s group by date"
self.date_list=self.engine_stock.execute(query%self.start_date)
print(self.date_list)
# 코스피 주식 리스트 저장
def get_item_kospi(self):
print("get_item_kospi!!")
self.kospi_list = pd.read_html(
'http://kind.krx.co.kr/corpgeneral/corpList.do?method=download&searchType=13&marketType=stockMkt',
header=0)[0]
self.kospi_list.종목코드 = self.kospi_list.종목코드.map('{:06d}'.format)
self.kospi_list = self.kospi_list[['회사명', '종목코드']]
self.kospi_list = self.kospi_list.rename(columns={'회사명': 'code_name', '종목코드': 'code'})
# 코스닥 주식 리스트 저장
def get_item_kosdaq(self):
print("get_item_kosdaq!!")
self.kosdaq_list = pd.read_html(
'http://kind.krx.co.kr/corpgeneral/corpList.do?method=download&searchType=13&marketType=kosdaqMkt',
header=0)[0]
self.kosdaq_list.종목코드 = self.kosdaq_list.종목코드.map('{:06d}'.format)
self.kosdaq_list = self.kosdaq_list[['회사명', '종목코드']]
self.kosdaq_list = self.kosdaq_list.rename(columns={'회사명': 'code_name', '종목코드': 'code'})
# 코스피 테이블 생성
def create_kospi_table(self):
self.get_item_kospi()
table_kospi='stock_kospi'
query="select 1 from information_schema.tables where table_schema ='daily_info' and table_name = '%s'"
result=self.engine_daily.execute(query%table_kospi).fetchall()
if len(result)==0:
df=DataFrame(self.kospi_list)
df.to_sql(name=table_kospi,con=self.engine_daily,if_exists='replace')
# 코스닥 테이블 생성
def create_kosdaq_table(self):
self.get_item_kosdaq()
table_kosdaq="stock_kosdaq"
query = "select 1 from information_schema.tables where table_schema ='daily_info' and table_name = '%s'"
result=self.engine_daily.execute(query%table_kosdaq).fetchall()
if len(result)==0:
df=DataFrame(self.kosdaq_list)
df.to_sql(name=table_kosdaq,con=self.engine_daily,if_exists='replace')
# 코스피 + 코스닥 테이블 생성
def create_stock_all_table(self):
self.all_list=pd.concat([self.kospi_list,self.kosdaq_list],ignore_index=True)
table_all="stock_all"
query = "select 1 from information_schema.tables where table_schema ='daily_info' and table_name = '%s'"
result=self.engine_daily.execute(query%table_all).fetchall()
if len(result)==0:
self.all_list.to_sql(name=table_all,con=self.engine_daily,if_exists='replace')
# 주식 리스트 생성
def create_stocks(self):
self.create_kospi_table()
self.create_kosdaq_table()
self.create_stock_all_table()
# 데이터베이스에 저장된 모든 주식 리스트를 가져오는 함수
def get_all_stock_list(self):
query="select code_name,code from stock_all"
self.stock_all=self.engine_daily.execute(query).fetchall()
# stock info 데이터베이스에 code_name 테이블이 존재하는지 확인하는 함수
def is_stock_table_exist(self,code,code_name):
......
......@@ -124,7 +124,7 @@ class Open_Api(QAxWidget):
self._opw00018(sRQName,sTrCode)
elif sRQName == "opt10074_req":
logger.debug("일자별실현손익요청")
self._opt10084(sRQName,sTrCode)
self._opt10074(sRQName,sTrCode)
elif sRQName == "opw00015_req":
logger.debug("위탁종합거래내역요청")
self._opw00015(sRQName,sTrCode)
......@@ -201,7 +201,7 @@ class Open_Api(QAxWidget):
# 조회요청시 TR의 Input값을 지정하는 함수
# param : sId - TR에 명시된 Input이름
# svalue - Input이름으로 지정한 값
def _set_input_value(self,sId,sValue):
def set_input_value(self,sId,sValue):
try:
self.dynamicCall("SetInputValue(QString, QString)", sId, sValue)
except Exception as e:
......@@ -213,7 +213,7 @@ class Open_Api(QAxWidget):
# sTrCode - 조회하려는 TR이름
# nPrevNext - 연속조회여부
# sScreenNo - 화면번호
def _comm_rq_data(self,sRQName,sTrData,nPrevNext,sScrNo):
def comm_rq_data(self,sRQName,sTrData,nPrevNext,sScrNo):
self.dynamicCall("CommRqData(QString, QString, int, QString", sRQName, sTrData, nPrevNext, sScrNo)
self.tr_event_loop.exec_()
......@@ -241,18 +241,27 @@ class Open_Api(QAxWidget):
# 실전투자인지 모의투자인지 여부를 확인하고 그에 해당하는 데이터베이스를 생성하는 함수
def set_variable(self):
self.config=config
self.reset_opw00018_output()
if self.account_no==self.config.real_account_no:
logger.debug("실전투자")
self.simul_num=self.config.real_num
self.set_database(self.config.real_bot_name)
self.mod_classify=100
elif self.account_no==self.config.test_account_no:
logger.debug("모의투자")
self.simul_num=self.config.test_num
self.set_database(self.config.test_bot_name)
self.mod_classify=1
else:
logger.debug("Invalid Account Number. Check the Config.py")
exit(1)
self.is_balance_null=True
self.use=False
# 데이터베이스 생성 및 엔진 설정
def set_database(self,db_name):
self.db_name=db_name
......@@ -319,12 +328,14 @@ class Open_Api(QAxWidget):
def create_setting_data(self):
df_data={"limit_money":[],"per_invest":[],"max_per_invest":[],"min_per_invest":[],"set_per_invest":[],
"code_update":[],"today_finish":[],"balance_to_db":[],"posses_stocks":[],"today_profit":[],
"contract_check":[],"db_to_daily_info":[],"today_buy_list":[],"stock_info":[],"daily_info":[]}
"code_update":[],"today_finish":[],"balance_to_db":[],"posses_stocks":[],"today_profit":[],
"contract_check":[],"db_to_daily_info":[],"today_buy_list":[],"stock_info":[],"min_info":[],
"daily_info":[]}
df_setting_data=DataFrame(df_data,
columns=['limit_money','per_invest','max_per_invest','min_per_invest','set_per_invest',
'code_update','today_finish','balance_to_db','posses_stocks','today_profit',
'contract_check','db_to_daily_info','today_buy_list','stock_info','daily_info'])
'contract_check','db_to_daily_info','today_buy_list','stock_info','min_info',
'daily_info'])
df_setting_data.loc[0,'limit_money']=int(0)
df_setting_data.loc[0,'per_invest']=int(0)
......@@ -342,10 +353,13 @@ class Open_Api(QAxWidget):
df_setting_data.loc[0,'db_to_daily_info']=str(0)
df_setting_data.loc[0,'today_buy_list']=str(0)
df_setting_data.loc[0,'stock_info']=str(0)
df_setting_data.loc[0,'min_info']=str(0)
df_setting_data.loc[0,'daily_info']=str(0)
df_setting_data.to_sql("setting_data",self.engine_bot,if_exists="replace")
# 시뮬레이터에서 사용할 변수들을 설정
def set_simul_variable(self):
self.latest_date=self.simul_api.get_latest_date()
if not self.simul_api.is_table_exist(self.db_name,"transaction_history"):
......@@ -354,6 +368,12 @@ class Open_Api(QAxWidget):
self.create_transaction_history(0,0,0,0,0)
self.delete_item_by_code(0)
if not self.check_per_invest():
self.set_per_invest()
else:
self.per_invest=self.get_per_invest()
self.simul_api.per_invest=self.per_invest
# transaction_history 테이블 생성 및 column 설정
def create_transaction_history(self,order_num,code,contract_check,purchase_price,rate):
logger.debug("creating transaction_history table")
......@@ -384,30 +404,55 @@ class Open_Api(QAxWidget):
else:
return False
# 데이터베이스에서 per_invest항목을 반환
def get_per_invest(self):
query="select per_invest from setting_data"
result=self.engine_bot.execute(query).fetchall()
return result[0][0]
# per_invest 항목 설정
# per_ invest : 한 종목 당 투자할 금액
def set_per_invest(self):
self.get_deposit()
self.get_balance()
self.total_invest=self.deposit+self.total_purchase
self.per_invest=self.simul_api.per_invest
query="update setting_data set per_invest='%s', set_per_invest='%s'"
self.engine_bot.execute(query%(self.per_invest,self.today))
# 예수금 조회 및 저장
def get_deposit(self):
self._set_input_value("계좌번호",self.account_no)
self._set_input_value("비밀번호입력매체구분",00)
self._set_input_value("조회구분",1)
self._comm_rq_data("opw00001_req","opw00001",0,"2000")
self.set_input_value("계좌번호",self.account_no)
self.set_input_value("비밀번호입력매체구분",00)
self.set_input_value("조회구분",1)
self.comm_rq_data("opw00001_req","opw00001",0,"2000")
# 예수금 상세현황요청 함수
def _opw00001(self,sRQName,sTrCode):
self.deposit=self._get_comm_data(sTrCode,sRQName,0,"d+2출금가능금액")
self.deposit=int(self.deposit)
# 잔고 조회 및 저장
def get_balance(self):
self._set_input_value("계좌번호",self.account_no)
self._comm_rq_data("opw00018_req","opw00018",0,"2000")
self.reset_opw00018_output()
self.set_input_value("계좌번호",self.account_no)
self.comm_rq_data("opw00018_req","opw00018",0,"2000")
# 다음페이지가 존재할 경우 계속해서 조회
while self.remained_data:
self._set_input_value("계좌번호",self.account_no)
self._comm_rq_data("opw00018_req","opw00018",2,"2000")
self.set_input_value("계좌번호",self.account_no)
self.comm_rq_data("opw00018_req","opw00018",2,"2000")
# 계좌평가 잔고내역을 저장하는 변수 초기화
def reset_opw00018_output(self):
self.opw00018_output={'single':[],'multi':[]}
# 계좌평가 잔고내역 요청
# 싱글데이터를 통해 계좌에 대한 평가 잔고 데이터를 제공
# 멀티데이터를 통해 보유 종목별 평가 잔고 데이터를 제공
def _opw00018(self,sRQName,sTrCode):
# 계좌평가 잔고 데이터 - 싱글데이터 저장
self.total_purchase=self._get_comm_data(sTrCode,sRQName,0,"총매입금액")
self.total_evaluated_price=self._get_comm_data(sTrCode,sRQName,0,"총평가금액")
self.total_valuation=self._get_comm_data(sTrCode,sRQName,0,"총평가손익금액")
......@@ -420,7 +465,134 @@ class Open_Api(QAxWidget):
self.earning_rate=float(self.earning_rate)
self.estimated_deposit=int(self.estimated_deposit)
self.opw00018_output['single'].append(self.total_purchase)
self.opw00018_output['single'].append(self.total_evaluated_price)
self.opw00018_output['single'].append(self.total_valuation)
self.opw00018_output['single'].append(self.earning_rate)
self.opw00018_output['single'].append(self.estimated_deposit)
# 종목별 평가 잔고 데이터 - 멀티데이터 저장
rows=self._get_repeat_cnt(sTrCode,sRQName)
for i in range(rows):
code=self._get_comm_data(sTrCode,sRQName,i,"종목번호")
name=self._get_comm_data(sTrCode,sRQName,i,"종목명")
quantity=self._get_comm_data(sTrCode,sRQName,i,"보유수량")
purchase_price=self._get_comm_data(sTrCode,sRQName,i,"매입가")
current_price=self._get_comm_data(sTrCode,sRQName,i,"현재가")
total_valuation=self._get_comm_data(sTrCode,sRQName,i,"평가손익")
earning_rate=self._get_comm_data(sTrCode,sRQName,i,"수익률(%)")
total_purchase=self._get_comm_data(sTrCode,sRQName,i,"매입금액")
code=code[1:]
quantity=int(quantity)
purchase_price=int(purchase_price)
current_price=int(current_price)
total_valuation=int(total_valuation)
earning_rate=float(earning_rate)
total_purchase=int(total_purchase)
self.opw00018_output['multi'].append(
[name,quantity,purchase_price,current_price,total_valuation,earning_rate,total_purchase,code]
)
# 일자별 실현 손익 요청
def _opt10074(self,sRQName,sTrCode):
self.total_profit=self._get_comm_data(sTrCode,sRQName,0,"실현손익")
self.today_profit=self._get_comm_data(sTrCode,sRQName,0,"당일매도손익")
# open_api를 통해 보유한 종목을 가져오는 함수
# 가져온 정보를 posses_item이라는 테이블에 저장
def get_posses_item(self):
item_count=len(self.opw00018_output['multi'])
posses_item_data={'date':[],'code':[],'code_name':[],'holding_amount':[],'purchase_price':[],
'present_price':[],'valuation_profit':[],'rate':[],'item_total_purchase':[]}
posses_item=DataFrame(posses_item_data,
columns=['date','code','code_name','holding_amount','purchase_price',
'present_price','valuation_profit','rate','item_total_purchase'])
for i in range(item_count):
item=self.opw00018_output['multi'][i]
posses_item.loc[i,'date']=self.today
posses_item.loc[i,'code']=item[7]
posses_item.loc[i,'code_name']=item[0]
posses_item.loc[i,'holding_amount']=int(item[1])
posses_item.loc[i,'purchase_price']=int(item[2])
posses_item.loc[i,'present_price']=int(item[3])
posses_item.loc[i,'valuation_profit']=int(item[4])
posses_item.loc[i,'rate']=float(item[5])
posses_item.loc[i,'item_total_purchase']=int(item[6])
posses_item.to_sql("posses_item",self.engine_bot,if_exists='replace')
self.contract_sync()
# 현재 소유하고 있는 종목에 대해 transaction_history 테이블을 업데이트
def contract_sync(self):
query="select code,code_name,rate from posses_item p" \
"where p.code not in (select a.code from transaction_history a" \
"where a.sell_date='0' group by a.code)" \
"group by p.code"
result=self.engine_bot.execute(query).fetchall()
for item in result:
self.set_input_value("종목코드",item.code)
self.set_input_value("조회구분",1)
self.set_input_value("계좌번호",self.account_no)
self.comm_rq_data("opt10076_req","opt10076",0,"0350")
if self.not_contract['주문구분']=="+매수":
if self.not_contract['미체결수량']==0:
contract_check=0
else:
contract_check=1
elif self.not_contract['주문구분']=='':
self.create_transaction_history(self.today,item.code,0,0,item.rate)
continue
else:
continue
self.create_transaction_history(self.not_contract['주문번호'],item.code,contract_check,self.not_contract['체결가'],item.rate)
def _opt10076(self,sRQName,sTrCode):
outputs=['주문번호','종목명','주문구분','주문가격','주문수량','체결가','체결량','미체결수량',
'당일매매수수료','당일매매세금','주문상태','매매구분','원주문번호','주문시간','종목코드']
self.not_contract={}
for key in outputs:
if key not in ['주문번호','원주문번호','주문시간','종목코드']:
self.not_contract[key]=int(self._get_comm_data(sTrCode,sRQName,0,key))
self.not_contract[key]=self._get_comm_data(sTrCode,sRQName,0,key)
# posses_item 테이블을 업데이트 했을 경우 setting data 테이블에 업데이트 한 날짜를 표시
def setting_data_posses_stock(self):
query="update setting_data set posses_stocks='%s'"
self.engine_bot.execute(query%self.today)
def reset_opt10073_output(self):
self.opt10073_output={'single':[],'multi':[]}
def _opt10073(self,sRQName,sTrCode):
rows=self._get_repeat_cnt(sTrCode,sRQName)
for i in range(rows):
date=self._get_comm_data(sTrCode,sRQName,i,"일자")
code=self._get_comm_data(sTrCode,sRQName,i,"종목코드")
code_name=self._get_comm_data(sTrCode,sRQName,i,"종목명")
amount=self._get_comm_data(sTrCode,sRQName,i,"체결량")
today_profit=self._get_comm_data(sTrCode,sRQName,i,"당일매도손익")
earning_rate=self._get_comm_data(sTrCode,sRQName,i,"손익율")
code=code.lstrip('A')
self.opt10073_output['multi'].append([date,code,code_name,amount,today_profit,earning_rate])
if __name__=="__main__":
app=QApplication(sys.argv)
a=Open_Api()
a.get_balance()
\ No newline at end of file
a=Open_Api()
\ No newline at end of file
......
from sqlalchemy import *
from PyQt5.QtCore import *
import datetime
import pandas as pd
import config
class StockInfo():
def __init__(self,db_name,stock_info_name,daily_info_name):
class Stock_Info():
def __init__(self,db_name,daily_db_name,stock_db_name):
if db_name!=0:
self.db_name=db_name
self.stockInfo_name=stock_info_name
self.dailyInfo_name=daily_info_name
self.daily_db_name=daily_db_name
self.stock_db_name=stock_db_name
self.engine=create_engine(
"mysql+pymysql://" + config.db_id + ":" + config.db_pw + "@" + config.db_ip + ":" + config.db_port +
......@@ -24,11 +25,32 @@ class StockInfo():
self.mkt_end_time=QTime(15,31,0)
self.today=datetime.datetime.today().strftime("%Y%m%d")
self.today_time=datetime.datetime.today().strftime("%Y%m%d%H%M")
# 현재 시간이 주식장이 열린 시간인지 확인하는 함수
def time_check(self):
# 현재 시간이 주식 장이 열린 시간인지 확인하는 함수
def check_time(self):
self.current_time=QTime.currentTime()
if (self.current_time>self.mkt_start_time and self.current_time<self.mkt_end_time):
if self.current_time>self.mkt_start_time and self.current_time<self.mkt_end_time:
return True
else:
return False
\ No newline at end of file
return False
# 코스피 주식 리스트 저장
def get_item_kospi(self):
self.kospi_list = pd.read_html(
'http://kind.krx.co.kr/corpgeneral/corpList.do?method=download&searchType=13&marketType=stockMkt',
header=0)[0]
self.kospi_list.종목코드 = self.kospi_list.종목코드.map('{:06d}'.format)
self.kospi_list = self.kospi_list[['회사명', '종목코드']]
self.kospi_list = self.kospi_list.rename(columns={'회사명': 'code_name', '종목코드': 'code'})
# 코스닥 주식 리스트 저장
def get_item_kosdaq(self):
self.kosdaq_list = pd.read_html(
'http://kind.krx.co.kr/corpgeneral/corpList.do?method=download&searchType=13&marketType=kosdaqMkt',
header=0)[0]
self.kosdaq_list.종목코드 = self.kosdaq_list.종목코드.map('{:06d}'.format)
self.kosdaq_list = self.kosdaq_list[['회사명', '종목코드']]
self.kosdaq_list = self.kosdaq_list.rename(columns={'회사명': 'code_name', '종목코드': 'code'})
\ No newline at end of file
......
No preview for this file type