用pytorch写一段代码,实现lstm多特征预测股票
时间: 2023-04-08 16:03:42 浏览: 184
我可以回答这个问题。以下是一个使用 PyTorch 实现 LSTM 多特征预测股票的代码示例:
```python
import torch
import torch.nn as nn
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
# 加载数据
data = pd.read_csv('stock_data.csv')
# 特征选择
features = ['open', 'high', 'low', 'close', 'volume']
data = data[features]
# 数据归一化
scaler = MinMaxScaler()
data = scaler.fit_transform(data)
# 划分训练集和测试集
train_size = int(len(data) * 0.8)
train_data = data[:train_size]
test_data = data[train_size:]
# 定义 LSTM 模型
class LSTM(nn.Module):
def __init__(self, input_size, hidden_size, output_size):
super(LSTM, self).__init__()
self.hidden_size = hidden_size
self.lstm = nn.LSTM(input_size, hidden_size)
self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x):
h0 = torch.zeros(1, x.size(1), self.hidden_size)
c0 = torch.zeros(1, x.size(1), self.hidden_size)
out, _ = self.lstm(x, (h0, c0))
out = self.fc(out[-1, :, :])
return out
# 定义模型参数
input_size = len(features)
hidden_size = 64
output_size = 1
lr = 0.001
epochs = 100
# 初始化模型和优化器
model = LSTM(input_size, hidden_size, output_size)
criterion = nn.MSELoss()
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
# 训练模型
for epoch in range(epochs):
train_inputs = torch.Tensor(train_data[:-1])
train_labels = torch.Tensor(train_data[1:, 3])
optimizer.zero_grad()
outputs = model(train_inputs.unsqueeze(1))
loss = criterion(outputs.squeeze(), train_labels)
loss.backward()
optimizer.step()
print('Epoch [{}/{}], Loss: {:.4f}'.format(epoch+1, epochs, loss.item()))
# 测试模型
test_inputs = torch.Tensor(test_data[:-1])
test_labels = torch.Tensor(test_data[1:, 3])
with torch.no_grad():
outputs = model(test_inputs.unsqueeze(1))
test_loss = criterion(outputs.squeeze(), test_labels)
print('Test Loss: {:.4f}'.format(test_loss.item()))
# 反归一化并可视化预测结果
predicted = scaler.inverse_transform(np.concatenate((train_data[-1:, :], outputs.squeeze().detach().numpy()), axis=0))
actual = scaler.inverse_transform(np.concatenate((train_data[-1:, :], test_data[1:, :]), axis=0))
import matplotlib.pyplot as plt
plt.plot(predicted[:, 3], label='Predicted')
plt.plot(actual[:, 3], label='Actual')
plt.legend()
plt.show()
```
这个代码示例使用 PyTorch 实现了一个 LSTM 模型,用于预测股票的收盘价。模型使用了股票的开盘价、最高价、最低价、收盘价和成交量作为特征,使用均方误差作为损失函数,使用 Adam 优化器进行优化。在训练过程中,模型每个 epoch 都会输出当前的损失值。在测试过程中,模型会输出测试集上的损失值。最后,模型会将预测结果反归一化,并将预测结果和实际结果可视化。
阅读全文