用RNN算法预测股票未来的开盘价、收盘价等,有完整的代码
时间: 2024-02-11 09:07:48 浏览: 78
RNN_股票预测,rnn股票预测,Python
5星 · 资源好评率100%
当然可以,下面是一个基于RNN算法的股票预测的代码示例,您可以根据需要进行调整和修改:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
# 读取股票数据
df = pd.read_csv('stock_data.csv')
# 取出开盘价和收盘价数据
data = df.filter(['Open', 'Close'])
# 将数据归一化处理
scaler = MinMaxScaler(feature_range=(0, 1))
scaled_data = scaler.fit_transform(data)
# 定义训练集和测试集
train_size = int(len(scaled_data) * 0.7)
train_data = scaled_data[0:train_size, :]
test_data = scaled_data[train_size:len(scaled_data), :]
# 定义X和y
def create_dataset(dataset, look_back=1):
X, y = [], []
for i in range(len(dataset) - look_back - 1):
a = dataset[i:(i + look_back), :]
X.append(a)
y.append(dataset[i + look_back, 0])
return np.array(X), np.array(y)
look_back = 10
train_X, train_y = create_dataset(train_data, look_back)
test_X, test_y = create_dataset(test_data, look_back)
# 定义RNN模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(train_X.shape[1], train_X.shape[2])))
model.add(LSTM(units=50))
model.add(Dense(units=1))
# 编译模型
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(train_X, train_y, epochs=100, batch_size=64, verbose=1)
# 测试模型
predicted_stock_price = model.predict(test_X)
predicted_stock_price = scaler.inverse_transform(predicted_stock_price)
# 绘制预测结果
plt.plot(df['Open'][train_size + look_back + 1:], label='Real Stock Price')
plt.plot(predicted_stock_price, label='Predicted Stock Price')
plt.legend()
plt.show()
```
需要注意的是,该代码示例仅供参考,实际应用中还需要根据股票的特点和市场情况进行调整和修改。
阅读全文