LSTM--【单变量多步输入+单变量多步输出】--(股票)预测代码-python

目录

解决需求

案例

代码

预测结果

参考链接


解决需求

利用LSTM模型实现【单变量多步输入+单变量多步输出】预测,即向LSTM模型中输入N个步长的单变量序列,得到该变量未来M个步长的输出预测值。

案例

利用LSTM模型预测上证指数最高价n_forecast步长的未来值。

代码

import numpy as np
import pandas as pd
#import yfinance as yf
import tensorflow as tf
from tensorflow.keras.layers import Dense, LSTM
from tensorflow.keras.models import Sequential
from sklearn.preprocessing import MinMaxScaler
import matplotlib.pyplot as plt
pd.options.mode.chained_assignment = None
tf.random.set_seed(0)

# 加载数据
shangzheng_DailyK_filepath = r'D:\个人文件\上证指数2012.xlsx'
shangzheng_DailyK = pd.read_excel(shangzheng_DailyK_filepath)
y = shangzheng_DailyK.copy()[['date', 'high']][:1000]
y.index = pd.DatetimeIndex(y['date'])
y.drop('date',axis=1,inplace=True)

# 对数据进行归一化处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaler = scaler.fit(y)
y = scaler.transform(y)

# 构造输入输出序列
n_lookback = 250  # 输入序列的长度  (回望周期==输入步长)
n_forecast = 20   # 输出序列的长度  (预测周期==输出步长)

X = []
Y = []

for i in range(n_lookback, len(y) - n_forecast + 1):
    X.append(y[i - n_lookback: i])
    Y.append(y[i: i + n_forecast])

X = np.array(X)
Y = np.array(Y)

# 拟合模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(n_lookback, 1)))
model.add(LSTM(units=50))
model.add(Dense(n_forecast))

model.compile(loss='mean_squared_error', optimizer='adam')
history = model.fit(X, Y, epochs=100, batch_size=32, verbose=0, shuffle=False)

# 生成预测值
X_ = y[- (n_lookback+n_forecast) : - n_forecast]  # 最后输入的X序列--最后60个数据作为输入序列
X_ = X_.reshape(1, n_lookback, 1)

Y_ = model.predict(X_).reshape(-1, 1)
Y_ = scaler.inverse_transform(Y_)


# 在数据帧中存储预测结果
df_future = shangzheng_DailyK.copy()[['date', 'high']]
df_future.rename(columns={'date': 'Date', 'high': 'High_Actual'}, inplace=True)
df_future['High_Forecast'] = np.nan
df_future.iloc[-n_forecast:, 2] = Y_.flatten()

# 画出实际和预测值
plt.figure(figsize=(20,10))
plt.plot(df_future['High_Actual'][-100:], label='true')
plt.plot(df_future['High_Forecast'][-100:], label='forecast')

# 做出标注
plt.legend(['True', 'Forecast'], ncol=2, prop={"family": "Times New Roman", "size": 20})

# 做出图片、X轴和Y轴名称
plt.title('Shangzheng_Comparison_Chart', fontdict={"family": "Times New Roman", "size": 25})
plt.xlabel('date_index', fontdict={"family": "Times New Roman", "size": 25})
plt.ylabel('shangzheng_price', fontdict={"family": "Times New Roman", "size": 25})


# 坐标轴刻度
plt.xticks(fontname="Times New Roman", fontsize=20)
plt.yticks(fontname="Times New Roman", fontsize=20)

预测结果

LSTM--【单变量多步输入+单变量多步输出】--(股票)预测代码-python_第1张图片

模型预测效果不是很好,待后续改进。

参考链接

如何使用LSTM模型进行多步预测? - 问答 - 腾讯云开发者社区-腾讯云

你可能感兴趣的:(量化投资,lstm,深度学习,机器学习)