46

利用Keras长短期记忆(LSTM)模型预测股票价格

 5 years ago
source link: http://shujuren.org/article/782.html?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

LSTMs在序列预测问题中非常强大,因为它们能够存储过去的信息。这在我们的案例中很重要,因为股票的前一个价格对于预测其未来的价格是至关重要的。

Jn2aYjU.png!web

编者按:本教程演示了如何开始使用LSTM模型预测时间序列。股票市场数据是一个很好的选择,因为它是相当常规的和广泛地提供给每个人。请不要把这当作理财建议,也不要用它来做你自己的交易。

在本教程中,我们将构建一个Python深度学习模型,用于预测股票价格的未来行为。我们假设读者熟悉Python中的深度学习概念,特别是LSTM。

虽然预测股票的实际价格是一个上坡路,但是我们可以建立一个模型来预测股票的价格是涨是跌。本教程使用的数据和notebook可以在 这里 找到。需要注意的是,影响股价的因素总是存在的,比如政治氛围和市场。然而,在本教程中,我们不会关注这些因素。

简介

LSTMs在序列预测问题中非常强大,因为它们能够存储过去的信息。这在我们的案例中很重要,因为股票的前一个价格对于预测其未来的价格是至关重要的。

我们将导入用于科学计算的 NumPy 、用于绘制图形的 Matplotlib 和用于加载和操作数据集的 Pandas

import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

加载数据集

下一步是加载我们的训练数据集,并选择我们将在建模中使用的Open和High列。

dataset_train = pd.read_csv('NSE-TATAGLOBAL.csv')
training_set = dataset_train.iloc[:, 1:2].values

我们检查数据集的头部,以便让我们对正在使用的数据集有一个大致的了解。

dataset_train.head()

2IBnq2F.png!web

某只股票在特定交易日的开盘价是是Open列,收盘价是Close列。最高和最低价分别是High列和Low列。

特征缩放

从以前使用深度学习模型的经验中,我们知道我们必须缩放数据以获得最佳性能。在我们的例子中,我们将使用Scikit- Learn的MinMaxScaler,并将数据集缩放到0到1之间的数字。

from sklearn.preprocessing import MinMaxScaler
sc = MinMaxScaler(feature_range = (0, 1))
training_set_scaled = sc.fit_transform(training_set)

使用Timesteps创建数据

LSTMs期望我们的数据具有特定的格式,通常是一个3D数组。我们首先在60个时间步骤中创建数据,然后使用NumPy将其转换为数组。接下来,我们将数据转换为具有X_train示例、60个时间戳和每个步骤一个特征的3D维度数组。

X_train = []
y_train = []
for i in range(60, 2035):
    X_train.append(training_set_scaled[i-60:i, 0])
    y_train.append(training_set_scaled[i, 0])
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))

构建LSTM

为了构建LSTM,我们需要从Keras中导入几个模块:

  • Sequential 用于初始化神经网络
  • Dense 用于添加密集连接的神经网络层
  • LSTM 用于添加长短期内存层
  • Dropout 用于添加防止过拟合的dropout层
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
from keras.layers import Dropout

我们添加LSTM层,然后添加一些Dropout层以防止过拟合。我们使用以下参数添加LSTM层:

50个单元,也就是输出空间的维度 return_sequence =True,它决定是否返回输出序列中的最后一个输出,还是返回完整的序列 input_shape作为训练集的shape

在定义Dropout层时,我们指定0.2,这意味着20%的层将被删除。然后,我们添加指定1个单元的输出的Dense层。在此之后,我们使用流行的adam优化器编译模型,并将损失设置为mean_squarred_error。这会计算平方误差的均值。接下来,我们将模型设置为在批大小为32的100个epochs上运行。请记住,根据您的计算机的规格,这可能需要几分钟来完成运行。

regressor = Sequential()

regressor.add(LSTM(units = 50, return_sequences = True, input_shape = (X_train.shape[1], 1)))
regressor.add(Dropout(0.2))

regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))

regressor.add(LSTM(units = 50, return_sequences = True))
regressor.add(Dropout(0.2))

regressor.add(LSTM(units = 50))
regressor.add(Dropout(0.2))

regressor.add(Dense(units = 1))

regressor.compile(optimizer = 'adam', loss = 'mean_squared_error')

regressor.fit(X_train, y_train, epochs = 100, batch_size = 32)

使用测试集预测未来的股票

首先,我们需要导入用于预测的测试集。

dataset_test = pd.read_csv('tatatest.csv')
real_stock_price = dataset_test.iloc[:, 1:2].values

为了预测未来的股票价格,我们需要在加载测试集之后做一些事情:

  1. 在0轴上合并训练集和测试集。
  2. 将时间步长设置为60(如前所述)
  3. 使用MinMaxScaler转换新数据集
  4. 如前所述,重新塑造数据集

在做出预测之后,我们使用inverse_transform以正常可读的格式返回股票价格。

dataset_total = pd.concat((dataset_train['Open'], dataset_test['Open']), axis = 0)
inputs = dataset_total[len(dataset_total) - len(dataset_test) - 60:].values
inputs = inputs.reshape(-1,1)
inputs = sc.transform(inputs)
X_test = []
for i in range(60, 76):
    X_test.append(inputs[i-60:i, 0])
X_test = np.array(X_test)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
predicted_stock_price = regressor.predict(X_test)
predicted_stock_price = sc.inverse_transform(predicted_stock_price)

可视化结果

最后,我们使用Matplotlib将预测股价和实际股价的结果可视化。

plt.plot(real_stock_price, color = 'black', label = 'TATA Stock Price')
plt.plot(predicted_stock_price, color = 'green', label = 'Predicted TATA Stock Price')
plt.title('TATA Stock Price Prediction')
plt.xlabel('Time')
plt.ylabel('TATA Stock Price')
plt.legend()
plt.show()

qUvUzqz.png!web

从图中我们可以看到,股票的实际价格上升了,而我们的模型也预测了股票的价格会上升。这清楚地显示了LSTMs在分析时间序列和顺序数据方面的强大功能。

总结

有一些其他的技术来预测股票价格,如移动平均线,线性回归,k近邻,ARIMA和Prophet。这些技术可以单独测试,并与Keras LSTM进行性能比较。如果你想更多地了解Keras和深度学习,你可以在 这里 找到我的文章。

作者:Derrick Mwiti 原文链接: https://heartbeat.fritz.ai/using-a-keras-long-shortterm-memory-lstm-model-to-predict-stock-prices-a08c9f69aa74

版权声明: 作者保留权利。文章为作者独立观点,不代表数据人网立场。严禁修改,转载请注明原文链接:http://shujuren.org/article/782.html

数据人网: 数据人学习,交流和分享的平台,诚邀您创造和分享数据知识,共建和共享数据智库。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK