多元 LSTM 股票预测

Posted

技术标签:

【中文标题】多元 LSTM 股票预测【英文标题】:Multivarate LSTM stock prediction 【发布时间】:2020-05-15 15:29:33 【问题描述】:

我正在使用 keras 构建股票预测。我知道如何用单变量(例如'Open')做一个简单的。我想处理多个变量,例如“打开、关闭、高”。处理数据以使其成为 3D 以馈送 NN 的代码如下 Uni.

X_train = []
y_train = []

for i in range(60, 1260): 
    X_train.append(data_training_scaled[i-60:i, :])
    y_train.append(data_training_scaled[i,:])

X_train, y_train = np.array(X_train), np.array(y_train)
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))

此代码将收集 0-59 天的历史数据并预测第 60 天(存储在 Y_train 中)。该数组的形状为 (1200,60,1),即 1200 行 60 天的历史数据向上计数。例如第 1 行 = 0-59 天,第 2 行 1-60 天等分别预测第 60 天和第 61 天。

当使用多个变量执行此操作时,最好的方法是什么?开放数据是否保持在维度 1,而其他变量保持在维度 2 和 3,因此 3D 数组的形状对于 3 个变量将是 (1200,60,3)?

【问题讨论】:

【参考方案1】:

第一步是将数据构建成一个有监督的学习问题,即根据先前的输入数据 (t-1)、(t-2) 等预测时间 (t)。一旦完成,这些数据需要重新整形在 3 维样本、时间步长、特征中。

【讨论】:

您能否详细说明一下。我想我知道你的意思,但我已经做到了,不是吗? “进入监督学习”是什么意思? 请通过link text 将时间序列转换为监督学习问题。如果这一步已经完成,请忽略。【参考方案2】:

您想预测第二天的股价,对。此代码将为您完成。

from pandas_datareader import data as wb
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.pylab import rcParams
from sklearn.preprocessing import MinMaxScaler

#from datetime import datetime, timedelta
#N = 60
#start = (datetime.now() - timedelta(days=N)).date()
#end = datetime.today().strftime('%Y-%m-%d')
#print(start)
#print(end)

start = '2019-02-28'
end = '2020-02-28'

tickers = ['AAPL']

thelen = len(tickers)

price_data = []
for ticker in tickers:
    prices = wb.DataReader(ticker, start = start, end = end, data_source='yahoo')[['Open','Adj Close']]
    price_data.append(prices.assign(ticker=ticker)[['ticker', 'Open', 'Adj Close']])

#names = np.reshape(price_data, (len(price_data), 1))

df = pd.concat(price_data)
df.reset_index(inplace=True)

for col in df.columns: 
    print(col) 

#used for setting the output figure size
rcParams['figure.figsize'] = 20,10
#to normalize the given input data
scaler = MinMaxScaler(feature_range=(0, 1))
#to read input data set (place the file name inside  ' ') as shown below
df.head()

df['Date'] = pd.to_datetime(df.Date,format='%Y-%m-%d')
#df.index = names['Date']
plt.figure(figsize=(16,8))
plt.plot(df['Adj Close'], label='Closing Price')

ntrain = 80
df_train = df.head(int(len(df)*(ntrain/100)))
ntest = -80
df_test = df.tail(int(len(df)*(ntest/100)))


#importing the packages 
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM

#dataframe creation
seriesdata = df.sort_index(ascending=True, axis=0)
new_seriesdata = pd.DataFrame(index=range(0,len(df)),columns=['Date','Adj Close'])
length_of_data=len(seriesdata)
for i in range(0,length_of_data):
    new_seriesdata['Date'][i] = seriesdata['Date'][i]
    new_seriesdata['Adj Close'][i] = seriesdata['Adj Close'][i]
#setting the index again
new_seriesdata.index = new_seriesdata.Date
new_seriesdata.drop('Date', axis=1, inplace=True)
#creating train and test sets this comprises the entire data’s present in the dataset
myseriesdataset = new_seriesdata.values
totrain = myseriesdataset[0:255,:]
tovalid = myseriesdataset[255:,:]
#converting dataset into x_train and y_train
scalerdata = MinMaxScaler(feature_range=(0, 1))
scale_data = scalerdata.fit_transform(myseriesdataset)
x_totrain, y_totrain = [], []
length_of_totrain=len(totrain)
for i in range(60,length_of_totrain):
    x_totrain.append(scale_data[i-60:i,0])
    y_totrain.append(scale_data[i,0])
x_totrain, y_totrain = np.array(x_totrain), np.array(y_totrain)
x_totrain = np.reshape(x_totrain, (x_totrain.shape[0],x_totrain.shape[1],1))

#LSTM neural network
lstm_model = Sequential()
lstm_model.add(LSTM(units=50, return_sequences=True, input_shape=(x_totrain.shape[1],1)))
lstm_model.add(LSTM(units=50))
lstm_model.add(Dense(1))
lstm_model.compile(loss='mean_squared_error', optimizer='adadelta')
lstm_model.fit(x_totrain, y_totrain, epochs=3, batch_size=1, verbose=2)
#predicting next data stock price
myinputs = new_seriesdata[len(new_seriesdata) - (len(tovalid)+1) - 60:].values
myinputs = myinputs.reshape(-1,1)
myinputs  = scalerdata.transform(myinputs)
tostore_test_result = []
for i in range(60,myinputs.shape[0]):
    tostore_test_result.append(myinputs[i-60:i,0])
tostore_test_result = np.array(tostore_test_result)
tostore_test_result = np.reshape(tostore_test_result,(tostore_test_result.shape[0],tostore_test_result.shape[1],1))
myclosing_priceresult = lstm_model.predict(tostore_test_result)
myclosing_priceresult = scalerdata.inverse_transform(myclosing_priceresult)



totrain = df_train
tovalid = df_test

#predicting next data stock price
myinputs = new_seriesdata[len(new_seriesdata) - (len(tovalid)+1) - 60:].values

#  Printing the next day’s predicted stock price. 
print(len(tostore_test_result));
print(myclosing_priceresult);

结果:

[[295.27402]]

模型预测为 295,实际收盘为 285。差异为 1%。不错!!它肯定比大多数投资组合经理、资产经理、对冲基金经理等所达到的更准确。

【讨论】:

以上是关于多元 LSTM 股票预测的主要内容,如果未能解决你的问题,请参考以下文章

利用LSTM实现预测时间序列(股票预测)

深度学习LSTM预测股票价格

基于LSTM的股票价格预测(完整金融类代码)

python深度学习之基于LSTM时间序列的股票价格预测

AI金融:LSTM预测股票

在 Keras 中使用 LSTM 预测股票(Python 3.7、Tensorflow 2.1.0)