lstm股票预测keras
时间: 2023-09-27 21:11:07 浏览: 99
以下是使用Keras构建LSTM模型进行股票预测的示例代码:
```python
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import Dense, LSTM, Dropout
from sklearn.preprocessing import MinMaxScaler
# 载入数据
df = pd.read_csv('stock_price.csv')
# 选择收盘价作为预测目标
data = df['Close'].values.reshape(-1, 1)
# 归一化
scaler = MinMaxScaler(feature_range=(0, 1))
data = scaler.fit_transform(data)
# 构造训练数据集
look_back = 60 # 使用前60天的数据作为输入特征
train_X, train_Y = [], []
for i in range(look_back, len(data)):
train_X.append(data[i-look_back:i, 0])
train_Y.append(data[i, 0])
train_X, train_Y = np.array(train_X), np.array(train_Y)
# 调整输入数据的形状
train_X = np.reshape(train_X, (train_X.shape[0], train_X.shape[1], 1))
# 构建LSTM模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(train_X.shape[1], 1)))
model.add(Dropout(0.2))
model.add(LSTM(units=50, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(units=1))
# 编译模型
model.compile(optimizer='adam', loss='mean_squared_error')
# 训练模型
model.fit(train_X, train_Y, epochs=100, batch_size=32)
# 预测未来30天的收盘价
test_X = data[-look_back:, 0]
test_X = np.reshape(test_X, (1, look_back, 1))
predictions = []
for i in range(30):
prediction = model.predict(test_X)
predictions.append(prediction)
test_X = np.append(test_X[:, 1:, :], [[prediction]], axis=1)
# 反归一化
predictions = scaler.inverse_transform(predictions)
# 输出预测结果
print(predictions)
```
其中,`stock_price.csv`是包含股票历史价格数据的CSV文件,第一列为日期,第五列为收盘价。该模型使用前60天的收盘价数据作为输入特征,训练LSTM模型,并使用该模型预测未来30天的收盘价。
阅读全文