The poor performance of your model and backtest results stems from several issues in your code, particularly in the data preparation and backtesting stages. Below, I'll analyze the problems and provide suggested improvements to help you get better results.
Issues in Your Code
1. Incorrect Label Calculation in Data Preparation
Problem:
In your data_preparation.py, the labels are calculated based on the difference between two scaled deltas:
delta_next = data[i+100] - data[i+99]
label = 1 if delta_next > 0 else 0
Since data[i] represents the scaled percentage change (delta) at time i, subtracting one scaled delta from another doesn't provide meaningful information about future price direction. This approach results in labels that don't accurately represent whether the price is moving up or down.
Solution:
Labels should be calculated based on the actual price movement between two time points. Specifically, you should compare the prices at i+99 and i+100 to determine if the price went up or down. Here's how you can fix it:
prices = df['close'].values
for i in range(len(data) - 100):
seq = data[i:i + 100]
# The label is whether the price increased from time i+99 to i+100
price_last = prices[i + 99]
price_next = prices[i + 100]
label = 1 if price_next > price_last else 0
sequences.append(seq)
labels.append(label)
2. Faulty Profit Calculation in Backtesting
Problem:
In your backtest.py, the profit calculation is incorrect. You're setting exit_price to constants (1 - fees) or (1 + fees), which doesn't make sense in the context of actual price movements:
if predictions[i] == 1: # Predict Up
entry_price *= (1 + fees)
exit_price = (1 - fees)
profit = (exit_price - entry_price) / entry_price
else: # Predict Down
entry_price = (1 - fees)
exit_price = (1 + fees)
profit = (entry_price - exit_price) / entry_price
This approach ignores the actual exit prices and miscalculates the profits, leading to erroneous backtest results.
Solution:
Revise the profit calculation to use the actual entry_price and exit_price, adjusting for fees appropriately. Here's the corrected code:
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) / 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) / effective_entry_price
profits.append(profit)
3. Misalignment of Data Indices
Problem:
The indices used when aligning sequences with prices may be off by one due to zero-based indexing, potentially causing misalignment between your sequences and corresponding prices.
Solution:
Ensure that your indices align correctly by carefully adjusting them based on the context. For example, when preparing sequences and labels, if you use data[i:i+100], then prices[i + 99] corresponds to the last price in the sequence, and prices[i + 100] is the next price.
4. Potential Data Leakage
Problem:
If data is not properly shuffled or split, there could be data leakage between training, validation, and test sets, leading to overfitting and poor generalization.
Solution:
Ensure that your data splitting is done correctly, and avoid any overlap between the datasets. Use proper shuffling and consider time-based split if applicable.
5. Model Architecture and Hyperparameters
Problem:
The model may not be sufficiently complex, or the hyperparameters may not be optimal for capturing the patterns in the data.
Solution:
Experiment with different model architectures and hyperparameters. Consider increasing the number of layers, using different activation functions, or trying other model types like LSTM or GRU that are often used for time series data.
Corrected and Improved Code
Updated data_preparation.py
# data_preparation.py
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler
def load_data(file_path):
df = pd.read_csv(file_path, parse_dates=['timestamp'])
df.sort_values('timestamp', inplace=True)
df.reset_index(drop=True, inplace=True)
return df
def preprocess_data(df):
# Calculate price change deltas
df['delta'] = df['close'].pct_change().fillna(0)
# Remove outliers
mean = df['delta'].mean()
std = df['delta'].std()
threshold = 3 * std
df = df[np.abs(df['delta'] - mean) <= threshold]
df.reset_index(drop=True, inplace=True)
# Normalize deltas
scaler = MinMaxScaler()
df['delta_scaled'] = scaler.fit_transform(df[['delta']])
# Prepare sequences of 100 steps and labels
sequences = []
labels = []
data = df['delta_scaled'].values
prices = df['close'].values
for i in range(len(data) - 100):
seq = data[i:i + 100]
# The label is whether the price increased from time i+99 to i+100
price_last = prices[i + 99]
price_next = prices[i + 100]
label = 1 if price_next > price_last else 0
sequences.append(seq)
labels.append(label)
sequences = np.array(sequences)
labels = np.array(labels)
return sequences, labels, scaler
def split_data(sequences, labels):
num_samples = sequences.shape[0]
train_end = int(num_samples * 0.7)
val_end = int(num_samples * 0.85)
X_train = sequences[:train_end]
y_train = labels[:train_end]
X_val = sequences[train_end:val_end]
y_val = labels[train_end:val_end]
X_test = sequences[val_end:]
y_test = labels[val_end:]
return X_train, y_train, X_val, y_val, X_test, y_test
def save_data(X_train, y_train, X_val, y_val, X_test, y_test, scaler):
np.save('data/X_train.npy', X_train)
np.save('data/y_train.npy', y_train)
np.save('data/X_val.npy', X_val)
np.save('data/y_val.npy', y_val)
np.save('data/X_test.npy', X_test)
np.save('data/y_test.npy', y_test)
import joblib
joblib.dump(scaler, 'data/scaler.save')
if __name__ == "__main__":
df = load_data('data/btcusdt_5min.csv')
sequences, labels, scaler = preprocess_data(df)
X_train, y_train, X_val, y_val, X_test, y_test = split_data(sequences, labels)
save_data(X_train, y_train, X_val, y_val, X_test, y_test, scaler)
print("Data preparation completed.")
Updated 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 = []
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) / 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) / effective_entry_price
profits.append(profit)
cumulative_returns = np.cumsum(profits)
return profits, cumulative_returns
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 = backtest(model, X_test, prices)
# Calculate Metrics
total_return = cumulative_returns[-1] * 100
win_rate = (np.array(profits) > 0).sum() / len(profits) * 100
max_drawdown = np.min(cumulative_returns) * 100
print(f'Total Return: {total_return:.2f}%')
print(f'Win Rate: {win_rate:.2f}%')
print(f'Max Drawdown: {max_drawdown:.2f}%')
# 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()
Note: Adjust the path 'models/best_model.pth' if necessary, and ensure that the model's .to(device) and map_location match your device configuration.
Additional Recommendations
-
Model Architecture: Consider experimenting with different model architectures, such as Long Short-Term Memory (LSTM) networks, which are well-suited for time-series data.
-
Hyperparameter Tuning: Adjust hyperparameters like learning rate, number of layers, and batch size. Using techniques like grid search or Bayesian optimization can help find optimal values.
-
Feature Engineering: Incorporate additional features that might help the model, such as technical indicators (e.g., moving averages, RSI, MACD).
-
Data Augmentation: Use techniques to augment your dataset if it's not sufficiently large, such as adding noise or simulating additional data.
-
Validation Strategy: Since financial data is time-dependent, consider using time-based cross-validation techniques, like walk-forward validation, to better assess model performance.
-
Regularization: Apply regularization methods like dropout or L2 regularization to prevent overfitting.
-
Early Stopping: Monitor validation loss and implement early stopping during training to prevent overfitting.
-
Normalization Consistency: Ensure that the same scaler used during training is applied during backtesting and inference to maintain consistency.
-
Logging and Monitoring: Use logging libraries or tensorboard to keep track of your training metrics over epochs.
By addressing the issues in your code and implementing these improvements, you should see better model performance and more realistic backtesting results. Remember that predicting financial markets is inherently challenging due to their complexity and the presence of random noise, so continuous experimentation and refinement are key.