用LSTM预测谷歌股票价格,用pandas_datareader的DataReader函数获取谷歌的数据,告诉我代码
时间: 2024-05-04 12:15:30 浏览: 114
基于LSTM的股票价格预测_数据+代码+报告
当然,我很乐意回答你的问题!以下是用LSTM预测谷歌股票价格的Python代码:
```python
#导入所需模块
from sklearn.preprocessing import MinMaxScaler
from keras.models import Sequential
from keras.layers import Dense, LSTM
import pandas_datareader as pdr
import datetime as dt
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
#指定起始时间和结束时间
start = dt.datetime(2012,1,1)
end = dt.datetime(2021,6,1)
#读取谷歌股票数据
df = pdr.DataReader('GOOGL', 'yahoo', start, end)
#创建一个数据框,只包括收盘价
data = df.filter(['Close'])
dataset = data.values
#将数据划分为训练集和测试集,并进行规范化处理
train_len = int(np.ceil(0.8*len(dataset)))
scaler = MinMaxScaler(feature_range=(0,1))
scaled_data = scaler.fit_transform(dataset)
train_data = scaled_data[0:train_len,:]
x_train = []
y_train = []
for i in range(60,len(train_data)):
x_train.append(train_data[i-60:i,0])
y_train.append(train_data[i,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))
#使用LSTM建立模型并进行训练
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(x_train.shape[1],1)))
model.add(LSTM(units=50, return_sequences=False))
model.add(Dense(units=25))
model.add(Dense(units=1))
model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(x_train, y_train, epochs=1, batch_size=1)
#使用模型进行预测,并将预测结果与实际结果绘制成图表展示
test_data = scaled_data[train_len-60:,:]
x_test = []
y_test = dataset[train_len:,:]
for i in range(60,len(test_data)):
x_test.append(test_data[i-60:i,0])
x_test = np.array(x_test)
x_test = np.reshape(x_test, (x_test.shape[0],x_test.shape[1],1))
predictions = model.predict(x_test)
predictions = scaler.inverse_transform(predictions)
rmse = np.sqrt(np.mean(predictions - y_test)**2)
print('RMSE:',rmse)
train = data[:train_len]
valid = data[train_len:]
valid['Predictions'] = predictions
plt.figure(figsize=(16,8))
plt.title('Model')
plt.xlabel('Date', fontsize=18)
plt.ylabel('Close Price USD ($)', fontsize=18)
plt.plot(train['Close'])
plt.plot(valid[['Close', 'Predictions']])
plt.legend(['Train', 'Val', 'Predictions'], loc='lower right')
plt.show()
```
希望你能够顺利地运行这个代码!
阅读全文