Hello! Let's develop an advanced AI model for intraday trading of Bitcoin (BTCUSDT) on Binance.
Goal:
Primary: Maximize profit from trading BTCUSDT.
Secondary: Achieve an accuracy of predicting the direction of price change (up/down) of at least 60%.
The model should take 100 steps of 5-minute Bitcoin price changes and predict the 101st step.
Constraints:
Maximum allowable drawdown is no more than 5%.
The maximum number of simultaneously open trades is 1.
Dataset:
Data: 5-minute BTCUSDT price data from Binance for the period from 01.01.2020 to 31.12.2022.
Format: Groups of 101 steps, where the first 100 steps are input data (price change relative to the previous step, delta), the 101st step is the target variable (direction of price change - up/down).
Outlier Handling: Exclude steps with a price change greater than 3 standard deviations from the mean.
Normalization: Apply MinMaxScaler to the input data.
Dataset Preparation:
Split the data into training and test sets*
Model:
I suggest choosing a Transformer architecture with an attention mechanism, so that it focuses on the last steps but does not lose sight of the first ones. It should be like a real trader - analyzing all the steps and looking for patterns.
Training: Use Reinforcement Learning, where the model will learn from its mistakes and strive to maximize profits while adhering to risk constraints.
(Apply modern methods to create this advanced model).
Model Testing:
Get steps from the test set.
Pass 100 steps to the model.
Get the prediction and compare it with the actual 101st step.
Figure out the rest yourself.
Possible problems:
Overfitting. The LLM should consider this problem and apply effective methods to prevent it.
Market volatility. The model should be adaptable to changing market conditions.
The problem of simply averaging the model's response into a constant.
Wishes:
Evaluate the model's performance using Sharpe Ratio, Sortino Ratio, Maximum Drawdown, and also take into account the percentage of profitable trades.
Conduct backtesting on historical data for 2023, simulating real trading, taking into account Binance fees.
Assistant
Provide a detailed description of the chosen model architecture, training method and justification of the decisions made.
You can apply all your ML specialist skills and create a truly advanced model capable of successfully predicting the price.
Use Pytorch to write advanced model code. The model will need to run on NVIDIA GPUs and CUDA
# single_prediction.py
import torch
import numpy as np
import random
from model import PriceDirectionTransformer
def single_prediction(model, X_test, y_test, device):
# Выбираем случайный индекс
random_index = random.randint(0, len(X_test) - 1)
# Извлекаем последовательность и соответствующую метку
sequence = X_test[random_index] # Shape: (100,)
true_label = y_test[random_index] # 0 или 1
# Преобразуем последовательность в тензор и отправляем на устройство
sequence_tensor = torch.Tensor(sequence).unsqueeze(0).to(device) # Shape: (1, 100)
# Пропускаем через модель
model.eval()
with torch.no_grad():
output = model(sequence_tensor) # Shape: (1, 2)
predicted_probabilities = output.cpu().numpy()[0] # Вероятности для классов
predicted_label = np.argmax(predicted_probabilities)
# Отображаем результаты
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]})")
# Дополнительно можно посмотреть на сами данные
# Например, вывести последние значения последовательности
print(f"Last 5 values in the sequence: {sequence[-5:]}")
if __name__ == "__main__":
# Устройство для вычислений
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Загрузка тестовых данных
X_test = np.load('data/X_test.npy')
y_test = np.load('data/y_test.npy')
# Загрузка модели
model = PriceDirectionTransformer()
model.load_state_dict(torch.load('models/best_model.pth', map_location=device))
model.to(device)
# Выполнение предсказания на одной последовательности
single_prediction(model, X_test, y_test, device)
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
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 = 20
LEARNING_RATE = 0.001
# 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
from o1_made.utils import BTCUSDTDataset
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)
# Training Loop
best_val_accuracy = 0
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
)
if val_accuracy > best_val_accuracy:
best_val_accuracy = val_accuracy
torch.save(model.state_dict(), 'models/best_model.pth')
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.")
Certainly! I'd be happy to review your project and suggest improvements. You've taken on an ambitious task, and your project structure looks organized. I'll go through each component of your project, point out potential issues, and suggest enhancements to help you create an advanced model for predicting Bitcoin price movements.
Project Overview
Your project aims to develop a Transformer-based model to predict the direction of Bitcoin price changes using 5-minute interval data from Binance. The goal is to maximize profit while maintaining risk constraints.
Key Components:
Data Preparation:
Data loading and preprocessing.
Handling outliers and normalization.
Model Architecture:
Transformer with attention mechanisms.
Custom positional encoding.
Training Loop:
Training and validation routines.
Early stopping and model checkpointing.
Evaluation:
Testing the model on unseen data.
Backtesting to simulate real trading scenarios.
Detailed Review and Suggestions
1. data_download.py and data_preparation.py
Since these files aren't included, I'll assume they handle data loading, cleaning, and splitting.
Suggestions:
Data Augmentation:
Consider incorporating additional features like volume, technical indicators (e.g., moving averages, RSI, MACD).
This can provide the model with more context.
Data Splitting:
Ensure that the data split (training, validation, test) is time-based to prevent data leakage.
For time series, it's crucial to avoid using future data to predict past prices.
2. model.py
You've defined a Transformer-based model with positional encoding.
Review:
Positional Encoding:
Your positional encoding implementation seems standard.
Embedding Layer:
The embedding layer projects the input to the desired feature size.
Transformer Encoder:
Configured with specified layers and heads.
Output Layer:
Outputs probabilities for two classes: Up or Down.
Suggestions:
Feature Expansion:
Since the input is a single feature (price change delta), you might benefit from expanding it.
Include more features per timestep (e.g., high, low, close prices, technical indicators).
Normalization within the Model:
Consider adding Layer Normalization (nn.LayerNorm) after the positional encoding or transformer encoder layers to stabilize training.
Remove Softmax in Output Layer:
In PyTorch, nn.CrossEntropyLoss expects raw logits, not probabilities.
Remove the self.softmax(output) and let the loss function handle it.
# Remove this line in the forward method:
output = self.softmax(output)
Adjust Output Dimension:
Ensure the output dimension matches the number of classes.
Parameter Initialization:
Initialize the model weights using appropriate methods (e.g., Xavier initialization).
3. train.py
Your training loop sets up the data loaders, model, loss function, optimizer, and runs the training process.
Review:
DataLoader:
Uses BTCUSDTDataset to load data.
Training Loop:
Tracks loss and accuracy.
Saves the best model based on validation accuracy.
Suggestions:
Learning Rate Scheduler:
Implement a learning rate scheduler like ReduceLROnPlateau or StepLR to adjust the learning rate during training.
Experiment with different batch sizes to find the optimal setting.
Performance Metrics:
In addition to accuracy, track precision, recall, F1-score, and confusion matrix to get a better understanding of model performance.
Seed for Reproducibility:
Set seeds for NumPy and PyTorch to make training reproducible.
import random
torch.manual_seed(42)
np.random.seed(42)
random.seed(42)
Model Checkpointing:
Save model checkpoints after each epoch in case you need to resume training.
4. test.py
Your testing script evaluates the model on the test dataset.
Review:
Evaluation Metrics:
Calculates loss and accuracy.
Suggestions:
Comprehensive Metrics:
Evaluate additional metrics like the ROC-AUC score, especially since the dataset might be imbalanced.
Confusion Matrix:
Plot a confusion matrix to understand where the model is making mistakes.
Threshold Adjustment:
If using probabilities, consider adjusting the classification threshold to optimize for your specific metrics (e.g., precision or recall).
5. backtest.py
Simulates trading using model predictions and calculates profits.
Review:
Trading Logic:
Simulates both long and short positions based on predictions.
Incorporates trading fees.
Suggestions:
Position Sizing:
Implement position sizing strategies, such as risk per trade or fixed fractional.
Risk Management:
Include stop-loss and take-profit levels to simulate realistic trading scenarios.
Slippage and Market Impact:
Account for slippage, especially since high-frequency data can be affected by sudden price movements.
Evaluation Metrics:
Calculate the Sharpe Ratio, Sortino Ratio, Maximum Drawdown, and Win Rate as per your project goals.
# Example calculation of Sharpe Ratio
import pandas as pd
returns = pd.Series(profits)
sharpe_ratio = returns.mean() / returns.std() * np.sqrt(252) # Annualized
Array Bounds:
Ensure that the indices for prices do not exceed the array bounds, especially prices[i + 100].
Plot Equity Curve:
Plot the equity curve to visualize growth over time.
6. single_prediction.py
Performs a single prediction and compares it to the true label.
Review:
Random Sampling:
Selects a random test sample.
Suggestions:
Interactive Visualization:
Allow passing specific indices or timestamps to investigate particular events.
Feature Visualization:
Plot the selected sequence to see the pattern the model is analyzing.
7. utils.py
Defines the custom dataset.
Review:
Dataset Class:
Correctly implements __len__ and __getitem__.
Suggestions:
Data Augmentation Placeholder:
If you plan to add data augmentation, this is the place to implement it.
Dynamic Sequence Length:
Consider making the sequence length dynamic, allowing the model to handle varying input lengths.
8. General Suggestions
Model Complexity:
Transformers are powerful but can be overkill for simpler time series data. Experiment with LSTM or Temporal Convolutional Networks to compare performance.
Hyperparameter Tuning:
Use tools like Optuna or hyperopt to systematically tune hyperparameters.
Ensemble Methods:
Combine predictions from multiple models (e.g., Transformer, LSTM, CNN) to improve robustness.
Logging and Monitoring:
Integrate a monitoring tool like TensorBoard to visualize training progress.
from torch.utils.tensorboard import SummaryWriter
writer = SummaryWriter()
# Log losses and metrics during training
writer.add_scalar('Loss/train', train_loss, epoch)
Documentation and Comments:
Add docstrings and comments to explain your code, making it easier for others (and future you) to understand.
Code Refactoring:
Organize your code into modules and classes where appropriate.
Separate configuration parameters into a config file or use argument parsers.
Exception Handling:
Include try-except blocks to handle potential errors, especially in data loading and preprocessing scripts.
Version Control:
If not already, use Git for version control to track changes and collaborate.
9. Advanced Techniques
Reinforcement Learning:
Since you mentioned using reinforcement learning (RL), consider integrating an RL algorithm where the model learns a policy to maximize profit.
Approach:
Use an environment that simulates trading.
The agent (model) takes actions (buy, sell, hold) based on the state (market data).
Implement rewards based on profit and penalties for drawdowns.
Algorithms:
Proximal Policy Optimization (PPO)
Deep Q-Networks (DQN)
Deep Deterministic Policy Gradient (DDPG)
Libraries:
Use libraries like Stable Baselines3 for RL algorithms.
Integrate with custom environments using OpenAI Gym.
Feature Engineering:
Apply more sophisticated feature extraction methods, such as:
Time Embeddings:
Encode time-of-day or day-of-week information, as intraday trading can have temporal patterns.
Fourier Transforms:
Capture frequency components of the price movements.
Anomaly Detection:
Implement mechanisms to detect and handle anomalies or sudden market shifts (e.g., news events).
Transfer Learning:
Pre-train the model on larger datasets or related tasks before fine-tuning on your data.
10. Risk Management
Maximum Drawdown Constraint:
Implement logic to stop trading or adjust strategies if the maximum drawdown exceeds 5%.
# In backtest.py, track drawdowns
import pandas as pd
equity_curve = pd.Series(cumulative_returns)
running_max = equity_curve.cummax()
drawdown = (equity_curve - running_max) / running_max
max_drawdown = drawdown.min()
if max_drawdown < -0.05:
print("Maximum drawdown exceeded 5%. Adjusting strategy.")
# Logic to handle this scenario
Single Trade Constraint:
Ensure that at any given time, only one trade is open.
In your backtesting logic, you can model this by keeping track of the open positions and only allowing a new trade once the previous one is closed.
11. CUDA and GPU Utilization
Optimizing GPU Usage:
Ensure tensors and models are moved to the correct device.
Use .to(device) consistently.
DataLoader with Pin Memory:
When using GPUs, set pin_memory=True in your DataLoader for faster data transfer.
Utilize automatic mixed precision to speed up training and reduce memory usage.
scaler = torch.cuda.amp.GradScaler()
# In training loop:
with torch.cuda.amp.autocast():
outputs = model(sequences)
loss = criterion(outputs, labels)
scaler.scale(loss).backward()
scaler.step(optimizer)
scaler.update()
12. Compliance with Regulatory Requirements
Backtesting Standards:
Ensure your backtesting methodology complies with industry standards.
Risk Disclosures:
When presenting results, include appropriate disclaimers about potential risks.
Conclusion
Your project is on the right track, and with some refinements, it can become a robust tool for predicting Bitcoin price movements. Remember that financial markets are complex and noisy, so while advanced models can help, they should be part of a broader strategy that includes risk management and continuous adaptation.
Next Steps
Implement the suggested changes incrementally to observe their impact.
Experiment with different architectures and hyperparameters to find the optimal configuration.
Gather more data, if possible, to improve model generalization.
Stay updated with the latest research in financial machine learning to incorporate new techniques.
Document your findings and iterations, as this will help in understanding what works and what doesn't.
Feel free to ask if you need clarification on any of the suggestions or further assistance with specific implementations. Good luck with your project!