김명락

final

import win32com.client
import pythoncom
import pandas as pd
import time
class XASessionEventHandler:
login_state = 0
def OnLogin(self, code, msg):
if code == "0000":
print("로그인 성공")
XASessionEventHandler.login_state = 1
else:
print("로그인 실패")
class XAQueryEventHandler:
query_state = 0
def OnReceiveData(self, code):
XAQueryEventHandler.query_state = 1
# ===================================================================================================================
instXASession = win32com.client.DispatchWithEvents("XA_Session.XASession", XASessionEventHandler)
with open('account.txt') as f:
id, passwd, cert_passwd = f.read().split()
instXASession.ConnectServer("hts.ebestsec.co.kr", 20001)
instXASession.Login(id, passwd, cert_passwd, 0, 0)
while XASessionEventHandler.login_state == 0:
pythoncom.PumpWaitingMessages()
datecut = ["20210526", "20190517", "20170426","20150421","20130409","20110407","20090413","20070404","20050404","20030326","20010316","19900305","19880616","19860926","19850316"]
res=pd.DataFrame()
for i in range(0, 14):
# ----------------------------------------------------------------------------
# T8413
# ----------------------------------------------------------------------------
instXAQueryT8413 = win32com.client.DispatchWithEvents("XA_DataSet.XAQuery", XAQueryEventHandler)
instXAQueryT8413.ResFileName = "C:\\eBEST\\xingAPI\\Res\\t8413.res"
instXAQueryT8413.SetFieldData("t8413InBlock", "shcode", 0, "207940")
instXAQueryT8413.SetFieldData("t8413InBlock", "gubun", 0, "2")
instXAQueryT8413.SetFieldData("t8413InBlock", "sdate", 0, datecut[i+1])
instXAQueryT8413.SetFieldData("t8413InBlock", "edate", 0, datecut[i])
instXAQueryT8413.SetFieldData("t8413InBlock", "comp_yn", 0, "N")
instXAQueryT8413.Request(0)
while XAQueryEventHandler.query_state == 0:
pythoncom.PumpWaitingMessages()
count = instXAQueryT8413.GetBlockCount("t8413OutBlock1")
stockdata=[]
datelist=[]
for j in range(count):
date = instXAQueryT8413.GetFieldData("t8413OutBlock1", "date", j)
open = instXAQueryT8413.GetFieldData("t8413OutBlock1", "open", j)
high = instXAQueryT8413.GetFieldData("t8413OutBlock1", "high", j)
low = instXAQueryT8413.GetFieldData("t8413OutBlock1", "low", j)
close = instXAQueryT8413.GetFieldData("t8413OutBlock1", "close", j)
vol = instXAQueryT8413.GetFieldData("t8413OutBlock1", "jdiff_vol", j)
datelist.append(date)
stockdata.append([date, open, high, low, close, vol])
df = pd.DataFrame(stockdata, columns=['날짜','시가','고가','저가','종가','거래량'], index=datelist)
print(df)
res=res.append(df)
XAQueryEventHandler.query_state = 0
time.sleep(3)
# instXAQueryT8413 = win32com.client.DispatchWithEvents("XA_DataSet.XAQuery", XAQueryEventHandler)
# instXAQueryT8413.ResFileName = "C:\\eBEST\\xingAPI\\Res\\t8413.res"
# instXAQueryT8413.SetFieldData("t8413InBlock", "shcode", 0, "005930")
# instXAQueryT8413.SetFieldData("t8413InBlock", "gubun", 0, "2")
# instXAQueryT8413.SetFieldData("t8413InBlock", "sdate", 0, "20190520")
# instXAQueryT8413.SetFieldData("t8413InBlock", "edate", 0, "20210526")
# instXAQueryT8413.SetFieldData("t8413InBlock", "comp_yn", 0, "N")
# instXAQueryT8413.Request(0)
# while XAQueryEventHandler.query_state == 0:
# pythoncom.PumpWaitingMessages()
# count = instXAQueryT8413.GetBlockCount("t8413OutBlock1")
# stockdata.clear()
# for i in range(count):
# date = instXAQueryT8413.GetFieldData("t8413OutBlock1", "date", i)
# open = instXAQueryT8413.GetFieldData("t8413OutBlock1", "open", i)
# high = instXAQueryT8413.GetFieldData("t8413OutBlock1", "high", i)
# low = instXAQueryT8413.GetFieldData("t8413OutBlock1", "low", i)
# close = instXAQueryT8413.GetFieldData("t8413OutBlock1", "close", i)
# vol = instXAQueryT8413.GetFieldData("t8413OutBlock1", "jdiff_vol", i)
# stockdata.append([date, open, high, low, close, vol])
# df2 = df.append(pd.DataFrame(stockdata, columns=['날짜','시가','고가','저가','종가','거래량']))
# print(df2)
res.drop_duplicates()
print(res)
res.to_csv('C:/Users/myung/OneDrive/바탕 화면/삼성바이오로직스.csv', sep=',', na_rep='NaN',index=False)
\ No newline at end of file
from google.colab import drive
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler
import numpy as np
from keras.models import Sequential
from keras.layers import Dense
from keras.callbacks import EarlyStopping, ModelCheckpoint
from keras.layers import LSTM
drive.mount('/content/drive')
df_price = pd.read_csv('/content/drive/My Drive/Colab Notebooks/삼성바이오로직스.csv', encoding='cp949')
pd.to_datetime(df_price['날짜'], format='%Y%m%d')
df_price['날짜'] = pd.to_datetime(df_price['날짜'], format='%Y%m%d')
df_price['연도'] =df_price['날짜'].dt.year
df_price['월'] =df_price['날짜'].dt.month
df_price['일'] =df_price['날짜'].dt.day
df = df_price.loc[df_price['연도']>=1990]
scaler = MinMaxScaler()
scale_cols = ['시가', '고가', '저가', '종가', '거래량']
df_scaled = scaler.fit_transform(df[scale_cols])
df_scaled = pd.DataFrame(df_scaled)
df_scaled.columns = scale_cols
TEST_SIZE = 200
window_size=20
def make_dataset(data, label, window_size=20):
feature_list = []
label_list = []
for i in range(len(data) - window_size):
feature_list.append(np.array(data.iloc[i:i+window_size]))
label_list.append(np.array(label.iloc[i+window_size]))
return np.array(feature_list), np.array(label_list)
def main():
train = df_scaled[:-TEST_SIZE]
test = df_scaled[-TEST_SIZE:]
feature_cols = ['시가', '고가', '저가', '거래량']
label_cols = ['종가']
train_feature = train[feature_cols]
train_label = train[label_cols]
# train dataset
train_feature, train_label = make_dataset(train_feature, train_label, 20)
# train, validation set 생성
from sklearn.model_selection import train_test_split
x_train, x_valid, y_train, y_valid = train_test_split(train_feature, train_label, test_size=0.2)
x_train.shape, x_valid.shape
test_feature = test[feature_cols]
test_label = test[label_cols]
# test dataset (실제 예측 해볼 데이터)
test_feature, test_label = make_dataset(test_feature, test_label, 20)
test_feature.shape, test_label.shape
model = Sequential()
model.add(LSTM(16,
input_shape=(train_feature.shape[1], train_feature.shape[2]),
activation='relu',
return_sequences=False)
)
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
early_stop = EarlyStopping(monitor='val_loss', patience=10)
filename = '/content/drive/My Drive/Colab Notebooks/tmp_samba.h5'
checkpoint = ModelCheckpoint(filename, monitor='val_loss', verbose=1, save_best_only=True, mode='auto')
# history = model.fit(x_train, y_train,
# epochs=200,
# batch_size=16,
# validation_data=(x_valid, y_valid),
# callbacks=[early_stop, checkpoint])
# weight 로딩
model.load_weights(filename)
model.summary()
# 예측
pred = model.predict(test_feature)
plt.figure(figsize=(12, 9))
plt.plot(test_label, label='actual')
plt.plot(pred, label='prediction')
plt.legend()
plt.show()
if __name__ == "__main__":
main()
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
This diff is collapsed. Click to expand it.
This diff could not be displayed because it is too large.
No preview for this file type
No preview for this file type
This file is too large to display.
No preview for this file type
No preview for this file type