# Horizontal Resistance Breakout Strategy Backtester A modular backtesting system for a horizontal resistance breakout trading strategy using Python and backtrader. ## Strategy Overview This strategy identifies and trades breakouts above horizontal resistance levels with the following conditions: ### Entry Criteria: 1. **Resistance Level**: Price breaks above a horizontal resistance level (20-day high with 1% tolerance) 2. **Volume Confirmation**: Breakout occurs on 2x average volume (20-bar average) 3. **Higher Lows Pattern**: Price was making at least 2 higher lows before breakout 4. **Retracement Entry**: Wait for price to retrace back to resistance level with: - Low volume (< 50% of breakout volume) - Small body candles (body < 30% of total range) - Entry within 1% of resistance level 5. **Trend Filter**: Only trade when price is above 200 SMA ### Risk Management: - **Stop Loss**: Below the lowest low of the retracement - **Target**: 2:1 risk/reward ratio - **Position Size**: Risk 2% of account per trade ## Installation 1. Clone or download this repository 2. Install TA-Lib (required for technical indicators): - **Windows**: Download from [TA-Lib website](https://www.ta-lib.org/hdr_dw.html) - **Mac**: `brew install ta-lib` - **Linux**: `sudo apt-get install ta-lib` 3. Install Python dependencies: ```bash pip install -r requirements.txt ``` ## Project Structure ``` ├── config.py # Strategy configuration parameters ├── indicators.py # Custom indicators (resistance, higher lows, etc.) ├── utils.py # Helper functions and trade logging ├── strategy.py # Main strategy implementation ├── data_loader.py # Data loading and validation utilities ├── backtest.py # Main backtest runner ├── example_usage.py # Example scripts └── requirements.txt # Python dependencies ``` ## Usage ### Basic Usage Run a backtest on a single stock: ```bash python backtest.py AAPL --start 2023-01-01 --end 2023-12-31 ``` ### Command Line Options ```bash python backtest.py [SYMBOL] [OPTIONS] Arguments: SYMBOL Stock symbol to backtest (e.g., AAPL, MSFT) Options: --start DATE Start date (YYYY-MM-DD) [default: 2022-01-01] --end DATE End date (YYYY-MM-DD) [default: 2023-12-31] --data-source Data source: 'yahoo' or 'csv' [default: yahoo] --csv-path PATH Path to CSV file (if using csv source) --no-plot Disable chart plotting ``` ### Examples 1. **Single Stock Backtest**: ```bash python backtest.py TSLA --start 2023-06-01 --end 2023-12-31 ``` 2. **Using CSV Data**: ```bash python backtest.py CUSTOM --data-source csv --csv-path data/custom_data.csv ``` 3. **Run Without Plotting**: ```bash python backtest.py SPY --no-plot ``` 4. **Run Example Scripts**: ```bash python example_usage.py ``` ## Configuration Edit `config.py` to adjust strategy parameters: ```python # Strategy Parameters RESISTANCE_LOOKBACK = 20 # Days to look back for resistance RESISTANCE_TOLERANCE = 0.01 # 1% tolerance for horizontal resistance VOLUME_MULTIPLIER = 2.0 # Required volume multiplier for breakout # ... etc ``` ## Output The backtest provides comprehensive performance metrics: - **Portfolio Performance**: Starting/ending value, total return - **Risk Metrics**: Sharpe ratio, maximum drawdown - **Trade Statistics**: Win rate, average trade duration - **Strategy-Specific Metrics**: Number of breakouts detected, entries made ### Sample Output: ``` Starting Portfolio Value: $100,000.00 Ending Portfolio Value: $112,543.21 Total Return: 12.54% ============================================================== BACKTEST ANALYSIS ============================================================== Sharpe Ratio: 1.45 Max Drawdown: 8.32% Max Drawdown Duration: 45 bars Total Return: 12.54% Average Annual Return: 12.54% Total Trades: 28 Winning Trades: 18 Losing Trades: 10 Win Rate: 64.29% Average Trade Duration: 15.3 bars Total P&L: $12,543.21 Total Commission: $156.78 ============================================================== ``` ## Data Requirements ### CSV Format If using CSV data, ensure it has the following columns: - Date/DateTime (as index) - open - high - low - close - volume ### Data Quality The system includes data validation that checks for: - Missing values - Invalid price relationships (high < low, etc.) - Negative volumes - Time gaps ## Extending the Strategy ### Adding New Indicators Create new indicators in `indicators.py`: ```python class MyCustomIndicator(bt.Indicator): lines = ('my_line',) params = (('period', 20),) def __init__(self): # Indicator logic here pass def next(self): # Calculate indicator value self.lines.my_line[0] = calculated_value ``` ### Modifying Entry/Exit Logic Edit the strategy logic in `strategy.py`: - `check_for_breakout()`: Modify breakout detection - `check_for_entry()`: Adjust entry conditions - `manage_position()`: Change exit rules ## Troubleshooting 1. **TA-Lib Installation Issues**: - Ensure TA-Lib C library is installed before pip installing the Python wrapper - On Windows, use the appropriate .whl file for your Python version 2. **No Data Found**: - Check internet connection for Yahoo Finance - Verify the symbol exists and has data for the specified period - For hourly data, note that Yahoo Finance has limitations on historical data 3. **Memory Issues**: - Reduce the backtest period - Use daily instead of hourly data for longer periods ## Performance Optimization Tips 1. **Parameter Optimization**: Use `example_usage.py` as a template to test different parameters 2. **Multiple Timeframes**: Modify data compression in `backtest.py` 3. **Stock Universe**: Test on different market sectors and cap sizes 4. **Market Conditions**: Analyze performance in trending vs ranging markets ## License This project is for educational purposes. Always perform your own due diligence before trading with real money. ## Contributing Feel free to submit issues, fork the repository, and create pull requests for any improvements.