请写出使用RNN预测股票价格的python代码
时间: 2024-05-01 16:19:22 浏览: 105
RNN_股票预测,rnn股票预测,Python
5星 · 资源好评率100%
以下是一个使用RNN预测股票价格的简单Python代码示例:
```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_prices.csv')
# 将日期列删除,只保留收盘价列
data = df.iloc[:, 1:2].values
# 对数据进行归一化处理
scaler = MinMaxScaler(feature_range=(0, 1))
data = scaler.fit_transform(data)
# 划分数据集
train_size = int(len(data) * 0.67)
test_size = len(data) - train_size
train_data, test_data = data[0:train_size,:], data[train_size:len(data),:]
# 将数据集转换为适合RNN的数据格式
def create_dataset(dataset, look_back=1):
X, Y = [], []
for i in range(len(dataset)-look_back-1):
a = dataset[i:(i+look_back), 0]
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)
# 将数据集转换为3D张量
train_X = np.reshape(train_X, (train_X.shape[0], 1, train_X.shape[1]))
test_X = np.reshape(test_X, (test_X.shape[0], 1, test_X.shape[1]))
# 构建RNN模型
model = Sequential()
model.add(LSTM(4, input_shape=(1, look_back)))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
# 训练模型
model.fit(train_X, train_Y, epochs=100, batch_size=1, verbose=2)
# 测试模型
train_predict = model.predict(train_X)
test_predict = model.predict(test_X)
# 将数据转换为原始形式
train_predict = scaler.inverse_transform(train_predict)
train_Y = scaler.inverse_transform([train_Y])
test_predict = scaler.inverse_transform(test_predict)
test_Y = scaler.inverse_transform([test_Y])
# 绘制预测结果
plt.plot(train_Y.flatten())
plt.plot(train_predict.flatten())
plt.plot(test_Y.flatten())
plt.plot(test_predict.flatten())
plt.show()
```
需要注意的是,这只是一个简单的示例代码,实际应用中可能需要更复杂的模型和更多的特征工程。同时,在使用RNN预测股票价格时,一定要注意风险管理和投资策略,避免盲目追求高收益而导致亏损。
阅读全文