导入工具包
import tensorflow as tf
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from tensorflow.keras.layers import Dense,Dropout,SimpleRNN
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_absolute_error,mean_squared_error
import os
import math
读取数据
maotai = pd.read_csv('./SH600519.csv') # 读取股票文件
training_set = maotai.iloc[0:2126, 2:3].values #提取0-2125列的第2行作为训练集
test_set = maotai.iloc[2126:, 2:3].values # 后300天的开盘价作为测试集
print(training_set.shape)
print(test_set.shape)
输出:
(2126, 1)
(300, 1)
归一化训练集和测试集
#归一化
sc = MinMaxScaler(feature_range=(0,1))
training_set_scaled=sc.fit_transform(training_set)
test_set = sc.fit_transform(test_set)
初始化
#初始化训练集与数据集的特征和标签
x_train = []
y_train = []
x_test = []
y_test = []
训练集中,每连续60天的数据作为输入,第61天的作为标签,一共的到2426-300-60=2066组训练数据
for i in range(60, len(training_set_scaled)):
x_train.append(training_set_scaled[i - 60:i, 0])
y_train.append(training_set_scaled[i, 0])
# 对训练集进行打乱
np.random.seed(7)
np.random.shuffle(x_train)
np.random.seed(7)
np.random.shuffle(y_train)
tf.random.set_seed(7)
# 将训练集由list格式变为array格式
x_train, y_train = np.array(x_train), np.array(y_train)
#reshape为符合RNN输入要求:[送入样本数, 循环核时间展开步数, 每个时间步输入特征个数]
x_train = np.reshape(x_train, (x_train.shape[0], 60, 1))
print(x_train.shape)
输出:
(2066, 60, 1)
测试集做同样处理,得300-60=240组测试数据
for i in range(60, len(test_set)):
x_test.append(test_set[i - 60:i, 0])
y_test.append(test_set[i, 0])
x_test, y_test = np.array(x_test), np.array(y_test)
x_test = np.reshape(x_test, (x_test.shape[0], 60, 1))
print(x_test.shape)
输出:
(240, 60, 1)
搭建模型
model = tf.keras.Sequential([
SimpleRNN(80, return_sequences=True),
Dropout(0.2),
SimpleRNN(100),
Dropout(0.2),
Dense(1)
])
配置训练过程
model.compile(optimizer=tf.keras.optimizers.Adam(0.001),
loss='mean_squared_error') # 损失函数用均方误差
断点存续
checkpoint_save_path = "./checkpoint/rnn_stock.ckpt"
if os.path.exists(checkpoint_save_path + '.index'):
print('-------------load the model-----------------')
model.load_weights(checkpoint_save_path)
cp_callback = tf.keras.callbacks.ModelCheckpoint(filepath=checkpoint_save_path,
save_weights_only=True,
save_best_only=True,
monitor='val_loss')