GitHub
8a5ed52a1f
release: v1.28.1 — WebUI 名词解释折叠帮助 + AI 解读 Prompt 导出 + WF 窗口序列化修复(to_json_native 有限 float 落入 str 兜底,逐窗指标变字符串)
2026-09-02 15:49:41 +08:00
GitHub
534ab0e0c8
Merge branch 'main' of https://github.com/handsomejustin/easy_tdx
2026-09-02 13:16:41 +08:00
Justin Gu
0a00ca3f70
release: v1.28.0 — 深度风险报告+移动止损+黄金测试(借鉴 akquant):25 项绩效 / α·β·IR·TE 基准对比 / trail_stop OCO
2026-09-02 11:53:53 +08:00
GitHub
36ea8497ae
perf(engine): 信号管线提速 ×12.6 — 向量化快速路径 + 日期查找表 + 去 strftime
...
基准先行(scripts/bench_engine.py):ma_cross 800 根全流程基线 93.6ms。
profile 打破预期:85% 墙钟在 OrderSimulator._find_bar_index(每信号全列
strftime),而非计划认为的逐 bar 信号循环。三处优化(行为逐位一致):
- Strategy 新增 entry_exit_masks() 显式钩子,19 个内置策略全实现;引擎按
掩码 + 候选事件 bar 状态机一次产出信号,持仓估算逐行复刻
_update_strategy_position(含买不足 1 手退化路径);约束检测
_vectorize_eligibility 显式可测,signal_path=auto/vector/loop 可指定;
不满足约束(无钩子/缠论注入/掩码形状错)自动回退逐 bar
- OrderSimulator._build_dt_lookup:O(信号×bar) 全列扫描 → 每 simulate 一次
O(bar) 查找表(重复日期取首个、未命中 None、object 恒不匹配语义对齐)
- _datetime_to_int 去 strftime:year*10000+month*100+day 整数算术
(NaT→NaN 行为一致),_bind_data 与查找表共用
实测:ma_cross 全流程 93.6→7.4ms(×12.6),信号层 ×1.39~1.72(四策略);
32 点网格寻优 ~3.0s→231ms。对拍 39 例:19 策略×参数变体×warmup/低资金/
费率/缓存,performance/trades/equity/positions 逐位一致。
顺带记录:wr_reversal 默认阈值与 MyTT WR 刻度不匹配(策略恒不交易,既有问题未改)
2026-09-01 23:47:06 +08:00
GitHub
561e2d3e61
fix(lint): isinstance 元组写法改 PEP 604 联合类型,修复 CI 的 UP038
...
CI 经 requirements-dev.txt 锁定 ruff==0.11.11(UP038 仍生效),本地 0.16.4 已移除该
规则导致漏检。10 处 isinstance(x, (A, B)) 统一改为 isinstance(x, A | B)(项目
requires-python>=3.10,联合类型 isinstance 合法;strategy.py 已有同风格先例)。
已用 CI 同版本工具链本地复验:ruff 0.11.11 check/format、mypy 2.1.0 strict、
1252 单测全过。
2026-09-01 22:36:37 +08:00
GitHub
917295edaf
release: v1.27.0 — 通达信公式解析器三通道 + 轮动组合引擎 + 回测页WF/评估开关 + Docker 部署
...
升级计划 P3 + P4(部分)。全量 1252 单测、ruff/mypy strict、前端 vue-tsc+vite build 全绿。
- 通达信公式解析器(formula.py):自建 tokenizer + 递归下降 AST + 30+ 函数白名单求值
(不走 Python eval);命名布尔输出=信号列、数值输出=排名列;除零→NaN、预热期不出信号
- 公式三通道:CLI easy-tdx formula compute|screen|backtest;REST /formula/validate|compute|
backtest|screen(run/async);Python API run_formula_backtest(买/卖列自动挑选)
- 轮动组合引擎(rotation.py):排名定期换仓(打分只用截至当日数据)、槽位等额、
跌出排名自动补位、日/周/月刷新、槽内止盈止损;momentum_score/formula_score 打分;
REST /backtest/rotation/run/async
- 回测页附加分析开关(Web UI):勾选后随回测并行跑 WF(逐窗红涨绿跌柱状图+汇总卡,
窗口数 2~12)与一条龙评估(评分分项条/高适配徽标/买入持有对比/8 项适配检查);
新增 WalkForwardPanel/EvaluatePanel 组件与 store runWalkforward/runEvaluate;
WF 端点 ?n_windows= 透传;修复报告 numpy 标量 REST 400(源头清洗)
- Docker 部署(Dockerfile + docker-compose.yml,/data 卷 + 健康检查)与
scripts/verify_ci.sh 一键门禁
- 升级计划文档 docs/upgrade-plan-2026H2.md(四阶段全部完成 + 诚实实测数据)
- 未做(独立排期):Playwright E2E、WebSocket 实时联动、引擎逐 bar 向量化
2026-09-01 22:17:57 +08:00
GitHub
b2509a8d0e
release: v1.25.0 — Walk-Forward/适配性/一条龙评估防过拟合链 + 评分评级后端化 + 寻优加速
...
升级计划 P1:补上两个下游项目都在自研的样本外验证空白。
- Walk-Forward 引擎(walkforward.py):7 窗样本外、每窗独立开仓(backtest-system v1.2.1 踩坑语义)、
上下文预热不污染;CLI --wf、REST /backtest/wf/run/async
- 适配性评估(fitness.py):train/valid/test 三段 + 8 项可解释检查 + 高适配标记;
evaluate_prefix 滚动过滤原语(无未来泄漏)
- 一条龙评估(benchmark.py evaluate_strategy):回测+WF+适配性+评分+评级+买入持有基准对比;
CLI --evaluate、REST /backtest/evaluate/run/async
- 综合评分(scoring.py,收益50/夏普15/回撤10/Sortino5/WF20)+ 评级后端化(grading.py,
前端 TS 忠实移植,REST 响应新增 grade/score 字段)
- 多 seed 验证 + 四项晋级门槛(validation.py);REST /backtest/multiseed/run/async
- 寻优两段式加速:IndicatorCache(36 点网格命中率 41.7%)+ workers 进程并行(实测约 2x);
诚实注:指标缓存墙钟 ~1.01x,瓶颈在逐 bar 循环,后续向量化
- strategy.I() 指标缓存钩子 + 数据代理零拷贝(astype copy=False);
types.to_json_native 统一 numpy 清洗
2026-09-01 22:17:08 +08:00
GitHub
1fc1d00c90
release: v1.24.0 — QFQ 对拍验证体系 + 回测任务持久化 + 品种感知费率
...
升级计划 P0(docs/upgrade-plan-2026H2.md)。源自 backtest-system / indicator-lab 两个下游项目的逆向调研。
- QFQ 对拍验证:公式法(NONE+XDXR)与跳空检测法(板块感知涨跌停阈值)双证据链互检,
检出负价/残留跳空/方向反演/XDXR 缺记录四类问题,接入 MAC 同步/异步客户端(mac/qfq_check.py);
含茅台式多重分红、浦发式送转方向合成案例回归(13 用例)
- 回测任务 SQLite 持久化:~/.easy_tdx/tasks.db 双写内存 LRU + 磁盘(保留 500 条),serve 重启不丢;
重启恢复中断任务标记;GET /backtest/tasks/{id}/export?format=json|csv 导出端点
- 品种感知费率:ETF/可转债免印花税等法定差异(backtest/fees.py),CLI --auto-fees、
REST auto_fees 字段、组合引擎逐标的解析(34 用例)
- 修正 avg_holding_days 过时注释(实现早已是 FIFO 真实口径)
- tests/conftest.py 默认 EASY_TDX_NO_TASK_DB=1 防止单测污染用户任务库
- 注:engine/cli/routers/schemas 为跨版本累积态,后续版本提交继续演进
2026-09-01 22:16:44 +08:00
GitHub
3180ab3002
fix(backtest): 策略参数加跨语义约束,杜绝寻优选出快慢倒挂组合(issue #39)
...
寻优器网格探索不区分语义:ma_cross 的 fast∈[5..60] × slow∈[10..250]
笛卡尔积包含 {"fast":30,"slow":20} 这类倒挂组合,倒挂的双均线交叉
本质是反向策略,回测成绩可能反而突出,从而被选为"最优参数"展示
(即 issue #39 截图中 {"fast":30,"slow":20} 的来源)。presets.py 的
注释"快线<慢线才有意义;去重无效组合"早已写下意图但从未实现。
根因是参数校验只有单参数 min/max,缺跨参数语义约束:
- ParametrizedStrategy 新增 param_constraints 类属性 [(a,b), ...]
表示要求 a<b,在 __init__ 解析后统一校验,报错带中文标签;
语义约束不受 skip_bounds 影响(寻优跳过的只是数值边界)
- 7 个策略声明约束:ma_cross/ema_cross(fast<slow)、macd
(short<long)、triple_ma(short<mid<long)、rsi_reversal/cci/
wr_reversal(oversold<overbought)
- 寻优器 build 阶段的 ValueError 降为 info 级跳过(无堆栈噪音),
回测异常仍走 warning;预设网格 36 组合 → 有效 25 个
- 新增 10 个回归测试(旧代码全失败、新代码全通过)
2026-08-19 18:55:48 +08:00
GitHub
d84a08b7f2
fix(backtest): v1.20.3 修复回测绩效统计两个 bug(issues #30 #31)
...
#31 : RebalanceEngine 缺失价格导致净值假崩塌
已持仓标的当日缺 K 线(停牌/日历错位)时 prices.get(code,0)=0,
持仓市值记 0 → 净值单日暴跌(159915 在 20210208 缺一天,持仓 ~93%,
净值 1.1M→91,845,全期最大回撤 -92%)。
修复:last_known_price forward-fill,缺失日沿用最近已知收盘价。
附带:_compute_performance 最大回撤改正值口径(与 BacktestEngine 一致)。
验证:真实 ETF 数据 max_drawdown 24.01%(backtrader 基准 27%),
total_return 220.56% 不变。
#30 : PortfolioTracker 交易静默漏单
apply_trades 用 trade.datetime 作 dict key、df["datetime"].to_numpy()[i]
查找;两端类型不一致(int vs datetime64)时永不命中,交易被静默丢弃,
净值恒定(total_return=0 但 trades 表有 PnL)。
修复:改为按"位置索引"匹配(归一化 datetime 后查位置),类型无关。
验证:int-trade+datetime64-df 修复前净值=100000(恒定),修复后=100289。
测试:新增 4 回归测试(未修复代码上均失败,修复后通过);
全套 936 passed;mypy 改动文件零错误;ruff 全绿。
2026-07-10 15:12:47 +08:00
GitHub
a67e5588d0
fix(types): v1.20.2 修复 v1.20.1 引入的 CI mypy 失败
...
v1.20.1 把 BacktestResult.performance 扩大为 dict[str, float | str]
(为塞 diagnostic_warning 字符串),破坏 6 处下游消费方类型契约,
CI mypy job 转红。重构为更干净的设计:
- 诊断信息走独立的 BacktestResult.diagnostic 字段(performance.py
PerformanceAnalyzer.diagnostic 属性 → engine 透出 → to_dict 含该字段
→ CLI 显示),performance 字典回归 dict[str, float](保留别名键)。
- optimizer.py 补 npt.NDArray 标注,消除 3 个既有 ndarray type-arg 错误。
测试:932 passed;mypy backtest/+portfolio/ 零错误;ruff 全绿。
2026-07-09 20:34:23 +08:00
毛利哥
eb51770608
Merge pull request #27 from handsomejustin/fix/v1.20.1-backtest-bugs
...
fix(backtest): v1.20.1 修复回测引擎 3 个 bug(issues #22 #23 #25)
2026-07-09 20:17:00 +08:00
GitHub
00b8c6374a
fix(backtest): v1.20.1 修复回测引擎 3 个 bug(issues #22 #23 #25)
...
排查发现用户反馈的"回测统计数据缺失/异常"并非服务器连接问题,
而是回测引擎与组合优化器自身的代码缺陷:
#23 : 首根 bar 访问 close[-1] 崩溃
_SeriesAccessor 负向越界改返回 NaN(不抛 IndexError);
BacktestEngine 新增 warmup_bars 参数跳过指标预热期。
#25-A: FactorWeightedOptimizer 权重坍缩
n_stocks=2 且得分接近时,减最小值把低分标的权重压到 ~6e-8,
等于单股满仓、n_stocks 被无视,进而出现持仓1只/-99.98%回撤。
新增 _apply_weight_floor 权重下限保证入选标的都有实质权重。
#25-B: RebalanceEngine total_trades 统计错误
total_trades = len(equity_curve)(天数)改为 len(trades_df)(真实笔数)。
#22 : 绩效别名键 + 数据异常诊断
performance dict 新增 sharpe_ratio/start_cash/end_value 别名键;
资金曲线异常时返回 diagnostic_warning 而非静默全 0,CLI 显示提示。
文档:README 加入回测手册导航;backtest_usage.md 补充 warmup 说明。
测试:新增 6 个回归测试,更新 3 个;932 passed。
2026-07-09 20:16:12 +08:00
GitHub
052119e6ae
feat(backtest): v4.2 新增 FSL 分水岭指标策略(单标的/组合/寻优)
...
- MyTT.py: 新增 FSL(CLOSE, VOL, CAPITAL) 分水岭指标
- SWL = (EMA(C,5)*7 + EMA(C,10)*3) / 10
- SWS = DMA(EMA(C,12), MAX(1, 100*SUM(VOL,5)/(3*CAPITAL)))
MIN(A,1.0) 模拟通达信 DMA(X,A) 内部钳制 A<=1 的语义
- MyTT.pyi: 补 FSL 类型 stub(CI mypy 用 .pyi 校验)
- strategies/builtin.py: 注册 FslStrategy(SWL/SWS 金叉死叉)
capital 作为 Param 暴露流通股本输入
- strategies/presets.py: fsl 寻优网格(4 档 capital)
- tests: 注册表断言加 fsl,阈值 18→19
2026-07-09 18:42:00 +08:00
Justin Gu
239ff46ac8
release: v1.17.13 — 修复多策略组合回测最大回撤虚高(分母误用初始值而非峰值)
...
用户反馈:3 个策略各自最大回撤仅 45.53%/40.16%/16.89%,组合却显示 83.76%。
根因:_build_combined_equity 的 drawdown_pct 分母误用 initial(固定初始资金),
净值大涨后(总收益 545%,峰值≈6.45×初始)绝对回撤额除以小初始值被等比放大。
改为 drawdown / peak(相对当时峰值,0~1),与单标的 PortfolioTracker 一致。
连带修复卡玛比率(年化/最大回撤)。其余指标经核对均正确。加回归守卫。
2026-07-04 21:07:39 +08:00
Justin Gu
05dc9a74af
release: v1.17.11 — Web UI 策略库(SQLite 持久化)+ 多策略资金分仓组合回测
...
新增两层能力:
1. 策略库:单标的/组合回测结果可保存到本地 SQLite 单文件
(~/.easy_tdx/strategies.db),策略库页可载入回填、重跑、删除。
2. 多策略组合回测:勾选 N 个单标的策略,各拿 1/N 资金、各跑原标的,
净值曲线按日期并集对齐求和,组合结果含 19 项完整绩效指标 + 持仓表。
后端:strategy_store.py(SQLite CRUD) + multi_strategy_engine.py(资金分仓引擎)
+ routers/strategies.py + /backtest/multi-strategy/run/async。
前端:StrategiesView.vue + 保存策略按钮 + 复用组合页图表组件。
895 单测全绿(+24 新增),ruff/mypy strict/前端 vue-tsc 全通过。
2026-07-04 20:40:57 +08:00
Justin Gu
57cad1f3db
release: v1.17.9 — 修复回测交易统计离谱数值(前后端口径错配 + 持仓天数跨月放大)
...
- 交易盈亏指标改为收益率口径(avg_win/loss/max_win/loss = pnl/cost_basis)
- 平均持仓天数改用真实日历日相减(原 YYYYMMDD 整数差跨月放大)
- 盈亏比无亏损时记 999.0(原 0.0,与 100% 胜率自相矛盾)
- 新增 Trade.cost_basis 字段 + engine 填充
- 3 个回归守卫;870 单测全绿,ruff/mypy strict/前端 vue-tsc 通过
2026-07-04 03:55:05 +08:00
Justin Gu
f6ae69845d
feat(backtest): 成交价精简 + 一键寻优全策略 + 预设网格
...
- 成交价精简为 next_open/next_close,删除 this_close/worst/best 三种
非真实模式(this_close 有未来函数偏差,worst/best 为压力测试边界)
- 初始资金默认统一为 1,000,000(原 10万/20万)
- 新增 presets.py:18 策略各配 1-2 参数的预设寻优网格(笛卡尔积≤200)
- registry.to_schema() 返回 preset_grid 字段供前端自动填充
- 新增 POST /backtest/optimize-all/run/async:逐策略预设网格寻优 +
全局排名(OptimizeAllResult:ranking/best/per_strategy/total_grid_points)
- 新增 optimize-all 端到端单测 2 例(838 单测全绿)
2026-07-04 00:08:38 +08:00
Justin Gu
8323223937
fix: 寻优跳过参数范围/对比支持组合/日线x轴年份/寻优跳转填充参数
...
4 个独立修复:
1. 寻优跳过参数范围检查:Param.validate 加 skip_bounds 参数,
RegisteredStrategy.build 透传,ParamGridOptimizer 传 skip_bounds=True。
修复寻优时 fast=250 被 max_value=60 拦截的问题(探索超范围值是寻优目的)。
2. 对比页支持组合回测:CompareView 新增 extractComparable() 统一提取净值+指标,
支持单标的(performance/equity_curve)和组合(total_performance/combined_equity)。
修复勾选组合回测任务报「非单标的回测」错误。
3. K线x轴日线显示完整年份:isIntraday 判断从 length>10 改为检查时分秒非零
(日线归一化后带 T00:00:00 后缀,长度也 >10 导致误判为分钟线,slice 砍年份)。
4. 寻优跳转填充参数:BacktestView 加 useRoute(),onMounted 读 query.strategy +
query.params,await nextTick 后覆盖(避免 StrategyPicker watch 重置)。
修复寻优点「查看」跳转后参数未填充、仍用默认值的问题。
测试:823 passed, mypy 211 files OK, vue-tsc OK
2026-07-03 11:32:44 +08:00
Justin Gu
2903d8c800
feat(strategies): 内置策略从 5 个扩充到 18 个
...
新增 13 个经典策略,覆盖趋势/通道/震荡/均线四大类:
趋势类:
- ema_cross EMA 双线交叉(比 MA 反应更灵敏)
- triple_ma 三均线系统(多头/空头排列)
- dmi DMI 趋向指标(+DI/-DI 交叉)
- trix TRIX 三重平滑(过滤短期波动)
通道/突破类:
- donchian 唐安奇通道突破(海龟交易法)
- keltner 肯特纳通道(ATR-based)
- atr_breakout ATR 通道突破(均线±K×ATR)
震荡/反转类:
- cci CCI 超卖反弹
- wr_reversal WR 威廉超卖
- bias_reversal BIAS 乖离反弹
- emv EMV 简易波动(量价结合)
- dpo DPO 区间震荡
均线类:
- bbi BBI 多空指标(4 均线综合)
全部基于 MyTT 现成指标实现,每个策略声明参数 schema 供 Web 表单动态渲染。
18/18 策略冒烟测试通过(合成数据回测无运行时错误)。
2026-07-03 04:36:04 +08:00
Justin Gu
87fafe9131
feat(backtest): 参数网格寻优(optimizer + 前端寻优页)
...
对单个策略的 1-2 个参数做网格搜索,遍历用户指定的取值列表笛卡尔积,
每个组合跑一次回测,按 total_return 排序,返回排名表 + 热力图。
后端:
- ParamGridOptimizer(backtest/optimizer.py):itertools.product 遍历网格,
每点 entry.build(params) + BacktestEngine.run(df),复用同一 DataFrame
- 网格大小上限 200 防组合爆炸,单点失败容错(跳过不中断)
- 2 参数时生成热力图矩阵(x/y 轴取值 + cell 收益率)
- POST /backtest/optimize/run/async 端点(后台任务)
- OptimizeBacktestRequest schema(param_grid 1-2 参数)
前端(/optimize 寻优页):
- ParamGridPicker:勾选 1-2 个寻优参数,逗号分隔填取值列表
- OptimizeResultTable:网格点排名表(按收益降序,最优高亮)
- OptimizeHeatmap:2 参数热力图(ECharts heatmap,绿→红映射收益)
- 最优点「查看」按钮跳转单标的页用该参数回测
测试:821 passed(+10 寻优器单测 + 3 寻优路由测试)
2026-07-03 03:55:35 +08:00
Justin Gu
38731114b6
feat(backtest): 回测 REST API + 策略注册表 + 组合回测引擎
...
后端回测系统完整实现:
策略注册表(backtest/strategies/):
- Param schema 声明机制,支持动态表单渲染
- 5 个内置策略:MA交叉/MACD/布林/RSI/KDJ
- 参数校验(含 NaN/Inf 拦截、范围检查、类型强制转换)
REST API(web/routers/backtest.py):
- GET /backtest/strategies 策略枚举 + 参数 schema
- POST /backtest/run 同步回测(内联 OHLCV)
- POST /backtest/run/async 后台任务回测(含 symbol 取行情)
- POST /backtest/portfolio/run/async 组合回测(多标的)
- GET /backtest/tasks/{id} 任务轮询
后台任务执行器(web/task_runner.py):
- ThreadPoolExecutor + 进程内 LRU 任务表
- status-aware 淘汰(不淘汰 running 任务)
- 线程安全单例 + lifespan shutdown 接入
组合回测引擎改造(portfolio_engine.py):
- 接受策略实例,参数透传到每个标的
- 新增组合净值曲线(按日期并集 forward-fill 对齐求和)
审计修复(/check 三轮):
- Param.validate 拦截 NaN/Inf/giant-int(防 DoS)
- ohlcv max_length=2000(防内存耗尽)
- LRU 淘汰跳过 running 任务(修复结果丢失竞态)
- get_runner double-checked locking(修复单例竞态)
- shutdown 接入 lifespan(修复资源泄漏)
测试:808 passed(含 39 回测路由 + 8 组合引擎 + 安全回归)
2026-07-03 03:34:34 +08:00
GitHub
155328df8b
release: v1.16.2 — 三轮审计质量加固(B6.9→A7.9)
...
经三轮代码审计后的综合质量加固版本,覆盖协议核心层、数据正确性、
错误处理、测试真实度与可维护性。761 单测全绿(+58),ruff/mypy 全过。
主要修复:
- 离线 .day 写入原子化(fsync + _repair_tail + 读取校验,CQS 守住)
- 回测止损前视偏差(延迟下一根开盘 + 跳空保护)
- VWAP 权重索引 / bar_time fail-fast / 绩效除零保护
- 闭包绑定 / 路径穿越 / naive datetime 跨时区 / ruff UP038
重构:
- 抽 AsyncHeartbeatMixin 收敛 4 处心跳副本(12→1)
- 统一 _RETRY_DELAYS 退避序列 / scanner 失败可观测性
新增 5 个测试文件 + 公共 API 类型契约,CI 加 Windows 矩阵 +
trusted publishing 签名 + 锁文件。
详见 CHANGELOG.md
2026-07-02 03:37:37 +08:00
GitHub and Claude
c54071e85e
release: v1.14.1 — 高级回测 ExecutionModel 路径 3 个真实数据兼容 Bug 修复
...
- datetime 类型分歧(致命):Trade.datetime 转 int 与 PortfolioTracker 的 Timestamp key 失配,TWAP/VWAP/Limit 路径交易全部静默丢失、权益曲线恒定、收益归零
- volume 列名分歧:回测认 volume 而真实行情为 vol,滑点 volume 恒 0 退化百分比模式,VWAP 退化为等权
- date/datetime 列名分歧:日线返回 date 列引擎要 datetime,run() 入口由 date 派生下游无感兼容
新增 3 个回归测试(均红灯验证)。650 单测通过,backtest 模块 ruff + mypy strict 清洁。
Co-Authored-By: Claude <noreply@anthropic.com >
2026-06-15 20:50:49 +08:00
Justin Gu
5fc398255d
fix(types): 修复 CI mypy strict + ruff format 失败
...
mypy (13 errors → 0):
- portfolio/optimizer: register_optimizer 返回类型改为 Callable 装饰器签名
(原标注 type[WeightOptimizer] 导致 4 个子类 Too many arguments)
- factor/engine: _datetime_to_int 用 isinstance 收窄替代 object→int 强转
- factor/analysis: 删多余 type:ignore(改由 mypy override 统一处理 scipy)
- backtest/orders, execution: np.sqrt 表达式用 float() 包裹消除 no-any-return
- MyTT.pyi: MACD 签名删除错误的 LOW/HIGH 参数(与 MyTT.py 实际签名对齐)
- pyproject: 新增 scipy mypy override (ignore_missing_imports)
ruff format: 8 个 test 文件格式化
验证: 564 passed, mypy 192 文件零错误, ruff check/format 全绿
2026-06-13 21:21:33 +08:00
Justin Gu
be41746aa9
fix(backtest): _find_bar_index 用 to_numpy().argmax() 取真实位置
...
idxmax() 返回 index label,后续 iloc[] 按位置取行;当 df.index 非默认
RangeIndex 时 label != position,撮合会取错 K 线。两处分支统一改为位置索引。
新增 2 例非连续 index 回归测试。
2026-06-13 21:10:15 +08:00
GitHub and Claude
06f2e1f1a2
feat(backtest): add AttributionAnalyzer with Brinson, factor, cost attribution
...
Co-Authored-By: Claude <noreply@anthropic.com >
2026-06-12 21:10:50 +08:00
GitHub
0945e47990
feat(backtest): integrate SlippageModel + ExecutionModel into BacktestEngine
2026-06-12 21:04:24 +08:00
GitHub
d18af98855
feat(backtest): add LimitExecution
2026-06-12 20:59:59 +08:00
GitHub
fe68d9da95
feat(backtest): add TWAPExecution + VWAPExecution
2026-06-12 20:56:57 +08:00
GitHub
0772666be3
feat(backtest): add ExecutionModel ABC + ImmediateExecution
2026-06-12 20:53:07 +08:00
GitHub
6414c2cc11
feat(backtest): integrate SlippageModel into OrderSimulator
2026-06-12 20:50:42 +08:00
GitHub
d081eeb265
feat(backtest): add SquareRootSlippage + VolumeSlippage
2026-06-12 20:47:03 +08:00
GitHub
4098af02bf
feat(backtest): add SlippageModel ABC + FixedSlippage + PercentSlippage
2026-06-12 20:44:28 +08:00
Justin Gu
15cc7680c4
release: v1.9.7 — CLI全量集成(workers/cache/chanlun-level/portfolio/multi-level)+ bugfix
2026-06-11 03:57:48 +08:00
Justin Gu
9c39ad054d
feat: multi-stock portfolio backtest engine
...
- Add PortfolioBacktestEngine for shared-capital multi-stock backtesting
- Support equal allocation mode (total_cash / N per stock)
- Individual BacktestEngine per stock with allocated capital
- Aggregate performance via capital-weighted returns
- Add StockData, PortfolioResult data classes
- Add 4 tests: basic run, equal allocation, empty stocks, serialization
2026-06-11 02:31:43 +08:00
Justin Gu
af005d9fe4
feat: auto-bridge chanlun analysis into backtest strategies
...
- Add chanlun_level param to BacktestEngine constructor
- When set, auto-create ChanlunAnalyser and compute ChanlunResult
- Manual chanlun_result in run() takes priority over auto-compute
- Update Strategy.chanlun type to Any (accepts ChanlunResult or dict)
- Add 2 tests: auto-bridge and manual override priority
2026-06-11 01:56:59 +08:00
Justin Gu
815b3ddf7c
feat: implement stop-loss/take-profit execution in backtest engine
...
- Track SL/TP conditions from BUY signals in _generate_signals loop
- Check active conditions against each bar's high/low price range
- Auto-generate SELL signal at trigger price when condition is met
- Modify OrderSimulator to respect signal.price for direct execution
(previously signal.price was stored but never used in execution)
- SL/TP activates on bar AFTER BUY signal (consistent with next_open)
- Stop-loss checked before take-profit (conservative for holder)
- Add 4 tests: SL trigger, TP trigger, no-trigger, priority over manual sell
2026-06-11 01:53:11 +08:00
Justin Gu
06b2617ebc
fix: CI coverage enforcement, real avg_holding_days, vectorize _datetime_to_int
...
- Add --cov and --cov-fail-under=50 to CI pytest command
- Replace hardcoded avg_holding_days=5.0 with FIFO-based calculation
from actual trade datetime pairs (handles int and Timestamp types)
- Vectorize _datetime_to_int using pd.to_datetime().strftime()
instead of Python for-loop (~100-200x faster on large arrays)
- Add 3 new test cases: weighted holding days, no datetime fallback,
only-buys edge case
2026-06-11 01:44:39 +08:00
GitHub and Claude Opus 4.8
4dfd18050e
fix: resolve all CI mypy (265→0) and ruff (26→0) errors
...
- pyproject.toml: add mypy overrides for pandas/tabulate/matplotlib stubs,
disable strict checking for vendored MyTT library
- config.py: use cast() for dict[str, Any] .get() returns
- beichi.py: widen _calc_bi_force param to BI | XD, import XD
- backtest/cli.py: split combo/single strategy into separate typed variables
- backtest/combo.py: add bool_array() helper for numpy return types
- chanlun/analyser.py: type ignore for pandas row access, fix dict type arg
- unified.py: change fields param from object to Any
- ex/mac_client.py: add type args to list literals
- cli/cmd_offline.py: wrap int market as Market enum before API call
- cli/cmd_chanlun.py: fix dict type arg
- offline/write_*.py: explicit int() cast for struct.unpack returns
- MyTT.py: fix line-too-long comments, UP038 isinstance syntax
- tests: fix E712 (==False → ~mask), E741 (noqa), F841, import sorting
- ruff format applied across codebase
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com >
2026-06-10 15:03:41 +08:00
Justin Gu
5691bb8432
refactor: screen() reuses run_combination(), single runner across combo sizes
...
- screen() now calls run_combination() internally, eliminating duplicated
signal extraction/combination logic
- _run_combo_screen creates one CombinationRunner before the size loop,
so signal cache is reused across 2-factor and 3-factor screens
- Add MAJORITY(2)=AND note to screen() docstring
2026-06-10 02:13:28 +08:00
Justin Gu
1e99feb7c2
feat: multi-factor combo backtest engine (v1.9.0)
...
- Add backtest/combo.py: CombinationRunner, extract_factor_signals, combine_masks
- Signal merge modes: AND / OR / MAJORITY (majority default)
- CLI: --combo-strategies and --combo-mode for easy-tdx backtest
- run_all_strategies.py: --combo 2 --combo 3 auto-screen best combos
- Fix MyTT MFI/CR divide-by-zero RuntimeWarning
- 14 new unit tests, 328 total passing
2026-06-10 01:37:28 +08:00
GitHub and Claude Opus 4.8
b5b5d0dc5b
release: v1.8.0 - backtest engine with batch strategy comparison
...
- Add backtest section to README with CLI usage and run_all_strategies.py demo
- Update all version numbers to 1.8.0 (pyproject.toml, __init__.py, cli/__init__.py, docs/conf.py)
- Fix turtle_breakout strategy: TAQ returns 3 values (UP, MID, DOWN)
- Add run_all_strategies.py batch comparison script
- Update README intro to highlight backtest feature
- Add backtest to CLI command table and architecture tree
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com >
2026-06-09 20:35:38 +08:00
GitHub and Claude Opus 4.8
70c69c8a66
fix(backtest): cli _print_table used wrong key 'sharpe_ratio' instead of 'sharpe'
...
Performance dict outputs 'sharpe' but _print_table looked up 'sharpe_ratio',
so perf.get('sharpe_ratio', 0) always returned the default 0 regardless of
actual Sharpe value.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com >
2026-06-09 20:02:20 +08:00
GitHub and Claude Opus 4.8
46298e68d7
fix(backtest): max drawdown now correctly measures peak-to-trough percentage
...
Previous formula was: max(absolute_drawdown) / initial_capital, which
exceeds 100% when the portfolio grows then drops (e.g. from 600k to 300k
on a 100k initial = 300% drawdown, which is nonsensical).
Fixed to use drawdown_pct (drawdown / peak) which is always in [0, 1].
This correctly measures the maximum percentage drop from the highest
equity peak, matching the standard financial definition.
Also added regression test: test_max_drawdown_never_exceeds_100_pct.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com >
2026-06-09 19:00:11 +08:00
GitHub and Claude Opus 4.8
6a6d75f5d5
fix(backtest): strategy position not tracked during signal generation
...
Root cause: _generate_signals() iterated all bars calling strategy.next()
but never updated _position_size or _cash on the strategy. Strategies
that check self.position['size'] before buy/sell always saw 0, producing
only BUY signals with no SELL — exhausting cash and producing drawdowns
exceeding 100%.
Fix: add _update_strategy_position() that estimates position changes
after each bar's signals using close price. This gives the strategy an
accurate view of its holdings so it can correctly alternate buy/sell.
Regression tests added:
- test_position_aware_buy_sell_alternation: verifies BUY/SELL alternation
- test_position_aware_no_duplicate_buys: no suspicious tiny duplicate buys
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com >
2026-06-09 18:50:13 +08:00
GitHub and Claude Opus 4.8
04c2be1d7f
fix(backtest): resolve mypy and ruff lint issues
...
- dsl.py: use NDArray type annotations, fix None narrowing
- cli.py: add type annotations, fix import sorting
- strategy.py: fix UP038 isinstance, add noqa for I() method name
- tests: fix E712 bool comparison assertions
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com >
2026-06-09 18:21:25 +08:00
GitHub and Claude Opus 4.8
fc0777533e
feat(backtest): add CLI command with auto data fetch and table output
...
- Created src/easy_tdx/backtest/cli.py with backtest command
- Supports --strategy-file to load Python strategy classes
- Supports --indicators to precompute technical indicators
- Supports --cash, --commission, --execution, --period, --adjust, --count options
- Supports json/table/csv output formats
- Auto-loads K-line data via get_mac_client()
- Registered backtest command in src/easy_tdx/cli/__init__.py
- Added tests/unit/test_backtest_cli.py with basic CLI tests
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com >
2026-06-09 18:15:37 +08:00
GitHub and Claude Opus 4.8
706f22ba5e
feat(backtest): add DSL strategy skeleton and update __init__.py exports
...
- Add dsl_strategy decorator in dsl.py (P1 skeleton implementation)
- Update __init__.py to export BacktestEngine, Strategy, and related types
- All 106 backtest unit tests pass
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com >
2026-06-09 18:12:38 +08:00
GitHub and Claude Opus 4.8
371915a5f9
feat(backtest): add BacktestEngine with vectorized execution pipeline
...
- Implement BacktestEngine orchestrator with 4-step pipeline:
1. Signal generation (Strategy)
2. Order simulation (OrderSimulator)
3. Portfolio tracking (PortfolioTracker)
4. Performance analysis (PerformanceAnalyzer)
- Support both strategy class and instance initialization
- Add PnL calculation for sell trades
- Add JSON serialization with numpy/timestamp support
- Include comprehensive test coverage (12 tests, all passing)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com >
2026-06-09 18:11:20 +08:00