深度学习|基于LSTM网络的黄金期货价格预测--转载

深度学习|基于LSTM网络的黄金期货价格预测

前些天看到一位大佬的深度学习的推文,内容很适用于实战,争得原作者转载同意后,转发给大家。之后会介绍LSTM的理论知识。

我把code先放在我github上,大家有需要的自行下载,等原作者上传相关code时,我再告诉大家。欢迎大家关注大佬的公众号。

import pandas as pd
import datetime
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
import pandas as pd
import os
from keras.models import Sequential, load_model

df = pd.read_excel(r"*\黄金期货历史价格.xlsx")
df2 = df.iloc[::-1]
dataset = df2["开盘"].values
# 将整型变为float
dataset = dataset.astype('float32')
train_size = int(len(dataset) * 0.8)
trainlist = dataset[:train_size]
testlist = dataset[train_size:]
import numpy as np
def create_dataset(dataset, look_back):
#这里的look_back与timestep相同
    dataX, dataY = [], []
    for i in range(len(dataset)-look_back-1):
        a = dataset[i:(i+look_back)]
        dataX.append(a)
        dataY.append(dataset[i + look_back])
    return np.array(dataX),np.array(dataY)

look_back = 15
trainX,trainY  = create_dataset(trainlist,look_back)
testX,testY = create_dataset(testlist,look_back)
trainX = np.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))
testX = np.reshape(testX, (testX.shape[0], testX.shape[1] ,1 ))

# create and fit the LSTM network
model = Sequential()
model.add(LSTM(1024, input_shape=(None,1)))
model.add(Dense(256, activation="relu"))
model.add(Dense(128, activation="relu"))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=100, batch_size=128, verbose=2)
model.save(os.path.join(r"*\LSTM介绍","Test" + ".h5"))

trainPredict = model.predict(trainX)
testPredict = model.predict(testX)

## 绘图评价
fig = plt.subplot()
plt.plot(trainY, label = 'trainY' )
plt.plot(trainPredict[1:], label = 'trainPredict')
plt.plot(testY, label = 'testY')
plt.plot(testPredict[1:], label = 'testPredict')
plt.legend()
plt.savefig(r"D:\PycharmProjects\pythonProject\LSTM介绍\Evaluation.pdf")
plt.show()

## MSE
from sklearn.metrics import r2_score, mean_squared_error
c = testPredict.ravel()
DNN_r2 = r2_score(testY, c)
print('LSTM模型的R平方值为:',DNN_r2)
DNN_MSE = mean_squared_error(testY, c)
print('LSTM模型的MSE 值为:',DNN_MSE)

## 预测
pre_df = pd.read_excel(r"D:\PycharmProjects\pythonProject\LSTM介绍\predict.xlsx")
pre_df_x = np.array(pre_df["开盘"].iloc[::-1])
pre_df_x = pre_df_x.reshape(1,25,1)
Predict = model.predict(pre_df_x)
print("2021年3月28日的黄金期货开盘预测价为:",Predict)

上一篇:CRNN模型


下一篇:DL - LSTM