LSTM模型预测股价,具有滞后性怎么解决,python代码
时间: 2024-05-03 19:20:28 浏览: 114
为了解决LSTM模型预测股价时的滞后性,可以考虑引入历史数据作为特征,从而让模型能够更好地学习到股价的趋势。同时,还可以利用技术指标等相关信息提高模型的预测精度。
以下是一个用Python实现的LSTM模型预测股价的示例代码:
```python
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 加载股价数据
df = pd.read_csv('stock_price.csv')
# 整理数据
data = df.filter(['Close']).values
dataset_size = len(data)
# 将数据集分为训练集和测试集
train_data = data[:int(dataset_size*0.8), :]
test_data = data[int(dataset_size*0.8):, :]
# 特征缩放
scaler = MinMaxScaler(feature_range=(0, 1))
train_data = scaler.fit_transform(train_data)
test_data = scaler.transform(test_data)
# 准备训练数据和标签
look_back = 60 # 上一时刻数据的数量
x_train, y_train = [], []
for i in range(look_back, len(train_data)):
x_train.append(train_data[i-look_back:i, 0])
y_train.append(train_data[i, 0])
x_train, y_train = np.array(x_train), np.array(y_train)
# 转换为LSTM可用的输入格式
x_train = np.reshape(x_train, (x_train.shape[0], x_train.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)
# 准备测试数据
test_data = np.array(test_data)
x_test, y_test = [], []
for i in range(look_back, len(test_data)):
x_test.append(test_data[i-look_back:i, 0])
y_test.append(test_data[i, 0])
x_test, y_test = np.array(x_test), np.array(y_test)
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
# 进行股价预测
predicted_price = scaler.inverse_transform(model.predict(x_test))
# 评估模型性能
mse = np.mean((predicted_price - y_test)**2)
rmse = np.sqrt(mse)
print('模型的RMSE值为:', rmse)
```
阅读全文