ing the model...
Epoch 1/10
Traceback (most recent call last):
File "/home/elliot/Downloads/quant work/transformers/7nov1.py", line 575, in
model, history = main()
^^^^^^
File "/home/elliot/Downloads/quant work/transformers/7nov1.py", line 514, in main
history = model.fit(
^^^^^^^^^^
File "/home/elliot/Downloads/quant work/transformers/trans/lib/python3.11/site-packages/keras/src/utils/traceback_utils.py", line 122, in error_handler
raise e.with_traceback(filtered_tb) from None
File "/home/elliot/Downloads/quant work/transformers/trans/lib/python3.11/site-packages/keras/src/backend/tensorflow/nn.py", line 694, in binary_crossentropy
raise ValueError(
ValueError: Arguments target and output must have the same rank (ndim). Received: target.shape=(None,), output.shape=(None, 7) import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
import logging
from ta.volatility import AverageTrueRange, BollingerBands
from ta.momentum import RSIIndicator
from ta.trend import MACD, ADXIndicator
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import (
Input,
Dense,
Dropout,
MultiHeadAttention,
LayerNormalization,
GlobalAveragePooling1D,
)
from tensorflow.keras.models import Model
import tensorflow as tf
from binance.client import Client
df['BB_mavg'] = df['BB_width'].rolling(window=20).mean()
df['BB_vol'] = np.where(df['BB_width'] > 1.2 * df['BB_mavg'], 'High',
np.where(df['BB_width'] < 0.8 * df['BB_mavg'], 'Low', 'Medium'))
df['daily_return'] = df['close'].pct_change()
df['RV'] = df['daily_return'].rolling(window=20).std() * np.sqrt(252)
rv_80 = df['RV'].quantile(0.8)
rv_20 = df['RV'].quantile(0.2)
df['RV_vol'] = np.where(df['RV'] > rv_80, 'High',
np.where(df['RV'] < rv_20, 'Low', 'Medium'))
df['Volatility'] = df[['ATR_vol', 'BB_vol', 'RV_vol']].mode(axis=1)[0]
df['Trend'] = np.where(
(df['MACD'] > df['MACD_signal']) & (df['MACD'] > 0), 'Bullish',
np.where(
(df['MACD'] < df['MACD_signal']) & (df['MACD'] < 0), 'Bearish', 'Neutral'
)
)
df['Trend_strength'] = np.where(df['ADX'] > 25, 'Strong', 'Weak')
df['Market_Environment'] = df.apply(
lambda row: f"{row['Volatility']} Vol/{row['Trend']}" if row['Trend_strength'] == 'Strong' else f"{row['Volatility']} Vol/Neutral",
axis=1
)
# Encode categorical data to numeric
label_encoders = {}
for column in ['ATR_vol', 'BB_vol', 'RV_vol', 'Volatility', 'Trend', 'Trend_strength', 'Market_Environment']:
le = LabelEncoder()
df[column] = le.fit_transform(df[column].astype(str))
label_encoders[column] = le # Save encoder for each column if you need to decode later
return df, label_encoders # Returning encoders in case needed
def calculate_leg_data(df):
"""
Calculate leg data: current and previous leg percent change and length.
"""
df['percent_delta'] = df['close'].pct_change()
df = df.reset_index(drop=True)
percentiles = df['percent_change'].quantile([0.05, 0.20, 0.40, 0.60, 0.80, 0.95]).to_dict()
def classify(x, p):
if x < p[0.05]:
return 'Down a Lot'
elif x < p[0.20]:
return 'Down Moderate'
elif x < p[0.40]:
return 'Down a Little'
elif x < p[0.60]:
return 'No Change'
elif x < p[0.80]:
return 'Up a Little'
elif x < p[0.95]:
return 'Up Moderate'
else:
return 'Up a Lot'
df['percent_change_classification'] = df['percent_change'].apply(lambda x: classify(x, percentiles))
return df
def encode_and_scale(df, label_encoders=None, scalers=None):
"""
Encode categorical features and scale numerical features.
"""
if label_encoders is None:
label_encoders = {}
if scalers is None:
scalers = {}
code
# 1. Encode Categorical Input Features
categorical_features = ['percent_change_classification', 'Market_Environment']
for col in categorical_features:
le = LabelEncoder()
df[f'{col}_encoded'] = le.fit_transform(df[col].astype(str))
label_encoders[col] = le # Save the encoder for future use
# 2. Encode Categorical Target Features (if applicable)
# In this case, 'leg_direction' is binary (0 or 1), so no encoding is needed.
# 3. Scale Numerical Features
numerical_features = [
'RSI', 'MACD', 'MACD_signal', 'ATR', 'BB_width',
'previous_leg_change', 'previous_leg_length',
'current_leg_change', 'current_leg_length'
]
scaler = StandardScaler()
df[numerical_features] = scaler.fit_transform(df[numerical_features])
scalers['numerical'] = scaler # Save the scaler for future use
# 4. Scale Regression Targets
# Scale 'close_price'
scaler_close = StandardScaler()
df['close_price_scaled'] = scaler_close.fit_transform(df[['close']])
scalers['close_price'] = scaler_close
# Scale 'leg_length'
scaler_leg_length = StandardScaler()
df['leg_length_scaled'] = scaler_leg_length.fit_transform(df[['current_leg_length']])
scalers['leg_length'] = scaler_leg_length
return df, label_encoders, scalers
def prepare_sequences(df, seq_length=60, target_steps=1):
"""
Prepare input sequences and corresponding multiple targets for the Transformer.
code
Returns:
- X (np.ndarray): Input sequences.
- Y (dict): Dictionary containing multiple targets.
"""
FEATURES = [
'RSI', 'MACD', 'MACD_signal', 'ATR', 'BB_width',
'previous_leg_change', 'previous_leg_length',
'current_leg_change', 'current_leg_length',
'Market_Environment_encoded'
]
X = []
Y_close = []
Y_percent_change = []
Y_leg_direction = []
Y_leg_length = []
for i in range(len(df) - seq_length - target_steps + 1):
seq = df.iloc[i:i + seq_length][FEATURES].values
target_close = df.iloc[i + seq_length]['close_price_scaled']
target_percent_change = df.iloc[i + seq_length]['percent_change_classification_encoded']
target_leg_direction = 1 if df.iloc[i + seq_length]['current_leg_change'] > 0 else 0
target_leg_length = df.iloc[i + seq_length]['leg_length_scaled']
X.append(seq)
Y_close.append(target_close)
Y_percent_change.append(target_percent_change)
Y_leg_direction.append(target_leg_direction)
Y_leg_length.append(target_leg_length)
X = np.array(X)
Y = {
'close_price': np.array(Y_close).reshape(-1, 1),
'percent_change_classification': np.array(Y_percent_change),
'leg_direction': np.array(Y_leg_direction),
'leg_length': np.array(Y_leg_length).reshape(-1, 1)
}
return X, Y
def build_multi_output_transformer_model(
input_shape,
num_classes_classification,
head_size=256,
num_heads=4,
ff_dim=128,
num_transformer_blocks=2,
dropout=0.1
):
"""
Builds a Transformer model with multiple outputs.
"""
inputs = Input(shape=input_shape, name='input')
code
# Positional Encoding (Learnable)
position_indices = tf.range(start=0, limit=input_shape[0], delta=1)
positional_embedding = Dense(input_shape[1])(tf.expand_dims(position_indices, axis=1))
x = inputs + positional_embedding # Broadcasting addition
# Transformer Encoder Blocks
for _ in range(num_transformer_blocks):
# Layer Normalization 1
x_norm = LayerNormalization(epsilon=1e-6)(x)
# Multi-Head Attention
attention = MultiHeadAttention(key_dim=head_size, num_heads=num_heads, dropout=dropout)(x_norm, x_norm)
attention = Dropout(dropout)(attention)
x = x + attention # Residual connection
# Layer Normalization 2
x_norm = LayerNormalization(epsilon=1e-6)(x)
# Feed-Forward Network
ffn = Dense(ff_dim, activation="relu")(x_norm)
ffn = Dropout(dropout)(ffn)
ffn = Dense(input_shape[-1])(ffn)
ffn = Dropout(dropout)(ffn)
x = x + ffn # Residual connection
# Global Average Pooling
x = GlobalAveragePooling1D()(x)
x = Dropout(dropout)(x)
x = Dense(128, activation="relu")(x)
x = Dropout(dropout)(x)
# Output: Predicted Close Price (Regression)
close_price_output = Dense(1, activation='linear', name='close_price')(x)
# Output: Percent Change Classification (7 classes)
percent_change_output = Dense(num_classes_classification, activation='softmax', name='percent_change_classification')(x)
# Output: Leg Direction (Binary Classification)
leg_direction_output = Dense(1, activation='sigmoid', name='leg_direction')(x) # Changed to sigmoid
# Output: Leg Length (Regression)
leg_length_output = Dense(1, activation='linear', name='leg_length')(x)
# Define the Model
model = Model(
inputs=inputs,
outputs=[
close_price_output,
percent_change_output,
leg_direction_output,
leg_length_output
]
)
return model
def compile_multi_output_model(model):
"""
Compiles the multi-output Transformer model with appropriate loss functions and metrics.
"""
model.compile(
optimizer='adam',
loss={
'close_price': 'mse',
'percent_change_classification': 'sparse_categorical_crossentropy',
'leg_direction': 'binary_crossentropy', # Changed to binary_crossentropy
'leg_length': 'mse'
},
metrics={
'close_price': ['mae'],
'percent_change_classification': ['accuracy'],
'leg_direction': ['accuracy'],
'leg_length': ['mae']
}
)
return model
def plot_attention_matrices(model, sample_input, seq_length, input_dim):
"""
Visualize attention matrices for a sample input.
Note: Accessing exact attention weights requires custom layers or callbacks.
Here, we'll provide a simplified visualization.
"""
# Get the first transformer block's attention layer
attention_layer = None
for layer in model.layers:
if isinstance(layer, MultiHeadAttention):
attention_layer = layer
break
code
if attention_layer is None:
print("No MultiHeadAttention layer found in the model.")
return
# Create a temporary model to get attention outputs
attention_model = Model(inputs=model.input, outputs=attention_layer.output)
attention_output = attention_model.predict(sample_input[np.newaxis, ...])
# Since TensorFlow doesn't expose attention weights directly, we'll visualize the output.
# For detailed attention weights, consider using custom training loops or TensorFlow callbacks.
plt.figure(figsize=(10, 6))
sns.heatmap(attention_output[0].mean(axis=-1), cmap='viridis')
plt.title('Attention Output Heatmap (Mean over Feature Dimensions)')
plt.xlabel('Sequence Position')
plt.ylabel('Sequence Step')
plt.show()
def main():
# Configuration
BINANCE_API_KEY = 'YOUR_API_KEY' # Replace with your API key
BINANCE_API_SECRET = 'YOUR_API_SECRET' # Replace with your API secret
code
SYMBOL = 'BTCUSDT' # You can change this to your desired symbol
INTERVAL = '1m' # Changed to '1m' for practicality; '1s' may cause rate limits
SEQ_LENGTH = 60 # Number of time steps in each input sequence
TARGET_STEPS = 1 # Predicting the next time step
LIMIT = 2000 # Number of historical data points to fetch per symbol (increased for better training)
# Initialize Binance client
client = Client(BINANCE_API_KEY, BINANCE_API_SECRET)
# Load and prepare data
print("Loading data...")
df = load_data(client, SYMBOL, interval=INTERVAL, limit=LIMIT)
if df.empty:
print("No data fetched. Exiting.")
return
print("Adding technical indicators...")
df = add_technical_indicators(df)
print("Classifying market environments...")
df, market_env_encoders = classify_market_environments(df)
print("Calculating leg data...")
df = calculate_leg_data(df)
print("Classifying percent changes...")
df = classify_percent_change(df)
# Encode and scale data
print("Encoding and scaling data...")
df, label_encoders, scalers = encode_and_scale(df)
# Prepare sequences with multiple targets
print("Preparing sequences...")
X, Y = prepare_sequences(df, SEQ_LENGTH, TARGET_STEPS)
# Validate data shapes
print(f"Shape of X: {X.shape}")
for key in Y:
print(f"Shape of Y[{key}]: {Y[key].shape}")
# Check if data is sufficient
if len(X) == 0:
print("Insufficient data after preparing sequences.")
return
# Unpack Y dictionary
Y_close = Y['close_price']
Y_percent_change = Y['percent_change_classification']
Y_leg_direction = Y['leg_direction']
Y_leg_length = Y['leg_length']
# Assert consistent sample sizes
assert X.shape[0] == Y_close.shape[0] == Y_percent_change.shape[0] == Y_leg_direction.shape[0] == Y_leg_length.shape[0], "Mismatch in sample sizes between X and Y."
# Verify label ranges
print("Verifying label ranges...")
print(f"percent_change_classification labels: min={Y_percent_change.min()}, max={Y_percent_change.max()}")
print(f"leg_direction labels: min={Y_leg_direction.min()}, max={Y_leg_direction.max()}")
assert Y_percent_change.min() >= 0 and Y_percent_change.max() < 7, "percent_change_classification labels out of range [0,6]"
assert Y_leg_direction.min() >= 0 and Y_leg_direction.max() <= 1, "leg_direction labels should be binary (0 or 1)"
# Split data
print("Splitting data into training and testing sets...")
X_train, X_test, y_close_train, y_close_test, y_percent_change_train, y_percent_change_test, y_leg_direction_train, y_leg_direction_test, y_leg_length_train, y_leg_length_test = train_test_split(
X,
Y_close,
Y_percent_change,
Y_leg_direction,
Y_leg_length,
test_size=0.2,
random_state=42
)
# Reassemble Y_train and Y_test dictionaries
Y_train = {
'close_price': y_close_train,
'percent_change_classification': y_percent_change_train,
'leg_direction': y_leg_direction_train,
'leg_length': y_leg_length_train
}
Y_test = {
'close_price': y_close_test,
'percent_change_classification': y_percent_change_test,
'leg_direction': y_leg_direction_test,
'leg_length': y_leg_length_test
}
# Build and compile model
print("Building the Transformer model...")
input_shape = (SEQ_LENGTH, X.shape[2])
num_classes = len(np.unique(Y_percent_change)) # Should be 7
model = build_multi_output_transformer_model(input_shape, num_classes)
model = compile_multi_output_model(model)
# Print model summary
print("Model Summary:")
model.summary()
# Train model
print("Training the model...")
history = model.fit(
X_train,
{
'close_price': Y_train['close_price'],
'percent_change_classification': Y_train['percent_change_classification'],
'leg_direction': Y_train['leg_direction'],
'leg_length': Y_train['leg_length']
},
epochs=10,
batch_size=32,
validation_split=0.2
)
# Save encoders and scalers for future use
print("Saving label encoders and scalers...")
with open('label_encoders.pkl', 'wb') as f:
pickle.dump(label_encoders, f)
with open('scalers.pkl', 'wb') as f:
pickle.dump(scalers, f)
# Save the model
print("Saving the trained model...")
model.save('multi_output_transformer_model.h5')
# Visualize training history
print("Plotting training history...")
plt.figure(figsize=(12, 4))
# Plot loss
plt.subplot(1, 2, 1)
for key in history.history:
if 'loss' in key and key != 'loss':
plt.plot(history.history[key], label=key)
plt.title('Training Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
# Plot accuracy
plt.subplot(1, 2, 2)
for key in history.history:
if 'accuracy' in key:
plt.plot(history.history[key], label=key)
plt.title('Training Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.tight_layout()
plt.show()
# Visualization of attention matrices (simplified)
print("Visualizing attention matrices for a sample input...")
sample_input = X_test[0]
plot_attention_matrices(model, sample_input, SEQ_LENGTH, X.shape[2])
print("Training and visualization complete.")
return model, history
if name == "main":
model, history = main()
The error you encountered:
plaintext
ValueError: Arguments `target` and `output` must have the same rank (ndim). Received: target.shape=(None,), output.shape=(None, 7)
indicates a mismatch between the shape of your model's output and the shape of your target labels for one of the outputs during training. Specifically, Keras expects the target and output tensors to have the same number of dimensions (ranks), but it received targets with shape (None,) (i.e., a 1D tensor) and outputs with shape (None, 7) (i.e., a 2D tensor with 7 classes).
Based on your provided code and the error traceback, the issue is likely related to the 'percent_change_classification' output. Let's walk through the potential causes and how to resolve them.
1. Understanding the Root Cause
Your model has multiple outputs, one of which is 'percent_change_classification', designed to perform multi-class classification with 7 classes. Here's how it's defined:
The error suggests that for 'percent_change_classification', Keras is receiving targets with shape (None,) but expects (None, 7) because the model's output layer for this task has 7 units (representing 7 classes) with a softmax activation.
However, since you're using 'sparse_categorical_crossentropy' as the loss function, Keras expects the targets (Y) for 'percent_change_classification' to be integer-encoded labels with shape (None,), not one-hot encoded labels. This mismatch is typically acceptable. But the fact that the error points to the binary_crossentropy loss function suggests that Keras is possibly misapplying the losses to the outputs.
2. Potential Issues and Solutions
a. Misalignment of Output Names and Labels
Ensure that the names of the outputs in your model precisely match the keys in your target dictionary. Keras relies on these names to correctly map losses and metrics to each output.
Solution:
Double-check that the output layer names in your model match exactly with the keys in the loss and target dictionaries.
Ensure that the labels for 'percent_change_classification' are correctly integer-encoded ranging from 0 to 6 (since there are 7 classes). Any labels outside this range or improper encoding can cause shape mismatches.
Solution:
Verify the unique values in Y_percent_change to ensure they range from 0 to 6.
Add debug statements to confirm label ranges.
Example Debugging:
Before training, add:
python
print(f"Unique labels for 'percent_change_classification': {np.unique(Y_train['percent_change_classification'])}")
c. Accidental Misapplication of Loss Functions
Given that the error message points to binary_crossentropy, it's possible that Keras is mistakenly applying the 'binary_crossentropy' loss to the 'percent_change_classification' output instead of to 'leg_direction'.
Solution:
Ensure that each output has a unique name and that the loss functions are correctly mapped.
Update the model to make all output names unique and distinct.
d. Keras or TensorFlow Version Issues
Certain versions of Keras or TensorFlow might have bugs or unexpected behaviors, especially concerning multi-output models.
Solution:
Ensure you're using compatible and up-to-date versions of Keras and TensorFlow.
You can check your versions using:
python
import tensorflow as tf
print(tf.__version__)
If necessary, update them:
bash
pip install --upgrade tensorflow
3. Step-by-Step Resolution
Let's walk through a step-by-step process to identify and fix the issue.
a. Verify Label Encoding
Ensure that 'percent_change_classification' labels are correctly encoded from 0 to 6.
python
# After encoding and before training
unique_labels = np.unique(Y['percent_change_classification'])
print(f"Unique labels for 'percent_change_classification': {unique_labels}")
# Ensure labels are within the expected range
assert unique_labels.min() == 0 and unique_labels.max() == 6, "Labels out of range for 7 classes."
b. Confirm Output-Label Mapping
Ensure that the output names in the model match the keys in the target dictionary.
Example Check:
python
# After building the model
print("Model Output Names:")
for output in model.outputs:
print(output.name)
Ensure that these names match exactly with the keys in your target dictionary passed to model.fit().
c. Simplify the Model for Debugging
To isolate the issue, temporarily train the model with only the 'percent_change_classification' output.
How to Do It:
Modify the build_multi_output_transformer_model to return only the 'percent_change_classification' output.
python
def build_classification_transformer_model(input_shape, num_classes_classification):
inputs = Input(shape=input_shape, name='input')
# [Transformer layers as before...]
# Output: Percent Change Classification (7 classes)
percent_change_output = Dense(num_classes_classification, activation='softmax', name='percent_change_classification')(x)
model = Model(inputs=inputs, outputs=percent_change_output)
return model
Adjust the compile and fit methods accordingly.
python
model = build_classification_transformer_model(input_shape, num_classes)
model.compile(
optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
history = model.fit(
X_train,
Y_train['percent_change_classification'],
epochs=10,
batch_size=32,
validation_split=0.2
)
Run the training. If it works without errors, the issue likely lies in the multi-output configuration.
d. Check for Naming Conflicts
Ensure that no other layers or outputs are inadvertently named 'percent_change_classification' or any other conflicting name.
e. Modify the Loss Configuration as a Temporary Test
As a temporary test, change the loss for 'percent_change_classification' to 'categorical_crossentropy' and one-hot encode the labels to see if the error persists.
How to Do It:
One-hot encode the labels:
python
from tensorflow.keras.utils import to_categorical
Y_percent_change_one_hot = to_categorical(Y['percent_change_classification'], num_classes=7)
If this resolves the error, it suggests that Keras was expecting one-hot encoded labels for 'percent_change_classification' due to some misconfiguration.
Note: This is a temporary workaround. Using 'sparse_categorical_crossentropy' with integer labels is more efficient and generally preferred when you have integer-encoded labels.
4. Comprehensive Example of Fixes
Here's an updated version of your code with added debug statements and checks to help identify and resolve the issue.
python
Key Additions:
Debug Statements:
After encoding and before training, the code now prints the unique labels for 'percent_change_classification' to ensure they range from 0 to 6.
Prints the shapes of each output layer in the model to confirm they match expectations.
Assertion Checks:
Asserts that the number of classes for 'percent_change_classification' is exactly 7.
Ensures that the labels for 'percent_change_classification' fall within the expected range.
Exception Handling:
Wrapped the model.fit() call in a try-except block to catch and display errors during training, preventing the script from crashing and providing more context.
5. Alternative Temporary Workaround
If after the above steps the issue persists, consider temporarily switching from 'sparse_categorical_crossentropy' to 'categorical_crossentropy' and one-hot encode your labels. This isn't ideal for efficiency but can help determine if the issue is with label formatting.
Steps:
One-Hot Encode Labels:
python
from tensorflow.keras.utils import to_categorical
# Before train_test_split
df['percent_change_classification_one_hot'] = to_categorical(df['percent_change_classification'], num_classes=7)
Adjust prepare_sequences:
Modify the prepare_sequences function to include the one-hot encoded labels:
python
Y = {
'close_price': np.array(Y_close).reshape(-1, 1),
'percent_change_classification': np.array(Y_percent_change_one_hot), # Replace with one-hot
'leg_direction': np.array(Y_leg_direction),
'leg_length': np.array(Y_leg_length).reshape(-1, 1)
}
Update compile_multi_output_model:
Change the loss for 'percent_change_classification' to 'categorical_crossentropy':
Attempt to train the model. If successful, it further indicates that the issue was with label encoding for 'percent_change_classification'.
Important Note: This is only a diagnostic step. For efficient training, especially with a large number of classes, it's preferable to use 'sparse_categorical_crossentropy' with integer-encoded labels.
6. Final Recommendations
Consistent Naming: Ensure that output layer names and target dictionary keys are consistent and unique.
Label Verification: Always verify the encoding and range of your labels before training.
Debugging Incrementally: Simplify your model to isolate issues. Start with a single output and gradually add more.
Version Compatibility: Keep your TensorFlow and Keras versions up-to-date to avoid unexpected bugs.
By following these steps, you should be able to identify and resolve the shape mismatch issue in your multi-output Transformer model. If problems persist after these adjustments, consider providing additional information or specific snippets where conflicts might be occurring for further assistance.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import pickle
import logging
from ta.volatility import AverageTrueRange, BollingerBands
from ta.momentum import RSIIndicator
from ta.trend import MACD, ADXIndicator
from sklearn.preprocessing import LabelEncoder, StandardScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.layers import (
Input,
Dense,
Dropout,
MultiHeadAttention,
LayerNormalization,
GlobalAveragePooling1D,
)
from tensorflow.keras.models import Model
import tensorflow as tf
from binance.client import Client
# Suppress TensorFlow warnings for clarity
logging.getLogger("tensorflow").setLevel(logging.ERROR)
# [All your function definitions remain unchanged until 'main']
def main():
# Configuration
BINANCE_API_KEY = 'YOUR_API_KEY' # Replace with your API key
BINANCE_API_SECRET = 'YOUR_API_SECRET' # Replace with your API secret
SYMBOL = 'BTCUSDT' # You can change this to your desired symbol
INTERVAL = '1m' # Changed to '1m' for practicality; '1s' may cause rate limits
SEQ_LENGTH = 60 # Number of time steps in each input sequence
TARGET_STEPS = 1 # Predicting the next time step
LIMIT = 2000 # Number of historical data points to fetch per symbol (increased for better training)
# Initialize Binance client
client = Client(BINANCE_API_KEY, BINANCE_API_SECRET)
# Load and prepare data
print("Loading data...")
df = load_data(client, SYMBOL, interval=INTERVAL, limit=LIMIT)
if df.empty:
print("No data fetched. Exiting.")
return
print("Adding technical indicators...")
df = add_technical_indicators(df)
print("Classifying market environments...")
df, market_env_encoders = classify_market_environments(df)
print("Calculating leg data...")
df = calculate_leg_data(df)
print("Classifying percent changes...")
df = classify_percent_change(df)
# Encode and scale data
print("Encoding and scaling data...")
df, label_encoders, scalers = encode_and_scale(df)
# Prepare sequences with multiple targets
print("Preparing sequences...")
X, Y = prepare_sequences(df, SEQ_LENGTH, TARGET_STEPS)
# Validate data shapes
print(f"Shape of X: {X.shape}")
for key in Y:
print(f"Shape of Y[{key}]: {Y[key].shape}")
# Check if data is sufficient
if len(X) == 0:
print("Insufficient data after preparing sequences.")
return
# Unpack Y dictionary
Y_close = Y['close_price']
Y_percent_change = Y['percent_change_classification']
Y_leg_direction = Y['leg_direction']
Y_leg_length = Y['leg_length']
# Assert consistent sample sizes
assert X.shape[0] == Y_close.shape[0] == Y_percent_change.shape[0] == Y_leg_direction.shape[0] == Y_leg_length.shape[0], "Mismatch in sample sizes between X and Y."
# Verify label ranges
print("Verifying label ranges...")
print(f"percent_change_classification labels: min={Y_percent_change.min()}, max={Y_percent_change.max()}")
print(f"leg_direction labels: min={Y_leg_direction.min()}, max={Y_leg_direction.max()}")
assert Y_percent_change.min() >= 0 and Y_percent_change.max() < 7, "percent_change_classification labels out of range [0,6]"
assert Y_leg_direction.min() >= 0 and Y_leg_direction.max() <= 1, "leg_direction labels should be binary (0 or 1)"
# Debug: Check unique labels
unique_percent_change = np.unique(Y_percent_change)
print(f"Unique labels for 'percent_change_classification': {unique_percent_change}")
# Split data
print("Splitting data into training and testing sets...")
X_train, X_test, y_close_train, y_close_test, y_percent_change_train, y_percent_change_test, y_leg_direction_train, y_leg_direction_test, y_leg_length_train, y_leg_length_test = train_test_split(
X,
Y_close,
Y_percent_change,
Y_leg_direction,
Y_leg_length,
test_size=0.2,
random_state=42
)
# Reassemble Y_train and Y_test dictionaries
Y_train = {
'close_price': y_close_train,
'percent_change_classification': y_percent_change_train,
'leg_direction': y_leg_direction_train,
'leg_length': y_leg_length_train
}
Y_test = {
'close_price': y_close_test,
'percent_change_classification': y_percent_change_test,
'leg_direction': y_leg_direction_test,
'leg_length': y_leg_length_test
}
# Build and compile model
print("Building the Transformer model...")
input_shape = (SEQ_LENGTH, X.shape[2])
num_classes = len(np.unique(Y_percent_change)) # Should be 7
assert num_classes == 7, f"Expected 7 classes, but got {num_classes}"
model = build_multi_output_transformer_model(input_shape, num_classes)
model = compile_multi_output_model(model)
# Print model summary
print("Model Summary:")
model.summary()
# Additional Debug: Ensure output layers have correct shapes
for output in model.outputs:
print(f"Output layer '{output.name}' shape: {output.shape}")
# Train model
print("Training the model...")
try:
history = model.fit(
X_train,
{
'close_price': Y_train['close_price'],
'percent_change_classification': Y_train['percent_change_classification'],
'leg_direction': Y_train['leg_direction'],
'leg_length': Y_train['leg_length']
},
epochs=10,
batch_size=32,
validation_split=0.2
)
except ValueError as e:
print(f"Error during training: {e}")
return
# Save encoders and scalers for future use
print("Saving label encoders and scalers...")
with open('label_encoders.pkl', 'wb') as f:
pickle.dump(label_encoders, f)
with open('scalers.pkl', 'wb') as f:
pickle.dump(scalers, f)
# Save the model
print("Saving the trained model...")
model.save('multi_output_transformer_model.h5')
# Visualize training history
print("Plotting training history...")
plt.figure(figsize=(12, 4))
# Plot loss
plt.subplot(1, 2, 1)
for key in history.history:
if 'loss' in key and key != 'loss':
plt.plot(history.history[key], label=key)
plt.title('Training Loss')
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.legend()
# Plot accuracy
plt.subplot(1, 2, 2)
for key in history.history:
if 'accuracy' in key:
plt.plot(history.history[key], label=key)
plt.title('Training Accuracy')
plt.xlabel('Epoch')
plt.ylabel('Accuracy')
plt.legend()
plt.tight_layout()
plt.show()
# Visualization of attention matrices (simplified)
print("Visualizing attention matrices for a sample input...")
sample_input = X_test[0]
plot_attention_matrices(model, sample_input, SEQ_LENGTH, X.shape[2])
print("Training and visualization complete.")
return model, history
if __name__ == "__main__":
model, history = main()