msd-backtest 0.1.22__tar.gz → 0.2.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/PKG-INFO +32 -14
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/README.md +31 -13
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/account.py +4 -4
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/portfolio.py +72 -44
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/run/cli.py +35 -12
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/run/report.py +324 -26
- msd_backtest-0.2.0/mbt/run/runner.py +489 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/strategy.py +22 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/msd_backtest.egg-info/PKG-INFO +32 -14
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/msd_backtest.egg-info/SOURCES.txt +2 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/pyproject.toml +1 -1
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_fee.py +2 -2
- msd_backtest-0.2.0/tests/test_holding_ror_grid.py +202 -0
- msd_backtest-0.2.0/tests/test_runner_fast_path.py +412 -0
- msd_backtest-0.1.22/mbt/run/runner.py +0 -333
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/LICENSE +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/__init__.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/data_provider.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/doctor.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/gui/__init__.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/gui/__main__.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/gui/app.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/gui/chart.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/gui/config.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/gui/dialogs.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/gui/downsample.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/gui/dpi.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/gui/inspect_strategy.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/gui/views.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/gui/worker.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/notify.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/run/__init__.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/run/backend.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/run/msd.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/run/overview.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/run/review.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/run/server.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/run/validator.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/select/__init__.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/select/cli.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/select/msd.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/select/panel.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/select/selector.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/shared/__init__.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/shared/financial.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/shared/stocks.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/strategy_templates/__init__.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/strategy_templates/cta_momentum.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/strategy_templates/fundamental_timing.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/mbt/strategy_templates/multifactor_rotation.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/msd_backtest.egg-info/dependency_links.txt +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/msd_backtest.egg-info/requires.txt +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/msd_backtest.egg-info/top_level.txt +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/setup.cfg +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_account.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_agent_first.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_alpha.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_benchmark_decouple.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_cli_smoke.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_dreman_strategy.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_feedback_fixes.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_financial_lag.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_fix_phase1.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_fix_phase2.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_fix_phase3.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_gui.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_load_strategy.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_mdate.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_msd_setup.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_multi_start_and_holdout.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_notify.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_overview.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_panel_resample.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_panel_zero_copy.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_portfolio.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_position_computed_properties.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_position_cost_and_ror.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_raw_prices.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_rebalance_sell_conflict.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_report.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_run_cli_selector.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_run_msd.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_runner.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_select_financial.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_selector.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_selector_contract.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_selector_financial.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_stocks.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_strategy.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_strategy_finalize.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_strategy_loading_complex.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_strategy_templates.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_volume_breakout_monthly_yang_selector.py +0 -0
- {msd_backtest-0.1.22 → msd_backtest-0.2.0}/tests/test_warmup_bars.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: msd-backtest
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.2.0
|
|
4
4
|
Summary: MSD backtest framework
|
|
5
5
|
License-Expression: BSD-2-Clause
|
|
6
6
|
Requires-Python: >=3.12
|
|
@@ -27,9 +27,38 @@ Provides-Extra: notify
|
|
|
27
27
|
Requires-Dist: apprise>=2.2.0; extra == "notify"
|
|
28
28
|
Dynamic: license-file
|
|
29
29
|
|
|
30
|
-
#
|
|
30
|
+
# 简介
|
|
31
31
|
|
|
32
|
-
`msd-backtest` 是一个基于 Python
|
|
32
|
+
`msd-backtest` 是一个基于 Python 的, Agent First 的高性能、向量化量化投研与回测框架。框架深度融合 [MSD (Market Strategy Data)](.agents/skills/msd-strategy-guide/references/msd.md) 数据服务与 [py-alpha-lib](.agents/skills/msd-strategy-guide/references/algo.md) 并行算法库,全面支持**横截面选股(Selector)**、**单标的独立交易策略(Trading Strategy)**以及**多标的多资产组合配置与动态调仓策略(Portfolio Strategy)**。
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
## 实测性能
|
|
36
|
+
|
|
37
|
+
| 策略 | 起始池大小 | 耗时(秒) | 示例 |
|
|
38
|
+
|-----|---------|-------|----|
|
|
39
|
+
| 1. 近三年盈利持续增长且为正 (使用 f137: 净利润)<br/>2. 大盘股 (市值排名前 20% 的股票)<br/>3. 最近 3 日内跌破 15 日均线 | 5031 | 0.07 | [策略代码](./strategy/growth_large_cap_ma15_selector.py)
|
|
40
|
+
| 1. 基础过滤:剔除 ST 股票、停牌股及无成交股票,要求当日收阳(收盘价 >= 开盘价)。<br/> 2. 月线三连阳:最近 3 个自然月(包含当前月)每个月的月线均为阳线(收盘价 > 开盘价)。<br/> 3. 放量突破:当日收盘价突破过去 N 日(默认 20 日)最高价,且当日成交量达到前 5 日均量的指定倍数(默认 >= 1.5 倍)且大于昨日成交量。| 5031 | 0.04| [策略代码](./strategy/volume_breakout_monthly_yang_selector.py)
|
|
41
|
+
|德瑞曼式「业绩为王 + 低市盈率」选股与半年度调仓策略|5000股票<br/>每半年一次选股调仓<br/>按日回测5年| 5 | [策略代码](./feedback/015/strategy.py) |
|
|
42
|
+
|
|
43
|
+
# Vibe Coding 的说明
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
AI Agent 可以通过项目提供的 Skill, 自主完成(已经过大量实测)
|
|
47
|
+
|
|
48
|
+
- 自主构建数据环境
|
|
49
|
+
- 正确编写策略
|
|
50
|
+
- 根据要求优化策略, 生成优化报告
|
|
51
|
+
|
|
52
|
+
做到这一点, 只需在你的 Agent 工具(Claude Code, Codex, Antigravity, DeepSeek Hermes, CodeBuddy等)中, 安装 Skill
|
|
53
|
+
|
|
54
|
+
```
|
|
55
|
+
npx skills add msd-rs/msd-backtest
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
然后, 告知它你的想要的策略逻辑即可. 如果你的 LLM 支持识图, 你甚至可以将贴给它, *复刻你平常看到的策略时最方便*
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
# Hand Write 的说明
|
|
33
62
|
|
|
34
63
|
---
|
|
35
64
|
|
|
@@ -328,18 +357,7 @@ uv run python -m mbt.run.cli strategy/my_strategy.py -s SH600000 -b 2023-01-01 -
|
|
|
328
357
|
|
|
329
358
|
---
|
|
330
359
|
|
|
331
|
-
## 🧠 AI 辅助策略编写与调优
|
|
332
|
-
|
|
333
|
-
本项目深度集成量化 AI 研发助手机制。项目中内置了专门的 Agent 技能指南:
|
|
334
|
-
- 核心技能定义:[`msd-strategy-guide`](.agents/skills/msd-strategy-guide/SKILL.md)
|
|
335
|
-
- 详细参考规范:
|
|
336
|
-
- [选股器构建指引](.agents/skills/msd-strategy-guide/references/selector.md)
|
|
337
|
-
- [交易策略构建指引](.agents/skills/msd-strategy-guide/references/trading.md)
|
|
338
|
-
- [组合调仓策略指引](.agents/skills/msd-strategy-guide/references/portfolio.md)
|
|
339
|
-
- [财务字段与对齐规范](.agents/skills/msd-strategy-guide/references/financial.md)
|
|
340
|
-
- [策略调优与防过拟合指南](.agents/skills/msd-strategy-guide/references/optimize.md)
|
|
341
360
|
|
|
342
|
-
AI 助手能够基于自然语言描述,依据上述规范生成经过向量化优化、杜绝未来函数、严格对齐价格语义的高质量策略代码。
|
|
343
361
|
|
|
344
362
|
---
|
|
345
363
|
|
|
@@ -1,6 +1,35 @@
|
|
|
1
|
-
#
|
|
1
|
+
# 简介
|
|
2
2
|
|
|
3
|
-
`msd-backtest` 是一个基于 Python
|
|
3
|
+
`msd-backtest` 是一个基于 Python 的, Agent First 的高性能、向量化量化投研与回测框架。框架深度融合 [MSD (Market Strategy Data)](.agents/skills/msd-strategy-guide/references/msd.md) 数据服务与 [py-alpha-lib](.agents/skills/msd-strategy-guide/references/algo.md) 并行算法库,全面支持**横截面选股(Selector)**、**单标的独立交易策略(Trading Strategy)**以及**多标的多资产组合配置与动态调仓策略(Portfolio Strategy)**。
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
## 实测性能
|
|
7
|
+
|
|
8
|
+
| 策略 | 起始池大小 | 耗时(秒) | 示例 |
|
|
9
|
+
|-----|---------|-------|----|
|
|
10
|
+
| 1. 近三年盈利持续增长且为正 (使用 f137: 净利润)<br/>2. 大盘股 (市值排名前 20% 的股票)<br/>3. 最近 3 日内跌破 15 日均线 | 5031 | 0.07 | [策略代码](./strategy/growth_large_cap_ma15_selector.py)
|
|
11
|
+
| 1. 基础过滤:剔除 ST 股票、停牌股及无成交股票,要求当日收阳(收盘价 >= 开盘价)。<br/> 2. 月线三连阳:最近 3 个自然月(包含当前月)每个月的月线均为阳线(收盘价 > 开盘价)。<br/> 3. 放量突破:当日收盘价突破过去 N 日(默认 20 日)最高价,且当日成交量达到前 5 日均量的指定倍数(默认 >= 1.5 倍)且大于昨日成交量。| 5031 | 0.04| [策略代码](./strategy/volume_breakout_monthly_yang_selector.py)
|
|
12
|
+
|德瑞曼式「业绩为王 + 低市盈率」选股与半年度调仓策略|5000股票<br/>每半年一次选股调仓<br/>按日回测5年| 5 | [策略代码](./feedback/015/strategy.py) |
|
|
13
|
+
|
|
14
|
+
# Vibe Coding 的说明
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
AI Agent 可以通过项目提供的 Skill, 自主完成(已经过大量实测)
|
|
18
|
+
|
|
19
|
+
- 自主构建数据环境
|
|
20
|
+
- 正确编写策略
|
|
21
|
+
- 根据要求优化策略, 生成优化报告
|
|
22
|
+
|
|
23
|
+
做到这一点, 只需在你的 Agent 工具(Claude Code, Codex, Antigravity, DeepSeek Hermes, CodeBuddy等)中, 安装 Skill
|
|
24
|
+
|
|
25
|
+
```
|
|
26
|
+
npx skills add msd-rs/msd-backtest
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
然后, 告知它你的想要的策略逻辑即可. 如果你的 LLM 支持识图, 你甚至可以将贴给它, *复刻你平常看到的策略时最方便*
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
# Hand Write 的说明
|
|
4
33
|
|
|
5
34
|
---
|
|
6
35
|
|
|
@@ -299,18 +328,7 @@ uv run python -m mbt.run.cli strategy/my_strategy.py -s SH600000 -b 2023-01-01 -
|
|
|
299
328
|
|
|
300
329
|
---
|
|
301
330
|
|
|
302
|
-
## 🧠 AI 辅助策略编写与调优
|
|
303
|
-
|
|
304
|
-
本项目深度集成量化 AI 研发助手机制。项目中内置了专门的 Agent 技能指南:
|
|
305
|
-
- 核心技能定义:[`msd-strategy-guide`](.agents/skills/msd-strategy-guide/SKILL.md)
|
|
306
|
-
- 详细参考规范:
|
|
307
|
-
- [选股器构建指引](.agents/skills/msd-strategy-guide/references/selector.md)
|
|
308
|
-
- [交易策略构建指引](.agents/skills/msd-strategy-guide/references/trading.md)
|
|
309
|
-
- [组合调仓策略指引](.agents/skills/msd-strategy-guide/references/portfolio.md)
|
|
310
|
-
- [财务字段与对齐规范](.agents/skills/msd-strategy-guide/references/financial.md)
|
|
311
|
-
- [策略调优与防过拟合指南](.agents/skills/msd-strategy-guide/references/optimize.md)
|
|
312
331
|
|
|
313
|
-
AI 助手能够基于自然语言描述,依据上述规范生成经过向量化优化、杜绝未来函数、严格对齐价格语义的高质量策略代码。
|
|
314
332
|
|
|
315
333
|
---
|
|
316
334
|
|
|
@@ -641,10 +641,10 @@ class Account:
|
|
|
641
641
|
self.action_shares = dp.all("action_shares", create_if_not_exist=np.float64)[s:e]
|
|
642
642
|
|
|
643
643
|
"""corporate actions"""
|
|
644
|
-
self.dividends = dp.all("dividend")[s:e]
|
|
645
|
-
self.transfer_shares = dp.all("transfer_shares")[s:e]
|
|
646
|
-
self.right_shares = dp.all("right_shares")[s:e]
|
|
647
|
-
self.right_prices = dp.all("right_price")[s:e]
|
|
644
|
+
self.dividends = dp.all("dividend")[s:e] if "dividend" in dp.data else np.zeros(dp.bars, dtype=np.float64)
|
|
645
|
+
self.transfer_shares = dp.all("transfer_shares")[s:e] if "transfer_shares" in dp.data else np.zeros(dp.bars, dtype=np.float64)
|
|
646
|
+
self.right_shares = dp.all("right_shares")[s:e] if "right_shares" in dp.data else np.zeros(dp.bars, dtype=np.float64)
|
|
647
|
+
self.right_prices = dp.all("right_price")[s:e] if "right_price" in dp.data else np.zeros(dp.bars, dtype=np.float64)
|
|
648
648
|
|
|
649
649
|
self.assets.fill(initial_cash)
|
|
650
650
|
self.ror.fill(0.0)
|
|
@@ -94,6 +94,7 @@ class PortfolioAccount:
|
|
|
94
94
|
self.groups = dp.groups
|
|
95
95
|
self.bars = dp.bars
|
|
96
96
|
self.positions = [Position.zero() for _ in range(self.groups)]
|
|
97
|
+
self._held_groups: set[int] = set()
|
|
97
98
|
self.entry_bars = np.full(self.groups, -1, dtype=np.int64)
|
|
98
99
|
self._obj_to_group: dict[str, int] = (
|
|
99
100
|
{s: i for i, s in enumerate(dp.objs)} if hasattr(dp, "objs") else {}
|
|
@@ -144,6 +145,20 @@ class PortfolioAccount:
|
|
|
144
145
|
else np.zeros(len(dp.dates), dtype=np.float64)
|
|
145
146
|
)
|
|
146
147
|
|
|
148
|
+
self._corp_groups_by_bar: dict[int, list[int]] = {}
|
|
149
|
+
if (
|
|
150
|
+
self.groups > 0
|
|
151
|
+
and self.bars > 0
|
|
152
|
+
and ("dividend" in dp.data or "transfer_shares" in dp.data or "right_shares" in dp.data)
|
|
153
|
+
):
|
|
154
|
+
has_corp = (
|
|
155
|
+
(np.nan_to_num(self.dividends, nan=0.0) > 0)
|
|
156
|
+
| (np.nan_to_num(self.transfer_shares, nan=0.0) > 0)
|
|
157
|
+
| (np.nan_to_num(self.right_shares, nan=0.0) > 0)
|
|
158
|
+
).reshape(self.groups, self.bars)
|
|
159
|
+
for b in np.flatnonzero(has_corp.any(axis=0)):
|
|
160
|
+
self._corp_groups_by_bar[int(b)] = np.flatnonzero(has_corp[:, int(b)]).tolist()
|
|
161
|
+
|
|
147
162
|
@property
|
|
148
163
|
def tradable_start(self) -> int:
|
|
149
164
|
"""Index of the first tradable group, maintained for backward compatibility."""
|
|
@@ -160,7 +175,7 @@ class PortfolioAccount:
|
|
|
160
175
|
|
|
161
176
|
@property
|
|
162
177
|
def market_value(self) -> float:
|
|
163
|
-
return float(sum(
|
|
178
|
+
return float(sum(self.positions[g].value for g in self._held_groups if self.tradable_mask[g]))
|
|
164
179
|
|
|
165
180
|
@property
|
|
166
181
|
def asset(self) -> float:
|
|
@@ -175,11 +190,11 @@ class PortfolioAccount:
|
|
|
175
190
|
@property
|
|
176
191
|
def held_groups(self) -> list[int]:
|
|
177
192
|
"""List of group indices that currently have held shares (> 0)."""
|
|
178
|
-
return
|
|
193
|
+
return sorted(
|
|
179
194
|
g
|
|
180
|
-
for g in
|
|
195
|
+
for g in self._held_groups
|
|
181
196
|
if self.tradable_mask[g] and self.positions[g].shares > 0
|
|
182
|
-
|
|
197
|
+
)
|
|
183
198
|
|
|
184
199
|
@property
|
|
185
200
|
def held_objs(self) -> list[str]:
|
|
@@ -299,7 +314,14 @@ class PortfolioAccount:
|
|
|
299
314
|
}
|
|
300
315
|
|
|
301
316
|
def apply_corporate_actions(self, ts: int):
|
|
302
|
-
|
|
317
|
+
if not self._held_groups:
|
|
318
|
+
return
|
|
319
|
+
corp_groups = self._corp_groups_by_bar.get(ts)
|
|
320
|
+
if not corp_groups:
|
|
321
|
+
return
|
|
322
|
+
for g in corp_groups:
|
|
323
|
+
if g not in self._held_groups:
|
|
324
|
+
continue
|
|
303
325
|
pos = self.positions[g]
|
|
304
326
|
if pos.shares <= 0:
|
|
305
327
|
continue
|
|
@@ -353,6 +375,7 @@ class PortfolioAccount:
|
|
|
353
375
|
self.positions[g] = pos - sell_pos
|
|
354
376
|
if self.positions[g].shares <= 0:
|
|
355
377
|
self.entry_bars[g] = -1
|
|
378
|
+
self._held_groups.discard(g)
|
|
356
379
|
self.deducted += fee
|
|
357
380
|
j = g * self.bars + ts
|
|
358
381
|
self.actions[j] = ACTION_SELL
|
|
@@ -407,6 +430,7 @@ class PortfolioAccount:
|
|
|
407
430
|
|
|
408
431
|
self.cash -= buy_pos.value + fee
|
|
409
432
|
self.positions[g] = self.positions[g] + buy_pos
|
|
433
|
+
self._held_groups.add(g)
|
|
410
434
|
self.deducted += fee
|
|
411
435
|
j = g * self.bars + ts
|
|
412
436
|
self.actions[j] = ACTION_BUY
|
|
@@ -499,7 +523,7 @@ class PortfolioAccount:
|
|
|
499
523
|
raise TypeError(f"Expected str or int for obj, got {type(obj).__name__}")
|
|
500
524
|
|
|
501
525
|
def update_mark_to_market(self, ts: int, mark_prices: np.ndarray):
|
|
502
|
-
for g in
|
|
526
|
+
for g in self._held_groups:
|
|
503
527
|
p = mark_prices[g]
|
|
504
528
|
if not np.isnan(p) and p > 0:
|
|
505
529
|
self.positions[g].raw_mark_price = float(p)
|
|
@@ -507,10 +531,11 @@ class PortfolioAccount:
|
|
|
507
531
|
self.positions[g].holding_days = max(0, ts - int(self.entry_bars[g]))
|
|
508
532
|
else:
|
|
509
533
|
self.positions[g].holding_days = 0
|
|
534
|
+
total_asset = self.asset
|
|
510
535
|
self.portfolio_cash[ts] = self.cash
|
|
511
|
-
self.portfolio_assets[ts] =
|
|
536
|
+
self.portfolio_assets[ts] = total_asset
|
|
512
537
|
self.portfolio_ror[ts] = (
|
|
513
|
-
(
|
|
538
|
+
(total_asset / self.initial_cash - 1.0) if self.initial_cash > 0 else 0.0
|
|
514
539
|
)
|
|
515
540
|
|
|
516
541
|
def rebalance_step(
|
|
@@ -542,7 +567,7 @@ class PortfolioAccount:
|
|
|
542
567
|
weights = weights / w_sum
|
|
543
568
|
|
|
544
569
|
# Update current valuation with deal_prices where valid before computing targets
|
|
545
|
-
for g in
|
|
570
|
+
for g in self._held_groups:
|
|
546
571
|
if not self.tradable_mask[g]:
|
|
547
572
|
continue
|
|
548
573
|
dp_g = deal_prices[g]
|
|
@@ -554,13 +579,8 @@ class PortfolioAccount:
|
|
|
554
579
|
|
|
555
580
|
# Apply tolerance band: keep current position value if deviation is within tolerance
|
|
556
581
|
if tol > 0.0 and total_equity > 0.0:
|
|
557
|
-
for g in
|
|
558
|
-
if not self.tradable_mask[g]:
|
|
559
|
-
continue
|
|
582
|
+
for g in np.flatnonzero(self.tradable_mask & (weights > 0.0)):
|
|
560
583
|
tgt_w = weights[g]
|
|
561
|
-
# Explicit liquidation (target 0) is never suppressed
|
|
562
|
-
if tgt_w == 0.0:
|
|
563
|
-
continue
|
|
564
584
|
dp_g = deal_prices[g]
|
|
565
585
|
if np.isnan(dp_g) or dp_g <= 0:
|
|
566
586
|
continue
|
|
@@ -569,8 +589,8 @@ class PortfolioAccount:
|
|
|
569
589
|
if abs(tgt_w - curr_w) <= tol:
|
|
570
590
|
target_values[g] = curr_val
|
|
571
591
|
|
|
572
|
-
# Pass 1: Sells first to free up cash
|
|
573
|
-
for g in
|
|
592
|
+
# Pass 1: Sells first to free up cash (only held positions can be sold)
|
|
593
|
+
for g in sorted(self._held_groups):
|
|
574
594
|
if not self.tradable_mask[g]:
|
|
575
595
|
continue
|
|
576
596
|
lim = limited[g] if limited is not None else 0
|
|
@@ -590,11 +610,9 @@ class PortfolioAccount:
|
|
|
590
610
|
if shares_to_sell > 0:
|
|
591
611
|
self._sell_group(g, ts, float(shares_to_sell), dp_g)
|
|
592
612
|
|
|
593
|
-
# Pass 2: Buys using available cash
|
|
613
|
+
# Pass 2: Buys using available cash (only non-zero target values can exceed curr_val)
|
|
594
614
|
buy_deficits = []
|
|
595
|
-
for g in
|
|
596
|
-
if not self.tradable_mask[g]:
|
|
597
|
-
continue
|
|
615
|
+
for g in np.flatnonzero(self.tradable_mask & (target_values > 0.0)):
|
|
598
616
|
if universe is not None and self.dp.objs[g] not in universe:
|
|
599
617
|
continue
|
|
600
618
|
lim = limited[g] if limited is not None else 0
|
|
@@ -919,6 +937,18 @@ class PortfolioContext(Context):
|
|
|
919
937
|
"""Return number of bars since position was first acquired."""
|
|
920
938
|
return self.account.holding_days(obj, current_bar=self.dp.i)
|
|
921
939
|
|
|
940
|
+
def holding_shares(self) -> np.ndarray:
|
|
941
|
+
"""Return 1D float64 array of currently held shares across all objs."""
|
|
942
|
+
return np.array([p.shares for p in self.account.positions], dtype=np.float64)
|
|
943
|
+
|
|
944
|
+
def holding_rors(self) -> np.ndarray:
|
|
945
|
+
"""Return 1D float64 array of holding ROR across all objs at current bar."""
|
|
946
|
+
cur_bar = self.dp.i
|
|
947
|
+
return np.array(
|
|
948
|
+
[self.account.position(g, current_bar=cur_bar).holding_ror for g in range(self.dp.groups)],
|
|
949
|
+
dtype=np.float64,
|
|
950
|
+
)
|
|
951
|
+
|
|
922
952
|
def _resolve_bar_flags(self, flags) -> tuple[np.ndarray, np.ndarray]:
|
|
923
953
|
idx = self._group_offsets + self.dp.i
|
|
924
954
|
if isinstance(flags, str):
|
|
@@ -1091,8 +1121,8 @@ class PortfolioRunner:
|
|
|
1091
1121
|
for i in dp:
|
|
1092
1122
|
bar_ctx.end = i + 1
|
|
1093
1123
|
bar_ctx.apply()
|
|
1094
|
-
strategy.execute(self.ctx)
|
|
1095
1124
|
acc.apply_corporate_actions(i)
|
|
1125
|
+
strategy.execute(self.ctx)
|
|
1096
1126
|
|
|
1097
1127
|
sig_i = i - 1 if self.exec_mode == "next_open" else i
|
|
1098
1128
|
idx_now = offsets + i
|
|
@@ -1111,18 +1141,17 @@ class PortfolioRunner:
|
|
|
1111
1141
|
buy_p = self.ctx.buy_percents[idx_sig]
|
|
1112
1142
|
|
|
1113
1143
|
has_explicit_sells = False
|
|
1114
|
-
|
|
1115
|
-
|
|
1144
|
+
sell_candidates = np.flatnonzero(acc.tradable_mask & (sell_p > 0.0))
|
|
1145
|
+
for g in sell_candidates:
|
|
1146
|
+
g_int = int(g)
|
|
1147
|
+
if lim_now is not None and lim_now[g_int] == -1:
|
|
1116
1148
|
continue
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
if shares_to_sell > 0:
|
|
1124
|
-
acc._sell_group(g, i, shares_to_sell, deal_p[g])
|
|
1125
|
-
has_explicit_sells = True
|
|
1149
|
+
shares_to_sell = acc.positions[g_int].shares * sell_p[g_int]
|
|
1150
|
+
if sell_p[g_int] < 1.0:
|
|
1151
|
+
shares_to_sell = float(int(shares_to_sell) - (int(shares_to_sell) % acc.unit))
|
|
1152
|
+
if shares_to_sell > 0:
|
|
1153
|
+
acc._sell_group(g_int, i, shares_to_sell, deal_p[g_int])
|
|
1154
|
+
has_explicit_sells = True
|
|
1126
1155
|
|
|
1127
1156
|
# 2. Check if explicit target_weights were provided at sig_i
|
|
1128
1157
|
tgt_w = self.ctx.target_weights[sig_i]
|
|
@@ -1133,9 +1162,8 @@ class PortfolioRunner:
|
|
|
1133
1162
|
# If explicit sells occurred on group g, reduce/zero target weight accordingly
|
|
1134
1163
|
if has_explicit_sells:
|
|
1135
1164
|
tgt_w = tgt_w.copy()
|
|
1136
|
-
for g in
|
|
1137
|
-
|
|
1138
|
-
tgt_w[g] = max(0.0, tgt_w[g] * (1.0 - sell_p[g]))
|
|
1165
|
+
for g in sell_candidates:
|
|
1166
|
+
tgt_w[g] = max(0.0, tgt_w[g] * (1.0 - sell_p[g]))
|
|
1139
1167
|
|
|
1140
1168
|
acc.rebalance_step(
|
|
1141
1169
|
i, tgt_w, deal_p, mark_p, lim_now, tolerance=tol_val, universe=self.ctx.universe
|
|
@@ -1143,17 +1171,17 @@ class PortfolioRunner:
|
|
|
1143
1171
|
continue
|
|
1144
1172
|
|
|
1145
1173
|
# 3. Otherwise process buy signals sharing available cash across active signals
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
]
|
|
1174
|
+
buy_mask = acc.tradable_mask & (buy_p > 0.0)
|
|
1175
|
+
if lim_now is not None:
|
|
1176
|
+
buy_mask = buy_mask & (lim_now != 1)
|
|
1177
|
+
buy_groups = np.flatnonzero(buy_mask)
|
|
1151
1178
|
if len(buy_groups) > 0 and acc.cash > 0:
|
|
1152
|
-
total_req = sum(buy_p[
|
|
1179
|
+
total_req = float(np.sum(buy_p[buy_groups]))
|
|
1153
1180
|
alloc_cash = acc.cash * min(1.0, total_req)
|
|
1154
1181
|
for g in buy_groups:
|
|
1155
|
-
|
|
1156
|
-
|
|
1182
|
+
g_int = int(g)
|
|
1183
|
+
budget = alloc_cash * (buy_p[g_int] / total_req)
|
|
1184
|
+
acc._buy_group(g_int, i, budget, deal_p[g_int])
|
|
1157
1185
|
|
|
1158
1186
|
acc.update_mark_to_market(i, mark_p)
|
|
1159
1187
|
finally:
|
|
@@ -177,7 +177,7 @@ def parse_args() -> Tuple[RunRequest, str, str, Fee]:
|
|
|
177
177
|
"--cash",
|
|
178
178
|
type=float,
|
|
179
179
|
default=None,
|
|
180
|
-
help="initial cash (default:
|
|
180
|
+
help="initial cash (default: 10000000)",
|
|
181
181
|
)
|
|
182
182
|
parser.add_argument(
|
|
183
183
|
"-S",
|
|
@@ -481,14 +481,37 @@ def build_output(
|
|
|
481
481
|
ext = output.split(".")[-1].lower()
|
|
482
482
|
logger.info(f"output kind: {ext}")
|
|
483
483
|
if ext == "csv":
|
|
484
|
-
|
|
485
|
-
df = pl.DataFrame(
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
484
|
+
if not reports:
|
|
485
|
+
df = pl.DataFrame(
|
|
486
|
+
schema={
|
|
487
|
+
"obj": pl.Utf8,
|
|
488
|
+
"date": pl.Int64,
|
|
489
|
+
"ror": pl.Float64,
|
|
490
|
+
"ror_hold": pl.Float64,
|
|
491
|
+
"ror_original": pl.Float64,
|
|
492
|
+
"actions": pl.Int32,
|
|
493
|
+
}
|
|
494
|
+
)
|
|
495
|
+
elif len(reports) == 1:
|
|
496
|
+
r = reports[0]
|
|
497
|
+
df = pl.DataFrame({
|
|
498
|
+
"obj": np.repeat(r.obj, len(r.date)),
|
|
499
|
+
"date": r.date,
|
|
500
|
+
"ror": np.round(r.ror, 6),
|
|
501
|
+
"ror_hold": np.round(r.ror_hold, 6),
|
|
502
|
+
"ror_original": np.round(r.ror_original, 6),
|
|
503
|
+
"actions": r.actions,
|
|
504
|
+
})
|
|
505
|
+
else:
|
|
506
|
+
df = pl.DataFrame({
|
|
507
|
+
"obj": np.repeat([r.obj for r in reports], [len(r.date) for r in reports]),
|
|
508
|
+
"date": np.concatenate([r.date for r in reports]),
|
|
509
|
+
"ror": np.round(np.concatenate([r.ror for r in reports]), 6),
|
|
510
|
+
"ror_hold": np.round(np.concatenate([r.ror_hold for r in reports]), 6),
|
|
511
|
+
"ror_original": np.round(np.concatenate([r.ror_original for r in reports]), 6),
|
|
512
|
+
"actions": np.concatenate([r.actions for r in reports]),
|
|
513
|
+
})
|
|
514
|
+
df.write_csv(output)
|
|
492
515
|
elif ext == "xlsx":
|
|
493
516
|
import xlsxwriter
|
|
494
517
|
wb = xlsxwriter.Workbook(output, options={
|
|
@@ -629,7 +652,7 @@ def run_single_period(
|
|
|
629
652
|
|
|
630
653
|
bench_obj = getattr(req, "benchmark", None)
|
|
631
654
|
if use_portfolio:
|
|
632
|
-
init_cash = custom_cash if custom_cash is not None else
|
|
655
|
+
init_cash = custom_cash if custom_cash is not None else 10000000.0
|
|
633
656
|
p_account = PortfolioAccount(init_cash, dp, fee=fee, benchmark=bench_obj)
|
|
634
657
|
logger.info(f"portfolio account created, initial_cash={init_cash}")
|
|
635
658
|
p_runner = PortfolioRunner(p_account, exec_mode=exec_mode)
|
|
@@ -640,9 +663,9 @@ def run_single_period(
|
|
|
640
663
|
reports = build_portfolio_report(dp, p_account, diagnostics=diag)
|
|
641
664
|
return reports, dp, p_account
|
|
642
665
|
else:
|
|
643
|
-
init_cash = custom_cash if custom_cash is not None else
|
|
666
|
+
init_cash = custom_cash if custom_cash is not None else 10000000.0
|
|
644
667
|
account = Account(init_cash, dp, fee=fee)
|
|
645
|
-
logger.info("account created")
|
|
668
|
+
logger.info(f"account created, initial_cash={init_cash}")
|
|
646
669
|
runner = Runner(account, exec_mode=exec_mode)
|
|
647
670
|
logger.info(f"runner created, exec_mode={exec_mode}")
|
|
648
671
|
runner.run(req.strategy)
|