写一段LSTM预测股价的python代码
时间: 2023-10-24 09:08:05 浏览: 111
以下是一个简单的LSTM模型用于预测股票价格的Python代码示例。这里使用了Keras和Tensorflow等库:
```python
import numpy as np
import pandas as pd
from keras.models import Sequential
from keras.layers import LSTM, Dense
# 读取数据集
df = pd.read_csv('stock_prices.csv')
# 数据预处理
data = df['Close'].values.reshape(-1, 1) # 转换为二维数组
data = data.astype('float32')
train_size = int(len(data) * 0.7) # 训练集和测试集的分割
test_size = len(data) - train_size
train, test = data[0:train_size,:], data[train_size:len(data),:]
# 创建数据集
def create_dataset(dataset, look_back=1):
dataX, dataY = [], []
for i in range(len(dataset)-look_back-1):
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 = 3
trainX, trainY = create_dataset(train, look_back)
testX, testY = create_dataset(test, look_back)
# 调整输入数据形状
trainX = np.reshape(trainX, (trainX.shape[0], 1, trainX.shape[1]))
testX = np.reshape(testX, (testX.shape[0], 1, testX.shape[1]))
# 创建和训练LSTM模型
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(trainX, trainY, epochs=100, batch_size=1, verbose=2)
# 预测测试集股票价格
testPredict = model.predict(testX)
# 反归一化预测结果
testPredict = scaler.inverse_transform(testPredict)
# 计算均方误差
mse = np.mean((testPredict - testY) ** 2)
print('均方误差:%.6f' % mse)
```
这段代码中,我们使用了LSTM来构建模型,并使用历史数据来预测股票价格。模型的输入是过去的股票价格,输出是未来一个时间段内的股票价格。我们还使用了均方误差来衡量模型的精度。
阅读全文