问小白 wenxiaobai
资讯
历史
科技
环境与自然
成长
游戏
财经
文学与艺术
美食
健康
家居
文化
情感
汽车
三农
军事
旅行
运动
教育
生活
星座命理

运用LSTM预测黄金和比特币价格

创作时间:
作者:
@小白创作中心

运用LSTM预测黄金和比特币价格

引用
CSDN
1.
https://blog.csdn.net/2301_77294529/article/details/137124002

LSTM(长短期记忆)模型是一种特殊的循环神经网络(RNN),通过引入门机制解决了传统RNN的长记忆性问题。本文将介绍如何使用LSTM模型对黄金和比特币的价格进行预测,包括数据预处理、模型构建和结果可视化等步骤。

LSTM模型简介

LSTM模型通过引入三个门机制(遗忘门、更新门和输出门)来保护和控制细胞状态。门机制通过sigmoid函数和点乘操作实现,sigmoid函数的取值范围为0到1,决定了信息的传递量。当sigmoid取0时表示舍弃信息,取1时表示完全传输。

数据准备

本文使用2022年美赛C题提供的黄金和比特币数据。为了简化计算,将观察跨度设置为2,即根据前2天的数据预测下一天的价格。数据预处理步骤包括数据标准化和数据集划分。

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

filepath = 'E:\desktop\chain1.csv'
data = pd.read_csv(filepath)
data = data.sort_values('Date')
print(data.head())
print(data.shape)

price = data[['Value']]
print(price.info())

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(-1, 1))
price['Value'] = scaler.fit_transform(price['Value'].values.reshape(-1, 1))
print(price['Value'].shape)

def split_data(stock, lookback):
    data_raw = stock.to_numpy()
    data = []
    for index in range(len(data_raw) - lookback):
        data.append(data_raw[index: index + lookback])
    data = np.array(data);
    test_set_size = data.shape[0]
    train_set_size = data.shape[0]
    x_train = data[:train_set_size, :-1, :]
    y_train = data[:train_set_size, -1, :]
    x_test = data[:train_set_size, :-1, :]
    y_test = data[:train_set_size, -1, :]
    return [x_train, y_train, x_test, y_test]

lookback = 2
x_train, y_train, x_test, y_test = split_data(price, lookback)
print('x_train.shape = ', x_train.shape)
print('y_train.shape = ', y_train.shape)
print('x_test.shape = ', x_test.shape)
print('y_test.shape = ', y_test.shape)

模型构建与训练

使用PyTorch构建LSTM模型,设置输入维度为1(只有Value),隐藏层特征维度为32,循环层数为2,预测维度为1。使用均方误差损失函数和Adam优化器进行模型训练。

import torch
import torch.nn as nn

x_train = torch.from_numpy(x_train).type(torch.Tensor)
x_test = torch.from_numpy(x_test).type(torch.Tensor)
y_train_lstm = torch.from_numpy(y_train).type(torch.Tensor)
y_test_lstm = torch.from_numpy(y_test).type(torch.Tensor)
y_train_gru = torch.from_numpy(y_train).type(torch.Tensor)
y_test_gru = torch.from_numpy(y_test).type(torch.Tensor)

input_dim = 1
hidden_dim = 32
num_layers = 2
output_dim = 1
num_epochs = 100

class LSTM(nn.Module):
    def __init__(self, input_dim, hidden_dim, num_layers, output_dim):
        super(LSTM, self).__init__()
        self.hidden_dim = hidden_dim
        self.num_layers = num_layers
        self.lstm = nn.LSTM(input_dim, hidden_dim, num_layers, batch_first=True)
        self.fc = nn.Linear(hidden_dim, output_dim)
    def forward(self, x):
        h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).requires_grad_()
        c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_dim).requires_grad_()
        out, (hn, cn) = self.lstm(x, (h0.detach(), c0.detach()))
        out = self.fc(out[:, -1, :])
        return out

model = LSTM(input_dim=input_dim, hidden_dim=hidden_dim, output_dim=output_dim, num_layers=num_layers)
criterion = torch.nn.MSELoss()
optimiser = torch.optim.Adam(model.parameters(), lr=0.01)

hist = np.zeros(num_epochs)
start_time = time.time()
lstm = []
for t in range(num_epochs):
    y_train_pred = model(x_train)
    loss = criterion(y_train_pred, y_train_lstm)
    print("Epoch ", t, "MSE: ", loss.item())
    hist[t] = loss.item()
    optimiser.zero_grad()
    loss.backward()
    optimiser.step()

training_time = time.time() - start_time
print("Training time: {}".format(training_time))

结果可视化

使用Seaborn库对预测结果和损失函数进行可视化。从图中可以看出,比特币和黄金的预测值拟合效果良好,损失函数值均低于0.5。

predict = pd.DataFrame(scaler.inverse_transform(y_train_pred.detach().numpy()))
original = pd.DataFrame(scaler.inverse_transform(y_train_lstm.detach().numpy()))

import seaborn as sns
sns.set_style("darkgrid")
fig = plt.figure()
fig.subplots_adjust(hspace=0.2, wspace=0.2)

plt.subplot(1, 2, 1)
ax = sns.lineplot(x=original.index, y=original[0], label="Data", color='royalblue')
ax = sns.lineplot(x=predict.index, y=predict[0], label="Training Prediction (LSTM)", color='tomato')
ax.set_title('Stock price', size=14, fontweight='bold')
ax.set_xlabel("Days", size=14)
ax.set_ylabel("Cost (USD)", size=14)
ax.set_xticklabels('', size=10)

plt.subplot(1, 2, 2)
ax = sns.lineplot(data=hist, color='royalblue')
ax.set_xlabel("Epoch", size=14)
ax.set_ylabel("Loss", size=14)
ax.set_title("Training Loss", size=14, fontweight='bold')

fig.set_figheight(6)
fig.set_figwidth(16)
plt.show()

结果分析

从预测结果来看,LSTM模型对黄金和比特币价格的预测效果良好,损失函数值均低于0.5。但是需要注意的是,金融市场具有波动性和不确定性,模型预测结果并不能完全准确地反映市场变动。为了提高预测精度,可以尝试加入智能优化算法(如模拟退火、遗传算法、粒子群优化等)对模型进行优化。



© 2023 北京元石科技有限公司 ◎ 京公网安备 11010802042949号