帮我添加预测后续60天价格的走势图功能,写出完整的代码
时间: 2024-02-19 14:00:05 浏览: 77
好的,下面是添加预测走势图功能的完整代码:
```
import tushare as ts
import pandas as pd
import tkinter as tk
from tkinter import filedialog
import numpy as np
import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
# 设置你的Tushare token
ts.set_token('28c9658117ea308395a1d51076a842f9564097c607097a6900eeca99')
# 初始化pro接口
pro = ts.pro_api()
# 获取股票数据
df = pro.daily(ts_code='002635.SZ', start_date='20200130', end_date='20230518')
# 使用更多特征
df = df[['open', 'high', 'low', 'close', 'vol']]
# 数据缩放
scaler = MinMaxScaler(feature_range=(0, 1))
df_scaled = scaler.fit_transform(df)
# 将数据保存为Excel文件
root = tk.Tk()
root.withdraw() # 隐藏Tkinter窗口
file_path = filedialog.asksaveasfilename(defaultextension='.xlsx')
df.to_excel(file_path, index=False)
# 定义LSTM神经网络模型
def lstm(X, rnn_unit, lstm_layers, keep_prob):
# 创建多层LSTM
layers = [tf.nn.rnn_cell.LSTMCell(rnn_unit) for _ in range(lstm_layers)]
multi_lstm = tf.nn.rnn_cell.MultiRNNCell(layers)
# 添加dropout
drop_lstm = tf.nn.rnn_cell.DropoutWrapper(multi_lstm, output_keep_prob=keep_prob)
# 初始化状态
init_state = drop_lstm.zero_state(tf.shape(X)[0], dtype=tf.float32)
# 运行LSTM
outputs, _ = tf.nn.dynamic_rnn(drop_lstm, X, initial_state=init_state, dtype=tf.float32)
# 输出层
out = tf.layers.dense(outputs[:, -1, :], 1)
return out
# 训练LSTM模型
def train_lstm(df_scaled, rnn_unit, lstm_layers, lr, keep_prob, batch_size, time_step, train_begin, train_end):
# 划分训练集和测试集
train_data = df_scaled[train_begin:train_end]
test_data = df_scaled[train_end:]
# 构造训练数据
x_train, y_train = [], []
for i in range(len(train_data) - time_step - 1):
x_train.append(train_data[i:i + time_step])
y_train.append(train_data[i + time_step, 3]) # 使用收盘价作为目标
x_train, y_train = np.array(x_train), np.array(y_train).reshape(-1, 1)
# 构造测试数据
x_test, y_test = [], []
for i in range(len(test_data) - time_step - 1):
x_test.append(test_data[i:i + time_step])
y_test.append(test_data[i + time_step, 3]) # 使用收盘价作为目标
x_test, y_test = np.array(x_test), np.array(y_test).reshape(-1, 1)
# 定义模型输入、输出和损失函数
X = tf.placeholder(tf.float32, [None, time_step, input_size])
Y = tf.placeholder(tf.float32, [None, 1])
output = lstm(X, rnn_unit, lstm_layers, keep_prob)
loss = tf.reduce_mean(tf.square(output - Y))
train_op = tf.train.AdamOptimizer(lr).minimize(loss)
# 训练模型
with tf.Session() as sess:
sess.run(tf.global_variables_initializer())
for i in range(batch_size):
for j in range(len(x_train)):
_, loss_ = sess.run([train_op, loss], feed_dict={X: x_train[j:j+1], Y: y_train[j:j+1]})
if i % 100 == 0:
print('batch %d, step %d, loss = %.6f' % (i, j, loss_))
# 保存模型
saver = tf.train.Saver()
saver.save(sess, 'stock_lstm_model')
# 使用模型预测未来60天的股票价格
predict_data = test_data[-time_step:]
predict_result = []
for i in range(60):
predict_input = np.reshape(predict_data, (1, time_step, input_size))
predict_price = sess.run(output, feed_dict={X: predict_input})
predict_result.append(predict_price[0, 0])
predict_data = np.concatenate((predict_data[1:], predict_price), axis=0)
# 绘制预测结果走势图
plt.plot(range(len(df)), df['close'], 'b')
plt.plot(range(len(df)-60, len(df)), predict_result, 'r')
plt.show()
# 设置模型参数
input_size = 5
rnn_unit = 128
lstm_layers = 2
lr = 0.0006
keep_prob = 0.8
batch_size = 200
time_step = 20
train_begin = 0
train_end = int(len(df_scaled) * 0.8)
# 训练LSTM模型,并绘制预测结果走势图
train_lstm(df_scaled, rnn_unit, lstm_layers, lr, keep_prob, batch_size, time_step, train_begin, train_end)
```
在这个代码中,我添加了以下步骤:
1. 在训练LSTM模型的函数中,使用训练好的模型预测未来60天的股票价格。
2. 在预测完未来60天的股票价格后,使用Matplotlib库绘制预测结果走势图。
阅读全文