lstm股票预测模型python源码
时间: 2024-04-19 13:23:10 浏览: 116
LSTM(Long Short-Term Memory)是一种常用的循环神经网络(RNN)模型,用于处理序列数据。在股票预测中,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 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 = 10
X_train, y_train = create_dataset(train_data, time_step)
X_test, y_test = create_dataset(test_data, time_step)
# 转换为LSTM所需的输入格式 [样本数,时间步长,特征数]
X_train = X_train.reshape(X_train.shape, X_train.shape, 1)
X_test = X_test.reshape(X_test.shape, X_test.shape, 1)
# 构建LSTM模型
model = Sequential()
model.add(LSTM(50, return_sequences=True, input_shape=(time_step, 1)))
model.add(LSTM(50))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 模型训练
model.fit(X_train, y_train, validation_data=(X_test, y_test), epochs=100, batch_size=64, verbose=1)
# 预测股票价格
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)))
print("训练集RMSE:", train_rmse)
print("测试集RMSE:", test_rmse)
```
请注意,这只是一个简单的示例,实际的股票预测模型可能需要更多的特征和更复杂的网络结构来提高预测准确性。你可以根据自己的需求进行修改和优化。
阅读全文