333 lines
10 KiB
Markdown
333 lines
10 KiB
Markdown
# Cycles - Advanced Trading Strategy Backtesting Framework
|
|
|
|
A Python framework for backtesting cryptocurrency trading strategies with multi-timeframe analysis, strategy combination, and advanced signal processing. **Recently refactored** for improved modularity, reusability, and maintainability.
|
|
|
|
## ✨ Key Features
|
|
|
|
- **🏗️ Modular Architecture**: Clean separation of concerns with reusable components
|
|
- **🔧 Multi-Strategy System**: Combine multiple trading strategies with configurable weights and rules
|
|
- **⏱️ Multi-Timeframe Analysis**: Strategies operate on different timeframes (1min, 5min, 15min, 1h, etc.)
|
|
- **📊 Advanced Strategies**:
|
|
- **Default Strategy**: Meta-trend analysis using multiple Supertrend indicators
|
|
- **BBRS Strategy**: Bollinger Bands + RSI with market regime detection
|
|
- **🎯 Flexible Signal Combination**: Weighted consensus, majority voting, any/all combinations
|
|
- **⚡ Precise Execution**: 1-minute precision for accurate risk management
|
|
- **📈 Comprehensive Analysis**: Detailed performance metrics and trade analysis
|
|
- **📱 Enhanced CLI**: Improved command-line interface with better error handling
|
|
- **🔍 Debug Mode**: Sequential execution with interactive plotting
|
|
|
|
## 🚀 Quick Start
|
|
|
|
### Prerequisites
|
|
|
|
- Python 3.8+
|
|
- [uv](https://github.com/astral-sh/uv) package manager (recommended) or pip
|
|
|
|
### Installation
|
|
|
|
```bash
|
|
# Clone the repository
|
|
git clone <repository-url>
|
|
cd Cycles
|
|
|
|
# Install dependencies with uv (recommended)
|
|
uv sync
|
|
|
|
# Or install with pip
|
|
pip install -r requirements.txt
|
|
```
|
|
|
|
### Running Backtests
|
|
|
|
The new CLI provides a clean interface with automatic config discovery:
|
|
|
|
```bash
|
|
# Use default configuration
|
|
python main.py
|
|
|
|
# Use specific config (searches configs/ directory automatically)
|
|
python main.py config_bbrs.json
|
|
|
|
# Debug mode with interactive plotting
|
|
python main.py --debug config_combined.json
|
|
|
|
# Full path also supported
|
|
python main.py configs/config_default_5min.json
|
|
|
|
# Get help
|
|
python main.py --help
|
|
```
|
|
|
|
### Available Configurations
|
|
|
|
- **`config_default.json`**: Default meta-trend strategy (15min)
|
|
- **`config_default_5min.json`**: Default strategy on 5-minute timeframe
|
|
- **`config_bbrs.json`**: BBRS strategy with market regime detection
|
|
- **`config_bbrs_multi_timeframe.json`**: BBRS with multiple timeframes
|
|
- **`config_combined.json`**: Multi-strategy combination with weighted consensus
|
|
|
|
## 🏛️ Architecture Overview
|
|
|
|
The framework follows a **clean, modular architecture** for maximum reusability:
|
|
|
|
```
|
|
cycles/
|
|
├── application.py # 🎯 Main application orchestration
|
|
├── utils/
|
|
│ ├── config_manager.py # ⚙️ Centralized configuration management
|
|
│ ├── results_processor.py # 📊 Results processing & metrics calculation
|
|
│ ├── backtest_runner.py # 🚀 Backtest execution logic
|
|
│ ├── storage.py # 💾 Data storage utilities
|
|
│ └── system.py # 🖥️ System utilities
|
|
├── strategies/ # 📈 Strategy implementations
|
|
│ ├── base.py # 🏗️ Base strategy framework
|
|
│ ├── default_strategy.py # 📊 Meta-trend strategy
|
|
│ ├── bbrs_strategy.py # 🎯 BBRS strategy
|
|
│ └── manager.py # 🎛️ Strategy orchestration
|
|
├── backtest.py # ⚡ Core backtesting engine
|
|
└── charts.py # 📈 Visualization components
|
|
```
|
|
|
|
## 📱 Enhanced CLI Interface
|
|
|
|
```bash
|
|
python main.py [-h] [--debug] [config]
|
|
|
|
# Examples:
|
|
python main.py # Use default config
|
|
python main.py config_bbrs.json # Use specific config
|
|
python main.py --debug config_combined.json # Debug mode with plotting
|
|
|
|
# Available configs:
|
|
# - config_default.json: Default meta-trend strategy
|
|
# - config_bbrs.json: BBRS strategy
|
|
# - config_combined.json: Multi-strategy combination
|
|
```
|
|
|
|
## ⚙️ Configuration
|
|
|
|
Strategies are configured using JSON files in the `configs/` directory:
|
|
|
|
```json
|
|
{
|
|
"start_date": "2024-01-01",
|
|
"stop_date": "2024-01-31",
|
|
"initial_usd": 10000,
|
|
"timeframes": ["15min"],
|
|
"strategies": [
|
|
{
|
|
"name": "default",
|
|
"weight": 1.0,
|
|
"params": {
|
|
"timeframe": "15min",
|
|
"stop_loss_pct": 0.03
|
|
}
|
|
}
|
|
],
|
|
"combination_rules": {
|
|
"entry": "weighted_consensus",
|
|
"exit": "any",
|
|
"min_confidence": 0.6
|
|
}
|
|
}
|
|
```
|
|
|
|
### Strategy Configuration
|
|
|
|
#### Single Strategy
|
|
```json
|
|
{
|
|
"strategies": [
|
|
{
|
|
"name": "default",
|
|
"weight": 1.0,
|
|
"params": {
|
|
"timeframe": "15min",
|
|
"stop_loss_pct": 0.03
|
|
}
|
|
}
|
|
]
|
|
}
|
|
```
|
|
|
|
#### Multi-Strategy Combination
|
|
```json
|
|
{
|
|
"strategies": [
|
|
{
|
|
"name": "default",
|
|
"weight": 0.6,
|
|
"params": {"timeframe": "15min"}
|
|
},
|
|
{
|
|
"name": "bbrs",
|
|
"weight": 0.4,
|
|
"params": {"bb_width": 0.05}
|
|
}
|
|
],
|
|
"combination_rules": {
|
|
"entry": "weighted_consensus",
|
|
"exit": "any",
|
|
"min_confidence": 0.6
|
|
}
|
|
}
|
|
```
|
|
|
|
### Combination Rules
|
|
|
|
- **Entry Methods**: `any`, `all`, `majority`, `weighted_consensus`
|
|
- **Exit Methods**: `any`, `all`, `priority` (prioritizes stop-loss signals)
|
|
- **Min Confidence**: Threshold for signal acceptance (0.0 - 1.0)
|
|
|
|
## 🛠️ Programmatic Usage
|
|
|
|
The new modular architecture enables programmatic usage:
|
|
|
|
```python
|
|
from cycles.application import BacktestApplication
|
|
|
|
# Simple usage
|
|
app = BacktestApplication("configs/config_bbrs.json")
|
|
app.run(debug=False)
|
|
|
|
# Custom workflow
|
|
from cycles.utils import ConfigManager, BacktestRunner
|
|
|
|
config_manager = ConfigManager("my_config.json")
|
|
runner = BacktestRunner()
|
|
|
|
for timeframe in config_manager.timeframes:
|
|
config = config_manager.get_timeframe_task_config(timeframe)
|
|
results = runner.run_single_timeframe(data, timeframe, config)
|
|
# Process results...
|
|
```
|
|
|
|
## 📈 Available Strategies
|
|
|
|
### 1. Default Strategy (Meta-Trend Analysis)
|
|
- **Type**: Meta-trend analysis using multiple Supertrend indicators
|
|
- **Timeframes**: Configurable (5min, 15min, 1h, etc.)
|
|
- **Features**: Triple Supertrend confirmation, precise stop-loss
|
|
|
|
```json
|
|
{
|
|
"name": "default",
|
|
"params": {
|
|
"timeframe": "15min",
|
|
"stop_loss_pct": 0.03
|
|
}
|
|
}
|
|
```
|
|
|
|
### 2. BBRS Strategy (Bollinger Bands + RSI)
|
|
- **Type**: Bollinger Bands + RSI with market regime detection
|
|
- **Features**: Adaptive parameters, volume confirmation, multi-timeframe analysis
|
|
- **Market Regimes**: Trending vs sideways market detection
|
|
|
|
```json
|
|
{
|
|
"name": "bbrs",
|
|
"params": {
|
|
"bb_width": 0.05,
|
|
"strategy_name": "MarketRegimeStrategy",
|
|
"stop_loss_pct": 0.05
|
|
}
|
|
}
|
|
```
|
|
|
|
## 📊 Output & Results
|
|
|
|
### Generated Files
|
|
- **`YYYY_MM_DD_HH_MM_backtest.csv`**: Performance summary per timeframe
|
|
- **`YYYY_MM_DD_HH_MM_trades.csv`**: Individual trade records
|
|
- **`backtest.log`**: Detailed execution logs
|
|
|
|
### Debug Mode
|
|
- **Interactive Charts**: Real-time plotting of strategy signals and trades
|
|
- **Sequential Execution**: Step-by-step analysis
|
|
- **Enhanced Logging**: Detailed strategy information
|
|
|
|
### Performance Metrics
|
|
- **Trade Statistics**: Win rate, profit ratio, drawdown analysis
|
|
- **Portfolio Metrics**: Initial/final USD, total returns, fees
|
|
- **Risk Metrics**: Maximum drawdown, stop-loss frequency
|
|
|
|
## 📚 Documentation
|
|
|
|
Comprehensive documentation available in the `docs/` directory:
|
|
|
|
- **[🏗️ Refactoring Summary](./docs/refactoring_summary.md)** - Overview of new architecture improvements
|
|
- **[🎛️ Strategy Manager](./docs/strategy_manager.md)** - Multi-strategy orchestration
|
|
- **[📈 Strategies](./docs/strategies.md)** - Individual strategy implementations
|
|
- **[⏱️ Timeframe System](./docs/timeframe_system.md)** - Multi-timeframe management
|
|
- **[📊 Analysis](./docs/analysis.md)** - Technical analysis components
|
|
- **[💾 Storage Utils](./docs/utils_storage.md)** - Data management
|
|
- **[🖥️ System Utils](./docs/utils_system.md)** - System utilities
|
|
|
|
## 🎯 Migration & Compatibility
|
|
|
|
The refactored framework is **100% backward compatible**:
|
|
|
|
- ✅ Same command-line interface
|
|
- ✅ Same configuration file format
|
|
- ✅ Same output file format
|
|
- ✅ Same functionality
|
|
|
|
**Zero breaking changes** while providing a much cleaner, more maintainable architecture.
|
|
|
|
## 🔧 Advanced Usage
|
|
|
|
### Custom Strategy Development
|
|
```python
|
|
from cycles.strategies.base import StrategyBase, StrategySignal
|
|
|
|
class MyStrategy(StrategyBase):
|
|
def get_timeframes(self):
|
|
return ["1h"]
|
|
|
|
def initialize(self, backtester):
|
|
self._resample_data(backtester.original_df)
|
|
# Setup indicators...
|
|
self.initialized = True
|
|
|
|
def get_entry_signal(self, backtester, df_index):
|
|
# Your entry logic...
|
|
return StrategySignal("ENTRY", confidence=0.8)
|
|
```
|
|
|
|
### Custom Results Processing
|
|
```python
|
|
from cycles.utils import BacktestMetrics, ResultsProcessor
|
|
|
|
class CustomProcessor(ResultsProcessor):
|
|
def process_backtest_results(self, results, timeframe, config, summary):
|
|
# Custom processing logic...
|
|
return custom_summary, custom_trades
|
|
```
|
|
|
|
## 🚀 Future Enhancements
|
|
|
|
The new architecture enables easy addition of:
|
|
|
|
- **🌐 Web API Interface**: REST API for remote backtesting
|
|
- **⚡ Real-time Trading**: Live trading integration
|
|
- **📊 Advanced Analytics**: Enhanced performance analysis
|
|
- **🔌 Strategy Marketplace**: Plugin system for custom strategies
|
|
- **📈 Multiple Asset Classes**: Beyond cryptocurrency support
|
|
|
|
## 🤝 Contributing
|
|
|
|
We welcome contributions! The new modular architecture makes it easier to:
|
|
- Add new strategies
|
|
- Enhance analysis capabilities
|
|
- Improve visualization
|
|
- Extend data sources
|
|
|
|
## 📄 License
|
|
|
|
[Add your license information here]
|
|
|
|
---
|
|
|
|
**Recent Updates**: The framework has been significantly refactored for improved modularity and reusability while maintaining full backward compatibility. See [Refactoring Summary](./docs/refactoring_summary.md) for details.
|