Skip to content

Commit 9bfe069

Browse files
committed
Fix strategy regression baselines and tooling
1 parent d6cfcd7 commit 9bfe069

16 files changed

Lines changed: 2667 additions & 91 deletions

.gitignore

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -144,4 +144,54 @@ report.html
144144
backtrader_master_tests_report.html
145145
backtrader_remove_metaprogramming_report.html
146146
backtrader_remove_metaprogramming_report_timing.json
147-
backtrader-master/*
147+
backtrader-master/*
148+
149+
# Generated regression test baselines (per-strategy run.py produces them locally)
150+
tests/functional/strategies_regression/
151+
152+
# Large local market data fixtures (1GB+, not suitable for git)
153+
tests/functional/datas/
154+
155+
# Runtime / generated artifacts
156+
logs/
157+
examples/logs/
158+
*.log
159+
bandit-report.json
160+
bandit-report.*.json
161+
162+
# Matplotlib runtime font cache
163+
.mplconfig/
164+
docs/.mplconfig/
165+
166+
# Internal / personal docs (may contain credentials, real account info, etc.)
167+
docs/_internal/
168+
169+
# Live trading certification artefacts (CTP penetration test credentials, etc.)
170+
examples/live_certification/
171+
172+
# Reference-only local documentation config
173+
.readthedocs-zh.yaml
174+
175+
# Local data copied for experiments; current tests do not reference these paths
176+
tests/datas/CFFEX_Futures_Contract_Data.csv
177+
tests/datas/ChiNext_ETF.csv
178+
tests/datas/SSE50_ETF.csv
179+
tests/datas/binance_bbo_demo/
180+
tests/datas/tick_data/
181+
182+
# Local agent / planning workspaces
183+
_bmad/
184+
_bmad-output/
185+
.kiro/
186+
.opencode/
187+
.claude/
188+
.cursor/
189+
.windsurf/
190+
191+
# Editor settings
192+
.vscode/
193+
194+
# Misc local files
195+
*.csv.bak
196+
*.tmp
197+
*.bak

README.en.md

Lines changed: 31 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -2,21 +2,21 @@
22

33
English | [中文](README.md)
44

5-
[![Tests](https://github.com/yunjinqi/backtrader/actions/workflows/tests.yml/badge.svg)](https://github.com/yunjinqi/backtrader/actions/workflows/tests.yml)
6-
[![Build](https://github.com/yunjinqi/backtrader/actions/workflows/publish.yml/badge.svg)](https://github.com/yunjinqi/backtrader/actions/workflows/publish.yml)
7-
[![CodeQL](https://github.com/yunjinqi/backtrader/actions/workflows/codeql.yml/badge.svg)](https://github.com/yunjinqi/backtrader/actions/workflows/codeql.yml)
8-
[![Python Versions](https://img.shields.io/pypi/pyversions/backtrader.svg)](https://pypi.org/project/backtrader/)
9-
[![PyPI Version](https://img.shields.io/pypi/v/backtrader.svg)](https://pypi.org/project/backtrader/)
10-
[![License](https://img.shields.io/badge/license-GPL-blue.svg)](LICENSE)
5+
[![CI Tests](https://github.com/cloudQuant/backtrader/actions/workflows/tests.yml/badge.svg?branch=master)](https://github.com/cloudQuant/backtrader/actions/workflows/tests.yml)
6+
[![Python](https://img.shields.io/badge/python-3.8%20%7C%203.9%20%7C%203.10%20%7C%203.11%20%7C%203.12%20%7C%203.13-blue)](https://www.python.org/)
7+
[![License](https://img.shields.io/badge/license-GPL%203.0-green)](LICENSE)
8+
[![Code style: flake8](https://img.shields.io/badge/code%20style-flake8-black)](https://flake8.pycqa.org/)
9+
[![GitHub stars](https://img.shields.io/github/stars/cloudQuant/backtrader?style=social)](https://github.com/cloudQuant/backtrader/stargazers)
10+
[![GitHub forks](https://img.shields.io/github/forks/cloudQuant/backtrader?style=social)](https://github.com/cloudQuant/backtrader/network/members)
11+
[![Gitee](https://img.shields.io/badge/mirror-Gitee-red)](https://gitee.com/yunjinqi/backtrader)
1112

1213
## Introduction
1314

14-
A high-performance quantitative research tool built on backtrader, focused on medium-to-low frequency trading strategies with Cython/Numba optimizations for improved backtesting efficiency. This project is an enhanced version of backtrader that maintains compatibility while adding numerous practical features.
15+
An enhanced version of the backtrader Python library for quantitative trading and backtesting. This project keeps compatibility with the original backtrader while adding cryptocurrency support, futures-market integrations, extra testing utilities, and improved stability across Python 3.8-3.13.
1516

1617
### Core Features
1718

18-
- 🚀 **Performance Optimization**: Core computation modules optimized with Cython and Numba for significantly faster backtesting
19-
- 📊 **Vectorized Backtesting**: Support for Time Series (TS) and Cross-Sectional (CS) vectorized backtesting frameworks
19+
-**Event-Driven Architecture**: Fast and efficient event-driven backtesting engine
2020
- 🪙 **Cryptocurrency Support**:
2121
- CCXT integration supporting 100+ cryptocurrency exchanges
2222
- Funding rate backtesting for crypto perpetual contracts
@@ -26,8 +26,10 @@ A high-performance quantitative research tool built on backtrader, focused on me
2626
- CTP futures trading interface
2727
- Oanda forex trading
2828
- Traditional stock markets
29-
- 📈 **Rich Technical Indicators**: 60+ built-in technical indicators with custom indicator development support
30-
- 📝 **Strategy Analyzers**: Multiple performance analysis tools (Sharpe ratio, maximum drawdown, SQN, etc.)
29+
- 📈 **Rich Technical Indicators**: 50+ built-in indicators with custom indicator development support
30+
-**Comprehensive Analyzers**: Sharpe ratio, drawdown, trade statistics, PyFolio integration, and custom analyzers
31+
- 🎯 **Flexible Order Types**: Market, limit, stop, stop-limit, bracket, and OCO orders
32+
- 📉 **Data Processing**: Resampling, replaying, and multi-timeframe analysis
3133

3234
### Version Information
3335

@@ -38,7 +40,7 @@ A high-performance quantitative research tool built on backtrader, focused on me
3840

3941
### System Requirements
4042

41-
- Python 3.8 - 3.12 (Python 3.11 recommended for best performance)
43+
- Python 3.8 - 3.13 (Python 3.11 recommended for best performance)
4244
- Operating Systems: Windows, Linux, macOS
4345

4446
### Installation
@@ -141,7 +143,6 @@ cerebro.plot()
141143

142144
### 2. Strategy Development
143145
- Event-driven strategy framework
144-
- Vectorized strategy framework (CS/TS)
145146
- Multi-asset, multi-timeframe strategy support
146147
- Signal system
147148

@@ -192,39 +193,17 @@ data = store.getdata(
192193
cerebro.adddata(data)
193194
```
194195

195-
### Vectorized Backtesting Example
196-
197-
```python
198-
# Time series vectorized strategy
199-
from backtrader.vectors import TimeSeriesStrategy
200-
201-
class MyTSStrategy(TimeSeriesStrategy):
202-
def compute_signal(self, data):
203-
# Use numpy for vectorized calculations
204-
sma_20 = data['close'].rolling(20).mean()
205-
sma_50 = data['close'].rolling(50).mean()
206-
207-
# Generate signals
208-
signal = (sma_20 > sma_50).astype(int)
209-
return signal
210-
```
211-
212196
## Documentation & Resources
213197

198+
- 📚 [Project Documentation Index](docs/README.md)
199+
- 🛠️ [Installation & Troubleshooting Guide](docs/INSTALLATION_GUIDE.md)
200+
- 🧾 [Changelog](docs/CHANGELOG.md)
201+
- 🐛 [DataTrades Fix Note](docs/DATATRADES_FIX.md)
202+
- 🔌 [ExtendPandasFeed Fix Note](docs/EXTENDED_FEED_FIX.md)
214203
- 📚 [Official Documentation](https://www.backtrader.com/)
215204
- 📝 [CSDN Tutorial Series](https://blog.csdn.net/qq_26948675/category_10220116.html)
216205
- 💬 [Issue Tracker](https://gitee.com/yunjinqi/backtrader/issues)
217-
- 🔧 [Development Guide](CONTRIBUTING.md)
218-
219-
## Performance Comparison
220-
221-
Performance improvements with Cython optimization:
222-
223-
| Module | Original Speed | Optimized Speed | Improvement |
224-
|--------|---------------|-----------------|-------------|
225-
| Indicator Calculations | 1.00x | 3-5x | 200-400% |
226-
| Vectorized Backtesting | N/A | 10-20x | - |
227-
| Order Matching | 1.00x | 2-3x | 100-200% |
206+
- 🔧 [Development Guide](CLAUDE.md)
228207

229208
## Contributing
230209

@@ -238,18 +217,22 @@ We welcome code contributions, bug reports, and feature suggestions:
238217

239218
## Changelog
240219

241-
### Latest Updates 2024
242-
- ✅ Added funding rate backtesting support for cryptocurrency
243-
- ✅ Fixed Python 3.12+ compatibility issues
244-
- ✅ Optimized Cython compilation process
220+
### 2026 Updates
221+
- ✅ Reorganized helper scripts under `scripts/`
222+
- ✅ Added the strategies regression framework (generated locally and gitignored)
223+
- ✅ Made `backtrader.analyzers.pyfolio` lazy-load `empyrical`
224+
225+
### 2024 Updates
226+
- ✅ Added funding rate backtesting support for cryptocurrency perpetual contracts
227+
- ✅ Fixed Python 3.12 and 3.13 compatibility issues
228+
- ✅ Improved CCXT integration stability
245229
- ✅ Added CI/CD automated testing
246230

247231
### 2023 Updates
248-
- ✅ Implemented Time Series (TS) vectorized backtesting framework
249-
- ✅ Optimized Cross-Sectional (CS) strategy performance
232+
- ✅ Improved multi-exchange support
250233
- ✅ Fixed multiple known bugs
251234

252-
For detailed changelog, see [CHANGELOG.md](CHANGELOG.md)
235+
For detailed changelog, see [docs/CHANGELOG.md](docs/CHANGELOG.md)
253236

254237
## License
255238

README.md

Lines changed: 113 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -464,12 +464,48 @@ class FundingRateStrategy(bt.Strategy):
464464

465465
### Documentation & Resources
466466

467-
- 📚 [Official Backtrader Documentation](https://www.backtrader.com/)
467+
- 📚 [Project Documentation Index](docs/README.md)
468+
- 🛠️ [Installation & Troubleshooting Guide](docs/INSTALLATION_GUIDE.md)
469+
- 🧾 [Changelog](docs/CHANGELOG.md)
470+
- 🐛 [DataTrades Fix Note](docs/DATATRADES_FIX.md)
471+
- 🔌 [ExtendPandasFeed Fix Note](docs/EXTENDED_FEED_FIX.md)
472+
- 📖 [Official Backtrader Documentation](https://www.backtrader.com/)
468473
- 📝 [CSDN Tutorial Series (Chinese)](https://blog.csdn.net/qq_26948675/category_10220116.html)
469474
- 💬 [Issue Tracker - Gitee](https://gitee.com/yunjinqi/backtrader/issues)
470475
- 💬 [Issue Tracker - GitHub](https://github.com/cloudQuant/backtrader/issues)
471476
- 🔧 [Development Guide](CLAUDE.md)
472477

478+
### Project Structure
479+
480+
```
481+
backtrader/
482+
├── backtrader/ # Core framework package
483+
├── docs/ # Project docs, changelog, installation guide, fix notes
484+
├── examples/ # Runnable example projects
485+
├── scripts/ # Maintenance & QA helper scripts
486+
│ ├── run_master_tests.py # Full pytest run + HTML report
487+
│ ├── run_test_with_log.py # Run a single test with branch-aware logging
488+
│ ├── sync_and_test.py # Sync a test file across branches & run it
489+
│ ├── profile_performance.py # cProfile-based strategy profiler
490+
│ ├── debug_macd_replay.py # MACD-in-replay debugging harness
491+
│ ├── backtest_strategy_regression_expected.py # Regression baseline generator
492+
│ ├── run_all_backtests.py # Batch backtest runner
493+
│ └── test_python_versions_simple.sh/.bat # Multi-version conda test runner
494+
├── strategies/ # Shared strategy helpers (e.g. benchmark_metrics)
495+
├── studies/ # Research notebooks & UML
496+
├── tests/ # Pytest test suites
497+
│ ├── original_tests/ # Upstream backtrader tests
498+
│ ├── strategies/ # In-house strategy tests
499+
│ ├── funding_rate_examples/ # Crypto funding-rate tests
500+
│ └── functional/strategies_regression/ # 1000+ generated regression scripts (gitignored)
501+
├── pyproject.toml / setup.py / requirements.txt
502+
└── README.md / CLAUDE.md / LICENSE
503+
```
504+
505+
> `tests/functional/strategies_regression/` is generated locally by
506+
> `scripts/backtest_strategy_regression_expected.py` and is intentionally
507+
> excluded from version control.
508+
473509
### Testing
474510

475511
```bash
@@ -480,11 +516,21 @@ pytest tests
480516
pytest tests --cov=backtrader --cov-report=html
481517

482518
# Run specific test category
483-
pytest tests/original_tests # Core functionality
484-
pytest tests/funding_rate_examples # Crypto features
519+
pytest tests/original_tests # Core functionality
520+
pytest tests/funding_rate_examples # Crypto features
521+
pytest tests/strategies # In-house strategies
485522

486523
# Run in parallel
487524
pytest tests -n 4
525+
526+
# Convenience wrappers (always run from repo root)
527+
python scripts/run_master_tests.py # Full suite + HTML report
528+
python scripts/run_test_with_log.py tests/strategies/test_18_etf_rotation_strategy.py
529+
bash scripts/test_python_versions_simple.sh # Multi Python version sweep
530+
531+
# Regenerate strategy regression baselines (long-running)
532+
python scripts/backtest_strategy_regression_expected.py \
533+
tests/functional/strategies_regression --workers 4 --overwrite
488534
```
489535

490536
### Contributing
@@ -499,6 +545,13 @@ We welcome code contributions, bug reports, and feature suggestions:
499545

500546
### Changelog
501547

548+
#### 2026 Updates
549+
- ✅ Reorganised root-level helper scripts under `scripts/`
550+
- ✅ Added the strategies regression framework (1000+ per-strategy `run.py` baselines, generated locally and gitignored)
551+
- ✅ Made `backtrader.analyzers.pyfolio` lazy-load `empyrical` so `import backtrader` works without it on pandas 3
552+
- ✅ Replaced `risk_free_rate` keyword with `riskfreerate` for `SharpeRatio` across the regression suite
553+
- ✅ Normalised `comminfo.get_param('mult')` usage to `getattr(comminfo.p, 'mult', 1.0)`
554+
502555
#### 2024 Updates
503556
- ✅ Added funding rate backtesting support for cryptocurrency perpetual contracts
504557
- ✅ Fixed Python 3.12 and 3.13 compatibility issues
@@ -511,7 +564,7 @@ We welcome code contributions, bug reports, and feature suggestions:
511564
- ✅ Fixed multiple known bugs
512565
- ✅ Enhanced CTP integration
513566

514-
For detailed changelog, see [CHANGELOG.md](CHANGELOG.md) (if available)
567+
For detailed changelog, see [docs/CHANGELOG.md](docs/CHANGELOG.md)
515568

516569
### License
517570

@@ -976,12 +1029,47 @@ class FundingRateStrategy(bt.Strategy):
9761029

9771030
### 文档与资源
9781031

979-
- 📚 [官方 Backtrader 文档](https://www.backtrader.com/)
1032+
- 📚 [项目文档索引](docs/README.md)
1033+
- 🛠️ [安装与环境排查](docs/INSTALLATION_GUIDE.md)
1034+
- 🧾 [更新日志](docs/CHANGELOG.md)
1035+
- 🐛 [DataTrades 修复说明](docs/DATATRADES_FIX.md)
1036+
- 🔌 [ExtendPandasFeed 修复说明](docs/EXTENDED_FEED_FIX.md)
1037+
- 📖 [官方 Backtrader 文档](https://www.backtrader.com/)
9801038
- 📝 [CSDN 教程系列](https://blog.csdn.net/qq_26948675/category_10220116.html)
9811039
- 💬 [问题反馈 - Gitee](https://gitee.com/yunjinqi/backtrader/issues)
9821040
- 💬 [问题反馈 - GitHub](https://github.com/cloudQuant/backtrader/issues)
9831041
- 🔧 [开发指南](CLAUDE.md)
9841042

1043+
### 项目结构
1044+
1045+
```
1046+
backtrader/
1047+
├── backtrader/ # 核心框架包
1048+
├── docs/ # 项目文档、更新日志、安装指南和修复说明
1049+
├── examples/ # 可运行示例项目
1050+
├── scripts/ # 辅助维护与 QA 脚本
1051+
│ ├── run_master_tests.py # 完整 pytest 运行 + HTML 报告
1052+
│ ├── run_test_with_log.py # 单个测试运行并按分支输出日志
1053+
│ ├── sync_and_test.py # 在分支间同步测试文件并对比运行
1054+
│ ├── profile_performance.py # 基于 cProfile 的策略性能分析
1055+
│ ├── debug_macd_replay.py # MACD replay 模式调试环境
1056+
│ ├── backtest_strategy_regression_expected.py # 回归基准生成器
1057+
│ ├── run_all_backtests.py # 批量回测运行器
1058+
│ └── test_python_versions_simple.sh/.bat # 多 Python 版本 conda 测试
1059+
├── strategies/ # 公用策略辅助包(如 benchmark_metrics)
1060+
├── studies/ # 研究笔记与 UML 图
1061+
├── tests/ # Pytest 测试集
1062+
│ ├── original_tests/ # 上游原版测试
1063+
│ ├── strategies/ # 自用策略测试
1064+
│ ├── funding_rate_examples/ # 加密货币资金费率测试
1065+
│ └── functional/strategies_regression/ # 1000+ 个生成的回归脚本(已加入 .gitignore)
1066+
├── pyproject.toml / setup.py / requirements.txt
1067+
└── README.md / CLAUDE.md / LICENSE
1068+
```
1069+
1070+
> `tests/functional/strategies_regression/`
1071+
> `scripts/backtest_strategy_regression_expected.py` 本地生成,不跟随仓库提交。
1072+
9851073
### 测试
9861074

9871075
```bash
@@ -992,11 +1080,21 @@ pytest tests
9921080
pytest tests --cov=backtrader --cov-report=html
9931081

9941082
# 运行特定测试类别
995-
pytest tests/original_tests # 核心功能
996-
pytest tests/funding_rate_examples # 加密货币特性
1083+
pytest tests/original_tests # 核心功能
1084+
pytest tests/funding_rate_examples # 加密货币特性
1085+
pytest tests/strategies # 自用策略
9971086

9981087
# 并行运行
9991088
pytest tests -n 4
1089+
1090+
# 便捷包装脚本(始终从仓库根目录运行)
1091+
python scripts/run_master_tests.py # 完整测试套件 + HTML 报告
1092+
python scripts/run_test_with_log.py tests/strategies/test_18_etf_rotation_strategy.py
1093+
bash scripts/test_python_versions_simple.sh # 多 Python 版本扫描
1094+
1095+
# 重新生成策略回归基准(耗时较长)
1096+
python scripts/backtest_strategy_regression_expected.py \
1097+
tests/functional/strategies_regression --workers 4 --overwrite
10001098
```
10011099

10021100
### 贡献指南
@@ -1011,6 +1109,13 @@ pytest tests -n 4
10111109

10121110
### 更新日志
10131111

1112+
#### 2026年更新
1113+
- ✅ 根目录辅助脚本全部归档到 `scripts/`
1114+
- ✅ 新增策略回归测试框架(1000+ 个以策略为粒度的 `run.py`基准,本地生成、已 gitignore)
1115+
-`backtrader.analyzers.pyfolio` 改为懒加载 `empyrical`,在 pandas 3 下也能正常 `import backtrader`
1116+
- ✅ 策略回归套件中将 `SharpeRatio``risk_free_rate` 参数统一改为 `riskfreerate`
1117+
- ✅ 将 `comminfo.get_param('mult')` 调用统一为 `getattr(comminfo.p, 'mult', 1.0)`
1118+
10141119
#### 2024年更新
10151120
- ✅ 增加了加密货币永续合约资金费率回测支持
10161121
- ✅ 修复了 Python 3.12 和 3.13 兼容性问题
@@ -1023,7 +1128,7 @@ pytest tests -n 4
10231128
- ✅ 修复了多个已知 bug
10241129
- ✅ 增强了 CTP 集成
10251130

1026-
详细更新日志请查看 [CHANGELOG.md](CHANGELOG.md)(如果有)
1131+
详细更新日志请查看 [docs/CHANGELOG.md](docs/CHANGELOG.md)
10271132

10281133
### 许可证
10291134

0 commit comments

Comments
 (0)