Certainly! I've reviewed your project and have made several improvements to enhance the model's performance, prevent overfitting, and better meet the project's goals and constraints. Below are the updated files along with explanations of the changes made.
Key Improvements:
-
Model Architecture Enhancements:
- Implemented attention pooling over the time dimension to allow the model to focus on important time steps, especially recent ones.
- Added dropout layers to prevent overfitting.
- Included weight decay (L2 regularization) in the optimizer to penalize large weights.
-
Training Enhancements:
- Introduced learning rate scheduling using
ReduceLROnPlateau to adjust the learning rate during training based on validation loss.
- Implemented early stopping to prevent overfitting by halting training when validation performance stops improving.
- Increased the number of epochs to allow the model more training iterations, with early stopping in place to prevent overfitting.
-
Evaluation Metrics:
- Calculated Sharpe Ratio and Sortino Ratio during backtesting to provide a comprehensive evaluation of the model's performance.
- Ensured that the computation of profits and returns correctly accounts for fees and position types.
-
Logging and Visualization:
- Added plotting of training and validation loss and accuracy to monitor training progress.
- Included detailed print statements and logging for better traceability.
-
Code Optimization:
- Ensured compatibility with NVIDIA GPUs and CUDA.
- Refactored code for clarity and efficiency.
Updated Files and Explanations
1. model.py
# model.py
import torch
import torch.nn as nn
import numpy as np
class PositionalEncoding(nn.Module):
def __init__(self, d_model, max_len=100):
super().__init__()
position = torch.arange(0, max_len).unsqueeze(1) # Shape: (max_len, 1)
div_term = torch.exp(
torch.arange(0, d_model, 2) * (-np.log(10000.0) / d_model)
) # Shape: (d_model/2,)
pe = torch.zeros(1, max_len, d_model) # Shape: (1, max_len, d_model)
pe[0, :, 0::2] = torch.sin(position * div_term) # Broadcast multiplication
pe[0, :, 1::2] = torch.cos(position * div_term)
self.register_buffer('pe', pe) # pe is a buffer, not a parameter
def forward(self, x):
x = x + self.pe[:, :x.size(1)].to(x.device)
return x
class PriceDirectionTransformer(nn.Module):
def __init__(self, feature_size=64, num_layers=2, num_heads=4, dropout=0.1):
super().__init__()
self.model_type = 'Transformer'
self.embedding = nn.Linear(1, feature_size)
self.positional_encoding = PositionalEncoding(feature_size)
encoder_layers = nn.TransformerEncoderLayer(
d_model=feature_size,
nhead=num_heads,
dropout=dropout,
dim_feedforward=256,
batch_first=True,
)
self.transformer_encoder = nn.TransformerEncoder(
encoder_layer=encoder_layers,
num_layers=num_layers,
)
# Attention pooling over time dimension
self.attention_weights = nn.Linear(feature_size, 1)
self.fc_out = nn.Linear(feature_size, 2) # Up or Down
self.softmax = nn.Softmax(dim=1)
self.dropout = nn.Dropout(dropout)
def forward(self, src):
# src shape: (batch_size, seq_len)
src = src.unsqueeze(-1) # Shape: (batch_size, seq_len, 1)
src = self.embedding(src) # Shape: (batch_size, seq_len, feature_size)
src = self.positional_encoding(src)
src = self.dropout(src)
output = self.transformer_encoder(src) # Shape: (batch_size, seq_len, feature_size)
# Attention pooling over time dimension
attn_weights = self.attention_weights(output).squeeze(-1) # Shape: (batch_size, seq_len)
attn_weights = torch.softmax(attn_weights, dim=1) # Shape: (batch_size, seq_len)
pooled_output = torch.bmm(attn_weights.unsqueeze(1), output).squeeze(1) # Shape: (batch_size, feature_size)
output = self.fc_out(pooled_output)
output = self.softmax(output)
return output
Explanation:
- Attention Pooling: Replaced the global average pooling with an attention mechanism over the time dimension. This allows the model to learn which time steps are more important, focusing on recent steps if necessary.
- Dropout Layer: Added dropout after positional encoding to prevent overfitting.
- Model Adjustments: Ensured that all operations are compatible with CUDA and optimized for GPU computations.
2. train.py
# train.py
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from model import PriceDirectionTransformer
from utils import BTCUSDTDataset
import numpy as np
def train_model(model, dataloader, criterion, optimizer, device):
model.train()
epoch_loss = 0
correct_predictions = 0
total_predictions = 0
for sequences, labels in dataloader:
sequences = sequences.to(device)
labels = labels.to(device)
optimizer.zero_grad()
outputs = model(sequences)
loss = criterion(outputs, labels)
loss.backward()
optimizer.step()
epoch_loss += loss.item()
_, predicted = torch.max(outputs, 1)
correct_predictions += (predicted == labels).sum().item()
total_predictions += labels.size(0)
accuracy = correct_predictions / total_predictions
return epoch_loss / len(dataloader), accuracy
def validate_model(model, dataloader, criterion, device):
model.eval()
epoch_loss = 0
correct_predictions = 0
total_predictions = 0
with torch.no_grad():
for sequences, labels in dataloader:
sequences = sequences.to(device)
labels = labels.to(device)
outputs = model(sequences)
loss = criterion(outputs, labels)
epoch_loss += loss.item()
_, predicted = torch.max(outputs, 1)
correct_predictions += (predicted == labels).sum().item()
total_predictions += labels.size(0)
accuracy = correct_predictions / total_predictions
return epoch_loss / len(dataloader), accuracy
if __name__ == "__main__":
# Hyperparameters
FEATURE_SIZE = 64
NUM_LAYERS = 2
NUM_HEADS = 4
DROPOUT = 0.1
BATCH_SIZE = 64
NUM_EPOCHS = 50
LEARNING_RATE = 0.001
WEIGHT_DECAY = 1e-5
PATIENCE = 5 # Early stopping patience
# Device Configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Load Data
X_train = np.load('data/X_train.npy')
y_train = np.load('data/y_train.npy')
X_val = np.load('data/X_val.npy')
y_val = np.load('data/y_val.npy')
# Create Datasets and Dataloaders
train_dataset = BTCUSDTDataset(X_train, y_train)
val_dataset = BTCUSDTDataset(X_val, y_val)
train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE, shuffle=False)
# Initialize Model
model = PriceDirectionTransformer(
feature_size=FEATURE_SIZE,
num_layers=NUM_LAYERS,
num_heads=NUM_HEADS,
dropout=DROPOUT,
).to(device)
# Loss and Optimizer
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(model.parameters(), lr=LEARNING_RATE, weight_decay=WEIGHT_DECAY)
scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.5, patience=2)
# Training Loop
best_val_accuracy = 0
epochs_without_improvement = 0
train_losses = []
val_losses = []
train_accuracies = []
val_accuracies = []
for epoch in range(NUM_EPOCHS):
train_loss, train_accuracy = train_model(
model, train_loader, criterion, optimizer, device
)
val_loss, val_accuracy = validate_model(
model, val_loader, criterion, device
)
scheduler.step(val_loss)
train_losses.append(train_loss)
val_losses.append(val_loss)
train_accuracies.append(train_accuracy)
val_accuracies.append(val_accuracy)
if val_accuracy > best_val_accuracy:
best_val_accuracy = val_accuracy
torch.save(model.state_dict(), 'models/best_model.pth')
epochs_without_improvement = 0
else:
epochs_without_improvement += 1
if epochs_without_improvement >= PATIENCE:
print(f'Early stopping at epoch {epoch+1}')
break
print(
f'Epoch {epoch+1}/{NUM_EPOCHS}, '
f'Train Loss: {train_loss:.4f}, Train Acc: {train_accuracy:.4f}, '
f'Val Loss: {val_loss:.4f}, Val Acc: {val_accuracy:.4f}'
)
# Save Final Model
torch.save(model.state_dict(), 'models/final_model.pth')
print("Training completed.")
# Plot training and validation loss and accuracy
import matplotlib.pyplot as plt
epochs = range(1, len(train_losses) + 1)
plt.figure(figsize=(12,5))
plt.subplot(1,2,1)
plt.plot(epochs, train_losses, label='Train Loss')
plt.plot(epochs, val_losses, label='Val Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
plt.title('Loss')
plt.subplot(1,2,2)
plt.plot(epochs, train_accuracies, label='Train Acc')
plt.plot(epochs, val_accuracies, label='Val Acc')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.title('Accuracy')
plt.show()
Explanation:
- Learning Rate Scheduler: Added
ReduceLROnPlateau to reduce the learning rate when the validation loss plateaus.
- Early Stopping: Implemented early stopping to halt training when the model stops improving on the validation set.
- Weight Decay: Introduced weight decay in the optimizer to penalize large weights and prevent overfitting.
- Logging and Visualization: Added code to log and plot training and validation loss and accuracy for monitoring.
- Increased Epochs: Increased the maximum number of epochs to 50, but with early stopping to prevent unnecessary training.
3. backtest.py
# backtest.py
import torch
import numpy as np
import pandas as pd
from model import PriceDirectionTransformer
def backtest(model, sequences, prices, fees=0.001):
model.eval()
device = next(model.parameters()).device
sequences = torch.Tensor(sequences).to(device)
with torch.no_grad():
outputs = model(sequences)
_, predictions = torch.max(outputs, 1)
predictions = predictions.cpu().numpy()
profits = []
returns = []
for i in range(len(predictions)):
entry_price = prices[i + 99]
exit_price = prices[i + 100] if i + 100 < len(prices) else prices[-1]
if predictions[i] == 1: # Predict Up
# Buy at entry_price, sell at exit_price
effective_entry_price = entry_price * (1 + fees)
effective_exit_price = exit_price * (1 - fees)
profit = effective_exit_price - effective_entry_price
return_pct = (effective_exit_price - effective_entry_price) / effective_entry_price
else: # Predict Down
# Short sell at entry_price, buy back at exit_price
effective_entry_price = entry_price * (1 - fees)
effective_exit_price = exit_price * (1 + fees)
profit = effective_entry_price - effective_exit_price
return_pct = (effective_entry_price - effective_exit_price) / effective_entry_price
profits.append(profit)
returns.append(return_pct)
cumulative_returns = np.cumsum(returns)
return profits, cumulative_returns, returns
def calculate_metrics(returns, cumulative_returns):
total_return = cumulative_returns[-1] * 100
win_rate = (np.array(returns) > 0).sum() / len(returns) * 100
max_drawdown = np.min(cumulative_returns) * 100
avg_return = np.mean(returns)
std_return = np.std(returns)
sharpe_ratio = avg_return / std_return * np.sqrt(len(returns))
# For Sortino Ratio, need to compute downside standard deviation
downside_returns = np.array([r for r in returns if r < 0])
if len(downside_returns) > 0:
downside_std = np.std(downside_returns)
sortino_ratio = avg_return / downside_std * np.sqrt(len(returns))
else:
sortino_ratio = np.nan
return total_return, win_rate, max_drawdown, sharpe_ratio, sortino_ratio
if __name__ == "__main__":
# Load Test Data and Prices
X_test = np.load('data/X_test.npy')
y_test = np.load('data/y_test.npy')
df = pd.read_csv('data/btcusdt_5min.csv', parse_dates=['timestamp'])
df.sort_values('timestamp', inplace=True)
df.reset_index(drop=True, inplace=True)
total_sequences = len(X_test)
prices = df['close'].values[-(total_sequences + 100):] # Adjust the slice
# Load Scaler if needed
# scaler = joblib.load('data/scaler.save')
# Initialize Model
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
model = PriceDirectionTransformer()
model.load_state_dict(torch.load('models/best_model.pth', map_location=device))
model.to(device)
# Perform Backtesting
profits, cumulative_returns, returns = backtest(model, X_test, prices)
# Calculate Metrics
total_return, win_rate, max_drawdown, sharpe_ratio, sortino_ratio = calculate_metrics(returns, cumulative_returns)
print(f'Total Return: {total_return:.2f}%')
print(f'Win Rate: {win_rate:.2f}%')
print(f'Max Drawdown: {max_drawdown:.2f}%')
print(f'Sharpe Ratio: {sharpe_ratio:.4f}')
print(f'Sortino Ratio: {sortino_ratio:.4f}')
# Plotting Cumulative Returns
import matplotlib.pyplot as plt
plt.figure(figsize=(12,6))
plt.plot(cumulative_returns, label='Cumulative Returns')
plt.xlabel('Trade Number')
plt.ylabel('Cumulative Return')
plt.title('Backtesting Cumulative Returns')
plt.legend()
plt.show()
Explanation:
- Sharpe and Sortino Ratios: Implemented the calculation of Sharpe and Sortino Ratios to evaluate risk-adjusted returns.
- Profit Calculation: Ensured that the profit and return calculations correctly account for trading fees and position types (long vs. short).
- Metrics Function: Created a separate function
calculate_metrics for clarity and modularity.
- Compatibility: Made sure that all calculations are compatible with NumPy arrays and optimized for performance.
4. single_prediction.py
# single_prediction.py
import torch
import numpy as np
import random
from model import PriceDirectionTransformer
def single_prediction(model, X_test, y_test, device):
# Choose a random index
random_index = random.randint(0, len(X_test) - 1)
# Extract sequence and corresponding label
sequence = X_test[random_index] # Shape: (100,)
true_label = y_test[random_index] # 0 or 1
# Convert sequence to tensor and send to device
sequence_tensor = torch.Tensor(sequence).unsqueeze(0).to(device) # Shape: (1, 100)
# Forward pass through the model
model.eval()
with torch.no_grad():
output = model(sequence_tensor) # Shape: (1, 2)
predicted_probabilities = output.cpu().numpy()[0] # Probabilities for classes
predicted_label = np.argmax(predicted_probabilities)
# Display results
classes = ['Down', 'Up']
print(f"Sequence index: {random_index}")
print(f"Predicted probabilities: {predicted_probabilities}")
print(f"Predicted label: {predicted_label} ({classes[predicted_label]})")
print(f"True label: {true_label} ({classes[true_label]})")
# Additionally, inspect the data
print(f"Last 5 values in the sequence: {sequence[-5:]}")
if __name__ == "__main__":
# Device for computation
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Load test data
X_test = np.load('data/X_test.npy')
y_test = np.load('data/y_test.npy')
# Load the model
model = PriceDirectionTransformer()
model.load_state_dict(torch.load('models/best_model.pth', map_location=device))
model.to(device)
# Perform prediction on a single sequence
single_prediction(model, X_test, y_test, device)
Explanation:
- Code Optimization: Improved code readability and compatibility without changing functionality.
- Comments and Clarity: Added comments for better understanding.
5. test.py
# test.py
import torch
import torch.nn as nn
from torch.utils.data import DataLoader
from model import PriceDirectionTransformer
from utils import BTCUSDTDataset
import numpy as np
def test_model(model, dataloader, criterion, device):
model.eval()
epoch_loss = 0
correct_predictions = 0
total_predictions = 0
all_labels = []
all_predictions = []
with torch.no_grad():
for sequences, labels in dataloader:
sequences = sequences.to(device)
labels = labels.to(device)
outputs = model(sequences)
loss = criterion(outputs, labels)
epoch_loss += loss.item()
_, predicted = torch.max(outputs, 1)
correct_predictions += (predicted == labels).sum().item()
total_predictions += labels.size(0)
all_labels.extend(labels.cpu().numpy())
all_predictions.extend(predicted.cpu().numpy())
accuracy = correct_predictions / total_predictions
return epoch_loss / len(dataloader), accuracy, all_labels, all_predictions
if __name__ == "__main__":
# Device Configuration
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Load Test Data
X_test = np.load('data/X_test.npy')
y_test = np.load('data/y_test.npy')
test_dataset = BTCUSDTDataset(X_test, y_test)
test_loader = DataLoader(test_dataset, batch_size=64, shuffle=False)
# Initialize Model
model = PriceDirectionTransformer()
model.load_state_dict(torch.load('models/best_model.pth'))
model.to(device)
# Loss Function
criterion = nn.CrossEntropyLoss()
# Test Model
test_loss, test_accuracy, all_labels, all_predictions = test_model(
model, test_loader, criterion, device
)
print(f'Test Loss: {test_loss:.4f}, Test Accuracy: {test_accuracy:.4f}')
# Additional Metrics can be calculated here
Explanation:
- Code Optimization: Kept the test code efficient and compatible with the updated model.
- Metrics: Prepared the code to allow for the calculation of additional metrics if needed.
6. utils.py
# utils.py
import torch
from torch.utils.data import Dataset
class BTCUSDTDataset(Dataset):
def __init__(self, sequences, labels):
self.sequences = torch.Tensor(sequences)
self.labels = torch.LongTensor(labels)
def __len__(self):
return len(self.sequences)
def __getitem__(self, idx):
return self.sequences[idx], self.labels[idx]
Explanation:
- Code Clarity: Ensured the dataset class is clear and efficient.
- Compatibility: Made sure that data types are compatible with PyTorch operations.
Conclusion and Recommendations
By implementing these improvements, the model should better focus on relevant time steps, be less prone to overfitting, and provide a more comprehensive evaluation of its performance. The addition of attention pooling allows the model to weigh the importance of recent price changes more effectively, aligning with the behavior of a real trader.
Further Suggestions:
- Feature Engineering: Consider incorporating additional features such as technical indicators (e.g., moving averages, RSI, MACD) to provide the model with more information.
- Data Augmentation: Use data augmentation techniques to increase the diversity of training data.
- Reinforcement Learning: For future development, explore reinforcement learning approaches where the model's training objective is directly tied to trading performance metrics.
I hope these improvements enhance your model's performance and help you achieve your project goals!