To transform your current parameter optimization script into a more traditional backtesting framework that provides comprehensive insights such as portfolio size over time, equity curves, trade signals, and more, you'll need to make several adjustments and enhancements. Below is a step-by-step guide to help you achieve this, along with code snippets to illustrate the necessary changes.
Step 1: Separate Optimization from Backtesting
It's essential to decouple the parameter optimization process from the actual backtesting to ensure clarity and maintainability. This separation allows you to first find the best parameters and then perform a detailed backtest using those parameters.
1.1 Optimize Parameters
Your existing optimize_parameters function is well-suited for finding the optimal set of parameters based on a chosen metric (e.g., Sharpe Ratio). After optimization, you'll select the best parameters for a detailed backtest.
1.2 Run Detailed Backtest with Optimal Parameters
Once you've identified the best parameter combinations, you'll run a separate backtest using these parameters to generate detailed outputs such as equity curves, trade signals, and other portfolio metrics.
Step 2: Modify the Backtest Method for Detailed Outputs
Enhance your backtest method to ensure it retains all necessary information for detailed analysis. Since you're already using vectorbt, you can leverage its powerful plotting and analysis capabilities.
2.1 Update the backtest Method
Ensure that your backtest method returns the Portfolio object, which contains all the necessary information for further analysis and visualization.
def backtest(self, data, initial_capital, fee_rate):
"""Run backtest using vectorbt and return detailed portfolio data."""
# Existing code...
try:
portfolio = vbt.Portfolio.from_signals(
close=data['close'],
entries=signals['long_entries'] | signals['short_entries'],
exits=signals['exits'],
short_entries=signals['short_entries'],
sl_stop=self.risk_per_trade,
init_cash=initial_capital,
fees=fee_rate,
size=size,
freq=self.interval
)
trades = portfolio.trades.records
metrics = {
'Total Return (%)': portfolio.total_return() * 100,
'Sharpe Ratio': portfolio.sharpe_ratio(),
'Max Drawdown (%)': portfolio.max_drawdown() * 100,
'Number of Trades': len(trades) if trades is not None else 0,
'Win Rate (%)': (np.sum(trades['pnl'] > 0) / len(trades)) * 100 if trades is not None and len(trades) > 0 else 0,
'Profit Factor': np.sum(trades[trades['pnl'] > 0]['pnl']) / abs(np.sum(trades[trades['pnl'] < 0]['pnl'])) if trades is not None and len(trades) > 0 and abs(np.sum(trades[trades['pnl'] < 0]['pnl'])) > 0 else 0
}
return metrics, portfolio, data
except Exception as e:
print(f"\nError in vectorbt processing: {str(e)}")
raise
Step 3: Implement Detailed Backtesting and Visualization
After optimizing and identifying the best parameter set, perform a detailed backtest and visualize the results.
3.1 Update the Main Execution Block
Modify your __main__ section to perform both optimization and detailed backtesting.
if __name__ == "__main__":
# Initialize strategy
strategy = VolumeProfileStrategy(
symbol='SOL/USDT',
exchange_id='binance'
)
# Define parameter grid for optimization
param_grid = {
'price_bucket_count': [50, 60, 70], # Example ranges
'volume_threshold': [0.080789, 0.09, 0.1],
'node_distance': [0.00037, 0.0004, 0.00043],
'entry_confirmation_bars': [5, 6],
'exit_confirmation_bars': [4, 5],
'risk_per_trade': [0.02, 0.025]
}
# Optimize parameters
results = optimize_parameters(
strategy=strategy,
param_grid=param_grid,
initial_capital=10000,
fee_rate=0.001,
period='365d'
)
optimize_for = 'Sharpe Ratio'
print("\nTop 50 parameter combinations by Sharpe ratio:")
if optimize_for in results.columns:
pd.set_option('display.max_columns', None)
sorted_results = results.sort_values(optimize_for, ascending=False).head(50)
sorted_results.to_csv('sorted_results.csv', index=False) # Save to CSV without index
print(sorted_results)
else:
print("Sharpe Ratio not found in results.")
# Select the best parameter combination
if not sorted_results.empty:
best_params = sorted_results.iloc[0].to_dict()
print("\nBest Parameters:")
print(best_params)
# Remove metric entries from best_params
metric_keys = ['Total Return (%)', 'Sharpe Ratio', 'Max Drawdown (%)', 'Number of Trades', 'Win Rate (%)', 'Profit Factor']
for key in metric_keys:
best_params.pop(key, None)
# Update strategy with best parameters
for param, value in best_params.items():
setattr(strategy, param, value)
# Reprocess data with best parameters
print("\nRe-processing data with the best parameters...")
data = strategy.process_volume_nodes(strategy.fetch_raw_data('365d'))
# Run backtest with best parameters
print("Running backtest with best parameters...")
metrics, portfolio, detailed_data = strategy.backtest(data, initial_capital=10000, fee_rate=0.001)
print("\nBacktest Metrics:")
for metric, value in metrics.items():
print(f"{metric}: {value}")
# Plot Equity Curve
portfolio.plot().show()
# Plot Trades on Price Chart
fig = portfolio.plot_trades()
fig.show()
# Plot Portfolio Growth
portfolio.total_return().vbt.plot().show()
# Additional Visualizations (Optional)
# Equity Curve
plt.figure(figsize=(12, 6))
portfolio.total_return().vbt.plot(title='Equity Curve')
plt.show()
# Drawdown
plt.figure(figsize=(12, 6))
portfolio.drawdown().vbt.plot(title='Drawdown')
plt.show()
# Trade Statistics
if not portfolio.trades.records.empty:
print("\nTrade Details:")
print(portfolio.trades.records[['Entry Price', 'Exit Price', 'P&L']])
else:
print("No trades were executed.")
else:
print("No valid parameter combinations found during optimization.")
3.2 Explanation of the Changes
-
Parameter Grid Expansion: In the param_grid, expand the ranges or values for each parameter to explore a broader set of combinations. Adjust these ranges based on your domain knowledge and preliminary results.
-
Optimization Results: After optimization, the script selects the top 50 parameter combinations based on the Sharpe Ratio and saves them to a CSV file for review.
-
Selecting the Best Parameters: The script picks the top parameter set (highest Sharpe Ratio) and updates the strategy with these parameters.
-
Reprocessing Data: Using the best parameters, the raw data is reprocessed to ensure that volume nodes and other metrics align with the optimized settings.
-
Running the Detailed Backtest: With the best parameters, a detailed backtest is run, and the metrics are printed for review.
-
Visualization:
- Equity Curve: Visualizes the growth of the portfolio over time.
- Trades on Price Chart: Shows where buy/sell signals occurred on the price chart.
- Portfolio Growth and Drawdown: Additional plots to understand performance and risk.
- Trade Details: Provides a table of all executed trades with entry and exit prices and P&L.
Step 4: Enhance Visualization with Vectorbt
vectorbt offers extensive plotting capabilities that can be leveraged for more insightful visualizations.
4.1 Plotting the Portfolio
After obtaining the portfolio object from the backtest, you can use its built-in plotting methods:
# Plot the portfolio's performance
portfolio.plot().show()
# Plot trades on price chart
portfolio.plot_trades().show()
# Plot portfolio growth
portfolio.total_return().vbt.plot(title='Equity Curve').show()
# Plot drawdown
portfolio.drawdown().vbt.plot(title='Drawdown').show()
4.2 Customizing Plots
You can further customize the plots to suit your preferences. For example, adding annotations or customizing colors:
# Custom Equity Curve
fig = plt.figure(figsize=(12, 6))
plt.plot(portfolio.value(), label='Equity Curve', color='blue')
plt.title('Portfolio Equity Curve')
plt.xlabel('Time')
plt.ylabel('Portfolio Value')
plt.legend()
plt.grid(True)
plt.show()
Step 5: Save and Review Detailed Backtest Results
It's beneficial to save the detailed backtest results for future reference and analysis.
# Save the portfolio object for later analysis
portfolio.to_pickle('detailed_portfolio.pkl')
# Save detailed data with signals
detailed_data.to_pickle('detailed_data_with_signals.pkl')
# Optionally, export trade records to CSV
if not portfolio.trades.records.empty:
portfolio.trades.records.to_csv('trade_records.csv', index=False)
Step 6: Implement Logging and Error Handling (Optional but Recommended)
To make your backtesting framework more robust and easier to debug, consider implementing logging and enhanced error handling.
import logging
# Configure logging
logging.basicConfig(
filename='backtest.log',
filemode='a',
format='%(asctime)s - %(levelname)s - %(message)s',
level=logging.INFO
)
# Replace print statements with logging
logging.info("Starting parameter optimization...")
# ... other logging statements
Complete Updated Script Overview
Below is an overview of the updated script structure incorporating all the changes discussed:
-
Imports and Definitions: Remain largely the same, ensuring all necessary libraries are imported.
-
VolumeProfileStrategy Class: Enhanced with a modified backtest method that returns the Portfolio object.
-
Optimization Function: Remains mostly unchanged but is integrated into a more comprehensive main execution block.
-
Main Execution Block (__main__):
- Performs parameter optimization.
- Selects the best parameter set.
- Runs a detailed backtest with the best parameters.
- Generates and displays comprehensive visualizations.
- Saves results and logs for future analysis.
Additional Recommendations
-
Performance Optimization: Ensure your Numba-optimized functions are as efficient as possible, especially when dealing with large datasets.
-
Parameter Grid Tuning: Fine-tune the parameter ranges and steps in your param_grid based on preliminary results to focus on promising areas.
-
Modular Code Structure: Consider modularizing your code further by separating data fetching, processing, backtesting, and visualization into distinct modules or classes.
-
Version Control: Use version control (e.g., Git) to track changes and manage different versions of your backtesting framework.
-
Documentation: Add comprehensive docstrings and comments to your code to enhance readability and maintainability.
-
Unit Testing: Implement unit tests for critical functions to ensure their correctness and facilitate future modifications.
By following these steps and recommendations, you'll transform your current optimization script into a robust backtesting framework capable of providing detailed insights into your trading strategy's performance.
Note: The provided code snippets assume that you have a working environment with all necessary libraries installed and configured correctly. Ensure that you have the latest versions of vectorbt, ccxt, NumPy, Pandas, Matplotlib, and Seaborn to leverage all features effectively.