根据之前的代码:LSTM预测股票收盘价做了一点修改。
首先收集数据:
import tushare as ts
import pandas as pd
def get_data(code, date):
#数据准备/data preparation
#变量选取Open,High,Low,Close,Volume等,以浦发银行股票为例
pro = ts.pro_api('f3bbc97d0ffbbed8666e6f7c82e712165950d048987f5d6cfbf1e0ce') #token可以在新版tushare的网站上找到
stock_data = pro.query('daily', ts_code = code, start_date = '20000101', end_date = date)
stock_data = stock_data[::-1] #倒序,使日期靠前的排在前面
stock_data.reset_index(drop=True, inplace=True) #把每行的索引改为“0、1、2……”
return stock_data
然后进行预处理:
import numpy as np
from sklearn.preprocessing import MinMaxScaler
def preprocess(stock_data, day, seq_length, data_dim, output_dim, visual_window):
xy = stock_data[['open', 'close', 'high', 'low', 'vol', 'pct_chg', 'amount']] #选取需要的features
xy = np.array(xy.values) #转为array
dataXY = []
for i in range(0, len(xy) - seq_length - day + 1):
_xy = xy[i:i + seq_length + day] #包括用于计算的seq_length天的数据,以及day天后的价格
dataXY.append(_xy)
#调整数据的shape
xy_real = np.vstack(dataXY).reshape(-1, seq_length + day, data_dim)
dataXY = xy_real
app_dataX = []
for i in range(len(xy) - seq_length - day + 1, len(xy) - seq_length + 1):
_x = xy[i:i + seq_length] #包括用于计算的seq_length天的数据
app_dataX.append(_x)
#调整数据的shape
x_real = np.vstack(app_dataX).reshape(-1, seq_length, data_dim)
app_dataX = x_real
xy_visual = np.copy(dataXY[- visual_window:]) #取最近visual_window天的数据,用于最后的画图
np.random.shuffle(dataXY) #打乱顺序
#切分训练集合测试集/split to train and testing
train_size = int(len(dataXY) * 0.7) #训练集长度
test_size = len(dataXY) - train_size #测试集长度
xy_train, xy_test = np.array(dataXY[0:train_size]), np.array(dataXY[train_size:len(dataXY)]) #划分训练集、测试集
#先处理训练集的数据
scaler = MinMaxScaler()
xy_train = xy_train.reshape((-1, data_dim)) #先变成2维,才能transform
xy_train_new = scaler.fit_transform(xy_train) #预处理,按列操作,每列最小值为0,最大值为1
xy_train_new = xy_train_new.reshape((-1, seq_length + day, data_dim)) #变回3维
x_new = xy_train_new[:,0:seq_length] #features
y_new = xy_train_new[:,-1,1] * 10 #取最后一天的收盘价,用作label,适当放大,便于训练
trainX, trainY = x_new, y_new
#然后处理测试集的数据
xy_test = xy_test.reshape((-1, data_dim))
xy_test_new = scaler.transform(xy_test) #使用训练集的scaler预处理测试集的数据
xy_test_new = xy_test_new.reshape((-1, seq_length +