Python TensorFlow循环神经网络RNN-LSTM神经网络预测股票市场价格时间序列和MSE评估准确性
原创
©著作权归作者所有:来自51CTO博客作者拓端tecdat的原创作品,请联系作者获取转载授权,否则将追究法律责任
该项目包括:
- 自 2000 年 1 月以来的股票价格数据。我们使用的是 Microsoft 股票。
- 将时间序列数据转换为分类问题。
- 使用 TensorFlow 的 LSTM 模型
- 由 MSE 衡量的预测准确性
GPU 设置(如果可用)
gpus = tf.config.experimental.li
读取数据集
有几种方法可以获取股市数据。以下数据集是使用 R BatchGetSymbols 生成的。
#加载数据集
# ref.date是数组的第一列
datang = read_csv('stopriceo.csv', header=0)


我们的股票时间序列
我们为这个项目选择了微软(股票代码 MSFT)。
plt.rrms['fgre.dpi'] = 300
plt.plot(dfte['MSFT'])

时间序列显然不是平稳的,这是大多数预测模型所假设的属性。我们可以对时间序列应用变换,直到它达到平稳状态。Dickey-Fuller 检验使我们能够确定我们的时间序列是否具有季节性。
在这里,我们将应用对数转换来解决股票市场的指数行为。
其他有助于预测模型的转换:
df1 = datt['MSFT']
# 我们对数据集进行了对数转换
df1 = np.log(df1)

# 替代方案:我们可以对时间序列进行差分,从而去除季节性和平均值的变化。
# 创建一个差分序列
#dfdiff = diffe(df1,1)
预处理
在这里,我们对时间序列数据应用标准预处理。
在时间序列中,我们没有标签,但我们有时间序列的未来值,因此输出可以是 x(t),给定 x(t-1) 作为输入。这是将数据集构建为监督问题的一种实用(且直观)的方法。
scaer = ixSer(fatue_ange = (0,1))
scer.i_rrm(np.array(df1).rehape(-1,1))


LSTM 模型
我们在这里实现了一个堆叠的 LSTM 模型。
LSTM 网络是一种递归神经网络,能够学习序列预测问题中的序列依赖性。LSTM 模型主要用于语音识别、自然语言处理的上下文中。最近,它们也被应用于时间序列数据的分析。
from tensorflow.keras.models import Sequential
model.add(LSTM(50, retsueces = True
#stacked LSTM
model.add(Dropout(0.1))



表现
import math
from sklearn.metrics import mean_squared_error

plt.rcParams['figure.dpi'] = 300
plt.rcParams['savefig.dpi'] = 300
#移位预测
lokback = ie_step
trinPrectPot = numpy.empty_like(df1)
traireditPlot[:,:] = np.nan
in_y = scaler.nesetsfrm(df1)
plt.plot


未来 30 天的预测
我们现在可以递归地应用该模型,通过估计第二天的 (t+1) 价格,然后再次将其作为输入来推断 t+2 天的价格,依此类推。这个预测当然会有更大的误差,因为每个预测的日子都会带来很大的不确定性。然而,这个预测确实会告诉我们模型是否从过去的数据中学到了任何东西。
# 预测未来30天的情况
len(tesdata) # 1211
# 我认为在test_data中,最后一天是5月22日,例如
# 对于5月23日,我需要100个前一天的数据
x_input = test_data[(len

while(i<ftue_teps):
if(len(tep_put)>ie_sep):
x_input = np.array(tepinut[1:])
x_input = x_input.reshap


plt.plot(dy_ew, scaler.inverse_transf


