股票预测python神经网络lstm
时间: 2023-08-18 09:05:00 浏览: 105
基于python的LSTM神经网络的股票价格趋势预测的研究与实现
5星 · 资源好评率100%
股票预测中,使用 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(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 = 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=(time_step,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=10, batch_size=32)
# 预测股票价格
predicted_price = model.predict(X_test)
predicted_price = scaler.inverse_transform(predicted_price)
# 可视化结果
import matplotlib.pyplot as plt
plt.plot(data['Close'].values[train_size + time_step + 1:], color='blue', label='Actual Price')
p
阅读全文