基于bp神经网络的股票预测代码
时间: 2023-09-15 13:22:34 浏览: 105
用BP人工神经网络预测人口代码(matlab)
5星 · 资源好评率100%
以下是一个基于BP神经网络的简单股票预测代码示例:
```python
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
df = pd.read_csv('AAPL.csv') # 载入股票数据
# 数据预处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(df['Close'].values.reshape(-1, 1))
# 训练集和测试集划分
prediction_days = 30
x_train = []
y_train = []
for x in range(prediction_days, len(scaled_data)):
x_train.append(scaled_data[x-prediction_days:x, 0])
y_train.append(scaled_data[x, 0])
x_train, y_train = np.array(x_train), np.array(y_train)
x_train = np.reshape(x_train, (x_train.shape[0], x_train.shape[1], 1))
# 构建BP神经网络模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.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(x_train, y_train, epochs=25, batch_size=32)
# 使用模型进行预测
test_start = len(scaled_data) - prediction_days
test_data = scaled_data[test_start:, :]
x_test = []
for x in range(prediction_days, len(test_data)):
x_test.append(test_data[x-prediction_days:x, 0])
x_test = np.array(x_test)
x_test = np.reshape(x_test, (x_test.shape[0], x_test.shape[1], 1))
predicted_price = model.predict(x_test)
predicted_price = scaler.inverse_transform(predicted_price)
# 可视化预测结果
import matplotlib.pyplot as plt
plt.plot(df['Close'].values)
plt.plot(range(test_start, len(df)), predicted_price)
plt.show()
```
该代码使用了Keras库来构建BP神经网络模型,以预测苹果公司股票的价格。首先,将股票数据进行归一化处理,并将其划分为训练集和测试集。然后,使用LSTM层和Dropout层构建BP神经网络模型,并使用训练集对其进行训练。最后,使用测试集进行预测,并将预测结果与实际股票价格进行可视化比较。
阅读全文