The code you've provided aims to build an ensemble model combining a Convolutional Neural Network (CNN), a Long Short-Term Memory network (LSTM) with Attention, and a Temporal Convolutional Network (TCN) to predict the next day's adjusted closing price of the TQQQ ETF. It then uses these predictions to backtest a trading strategy.
Below is an analysis of your code with insights, potential issues, and suggestions for improvement to enhance the model's performance and ensure accurate backtesting.
1. Data Loading and Preprocessing
# 1. Load the SPY ETF data
spy = yf.download('TQQQ', start='2012-01-01', end='2024-09-01')
Issue:
- Future End Date: The end date
'2024-09-01' is in the future relative to the current date. This could cause yfinance to only download data up to today, leading to inconsistencies.
Suggestion:
-
Dynamic End Date: Use the current date as the end date to ensure all available data is captured without errors.
import datetime
end_date = datetime.datetime.today().strftime('%Y-%m-%d')
spy = yf.download('TQQQ', start='2012-01-01', end=end_date)
Calculating Returns:
spy['Returns'] = spy['Adj Close'].pct_change().fillna(0)
2. Feature Selection and Target Variable
# Select target and features
X = spy[['Open', 'High', 'Low', 'Close', 'Volume']].values
y = spy['Adj Close'].shift(-1).fillna(method='ffill').values
Issue:
- Data Leakage: Shifting
y by -1 aligns the target with future data. Using fillna(method='ffill') can introduce future information into the training data, leading to overly optimistic performance (look-ahead bias).
Suggestion:
-
Remove NaNs Properly: After shifting y, drop the last row to align X and y.
y = spy['Adj Close'].shift(-1).values[:-1]
X = X[:-1]
-
Avoid Filling Target NaNs: Do not fill NaNs in the target variable with future values.
3. Scaling the Data
# Scale the data
scaler_X = MinMaxScaler()
X_scaled = scaler_X.fit_transform(X)
scaler_y = MinMaxScaler()
y_scaled = scaler_y.fit_transform(y.reshape(-1, 1))
Suggestion:
- Scaling with Training Data Only: To prevent data leakage, fit the scalers on the training data only, not the entire dataset.
4. Preparing Sequences for Sequence Models
sequence_length = 45 # Using a window of 45 days for predictions
Issue:
- Inconsistent Comment: The comment mentions a 30-day window, but
sequence_length is set to 45.
Suggestion:
- Clarify Comments: Update the comment to match the code.
5. Model Definitions
CNN Model
def create_cnn_model(input_shape):
input_layer = Input(shape=input_shape)
x = Conv1D(filters=64, kernel_size=3, padding="same", activation='relu')(input_layer)
x = BatchNormalization()(x)
x = Flatten()(x)
output = Dense(64, activation='relu')(x)
return Model(inputs=input_layer, outputs=output)
LSTM Model with Attention
The custom Attention layer is implemented correctly.
6. Combining the Models into an Ensemble
combined_input = concatenate([cnn_model.output, lstm_model_with_attention.output, tcn_model.output])
x = Dense(64, activation="relu")(combined_input)
x = Dense(32, activation="relu")(x)
output = Dense(1)(x)
Suggestion:
- Model Complexity: Ensure that combining outputs of different models doesn't lead to overfitting, especially with limited data.
7. Training the Model
ensemble_model.fit([X_seq, X_seq, X_seq], y_seq, epochs=15, batch_size=32, validation_split=0.3)
Issue:
- Training the Same Data Multiple Times: All models are trained on the same input data (
X_seq).
Suggestion:
-
Diversify Inputs: If possible, feed different features or augmentations to different models to enrich the ensemble.
-
Validation Split and Data Leakage: Using validation_split=0.3 on time-series data can lead to data leakage because it shuffles the data.
Correct Approach:
-
Time-Series Split: Split the data chronologically to ensure that the validation set contains data from a later time period than the training set.
train_size = int(len(X_seq) * 0.7)
X_train = [X_seq[:train_size], X_seq[:train_size], X_seq[:train_size]]
y_train = y_seq[:train_size]
X_val = [X_seq[train_size:], X_seq[train_size:], X_seq[train_size:]]
y_val = y_seq[train_size:]
ensemble_model.fit(X_train, y_train, epochs=15, batch_size=32, validation_data=(X_val, y_val))
8. Making Predictions
predictions = ensemble_model.predict([X_seq, X_seq, X_seq])
# Inverse transform predictions to get actual values
predicted_prices = scaler_y.inverse_transform(predictions)
Issue:
- Data Leakage in Predictions: If the model was trained on future data (due to improper splitting), the predictions may be biased.
9. Backtesting Strategy
Assign Predictions to the Original DataFrame:
spy['Predicted'] = np.nan
spy['Predicted'].iloc[sequence_length:] = predicted_prices[:, 0]
Issue:
- Indexing Mismatch: Ensure that the indexing aligns correctly between
spy and predicted_prices.
Calculating Returns:
spy['Predicted_shifted'] = spy['Predicted'].shift(1)
spy['Actual_Return'] = spy['Returns'].shift(-1) # Shifted for alignment with predicted values
Issue:
- Misalignment: Shifting returns may misalign the data.
Suggestion:
- Align Returns Correctly: Returns should not be shifted when calculating strategy returns.
Calculating the Median of Actual Returns:
median_return = spy['Actual_Return'].median()
Issue:
- Look-Ahead Bias: Using the median of the entire dataset introduces future information into past predictions.
Suggestion:
- Use Rolling Median or Training Median: Calculate the median return using training data or implement a rolling median to avoid look-ahead bias.
10. Calculating Strategy Performance
# Buy signal: today's predicted return > median actual return
spy['Signal'] = np.where(
(spy['Predicted_Return'] > median_return),
1,
0
)
Issue:
- Simplistic Strategy: The strategy is based solely on whether the predicted return exceeds the median return, which may not be optimal.
Suggestion:
- Alternative Strategies: Consider setting a threshold based on predicted returns, or use the raw predicted returns to determine position sizing.
Calculating Strategy Returns:
spy['Strategy_Returns'] = spy['Returns'] * spy['Signal'].shift(1).fillna(0)
Issue:
- Signal Shift: Ensure that the signal is appropriately shifted to avoid look-ahead bias. The shift indicates that the signal generated today is applied on the next day's returns.
11. Performance Metrics
Sharpe Ratio Calculation:
def calculate_sharpe_ratio(returns, risk_free_rate=0.0, periods_per_year=252):
...
Max Drawdown Calculation:
def calculate_max_drawdown(returns):
...
Suggestion:
- Use Log Returns: When calculating cumulative returns, using log returns can provide more accurate results, especially over long time horizons.
12. Plotting Results
plt.figure(figsize=(14, 7))
plt.plot(spy['Cumulative_Strategy_Returns'], label='Strategy Cumulative Returns')
plt.plot(spy['Cumulative_Market_Returns'], label='Market Cumulative Returns (Buy and Hold)')
plt.legend()
plt.title(f"Backtest of SPY Ensemble Model with CNN, LSTM+Attention, and TCN\nSharpe Ratio: {sharpe_ratio:.2f} | Max Drawdown: {max_drawdown:.2%}")
plt.show()
Suggestion:
- Enhance Visualization: Add grid lines, axis labels, and a legend for clarity.
Overall Recommendations
-
Prevent Data Leakage:
- Ensure that all preprocessing steps, scaling, and splitting are done in a way that prevents future information from leaking into the training data.
- Use chronological train-test splits appropriate for time series data.
-
Model Evaluation:
- Use a separate test set that the model has not seen during training or validation to evaluate performance.
- Consider using cross-validation methods suitable for time series, like TimeSeriesSplit from
sklearn.model_selection.
-
Hyperparameter Tuning:
- Experiment with different network architectures, hyperparameters (e.g., number of layers, neurons, learning rates), and sequence lengths to improve model performance.
- Use tools like
GridSearchCV with TimeSeriesSplit for systematic tuning.
-
Ensemble Diversity:
- Feed different inputs to each model in the ensemble to increase diversity, which can improve the ensemble's overall performance.
- Example: Use technical indicators, macroeconomic data, or other relevant features.
-
Strategy Improvement:
- Explore more sophisticated trading strategies, such as using the magnitude of predicted returns for position sizing or incorporating risk management techniques (e.g., stop-loss, take-profit levels).
- Backtest the strategy over a walk-forward analysis to simulate real-world performance more closely.
-
Performance Metrics:
- In addition to Sharpe Ratio and Max Drawdown, consider other metrics like Sortino Ratio, Calmar Ratio, and profit factor.
- Analyze the distribution of returns and check for skewness and kurtosis.
-
Logging and Monitoring:
- Implement logging to record model training progress, losses, and other relevant metrics.
- Use TensorBoard for visualizing training and validation metrics over epochs.
-
Documentation and Comments:
- Ensure that all code comments accurately reflect the code to improve readability and maintainability.
Example Adjusted Code Snippets
Splitting Data Chronologically:
# Determine the split index
train_size = int(len(X_seq) * 0.7)
# Split the data
X_train = [X_seq[:train_size], X_seq[:train_size], X_seq[:train_size]]
y_train = y_seq[:train_size]
X_test = [X_seq[train_size:], X_seq[train_size:], X_seq[train_size:]]
y_test = y_seq[train_size:]
# Compile the model
ensemble_model.compile(optimizer=Adam(learning_rate=0.001), loss='mean_squared_error')
# Train the model
ensemble_model.fit(X_train, y_train, epochs=50, batch_size=32, validation_data=(X_test, y_test), callbacks=[EarlyStopping(patience=5)])
Calculating Strategy Returns Without Look-Ahead Bias:
# Use only test predictions for backtesting
predictions_test = ensemble_model.predict(X_test)
predicted_prices_test = scaler_y.inverse_transform(predictions_test)
# Align predictions with the test set dates
test_dates = spy.index[sequence_length + train_size:]
spy_test = spy.loc[test_dates].copy()
spy_test['Predicted'] = predicted_prices_test[:, 0]
# Calculate predicted returns
spy_test['Predicted_Return'] = spy_test['Predicted'].pct_change()
# Generate signals based on predicted returns
spy_test['Signal'] = np.where(spy_test['Predicted_Return'] > 0, 1, 0)
# Calculate strategy returns
spy_test['Strategy_Returns'] = spy_test['Returns'] * spy_test['Signal'].shift(1).fillna(0)
Conclusion
Your approach demonstrates a strong understanding of combining different deep learning models and applying them to financial time series forecasting. By addressing the potential issues outlined above, particularly concerning data leakage and proper backtesting procedures, you can enhance the reliability and validity of your results.
Next Steps:
- Implement the suggested changes to prevent data leakage and improve model evaluation.
- Experiment with different strategies and model configurations to optimize performance.
- Validate the model using a separate test set and consider using more robust evaluation metrics.
Feel free to ask if you have any questions about these suggestions or need further assistance with your model!