The main goal of this repository is to be equiped with necessary tools to optimize trading strategy with Backtesting.py library
- Create and simulate trading strategies
- Run backtests on historical data
- Visualize performance and trades
- Generate metrics (e.g., Sharpe ratio, drawdowns, returns, etc.)
- Define optimization parameters.
- Define cost function to maximize
- Run the optimization engine with two variantes (Grid, SAMBO)
- Drawing multiple heatmaps in a single figure for comparing parameter interactions visually, especially with more than 2 optimization parameters
This project demonstrates how to:
Implement a professional-grade trading strategy in Python
Run exhaustive or constrained parameter optimization
Apply custom cost metrics and performance filters
Visualize optimization results intuitively
This file is a start up example with simple assumptions
This file is a Juypter Notebook version of '1_Risk_Sizing_py.py'
This file includes backtesting without optimization, it is p preparation for file '3_Optimize.ipynb'
This repository contains a complete and educational workflow for optimizing a custom trading strategy using Backtesting.py, a Python library for vectorized backtesting.
The notebook 3_Optimize.ipynb
walks through:
- Implementing a technical strategy with RSI and dynamic risk sizing
- Running a grid search optimization over multiple parameters
- Applying constraints and custom cost functions
- Visualizing results using seaborn heatmaps
The strategy is based on:
- RSI (Relative Strength Index) indicator
- Dynamic position sizing based on account equity and user-defined risk percentage
- Stop-loss logic derived from a percentage-based SL
- Entry/exit triggers from RSI lower/upper bounds
The strategy is optimized using a multi-parameter grid search over:
Parameter | Description |
---|---|
u_bound |
RSI upper bound (overbought threshold) |
l_bound |
RSI lower bound (oversold threshold) |
rsi_window |
RSI lookback period |
sl_percent |
Stop-loss percentage (e.g., 0.001 = 0.1%) |
equity_risk |
% of equity to risk per trade |
The optimization uses a user-defined cost function:
def cost_function(series): if series['# Trades'] < 9: return -1 return series['Return [%]']
The results are visualized using seaborn heatmaps to show how different parameter combinations affect the strategy's performance. A utility function is included to:
Plot a single heatmap
Plot all possible 2D heatmap combinations for n parameters
Install required libraries using pip:
pip install backtesting pandas numpy seaborn matplotlib
If using method="sambo" for advanced optimization:
pip install sambo
_ https://kernc.github.io/backtesting.py/
_ ChatGPT propmpting