帮我写一段lstm预测股票价格趋势的python代码
时间: 2023-08-28 08:22:10 浏览: 117
Stock Trend Prediction with LSTM in Python
好的,以下是一个简单的LSTM预测股票价格趋势的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.filter(['close']).values
# 将数据划分为训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data[0:train_size,:]
test_data = data[train_size:len(data),:]
# 数据归一化
scaler = MinMaxScaler(feature_range=(0, 1))
train_data = scaler.fit_transform(train_data)
test_data = scaler.transform(test_data)
# 创建训练集和测试集的数据集
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset) - look_back):
a = dataset[i:(i + look_back), 0]
dataX.append(a)
dataY.append(dataset[i + look_back, 0])
return np.array(dataX), np.array(dataY)
look_back = 60
trainX, trainY = create_dataset(train_data, look_back)
testX, testY = create_dataset(test_data, look_back)
# 调整输入数据的形状
trainX = np.reshape(trainX, (trainX.shape[0], trainX.shape[1], 1))
testX = np.reshape(testX, (testX.shape[0], testX.shape[1], 1))
# 创建LSTM模型
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(trainX.shape[1], 1)))
model.add(LSTM(units=50))
model.add(Dense(1))
model.compile(loss='mean_squared_error', optimizer='adam')
model.fit(trainX, trainY, epochs=50, batch_size=32)
# 使用模型进行预测
train_predict = model.predict(trainX)
test_predict = model.predict(testX)
# 反归一化数据
train_predict = scaler.inverse_transform(train_predict)
trainY = scaler.inverse_transform([trainY])
test_predict = scaler.inverse_transform(test_predict)
testY = scaler.inverse_transform([testY])
# 计算均方根误差(RMSE)
train_score = np.sqrt(mean_squared_error(trainY[0], train_predict[:,0]))
print('Train Score: %.2f RMSE' % (train_score))
test_score = np.sqrt(mean_squared_error(testY[0], test_predict[:,0]))
print('Test Score: %.2f RMSE' % (test_score))
# 绘制预测结果
train_predict_plot = np.empty_like(data)
train_predict_plot[:, :] = np.nan
train_predict_plot[look_back:len(train_predict)+look_back, :] = train_predict
test_predict_plot = np.empty_like(data)
test_predict_plot[:, :] = np.nan
test_predict_plot[len(train_predict)+(look_back*2)+1:len(data)-1, :] = test_predict
plt.plot(scaler.inverse_transform(data))
plt.plot(train_predict_plot)
plt.plot(test_predict_plot)
plt.show()
```
上述代码中,我们使用Keras框架中的LSTM层来建立预测模型。首先,我们读取股票价格数据,然后将其归一化并将其划分为训练集和测试集。接下来,我们创建一个函数来生成LSTM模型所需的数据集。然后,我们调整输入数据的形状以适合LSTM模型,并训练模型。最后,我们使用模型进行预测,并绘制结果。
阅读全文