Initial commit: Add complete strategy, documentation, and backtest results

This commit is contained in:
Iván Lahuerta
2025-08-30 14:08:14 +02:00
commit 4bb7ea4ca5
9 changed files with 376817 additions and 0 deletions
+35
View File
@@ -0,0 +1,35 @@
# =================================================================
# .gitignore for the Backtrader ATR Stop-Loss Strategy
#
# This file specifies intentionally untracked files that Git
# should ignore. The goal is to keep the repository clean from
# generated logs, reports, and environment-specific files.
#
# The 'data/' directory is INTENTIONALLY NOT ignored so that
# the repository is self-contained and ready to run.
# =================================================================
# Python bytecode and cache
__pycache__/
*.pyc
*.pyo
*.pyd
# IDE and editor configuration files
.vscode/
.idea/
*.suo
*.ntvs*
*.njsproj
*.sln
# Generated log and report directories from strategy execution.
# These folders are created dynamically by the script and contain
# user-specific output that should not be in version control.
debug/
temp_reports/
src/strategy/temp_reports/
# Virtual environment folder
# (Assuming your virtual environment is named 'venv')
venv/
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) [year] [Your Full Name]
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
+141
View File
@@ -0,0 +1,141 @@
# Backtrader ATR Stop-Loss Strategy for USDCHF
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://www.python.org/downloads/)
[![Framework](https://img.shields.io/badge/Framework-Backtrader-orange.svg)](https://www.backtrader.com/)
[![Profit Factor](https://img.shields.io/badge/Profit_Factor-1.35-brightgreen.svg)](.)
This repository presents a complete and profitable algorithmic trading strategy for the **USDCHF** currency pair on a **5-minute timeframe**. The system is implemented in Python using the `Backtrader` framework and features an advanced, dynamic risk management system based on the Average True Range (ATR).
The strategy was backtested over 5 years of historical data, achieving a **1.35 Profit Factor** with a **35.4% return** on initial capital.
---
## 📊 Performance Analysis
The core of this project's backtesting methodology is the "Dual Cerebro" approach, where LONG and SHORT strategies are run as two independent portfolios. This prevents conflicting signals and allows each directional bias to be optimized and evaluated on its own merits. The final "Combined" performance is the aggregation of these two independent results.
### Portfolio Performance (5-Year Backtest)
![Dual Cerebro Performance Chart](images/sunrise_osiris.png)
* **Purple Line (Combined Portfolio):** Represents the total equity curve, showing a final P&L of **+$35,399**.
* **Green Line (LONG Only Portfolio):** Shows the performance if only buy signals were traded, resulting in a P&L of **+$18,343**.
* **Red Line (SHORT Only Portfolio):** Shows the performance if only sell signals were traded, resulting in a P&L of **+$17,056**.
This chart demonstrates that both the LONG and SHORT logic contribute positively and consistently to the overall profitability of the system.
---
## ✨ Key Features
- 📈 **Advanced Pullback Entry System**: The strategy does not enter on the initial signal. It waits for a confirmation pullback and enters on a breakout, significantly improving the entry quality and risk/reward ratio.
- **🛡️ Dynamic ATR Risk Management**: Stop Loss and Take Profit levels are not fixed. They are calculated dynamically for *every trade* based on the market's current volatility (ATR), adapting the risk profile to live conditions.
- **📐 EMA Angle Momentum Filter**: A unique filter that measures the slope of the confirmation EMA. It ensures trades are only taken during periods of strong, decisive market momentum, filtering out flat or choppy markets.
- **🔄 Dual Cerebro Backtesting**: By testing LONG and SHORT logic independently, the strategy avoids signal interference and provides a clearer picture of each component's performance.
- **🕰️ Time-of-Day Filtering**: Trading is restricted to the most liquid market hours (07:00 - 17:00 UTC) to focus on the highest probability setups.
- **💰 Risk-Based Position Sizing**: Automatically calculates trade size to risk a fixed 1% of the account on every position, maintaining consistent risk exposure.
---
## 🧠 Strategy Logic & Visualization
The strategy is a multi-layered, trend-following system. An entry is only triggered when a sequence of conditions are met.
### How It Works: The 3-Phase Entry
1. **Signal Detection**: A fast EMA (1) crosses over a basket of slower EMAs (14, 18, 24).
2. **Pullback Wait**: The system waits for a small, controlled move against the trend (e.g., 1-2 red candles for a LONG signal).
3. **Breakout Entry**: A market order is triggered only if the price breaks the high/low of the pullback, confirming the trend's continuation.
### Example of a LONG Trade
![Example of a LONG Trade in Backtrader](images/sunrise_osiris_long_entrys.png)
This chart shows the strategy in action:
- **Candlestick Chart**: The 5-minute price action for USDCHF.
- **EMA Lines**: The multiple EMAs used for signal generation.
- **Green Triangle (Buy Signal)**: Marks the exact bar where a LONG trade was executed.
- **Dashed Lines (SL/TP Observer)**: These are the most important feature. The **dashed red line** is the initial Stop Loss, and the **dashed green line** is the Take Profit target. Both are calculated using ATR multiples at the moment of entry.
---
## 📂 Code Overview
The entire logic is contained within `src/strategy/sunrise_osiris.py`. Here is a brief guide to its structure:
- **Global Configuration (Lines 1-150):** This top section contains all user-editable parameters, such as date ranges, starting cash, ATR thresholds, and filter settings. This makes tuning the strategy easy without touching the core logic.
- **`SunriseOsiris` Class `params` (Lines 153-270):** The official `Backtrader` parameters dictionary. These are the values that can be optimized during a parameter sweep.
- **`__init__(self)` (Lines 605-700):** The strategy constructor where all indicators (EMAs, ATR) and state variables (e.g., for the pullback machine) are initialized.
- **`next(self)` (Lines 875-1045):** The heart of the strategy. This method is called for every bar of data. It contains the main logic for checking entry/exit conditions and managing the trade lifecycle.
- **Pullback State Machine (`_handle_pullback_entry`)**: A set of helper functions that manage the 3-phase entry logic (Signal -> Wait -> Breakout).
- **Risk Management (`_calculate_forex_position_size`)**: A function dedicated to calculating the correct position size based on the stop-loss distance and the 1% account risk rule.
- **Order Notifications (`notify_order`, `notify_trade`)**: These methods handle the feedback from the broker (simulated or real), placing the OCA (One-Cancels-All) Stop Loss and Take Profit orders after an entry is confirmed.
---
## 🚀 Getting Started
Follow these instructions to set up and run the backtest on your local machine.
### Prerequisites
- Python 3.8 or newer.
- Git version control.
### 1. Clone the Repository
Open your terminal and clone the repository:
```bash
git clone https://github.com/[Your-Username]/backtrader-atr-stop-loss-usdchf.git
cd backtrader-atr-stop-loss-usdchf
```
### 2. Set Up a Virtual Environment
It is highly recommended to use a virtual environment to manage dependencies.
```bash
# Create the virtual environment
python -m venv venv
# Activate it
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
```
### 3. Install Requirements
Install the necessary Python libraries using the provided `requirements.txt` file.
```bash
pip install -r requirements.txt
```
### 4. Add Market Data
Place your 5-minute USDCHF data file into the `/data` directory. The project expects the file to be named `USDCHF_5m_5Yea.csv`.
### 5. Run the Backtest
Execute the strategy script from the root directory of the project.
```bash
python src/strategy/sunrise_osiris.py
```
The script will run the full Dual Cerebro backtest, print the performance summary to the console, generate detailed trade reports in the `/temp_reports` folder, and display the final performance chart.
---
## 🤝 Contributing
Contributions are welcome! Whether you want to report a bug, suggest an enhancement, or add a new feature, please feel free to do so.
- **Report a Bug:** Open an [Issue](https://github.com/[Your-Username]/backtrader-atr-stop-loss-usdchf/issues) and describe the problem in detail.
- **Suggest an Enhancement:** Open an [Issue](https://github.com/[Your-Username]/backtrader-atr-stop-loss-usdchf/issues) to discuss your idea.
- **Submit a Pull Request:** Fork the repository, make your changes, and submit a [Pull Request](https://github.com/[Your-Username]/backtrader-atr-stop-loss-usdchf/pulls) with a clear description of your work.
---
## 📜 License
This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.
---
## ⚠️ Disclaimer
This project is for educational and research purposes ONLY. It is not financial advice. Algorithmic trading involves substantial risk of loss and is not suitable for every investor. Past performance is not indicative of future results.
+162
View File
@@ -0,0 +1,162 @@
# 🏗️ Backtrader ATR Stop Loss USDCHF - Repository Structure
## 📂 Directory Tree
```
backtrader-atr-stop-loss-usdchf/
├── 📁 data/ # Market Data Files
│ └── 📄 USDCHF_5m_5Yea.csv # 🇨🇭 USDCHF 5-minute historical data (5 years)
├── 📁 debug/ # Debug & Logging Files
│ ├── 📄 entry_debug_20250830_123010.log # Entry signal debug log
│ ├── 📄 entry_debug_20250830_123132.log # Entry signal debug log
│ ├── 📄 entry_debug_20250830_132754.log # Entry signal debug log
│ └── 📄 entry_debug_20250830_132908.log # Entry signal debug log
├── 📁 images/ # Strategy Performance Charts
│ ├── 🖼️ sunrise_osiris.png # Main strategy performance chart
│ └── 🖼️ sunrise_osiris_long_entrys.png # LONG entries visualization
├── 📁 src/ # Source Code
│ └── 📁 strategy/ # Trading Strategy Implementation
│ ├── 📄 sunrise_osiris.py # 🌅 Main Sunrise Osiris Strategy (USDCHF)
│ └── 📁 temp_reports/ # Local strategy reports
│ ├── 📄 USDCHF_trades_20250830_132754.txt
│ └── 📄 USDCHF_trades_20250830_132908.txt
└── 📁 temp_reports/ # Global Trade Reports
├── 📄 USDCHF_trades_20250830_123010.txt # Detailed trade analysis
└── 📄 USDCHF_trades_20250830_123132.txt # Detailed trade analysis
```
---
## 📋 File Descriptions
### 📊 Data Files
- **`USDCHF_5m_5Yea.csv`**: 5-minute OHLCV historical data for USD/CHF currency pair covering approximately 5 years of trading history
### 🚀 Strategy Files
- **`sunrise_osiris.py`**: Main trading strategy implementation
- **Purpose**: USDCHF-focused trading system with pullback entry mechanics
- **Features**: 3-phase pullback system, ATR volatility filtering, dual cerebro mode
- **Configuration**: LONG/SHORT trading, risk management, forex calculations
- **Size**: ~2,640 lines of code
### 🐛 Debug & Logs
- **`entry_debug_*.log`**: Comprehensive entry signal analysis logs
- Tracks every potential entry signal
- Records blocking reasons (ATR filters, time filters, etc.)
- Shows success/failure rates for optimization
### 📈 Visual Reports
- **`sunrise_osiris.png`**: Strategy performance visualization
- **`sunrise_osiris_long_entrys.png`**: LONG entry points analysis chart
### 📋 Trade Reports
- **`USDCHF_trades_*.txt`**: Detailed trade execution reports
- Entry/exit timestamps and prices
- P&L calculations and pip movements
- ATR values and volatility analysis
- Risk metrics and position sizing
---
## ⚙️ Configuration Structure
### 🎯 Entry Parameters
```python
# Trading Direction
ENABLE_LONG_TRADES = True
ENABLE_SHORT_TRADES = True
RUN_DUAL_CEREBRO = True # Separate LONG/SHORT execution
# ATR Volatility Filters
LONG_ATR_MIN_THRESHOLD = 0.000200 # Minimum volatility for LONG
LONG_ATR_MAX_THRESHOLD = 0.000600 # Maximum volatility for LONG
SHORT_ATR_MIN_THRESHOLD = 0.000400 # Minimum volatility for SHORT
SHORT_ATR_MAX_THRESHOLD = 0.000750 # Maximum volatility for SHORT
# Pullback Entry System
LONG_USE_PULLBACK_ENTRY = True # 3-phase pullback for LONG
LONG_PULLBACK_MAX_CANDLES = 1 # Max red candles in LONG pullback
SHORT_USE_PULLBACK_ENTRY = True # 3-phase pullback for SHORT
SHORT_PULLBACK_MAX_CANDLES = 2 # Max green candles in SHORT pullback
```
### 💰 Risk Management
```python
# Position Sizing
STARTING_CASH = 100000.0 # Initial capital
RISK_PERCENT = 0.01 # 1% risk per trade
# Forex Configuration
FOREX_INSTRUMENT = 'USDCHF' # USD vs Swiss Franc
FOREX_PIP_VALUE = 0.0001 # 4 decimal places
FOREX_LOT_SIZE = 100000 # 100K USD lots
FOREX_LEVERAGE = 30.0 # 30:1 leverage
```
### 🕐 Trading Hours
```python
# Time Range Filter
USE_TIME_RANGE_FILTER = True
ENTRY_START_HOUR = 7 # 07:00 UTC
ENTRY_END_HOUR = 17 # 17:00 UTC
```
---
## 🏃‍♂️ Execution Commands
### From Repository Root
```bash
python src/strategy/sunrise_osiris.py
```
### From Strategy Directory
```bash
cd src/strategy
python sunrise_osiris.py
```
---
## 📊 Performance Summary
### Latest Results (Combined Strategy)
- **Total P&L**: +$35,398.93 (35.4% return)
- **Total Trades**: 155
- **Win Rate**: 34.19%
- **Profit Factor**: 1.35
### Strategy Breakdown
- **LONG-ONLY**: +$18,343.13 (100 trades, 27% win rate)
- **SHORT-ONLY**: +$17,055.80 (55 trades, 47.27% win rate)
---
## 🔧 Technical Features
### 🎯 Entry System
- **3-Phase Pullback Entry**: Signal Detection → Pullback → Breakout
- **EMA Crossover Detection**: Confirmation EMA vs Fast/Medium/Slow EMAs
- **ATR Volatility Filtering**: Dynamic market condition assessment
- **Time-Based Entry Windows**: UTC trading hours restriction
### 📈 Exit System
- **ATR-Based Stop Loss**: 2.5x ATR protection
- **ATR-Based Take Profit**: 12.0x ATR (LONG), 6.5x ATR (SHORT)
- **OCA Order Management**: One-Cancels-All protective orders
### 💱 Forex Features
- **USDCHF Optimization**: Specialized for USD/CHF currency pair
- **Dynamic Position Sizing**: Risk-based lot calculation
- **Pip Value Calculations**: Accurate P&L in USD terms
- **Leverage Integration**: 30:1 leverage with margin requirements
---
*Last Updated: August 30, 2025*
*Strategy Version: Sunrise Osiris USDCHF Clean*
+373798
View File
File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 106 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 135 KiB

+22
View File
@@ -0,0 +1,22 @@
# =================================================================
# Dependencies for the Backtrader ATR Stop-Loss Strategy
#
# This file was generated by 'pip freeze' to capture the exact
# versions of all direct and indirect dependencies, ensuring a
# fully reproducible environment.
#
# To install, run:
# pip install -r requirements.txt
# =================================================================
backtrader==1.9.76.123
matplotlib==3.8.4
numpy==1.26.4
Pillow==10.3.0
cycler==0.12.1
fonttools==4.51.0
kiwisolver==1.4.5
packaging==24.0
pyparsing==3.1.2
python-dateutil==2.9.0.post0
six==1.16.0
File diff suppressed because it is too large Load Diff