1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201
| import time import numpy as np import pandas as pd import torch import torch.nn as nn from torch.utils.data import Dataset, DataLoader from sklearn.preprocessing import MinMaxScaler import matplotlib.pyplot as plt
device = torch.device("cpu")
print(f"Using device: {device}")
torch.manual_seed(42)
data = pd.read_csv("./bitcoin.csv") data['date'] = pd.to_datetime(data['date']) data.set_index('date', inplace=True)
gold = pd.read_csv("./gold.csv") gold['date'] = pd.to_datetime(gold['date']) gold.set_index('date', inplace=True)
scaler = MinMaxScaler(feature_range=(0, 1)) scaled_bitcoin = scaler.fit_transform(data['value'].values.reshape(-1, 1)) scaled_gold = scaler.fit_transform(gold['value'].values.reshape(-1, 1))
class LSTMDataset(Dataset): def __init__(self, data, seq_length): self.data = data self.seq_length = seq_length
def __len__(self): return len(self.data) - self.seq_length
def __getitem__(self, index): x = self.data[index:index + self.seq_length] y = self.data[index + self.seq_length] return (torch.tensor(x, dtype=torch.float32).to(device), torch.tensor(y, dtype=torch.float32).to(device))
SEQ_LENGTH = 5 BATCH_SIZE = 512 LEARNING_RATE = 0.001 NUM_EPOCHS = 2000
dataset_bitcoin = LSTMDataset(scaled_bitcoin, SEQ_LENGTH) dataset_gold = LSTMDataset(scaled_gold, SEQ_LENGTH)
train_size = int(0.5 * len(dataset_bitcoin)) test_size = len(dataset_bitcoin) - train_size
train_dataset_bitcoin, test_dataset_bitcoin = ( torch.utils.data.random_split(dataset_bitcoin, [train_size, test_size])) train_loader_bitcoin = DataLoader(train_dataset_bitcoin, batch_size=BATCH_SIZE, shuffle=True) test_loader_bitcoin = DataLoader(test_dataset_bitcoin, batch_size=BATCH_SIZE, shuffle=False)
train_dataset_gold, test_dataset_gold = torch.utils.data.random_split(dataset_gold, [train_size, test_size]) train_loader_gold = DataLoader(train_dataset_gold, batch_size=BATCH_SIZE, shuffle=True) test_loader_gold = DataLoader(test_dataset_gold, batch_size=BATCH_SIZE, shuffle=False)
class LSTM(nn.Module): def __init__(self, input_size=1, hidden_size=5, num_layers=1, output_size=1): super(LSTM, self).__init__() self.hidden_size = hidden_size self.num_layers = num_layers self.lstm = nn.LSTM(input_size, hidden_size, num_layers, batch_first=True) self.fc = nn.Linear(hidden_size, output_size)
def forward(self, x): h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device) c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size).to(x.device) out, _ = self.lstm(x, (h0, c0)) out = self.fc(out[:, -1, :]) return out
model = LSTM().to(device) criterion = nn.SmoothL1Loss().to(device) optimizer = torch.optim.RMSprop(model.parameters(), lr=LEARNING_RATE)
st = time.time() print("Training started at:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(st))) train_losses = []
for epoch in range(NUM_EPOCHS): model.train() total_loss = 0.0 for ((inputs, targets), (inputs2, targets2)) in zip(train_loader_bitcoin, train_loader_gold): outputs = model(inputs) outputs2 = model(inputs2) loss = criterion(outputs, targets) + criterion(outputs2, targets2) optimizer.zero_grad() loss.backward() optimizer.step() total_loss += loss.item() aveLoss = total_loss / len(train_loader_bitcoin) train_losses.append(aveLoss) if (epoch + 1) % (NUM_EPOCHS / 10) == 0: print(f"Epoch [{epoch + 1}/{NUM_EPOCHS}], Loss: {aveLoss}") et = time.time() print("Training finished at:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(et)) + ", duration:", str(et - st), "seconds")
loss_samples = [] epochId = [] for i in range(NUM_EPOCHS): if (i + 1) % (NUM_EPOCHS / 50) == 0: loss_samples.append(train_losses[i]) epochId.append(i + 1)
plt.figure(figsize=(10, 6)) plt.plot(epochId, loss_samples, marker='o', label="Training Loss") plt.xlabel("Epochs") plt.ylabel("Loss") plt.title("Training Loss vs Epochs") plt.legend() plt.grid(True) plt.show()
def create_sequences(data, seq_length): sequences = [] labels = [] for i in range(len(data) - seq_length): seq = data[i:i + seq_length] label = data[i + seq_length] sequences.append(seq) labels.append(label) return (torch.tensor(np.array(sequences), dtype=torch.float32).to(device), torch.tensor(np.array(labels), dtype=torch.float32).to(device))
X, y = create_sequences(scaled_bitcoin, SEQ_LENGTH) X2, y2 = create_sequences(scaled_gold, SEQ_LENGTH)
model.eval() with torch.no_grad(): test_pred = model(X) test2_pred = model(X2)
test_pred = scaler.inverse_transform(test_pred.cpu().numpy()) test2_pred = scaler.inverse_transform(test2_pred.cpu().numpy())
y = scaler.inverse_transform(y.cpu().numpy()) y2 = scaler.inverse_transform(y2.cpu().numpy())
plt.figure(figsize=(14, 6)) plt.plot(y, label="Actual Price") plt.plot(test_pred, label="Predicted Price") plt.legend() plt.title("Bitcoin Price Prediction") plt.show()
plt.figure(figsize=(14, 6)) plt.plot(y2, label="Actual Price") plt.plot(test2_pred, label="Predicted Price") plt.legend() plt.title("Gold Price Prediction") plt.show()
mape_bitcoin = 0.0 mape_gold = 0.0 for i, j in zip(y, test_pred): mape_bitcoin += abs(j - i) / j mape_bitcoin /= len(y) for i, j in zip(y2, test2_pred): mape_gold += abs(j - i) / j mape_gold /= len(y2) mape_bitcoin = mape_bitcoin[0] mape_gold = mape_gold[0] print("Bitcoin's MAPE:", mape_bitcoin) print("Gold's MAPE:", mape_gold)
torch.save(model.state_dict(), "./models/price_predict_model-" + str(et) + ".pth") print("Model saved as " + "./models/price_predict_model-" + str(et) + ".pth")
|