Dev#14
Open
cloudQuant wants to merge 158 commits into
Open
Conversation
修改内容: - 重命名并优化测试文件 - 实现8个 SimNow 环境 - 添加 mock 数据支持 - 修复 CTP 连接和测试
- 添加类型存根依赖: types-python-dateutil, types-PyMySQL - 修复 writer.py: collections.abc 导入、类型注解、Optional 检查 - 修复 bokeh/utils/helpers.py: datanames 类型注解 - 配置 pyproject.toml: 添加 per-module mypy overrides,减少框架模式的误报 Made-with: Cursor
# Conflicts: # backtrader/stores/btapistore.py
- 标记Phase 0仓库卫生治理为已完成 - 更新风险点A-E,附精确行号和代码审计证据 - 纠正Store两套继承体系的错误描述 - 新增TestStrategy硬编码类名检查等新发现 - 更新Phase 1-4任务拆分和验收标准 - 更新文件映射、里程碑、任务单 - 新增附录A:代码审计证据摘要
…llback (T02-T05)
T02: Add 16 regression tests for strategy instantiation chain
T03: Remove hardcoded 'TestStrategy' class name check in __init__
T04: Fix _create_strategy_safely to pass kwargs through instead of {}
T05: Remove silent fallback that caught init exceptions and retried
All 746 tests pass, 0 regressions.
…T06-T08)
T06: Narrow channel mode 'except Exception: continue' to 'except StrategySkipError'
T07: Replace hardcoded ~/cerebro_runnext_error.log with logger.exception()
T08: Remove dead code: _rs/_rp unused vars, my_num debug counter,
unreachable code in btapistore.py:231-234, commented debug prints
All 746 tests pass, 0 regressions.
T09: Fix LiveStoreBase.start() to accept optional data/broker params,
matching actual usage in BtApiStore/btapifeed/btapibroker.
Add 7 Store contract tests verifying ABC enforcement,
incomplete subclass rejection, and BtApiStore compliance.
All 753 tests pass, 0 regressions.
R1: strategy.py:160-164 - params creation failure now raises TypeError
instead of silently creating empty ParamsInstance
R2: cerebro.py dt0<1 - clarified as valid sentinel guard, added
logger.warning for visibility
R3: while True loop - documented as intentional (_last() needs extra round)
R4: newqcheck - documented mixed live/historical qcheck override logic
R5: store.py - added docstring documenting two Store hierarchies
(legacy Store vs LiveStoreBase) and migration guidance
R6: _runnext - added phase docstring, cleaned commented-out plotfillers
and debug print; deeper method extraction deferred (tight coupling)
All 753 tests pass, 0 regressions.
- All Phase headers (0-4) marked ✅ - All milestones M1-M6 marked completed - All 16 task tickets (T01-T10, R1-R6) marked completed with evidence - Appendix A audit findings updated with fix status per item - Test coverage section updated: 730 → 753 tests (+23 new) - Fixed outdated LiveStoreBase.start() description - Added completion date header
Source code fixes: - dateintern: fix get_last_timeframe_timestamp infinite loop when time_diff<=0, optimize O(n)->O(1) - dateintern: fix tzparse crash (AttributeError) on unknown timezone strings - autodict: fix AutoDict._close() broken (private attrs stored as dict keys instead of __dict__) - autodict: fix AutoOrderedDict copy-paste bugs in __imul__/__idiv__/__itruediv__ (returned + instead of *,//,/) - autodict: add key info to KeyError in AutoDict/AutoOrderedDict.__missing__ - autodict: remove dead code (if False branches) in AutoDict - position: remove dead code in Position.__init__ (upopened/upclosed overwritten by set()) - mathsupport: add is_finite_real utility function - analyzers: centralize is_finite_real usage in sharpe/drawdown/leverage - strategy: fix mutable default args in _notify ([] -> None) - feed: add null check in CSVDataBase.preload for self.f - errors: improve ModuleImportError/FromModuleImportError New tests (87): test_quality_improvements_v2.py covering all fixes Verified: 1355 passed, 1 skipped (pytest tests -n 30)
…it, fix DotDict/Position/Writer
Code quality improvements:
- functions.py: Fix List.__contains__ to use identity check ('is') instead of
hash comparison, matching the original design intent and avoiding hash collisions
- trade.py: Add __repr__ for readable debugging output
- order.py: Add __repr__ to OrderExecutionBit for readable debugging output
- utils/autodict.py: Fix DotDict.__getattr__ to raise AttributeError for dunder
attributes instead of calling non-existent super().__getattr__
- position.py: Fix Position.set() upopened=size when opening from zero;
add __repr__ and __eq__ methods
- writer.py: Add context manager support and safer stop() for WriterFile
All 1415 tests pass (pytest tests -n 30).
…ontracts - AutoDict/AutoOrderedDict: __getattr__ now raises AttributeError with key info instead of bare AttributeError, improving debuggability and hasattr() behavior - Position: add explicit __hash__ = None (mutable objects must not be hashable) - Trade.__repr__: bounds-safe status name lookup prevents IndexError/TypeError - mathsupport: guard variance() and standarddev() against empty sequences - CommInfo subclasses: guard get_margin() against None margin parameter (ComminfoDC, ComminfoFuturesPercent, ComminfoFuturesFixed, ComminfoFundingRate) - Add 32 new unit tests covering all improvements
…ive guards - Order: add __hash__ based on immutable ref (enables use in sets/dicts) - Order.alive(): use frozenset for O(1) status membership lookup - Order.getstatusname()/getordername(): bounds-safe with try/except - SQN: explicit zero-stddev guard before division (avoids ZeroDivisionError) - Writer.stop(): narrow except to OSError instead of bare Exception - BuySell.next(): narrow except to (IndexError, AttributeError, TypeError) - Envelope: narrow except to (AttributeError, StopIteration, TypeError, KeyError) - HurstExponent: narrow except to (ValueError, TypeError, FloatingPointError) - Add 32 new unit tests covering all improvements
- trade.py: getdataname/open_datetime/close_datetime safe when data is None - position.py: clone() now preserves datetime/adjbase/updt state - mathsupport.py: average() handles negative denominator edge case (empty list + bessel) - stochastic.py: division by zero guard in Stochastic.next() - store.py: put_notification/get_notifications safe when notifs is None - Added 34 new tests covering all improvements (test_quality_improvements_v6.py) All 1513 tests pass (1479 original + 34 new), 1 skipped.
…pleteness
- timer.py: Fix mutable default arguments for weekdays/monthdays parameters
(changed from [] to None to prevent shared state across instances)
- percents_sizer.py: Add NaN guard for close_price in _getsizing
(float('nan') is truthy, so 'not close_price' didn't catch it)
- comminfo.py: Guard against None interest in _creditrate calculation
- position.py: Make clone() copy all state fields (upopened, upclosed, price_orig)
- Add 23 new unit tests covering all fixes (tests/unit/test_quality_fixes.py)
All 1536 tests pass (pytest tests -n 30), 1 skipped.
Add HFT broker/comparison modules, maker-taker commission handling, MixBroker/TickBroker support, examples/tests/docs, queue market making alignment, and NumPy 2.0 plot compatibility.
- Improve trade logger observer with better edge case handling - Update position modes for dual side trading support - Enhance BtApiStore with dual side capabilities - Add dual side trading examples: basic, hedge, and vs_net modes - Update CTP example configurations across all broker types - Add comprehensive test coverage for trade logger and CTP examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Backtrader 去元编程项目 - Pull Request
📋 PR 概述
基本信息
变更摘要
修改范围
backtrader/[模块名].py: [变更描述]tests/[测试文件].py: [变更描述]🎯 元编程移除验证 ⭐⭐⭐⭐⭐
移除的元编程模式
移除的元类:
移除的动态类创建:
替代方案实现
使用的替代技术:
__init_subclass__方法实现完整性验证:
工具验证
🔄 API兼容性验证 ⭐⭐⭐⭐
公共接口检查
方法签名保持不变:
属性访问保持一致:
行为兼容性
核心功能验证:
异常处理验证:
兼容性测试结果
⚡ 性能影响评估 ⭐⭐⭐
性能基准测试
执行性能对比:
内存使用分析:
性能测试命令
关键路径优化
🧪 测试覆盖验证 ⭐⭐⭐
测试覆盖率
新增测试用例
功能测试:
边界条件测试:
异常情况测试:
📊 代码质量检查 ⭐⭐⭐
静态分析结果
代码质量评估
可读性和维护性:
架构设计:
📚 文档更新 ⭐⭐
文档变更
API文档:
用户文档:
开发文档:
文档质量
🔍 回归测试验证
完整测试套件
核心功能测试:
集成测试:
已知问题
📝 变更详情
主要变更
[变更类别]: [详细描述]
[文件路径][变更类别]: [详细描述]
[文件路径]技术实现细节
设计决策
🚨 风险评估
潜在风险
高风险:
中等风险:
回滚计划
✅ 审查检查清单
自检完成项
待审查项
📞 联系信息
PR提交者: [姓名]
联系方式: [邮箱/Slack]
提交时间: [日期时间]
预计审查时间: [时间估算]
🔧 审查者使用指南
审查步骤
git checkout [branch-name]审查标准
审查反馈模板
请使用代码审查规范中的反馈模板进行审查反馈。
模板版本: 1.0
最后更新: 2025年05月30日