第一次做Tushare简单股票预测,仅用于交流学习,若有错误欢迎批评指正
下面是用Tushare进行中石化的股票预测
import tushare as ts
import pandas as pd
import keras
from keras import layers
from keras import models
from keras import Sequential
from keras.layers import Dense,Conv3D,MaxPooling3D,Flatten
from keras.callbacks import EarlyStopping
from keras.utils import to_categorical
pro = ts.pro_api(“fbf30cf25558b0aad1bf13f8e9b87df15077ed8a5e2c67b20705bf98”)#在Tushare获取token
#需要三组数据:训练组、测试组、预测组
df = pro.daily(ts_code=‘600028.SH’, start_date=‘20190101’, end_date=‘20200101’)
df2 = pro.daily(ts_code=‘600028.SH’, start_date=‘20200101’, end_date=‘20210101’)
df3 = pro.daily(ts_code=‘600028.SH’, start_date=‘20210426’, end_date=‘20210502’)
df.to_csv(“df1.csv”)
x_train = df[1:][[“open”,“high”,“close”,“change”,“pct_chg”,“vol”,“amount”]]
x_test = df2[1:][[“open”,“high”,“close”,“change”,“pct_chg”,“vol”,“amount”]]
x_predict = df3[[“open”,“high”,“close”,“change”,“pct_chg”,“vol”,“amount”]]
l = list(df[“close”])
y_train = []
for i in range(len(l)-1):
if (l[i] - l[i+1]) / l[i+1] > 0.0003:
y_train.append(1)
else:
y_train.append(0)
y_train = to_categorical(y_train)
l = list(df2[“close”])
y_test = []
for i in range(len(l)-1):
if (l[i] - l[i+1]) / l[i+1] > 0.0003:
y_test.append(1)
else:
y_test.append(0)
y_test = to_categorical(y_test)
model = Sequential()
input_num = 7
model.add(Dense(100,activation = “tanh”,input_shape = (input_num,)))
model.add(Dense(200,activation = “tanh”))
model.add(Dense(300,activation = “tanh”))
model.add(Dense(2,activation = “softmax”))
model.compile(optimizer=“adam”,loss=“categorical_crossentropy”)
model.fit(x_train,y_train,epochs = 60,batch_size=32)
e = model.evaluate(x_test,y_test)
p = model.predict(x_predict)
运行结果