基于LSTM算法的股票预测
时间: 2024-03-28 07:32:13 浏览: 149
基于LSTM算法的股票预测是一种利用长短期记忆网络(LSTM)来进行时间序列预测的方法。LSTM是一种递归神经网络,它能够有效地处理时间序列数据中的长期依赖关系。下面是一个基于LSTM算法的股票预测的示例代码:
```python
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import LSTM, Dense
# 读取股票数据
data = pd.read_csv('stock_data.csv')
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data['Close'].values.reshape(-1, 1))
# 划分训练集和测试集
train_size = int(len(scaled_data) * 0.8)
train_data = scaled_data[:train_size, :]
test_data = scaled_data[train_size:, :]
# 创建训练集和测试集
def create_dataset(dataset, time_step=1):
X, Y = [], []
for i in range(len(dataset) - time_step - 1):
a = dataset[i:(i + time_step), 0]
X.append(a)
Y.append(dataset[i + time_step, 0])
return np.array(X), np.array(Y)
time_step = 100
X_train, Y_train = create_dataset(train_data, time_step)
X_test, Y_test = create_dataset(test_data, time_step)
# 转换为LSTM所需的输入格式 [样本数,时间步,特征数]
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], 1))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
# 构建LSTM模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(X_train.shape[1], 1)))
model.add(LSTM(units=50))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
# 训练模型
model.fit(X_train, Y_train, epochs=100, batch_size=32)
# 预测股票价格
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)
# 反归一化
train_predict = scaler.inverse_transform(train_predict)
Y_train = scaler.inverse_transform([Y_train])
test_predict = scaler.inverse_transform(test_predict)
Y_test = scaler.inverse_transform([Y_test])
# 计算均方根误差(RMSE)
train_rmse = np.sqrt(np.mean(np.power((Y_train - train_predict), 2)))
test_rmse = np.sqrt(np.mean(np.power((Y_test - test_predict), 2)))
# 打印预测结果和RMSE
print("训练集预测结果:", train_predict)
print("测试集预测结果:", test_predict)
print("训练集RMSE:", train_rmse)
print("测试集RMSE:", test_rmse)
```
这段代码首先读取股票数据,然后进行数据预处理,包括归一化处理。接下来,将数据集划分为训练集和测试集,并创建LSTM模型。模型训练完成后,使用模型对训练集和测试集进行预测,并将预测结果反归一化。最后,计算训练集和测试集的均方根误差(RMSE),并打印预测结果和RMSE值。
阅读全文