@weaxs/openclaw-stock-analysis 0.2.9 → 0.2.10
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.
- package/README.md +3 -1
- package/dist/index.js +55 -2
- package/index.ts +56 -1
- package/openclaw.plugin.json +1 -0
- package/package.json +3 -3
- package/scripts/profile-offline.py +127 -0
- package/scripts/profile-workflows.py +87 -0
- package/skills/growth-quality/SKILL.md +2 -0
- package/skills/stock-analysis/SKILL.md +11 -3
- package/skills/stock-analysis/references/stateless-analysis.md +16 -2
- package/skills/stock-screener/SKILL.md +4 -0
- package/skills/strategy-backtest/SKILL.md +8 -3
- package/tools/_cache.py +93 -21
- package/tools/_subproc.py +43 -8
- package/tools/anomaly_detect.py +11 -6
- package/tools/backtest.py +225 -70
- package/tools/capabilities.py +1 -0
- package/tools/gather.py +63 -8
- package/tools/market_regime.py +26 -15
- package/tools/market_review.py +2 -2
- package/tools/position_context.py +5 -2
- package/tools/requirements.txt +2 -2
- package/tools/risk_screening.py +40 -15
- package/tools/screener.py +44 -18
- package/tools/search_intel.py +94 -32
- package/tools/sec_holders.py +27 -25
- package/tools/signal_tracker.py +100 -49
- package/tools/stateless_analysis.py +600 -33
- package/tools/stock_data.py +111 -26
- package/tools/technical.py +42 -40
- package/tools/trading_calendar.py +26 -21
- package/tools/value_data.py +6 -2
- package/tools/watchlist.py +24 -15
- package/tools/watchlist_context.py +63 -49
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Stock Analysis — OpenClaw Plugin
|
|
2
2
|
|
|
3
|
-
A股 / 港股 / 美股 / 日股 / 韩股 / 台股 行情、技术分析、筛选与回测。OpenClaw Gateway 加载后即可在对话中调用
|
|
3
|
+
A股 / 港股 / 美股 / 日股 / 韩股 / 台股 行情、技术分析、筛选与回测。OpenClaw Gateway 加载后即可在对话中调用 71 个工具。
|
|
4
4
|
|
|
5
5
|
## 安装
|
|
6
6
|
|
|
@@ -35,6 +35,8 @@ npm install
|
|
|
35
35
|
- `analyze_pattern` — 12+ 种 K 线形态识别
|
|
36
36
|
- `calculate_ma` — 独立均线计算
|
|
37
37
|
- `get_volume_analysis` — 量价分析
|
|
38
|
+
- `analyze_portfolio_risk` — 组合敞口、相关性、止损与确定性压力测试
|
|
39
|
+
- `plan_portfolio_rebalance` — 目标权重、整手和现金约束下的调仓清单
|
|
38
40
|
|
|
39
41
|
### 市场全景
|
|
40
42
|
- `get_market_indices` — 主要指数(CN/HK/US/JP/KR/TW)
|
package/dist/index.js
CHANGED
|
@@ -4627,7 +4627,7 @@ var index_default = definePluginEntry({
|
|
|
4627
4627
|
});
|
|
4628
4628
|
api.registerTool({
|
|
4629
4629
|
name: "analyze_portfolio_risk",
|
|
4630
|
-
description: "\u65E0\u72B6\u6001\u73B0\u8D27\u591A\u5934\u7EC4\u5408\u98CE\u9669\uFF1A\u8F93\u5165\u6301\u4ED3\u3001\u57FA\u51C6\u5E01\u79CD\u73B0\u91D1\u4E0E\u6C47\u7387\uFF0C\u8FD4\u56DE\u96C6\u4E2D\u5EA6\u3001\u5E01\u79CD/\u884C\u4E1A\u655E\u53E3\u3001\u4EF7\u683C\u76C8\u4E8F\
|
|
4630
|
+
description: "\u65E0\u72B6\u6001\u73B0\u8D27\u591A\u5934\u7EC4\u5408\u98CE\u9669\u4E0E\u538B\u529B\u6D4B\u8BD5\uFF1A\u8F93\u5165\u6301\u4ED3\u3001\u57FA\u51C6\u5E01\u79CD\u73B0\u91D1\u4E0E\u6C47\u7387\uFF0C\u8FD4\u56DE\u96C6\u4E2D\u5EA6\u3001\u5E01\u79CD/\u884C\u4E1A\u655E\u53E3\u3001\u4EF7\u683C\u76C8\u4E8F\u3001\u6B62\u635F\u60C5\u666F\u53CA\u53EF\u9009\u5E02\u573A/\u884C\u4E1A/\u4E2A\u80A1/\u6C47\u7387\u51B2\u51FB\u635F\u76CA\u3002\u7F3A\u6C47\u7387\u62A5\u9519\uFF1B\u4E0D\u4FDD\u5B58\u8D26\u6237\u3002",
|
|
4631
4631
|
parameters: typebox_exports.Object({
|
|
4632
4632
|
positions: typebox_exports.Array(typebox_exports.Object({
|
|
4633
4633
|
symbol: typebox_exports.String({ "description": "\u552F\u4E00\u4EE3\u7801\uFF0C\u91CD\u590D\u6301\u4ED3\u5148\u6C47\u603B" }),
|
|
@@ -4651,12 +4651,65 @@ var index_default = definePluginEntry({
|
|
|
4651
4651
|
date: typebox_exports.String({ "description": "YYYY-MM-DD\uFF0C\u552F\u4E00\u65E5\u671F" }),
|
|
4652
4652
|
close: typebox_exports.Number({ "description": "\u6B63\u6709\u9650\u6536\u76D8\u4EF7" })
|
|
4653
4653
|
}, { "additionalProperties": false }), { "description": "\u5B8C\u6574\u65E5K\u6536\u76D8\u5E8F\u5217\uFF0C2..20000\u6761\uFF0C\u4E0D\u5F97\u8DE8\u80A1\u7968\u6216\u6DF7\u7528\u590D\u6743\u53E3\u5F84" })
|
|
4654
|
-
}, { "additionalProperties": false }), { "description": "\u53EF\u9009\u5386\u53F2\uFF0C\u5171\u540C\u65E5\u671F\u672C\u5E01\u4EF7\u683C\u6536\u76CA\u76F8\u5173\u6027\uFF0C\u4E0D\u8BA1\u6C47\u7387" }))
|
|
4654
|
+
}, { "additionalProperties": false }), { "description": "\u53EF\u9009\u5386\u53F2\uFF0C\u5171\u540C\u65E5\u671F\u672C\u5E01\u4EF7\u683C\u6536\u76CA\u76F8\u5173\u6027\uFF0C\u4E0D\u8BA1\u6C47\u7387" })),
|
|
4655
|
+
stress_scenarios: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({
|
|
4656
|
+
name: typebox_exports.String({ "description": "\u60C5\u666F\u540D\u79F0" }),
|
|
4657
|
+
market_shock: typebox_exports.Optional(typebox_exports.Number({ "description": "\u5168\u5E02\u573A\u8D44\u4EA7\u4EF7\u683C\u51B2\u51FB\u6BD4\u4F8B\uFF0C\u5982-0.1" })),
|
|
4658
|
+
sector_shocks: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({
|
|
4659
|
+
sector: typebox_exports.String({ "description": "\u4E0E\u6301\u4ED3\u4E00\u81F4\u7684\u884C\u4E1A\u540D\u79F0" }),
|
|
4660
|
+
shock: typebox_exports.Number({ "description": "\u884C\u4E1A\u4EF7\u683C\u51B2\u51FB\u6BD4\u4F8B" })
|
|
4661
|
+
}, { "additionalProperties": false }), { "description": "\u53EF\u9009\u884C\u4E1A\u51B2\u51FB" })),
|
|
4662
|
+
symbol_shocks: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({
|
|
4663
|
+
symbol: typebox_exports.String({ "description": "\u6301\u4ED3\u6807\u7684\u4EE3\u7801" }),
|
|
4664
|
+
shock: typebox_exports.Number({ "description": "\u6807\u7684\u4EF7\u683C\u51B2\u51FB\u6BD4\u4F8B" })
|
|
4665
|
+
}, { "additionalProperties": false }), { "description": "\u53EF\u9009\u4E2A\u80A1\u51B2\u51FB" })),
|
|
4666
|
+
currency_shocks: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({
|
|
4667
|
+
currency: typebox_exports.String({ "description": "\u6301\u4ED3\u4E2D\u7684\u975E\u57FA\u51C6\u5E01\u79CD\uFF1B\u57FA\u51C6\u5E01\u79CD\u4E0D\u53EF\u76F8\u5BF9\u81EA\u8EAB\u51B2\u51FB" }),
|
|
4668
|
+
shock: typebox_exports.Number({ "description": "\u76F8\u5BF9\u57FA\u51C6\u5E01\u79CD\u7684\u6C47\u7387\u51B2\u51FB\u6BD4\u4F8B" })
|
|
4669
|
+
}, { "additionalProperties": false }), { "description": "\u53EF\u9009\u6C47\u7387\u51B2\u51FB" }))
|
|
4670
|
+
}, { "additionalProperties": false }), { "description": "\u53EF\u9009\u538B\u529B\u60C5\u666F\uFF1B\u6240\u6709\u51B2\u51FB\u5747\u4E3A\u6BD4\u4F8B\uFF0C\u7531\u5171\u4EAB\u6838\u5FC3\u8BA1\u7B97" }))
|
|
4655
4671
|
}, { "additionalProperties": false }),
|
|
4656
4672
|
async execute(_id, params) {
|
|
4657
4673
|
return asText(await withJsonInput(params, (path) => runPy("stateless_analysis.py", ["portfolio", "--input", path])));
|
|
4658
4674
|
}
|
|
4659
4675
|
});
|
|
4676
|
+
api.registerTool({
|
|
4677
|
+
name: "plan_portfolio_rebalance",
|
|
4678
|
+
description: "\u65E0\u72B6\u6001\u7EC4\u5408\u8C03\u4ED3\u8BA1\u5212\uFF1A\u6309\u5F53\u524D\u6301\u4ED3\u3001\u76EE\u6807\u6743\u91CD\u3001\u73B0\u91D1\u3001\u6C47\u7387\u3001\u6574\u624B\u3001\u8D39\u7528\u548C\u6362\u624B\u7EA6\u675F\u751F\u6210\u5148\u5356\u540E\u4E70\u6E05\u5355\uFF1B\u4E0D\u4FDD\u5B58\u8D26\u6237\u6216\u63D0\u4EA4\u8BA2\u5355\u3002",
|
|
4679
|
+
parameters: typebox_exports.Object({
|
|
4680
|
+
base_currency: typebox_exports.String({ "description": "\u57FA\u51C6\u5E01\u79CD" }),
|
|
4681
|
+
cash: typebox_exports.Number({ "description": "\u57FA\u51C6\u5E01\u79CD\u73B0\u91D1\uFF0C\u975E\u8D1F" }),
|
|
4682
|
+
positions: typebox_exports.Array(typebox_exports.Object({
|
|
4683
|
+
symbol: typebox_exports.String({ "description": "\u552F\u4E00\u4EE3\u7801\uFF0C\u91CD\u590D\u6301\u4ED3\u5148\u6C47\u603B" }),
|
|
4684
|
+
quantity: typebox_exports.Number({ "description": "\u6B63\u6301\u4ED3\u6570\u91CF" }),
|
|
4685
|
+
price: typebox_exports.Number({ "description": "\u6B63\u73B0\u4EF7" }),
|
|
4686
|
+
currency: typebox_exports.String({ "description": "\u6301\u4ED3\u5E01\u79CD\uFF0C\u5982CNY/USD/HKD" }),
|
|
4687
|
+
cost: typebox_exports.Optional(typebox_exports.Number({ "description": "\u540C\u5E01\u79CD\u6B63\u6210\u672C\u4EF7\uFF0C\u53EF\u9009\uFF1B\u8C03\u4ED3\u8BA1\u7B97\u4E0D\u4F7F\u7528" })),
|
|
4688
|
+
stop_price: typebox_exports.Optional(typebox_exports.Number({ "description": "\u540C\u5E01\u79CD\u6B63\u6B62\u635F\u4EF7\uFF0C\u53EF\u9009\uFF1B\u8C03\u4ED3\u8BA1\u7B97\u4E0D\u4F7F\u7528" })),
|
|
4689
|
+
sector: typebox_exports.Optional(typebox_exports.String({ "description": "\u7EDF\u4E00\u884C\u4E1A\u5206\u7C7B\uFF0C\u53EF\u9009" })),
|
|
4690
|
+
as_of: typebox_exports.Optional(typebox_exports.String({ "description": "\u5B9E\u9645\u4F30\u503C\u65F6\u70B9\uFF0C\u5EFA\u8BAEISO8601" }))
|
|
4691
|
+
}, { "additionalProperties": false }), { "description": "0..100\u4E2A\u73B0\u8D27\u591A\u5934\u6301\u4ED3\uFF0C\u7A7A\u6570\u7EC4\u8868\u793A\u7EAF\u73B0\u91D1\u5EFA\u4ED3" }),
|
|
4692
|
+
targets: typebox_exports.Array(typebox_exports.Object({
|
|
4693
|
+
symbol: typebox_exports.String({ "description": "\u76EE\u6807\u6807\u7684\u4EE3\u7801" }),
|
|
4694
|
+
weight: typebox_exports.Number({ "description": "\u76EE\u6807\u6743\u91CD\uFF1B\u5927\u4E8E0\u65F6lot_size\u5FC5\u586B" }),
|
|
4695
|
+
price: typebox_exports.Optional(typebox_exports.Number({ "description": "\u6B63\u76EE\u6807\u4EF7\u683C\uFF1B\u5F53\u524D\u672A\u6301\u6709\u7684\u65B0\u6807\u7684\u5FC5\u586B" })),
|
|
4696
|
+
currency: typebox_exports.Optional(typebox_exports.String({ "description": "\u76EE\u6807\u5E01\u79CD\uFF1B\u5F53\u524D\u672A\u6301\u6709\u7684\u65B0\u6807\u7684\u5FC5\u586B" })),
|
|
4697
|
+
sector: typebox_exports.Optional(typebox_exports.String({ "description": "\u7EDF\u4E00\u884C\u4E1A\u5206\u7C7B\uFF0C\u53EF\u9009" })),
|
|
4698
|
+
as_of: typebox_exports.Optional(typebox_exports.String({ "description": "\u5B9E\u9645\u4F30\u503C\u65F6\u70B9\uFF0C\u5EFA\u8BAEISO8601" })),
|
|
4699
|
+
lot_size: typebox_exports.Optional(typebox_exports.Number({ "description": "\u6B63\u6574\u6570\u4EA4\u6613\u5355\u4F4D\uFF1Bweight>0\u65F6\u5FC5\u586B" }))
|
|
4700
|
+
}, { "additionalProperties": false }), { "description": "1..100\u4E2A\u76EE\u6807\uFF1B\u65B0\u6807\u7684price/currency\u5FC5\u586B" }),
|
|
4701
|
+
fx_rates: typebox_exports.Optional(typebox_exports.Array(typebox_exports.Object({
|
|
4702
|
+
currency: typebox_exports.String({ "description": "\u552F\u4E00\u975E\u57FA\u51C6\u5E01\u79CD" }),
|
|
4703
|
+
rate: typebox_exports.Number({ "description": "\u4E00\u5355\u4F4D\u8BE5\u5E01\u79CD\u5BF9\u5E94\u591A\u5C11\u57FA\u51C6\u5E01\u79CD\uFF0C\u6B63\u6570" })
|
|
4704
|
+
}, { "additionalProperties": false }), { "description": "\u663E\u5F0F\u73B0\u4EF7\u6C47\u7387\uFF1B\u57FA\u51C6\u5E01\u79CD\u9690\u542B1\uFF0C\u4E0D\u5F97\u91CD\u590D" })),
|
|
4705
|
+
fee_rate: typebox_exports.Optional(typebox_exports.Number({ "description": "\u6BCF\u8FB9\u6BD4\u4F8B\u8D39\u75280..0.1\uFF0C\u9ED8\u8BA40\uFF1B\u4E0D\u542B\u672A\u63D0\u4F9B\u7A0E\u8D39/\u6700\u4F4E\u6536\u8D39" })),
|
|
4706
|
+
slippage_rate: typebox_exports.Optional(typebox_exports.Number({ "description": "\u6BCF\u8FB9\u6ED1\u70B90..0.1\uFF0C\u9ED8\u8BA40" })),
|
|
4707
|
+
max_turnover_fraction: typebox_exports.Optional(typebox_exports.Number({ "description": "\u975E\u8D1F\u6700\u5927\u603B\u6362\u624B\uFF0C\u6309\u4E70\u5356\u53C2\u8003\u91D1\u989D\u5408\u8BA1/\u521D\u59CB\u6743\u76CA\uFF1B\u9ED8\u8BA4\u4E0D\u9650\u5236\uFF0C\u53EF\u5927\u4E8E1" }))
|
|
4708
|
+
}, { "additionalProperties": false }),
|
|
4709
|
+
async execute(_id, params) {
|
|
4710
|
+
return asText(await withJsonInput(params, (path) => runPy("stateless_analysis.py", ["rebalance", "--input", path])));
|
|
4711
|
+
}
|
|
4712
|
+
});
|
|
4660
4713
|
api.registerTool({
|
|
4661
4714
|
name: "calculate_position_size",
|
|
4662
4715
|
description: "\u65E0\u72B6\u6001\u591A\u5934\u4ED3\u4F4D\u9884\u7B97\uFF1A\u540C\u5E01\u79CD\u91D1\u989D\uFF0C\u6309\u73B0\u91D1/\u98CE\u9669\u9884\u7B97/\u6700\u5927\u4ED3\u4F4D/\u4EA4\u6613\u5355\u4F4D\u53D6\u6700\u5C0F\u6570\u91CF\uFF0C\u53CC\u8FB9\u8D39\u7528\u548C\u6ED1\u70B9\u53C2\u4E0E\u6B62\u635F\u60C5\u666F\uFF1B\u4E0D\u6267\u884C\u4EA4\u6613\u3002",
|
package/index.ts
CHANGED
|
@@ -142,7 +142,7 @@ export default definePluginEntry({
|
|
|
142
142
|
|
|
143
143
|
api.registerTool({
|
|
144
144
|
name: "analyze_portfolio_risk",
|
|
145
|
-
description: "
|
|
145
|
+
description: "无状态现货多头组合风险与压力测试:输入持仓、基准币种现金与汇率,返回集中度、币种/行业敞口、价格盈亏、止损情景及可选市场/行业/个股/汇率冲击损益。缺汇率报错;不保存账户。",
|
|
146
146
|
parameters: Type.Object({
|
|
147
147
|
positions: Type.Array(Type.Object({
|
|
148
148
|
symbol: Type.String({"description": "唯一代码,重复持仓先汇总"}),
|
|
@@ -167,6 +167,22 @@ export default definePluginEntry({
|
|
|
167
167
|
close: Type.Number({"description": "正有限收盘价"}),
|
|
168
168
|
}, {"additionalProperties": false}), {"description": "完整日K收盘序列,2..20000条,不得跨股票或混用复权口径"}),
|
|
169
169
|
}, {"additionalProperties": false}), {"description": "可选历史,共同日期本币价格收益相关性,不计汇率"})),
|
|
170
|
+
stress_scenarios: Type.Optional(Type.Array(Type.Object({
|
|
171
|
+
name: Type.String({"description": "情景名称"}),
|
|
172
|
+
market_shock: Type.Optional(Type.Number({"description": "全市场资产价格冲击比例,如-0.1"})),
|
|
173
|
+
sector_shocks: Type.Optional(Type.Array(Type.Object({
|
|
174
|
+
sector: Type.String({"description": "与持仓一致的行业名称"}),
|
|
175
|
+
shock: Type.Number({"description": "行业价格冲击比例"}),
|
|
176
|
+
}, {"additionalProperties": false}), {"description": "可选行业冲击"})),
|
|
177
|
+
symbol_shocks: Type.Optional(Type.Array(Type.Object({
|
|
178
|
+
symbol: Type.String({"description": "持仓标的代码"}),
|
|
179
|
+
shock: Type.Number({"description": "标的价格冲击比例"}),
|
|
180
|
+
}, {"additionalProperties": false}), {"description": "可选个股冲击"})),
|
|
181
|
+
currency_shocks: Type.Optional(Type.Array(Type.Object({
|
|
182
|
+
currency: Type.String({"description": "持仓中的非基准币种;基准币种不可相对自身冲击"}),
|
|
183
|
+
shock: Type.Number({"description": "相对基准币种的汇率冲击比例"}),
|
|
184
|
+
}, {"additionalProperties": false}), {"description": "可选汇率冲击"})),
|
|
185
|
+
}, {"additionalProperties": false}), {"description": "可选压力情景;所有冲击均为比例,由共享核心计算"})),
|
|
170
186
|
}, {"additionalProperties": false}),
|
|
171
187
|
async execute(_id, params) {
|
|
172
188
|
return asText(await withJsonInput(params, (path: string) =>
|
|
@@ -174,6 +190,45 @@ export default definePluginEntry({
|
|
|
174
190
|
},
|
|
175
191
|
});
|
|
176
192
|
|
|
193
|
+
api.registerTool({
|
|
194
|
+
name: "plan_portfolio_rebalance",
|
|
195
|
+
description: "无状态组合调仓计划:按当前持仓、目标权重、现金、汇率、整手、费用和换手约束生成先卖后买清单;不保存账户或提交订单。",
|
|
196
|
+
parameters: Type.Object({
|
|
197
|
+
base_currency: Type.String({"description": "基准币种"}),
|
|
198
|
+
cash: Type.Number({"description": "基准币种现金,非负"}),
|
|
199
|
+
positions: Type.Array(Type.Object({
|
|
200
|
+
symbol: Type.String({"description": "唯一代码,重复持仓先汇总"}),
|
|
201
|
+
quantity: Type.Number({"description": "正持仓数量"}),
|
|
202
|
+
price: Type.Number({"description": "正现价"}),
|
|
203
|
+
currency: Type.String({"description": "持仓币种,如CNY/USD/HKD"}),
|
|
204
|
+
cost: Type.Optional(Type.Number({"description": "同币种正成本价,可选;调仓计算不使用"})),
|
|
205
|
+
stop_price: Type.Optional(Type.Number({"description": "同币种正止损价,可选;调仓计算不使用"})),
|
|
206
|
+
sector: Type.Optional(Type.String({"description": "统一行业分类,可选"})),
|
|
207
|
+
as_of: Type.Optional(Type.String({"description": "实际估值时点,建议ISO8601"})),
|
|
208
|
+
}, {"additionalProperties": false}), {"description": "0..100个现货多头持仓,空数组表示纯现金建仓"}),
|
|
209
|
+
targets: Type.Array(Type.Object({
|
|
210
|
+
symbol: Type.String({"description": "目标标的代码"}),
|
|
211
|
+
weight: Type.Number({"description": "目标权重;大于0时lot_size必填"}),
|
|
212
|
+
price: Type.Optional(Type.Number({"description": "正目标价格;当前未持有的新标的必填"})),
|
|
213
|
+
currency: Type.Optional(Type.String({"description": "目标币种;当前未持有的新标的必填"})),
|
|
214
|
+
sector: Type.Optional(Type.String({"description": "统一行业分类,可选"})),
|
|
215
|
+
as_of: Type.Optional(Type.String({"description": "实际估值时点,建议ISO8601"})),
|
|
216
|
+
lot_size: Type.Optional(Type.Number({"description": "正整数交易单位;weight>0时必填"})),
|
|
217
|
+
}, {"additionalProperties": false}), {"description": "1..100个目标;新标的price/currency必填"}),
|
|
218
|
+
fx_rates: Type.Optional(Type.Array(Type.Object({
|
|
219
|
+
currency: Type.String({"description": "唯一非基准币种"}),
|
|
220
|
+
rate: Type.Number({"description": "一单位该币种对应多少基准币种,正数"}),
|
|
221
|
+
}, {"additionalProperties": false}), {"description": "显式现价汇率;基准币种隐含1,不得重复"})),
|
|
222
|
+
fee_rate: Type.Optional(Type.Number({"description": "每边比例费用0..0.1,默认0;不含未提供税费/最低收费"})),
|
|
223
|
+
slippage_rate: Type.Optional(Type.Number({"description": "每边滑点0..0.1,默认0"})),
|
|
224
|
+
max_turnover_fraction: Type.Optional(Type.Number({"description": "非负最大总换手,按买卖参考金额合计/初始权益;默认不限制,可大于1"})),
|
|
225
|
+
}, {"additionalProperties": false}),
|
|
226
|
+
async execute(_id, params) {
|
|
227
|
+
return asText(await withJsonInput(params, (path: string) =>
|
|
228
|
+
runPy("stateless_analysis.py", ["rebalance", "--input", path])));
|
|
229
|
+
},
|
|
230
|
+
});
|
|
231
|
+
|
|
177
232
|
api.registerTool({
|
|
178
233
|
name: "calculate_position_size",
|
|
179
234
|
description: "无状态多头仓位预算:同币种金额,按现金/风险预算/最大仓位/交易单位取最小数量,双边费用和滑点参与止损情景;不执行交易。",
|
package/openclaw.plugin.json
CHANGED
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@weaxs/openclaw-stock-analysis",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.10",
|
|
4
4
|
"description": "OpenClaw plugin for stock analysis, screening, and strategy backtesting across A/HK/US/JP/KR/TW markets",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.ts",
|
|
@@ -13,8 +13,8 @@
|
|
|
13
13
|
"minGatewayVersion": "2026.3.24-beta.2"
|
|
14
14
|
},
|
|
15
15
|
"build": {
|
|
16
|
-
"openclawVersion": "2026.10.
|
|
17
|
-
"pluginSdkVersion": "2026.10.
|
|
16
|
+
"openclawVersion": "2026.10.9",
|
|
17
|
+
"pluginSdkVersion": "2026.10.9"
|
|
18
18
|
}
|
|
19
19
|
},
|
|
20
20
|
"scripts": {
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Offline baseline: python scripts/profile-offline.py > baseline.json.
|
|
3
|
+
|
|
4
|
+
CLI --help includes interpreter/import/argparse cost, never provider latency.
|
|
5
|
+
Synthetic compute timings exclude imports; this is not a production throughput test.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import cProfile
|
|
9
|
+
import json
|
|
10
|
+
import platform
|
|
11
|
+
import pstats
|
|
12
|
+
import statistics
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import tempfile
|
|
16
|
+
import time
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
20
|
+
sys.path.insert(0, str(ROOT / "tools"))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def measure(operation, repeats=5):
|
|
24
|
+
samples = []
|
|
25
|
+
for _ in range(repeats):
|
|
26
|
+
start = time.perf_counter()
|
|
27
|
+
operation()
|
|
28
|
+
samples.append(round((time.perf_counter() - start) * 1000, 3))
|
|
29
|
+
return {"median_ms": statistics.median(samples), "samples_ms": samples}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def main():
|
|
33
|
+
cli = {}
|
|
34
|
+
for path in sorted((ROOT / "tools").glob("*.py")):
|
|
35
|
+
if '__name__ == "__main__"' not in path.read_text():
|
|
36
|
+
continue
|
|
37
|
+
|
|
38
|
+
def help_call(path=path):
|
|
39
|
+
subprocess.run(
|
|
40
|
+
[sys.executable, str(path), "--help"],
|
|
41
|
+
stdout=subprocess.DEVNULL,
|
|
42
|
+
stderr=subprocess.PIPE,
|
|
43
|
+
timeout=15,
|
|
44
|
+
check=True,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
cli[path.name] = measure(help_call, 3)
|
|
48
|
+
|
|
49
|
+
import _cache
|
|
50
|
+
import numpy as np
|
|
51
|
+
import pandas as pd
|
|
52
|
+
from backtest import load_strategy, simulate
|
|
53
|
+
from stateless_analysis import portfolio
|
|
54
|
+
from technical import analyze_records
|
|
55
|
+
|
|
56
|
+
def bars(count):
|
|
57
|
+
rng = np.random.default_rng(68)
|
|
58
|
+
close = 100 * np.exp(np.cumsum(rng.normal(0.0002, 0.01, count)))
|
|
59
|
+
return pd.DataFrame(
|
|
60
|
+
{
|
|
61
|
+
"date": pd.bdate_range("2000-01-03", periods=count).strftime("%Y-%m-%d"),
|
|
62
|
+
"open": close,
|
|
63
|
+
"close": close,
|
|
64
|
+
"high": close * 1.01,
|
|
65
|
+
"low": close * 0.99,
|
|
66
|
+
"volume": rng.integers(100000, 1000000, count),
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
compute = {}
|
|
71
|
+
strategy = load_strategy(str(ROOT / "strategies/examples/ma_crossover.yaml"))
|
|
72
|
+
for count in (120, 2500):
|
|
73
|
+
frame = bars(count)
|
|
74
|
+
records = frame.to_dict("records")
|
|
75
|
+
assert "error" not in analyze_records("TEST", records)
|
|
76
|
+
compute[f"technical_{count}"] = measure(lambda records=records: analyze_records("TEST", records))
|
|
77
|
+
compute[f"backtest_{count}"] = measure(lambda frame=frame: simulate(frame, strategy, 100000, "TEST"))
|
|
78
|
+
for count in (10, 50, 100):
|
|
79
|
+
histories = []
|
|
80
|
+
for i in range(count):
|
|
81
|
+
records = bars(250).to_dict("records")
|
|
82
|
+
histories.append({"symbol": f"S{i}", "prices": [{"date": r["date"], "close": r["close"]} for r in records]})
|
|
83
|
+
payload = {
|
|
84
|
+
"base_currency": "USD",
|
|
85
|
+
"cash": 0,
|
|
86
|
+
"positions": [{"symbol": f"S{i}", "quantity": 1, "price": 100, "currency": "USD"} for i in range(count)],
|
|
87
|
+
"histories": histories,
|
|
88
|
+
}
|
|
89
|
+
result = portfolio(payload)
|
|
90
|
+
assert len(result["correlations"]) == count * (count - 1) // 2
|
|
91
|
+
compute[f"portfolio_{count}_assets_250_dates"] = measure(lambda payload=payload: portfolio(payload), 3)
|
|
92
|
+
profiler = cProfile.Profile()
|
|
93
|
+
profiler.runcall(simulate, frame, strategy, 100000, "TEST")
|
|
94
|
+
stats = pstats.Stats(profiler)
|
|
95
|
+
hotspots = [
|
|
96
|
+
{"function": f"{Path(file).name}:{line}:{name}", "calls": values[1], "cumulative_s": round(values[3], 4)}
|
|
97
|
+
for (file, line, name), values in sorted(stats.stats.items(), key=lambda item: item[1][3], reverse=True)[:12]
|
|
98
|
+
]
|
|
99
|
+
original_dir = _cache.CACHE_DIR
|
|
100
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
101
|
+
try:
|
|
102
|
+
_cache.CACHE_DIR = Path(directory)
|
|
103
|
+
payload = [{"symbol": str(i), "value": i} for i in range(10000)]
|
|
104
|
+
_cache.cached("profile", 60, lambda: payload)
|
|
105
|
+
|
|
106
|
+
def unexpected_fetch():
|
|
107
|
+
raise AssertionError("warm cache missed")
|
|
108
|
+
|
|
109
|
+
compute["cache_read_10000_rows"] = measure(lambda: _cache.cached("profile", 60, unexpected_fetch))
|
|
110
|
+
finally:
|
|
111
|
+
_cache.CACHE_DIR = original_dir
|
|
112
|
+
print(
|
|
113
|
+
json.dumps(
|
|
114
|
+
{
|
|
115
|
+
"python": platform.python_version(),
|
|
116
|
+
"platform": platform.platform(),
|
|
117
|
+
"cli": cli,
|
|
118
|
+
"compute": compute,
|
|
119
|
+
"backtest_hotspots": hotspots,
|
|
120
|
+
},
|
|
121
|
+
indent=2,
|
|
122
|
+
)
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
if __name__ == "__main__":
|
|
127
|
+
main()
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Offline workflow baseline with counted, fixed-latency CLI substitutes.
|
|
3
|
+
|
|
4
|
+
Run with the repo venv (pytest/pandas/numpy installed):
|
|
5
|
+
python scripts/profile-workflows.py [checkout-root]
|
|
6
|
+
This measures orchestration only, not provider throughput. Reuses the test OHLCV fixture.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import importlib.util
|
|
10
|
+
import json
|
|
11
|
+
import sys
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from collections import Counter
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parents[1]
|
|
18
|
+
sys.path.insert(0, str(root / "tools"))
|
|
19
|
+
import anomaly_detect # noqa: E402
|
|
20
|
+
import gather # noqa: E402
|
|
21
|
+
import risk_screening # noqa: E402
|
|
22
|
+
import technical # noqa: E402
|
|
23
|
+
import watchlist_context # noqa: E402
|
|
24
|
+
|
|
25
|
+
spec = importlib.util.spec_from_file_location("perf_fixtures", root / "tests/conftest.py")
|
|
26
|
+
fixtures = importlib.util.module_from_spec(spec)
|
|
27
|
+
spec.loader.exec_module(fixtures)
|
|
28
|
+
bars = fixtures.make_kline_data.__wrapped__()(120, "volatile")
|
|
29
|
+
for row in bars:
|
|
30
|
+
row["date"] = row["date"].strftime("%Y-%m-%d")
|
|
31
|
+
calls = Counter()
|
|
32
|
+
lock = threading.Lock()
|
|
33
|
+
active = peak = 0
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def invoke(script, args, **kwargs):
|
|
37
|
+
global active, peak
|
|
38
|
+
if script == "risk_screening.py" and args[0] == "screen":
|
|
39
|
+
return risk_screening.screen_risk(args[1])
|
|
40
|
+
if script == "technical.py":
|
|
41
|
+
rows = invoke("stock_data.py", ["kline", args[1], "--count", "120"])
|
|
42
|
+
return technical.analyze_records(args[1], rows)
|
|
43
|
+
if script == "anomaly_detect.py":
|
|
44
|
+
return anomaly_detect.detect_anomalies(args[1])
|
|
45
|
+
key = script + ":" + args[0]
|
|
46
|
+
with lock:
|
|
47
|
+
calls[key] += 1
|
|
48
|
+
active += 1
|
|
49
|
+
peak = max(peak, active)
|
|
50
|
+
time.sleep(0.01)
|
|
51
|
+
with lock:
|
|
52
|
+
active -= 1
|
|
53
|
+
if args[0] == "kline":
|
|
54
|
+
n = int(args[args.index("--count") + 1]) if "--count" in args else 120
|
|
55
|
+
return bars[-n:]
|
|
56
|
+
if args[0] == "quote":
|
|
57
|
+
return {"price": 10, "pe": 15, "pb": 2}
|
|
58
|
+
if args[0] == "lockup":
|
|
59
|
+
return {"upcoming_30d": [], "flags": [], "available": True}
|
|
60
|
+
if args[0] == "capital_flow":
|
|
61
|
+
return []
|
|
62
|
+
if script == "market_regime.py":
|
|
63
|
+
return {"market": args[1]}
|
|
64
|
+
return []
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
gather._run = lambda script, args, **kw: json.dumps(invoke(script, args, **kw))
|
|
68
|
+
risk_screening._run_tool = invoke
|
|
69
|
+
anomaly_detect._run_tool = invoke
|
|
70
|
+
anomaly_detect.fetch_kline = lambda symbol, period, count: invoke(
|
|
71
|
+
"stock_data.py", ["kline", symbol, "--count", str(count)]
|
|
72
|
+
)
|
|
73
|
+
watchlist_context._run_json = invoke
|
|
74
|
+
start = time.perf_counter()
|
|
75
|
+
result = watchlist_context.build_context(["600519", "000001", "000002"], workers=3)
|
|
76
|
+
assert result["summary"]["success"] == 3
|
|
77
|
+
print(
|
|
78
|
+
json.dumps(
|
|
79
|
+
{
|
|
80
|
+
"seconds": time.perf_counter() - start,
|
|
81
|
+
"calls": dict(calls),
|
|
82
|
+
"total_calls": sum(calls.values()),
|
|
83
|
+
"peak_leaf_calls": peak,
|
|
84
|
+
"summary": result["summary"],
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
)
|
|
@@ -28,6 +28,8 @@ gather 工具返回:
|
|
|
28
28
|
|
|
29
29
|
需要财务趋势时调用 `get_financials(symbol, annual=true, periods=10)`。港股配置 `LIXINGER_TOKEN` 后优先理杏仁非金融公司财报,按真实 `report_type` 判断年报,保留实际财年末、披露日期、币种;历史 ROE/毛利率/净利率为百分数,顶层 `roe/profit_margin` 延续小数比例。读取 `available_periods/warnings`,缺期不补造。有效 Yahoo 顶层快照与历史行分开读:`currency` 为快照财报币种、`market_cap_currency` 为市值币种,历史币种在 `periods` 每行,`snapshot_source` 标记快照来源;null 不用历史值补成跨期或跨币种数字;顶层 `report_date` 未知时读取 `periods` 的历史日期,不当作当前快照报告期。
|
|
30
30
|
|
|
31
|
+
Yahoo 顶层快照单位以 `snapshot_units` 为准:`roe/profit_margin/dividend_yield=ratio`,`debt_to_equity=percent`,例如 150 表示 150%,不是 150 倍;`pe=trailing`,不与 dynamic PE 直接比较。
|
|
32
|
+
|
|
31
33
|
`financials` 通常只是单期摘要。多期趋势、经营现金流、应收账款或同业估值未返回时,把对应维度标为“数据不足”,不推断趋势、不计分。
|
|
32
34
|
|
|
33
35
|
## 分析框架(4 步法)
|
|
@@ -17,7 +17,7 @@ description: 综合股票分析:联合技术、基本面、资金、消息和
|
|
|
17
17
|
|
|
18
18
|
## 无状态分析扩展
|
|
19
19
|
|
|
20
|
-
|
|
20
|
+
当用户要求同行比较、组合风险/压力测试、目标权重调仓、仓位预算或新旧分析比较时,MUST 读取[无状态研究工具](references/stateless-analysis.md),分别使用 compare_stocks、analyze_portfolio_risk、plan_portfolio_rebalance、calculate_position_size、compare_analysis_snapshots。所有用户状态均由本次输入提供;调仓计划数量不等于成交,现金不足或整手差额必须读取 unfilled 说明。
|
|
21
21
|
|
|
22
22
|
## 意图路由表
|
|
23
23
|
|
|
@@ -84,7 +84,11 @@ python3 scripts/gather.py <symbol>
|
|
|
84
84
|
1. 按 [报告 schema](../../schemas/report_schema.json) 构建结构化报告。
|
|
85
85
|
2. 每个结论只使用成功返回的数据;缺失维度在 `risk_warning` 中说明影响。必须填写 `evidence`,每项使用原始工具结果路径(如 `get_quote.price`)、读者可理解的 `label`、原始 `value`、实际 `source` 和数据时间 `as_of`;未知来源或时间填 null,不用采集时间替代。历史财报与顶层快照分别引用日期、币种和单位,不把不同期间的数值拼成同一结论。 来源与时间沿证据 path 继承最近父对象的 source(该键缺失时用 snapshot_source)和 data_as_of,子对象的对应值(包括显式 null)覆盖祖先;数组项及 warnings 字符串同样继承,不能仅因叶子字段没有来源就填 null。整条路径均未提供对应元数据时才填 null,不能用工具名或策略方法名代替来源;as_of 保留完整数据时间及其时区。report_date 是财报报告期,应单独引用 value,不能当成披露日期或 data_as_of。证据 path 不含调用参数,例如 get_financials.periods.0.roe;股票名称未返回时 stock_name 填“未知”,不能凭常识补名;已知返回对象中未提供的末级字段可用 value=null 表示未知,其 source/as_of 可填 null,若填写则必须来自已知父对象;不能编成空数组、字符串或数值,不能跨缺失对象或数组编造路径;错误 value 保留原始字符串,不加 error: 前缀。请求的期间或文件路径不证明实际数据覆盖期或文件内容,需与实际返回数据区分。
|
|
86
86
|
同时填写 `data_quality.flags/limitations`:关键数据缺失用 `partial_data`,明确过期行情用 `stale_quote`,同期间同口径来源冲突用 `conflicting_data`,回测/信号样本不足用 `insufficient_sample`。出现这些限制时降低置信度,不能给出 strong_buy;没有有效现价时不编造数值交易计划。数据完整时 flags 为空数组,限制仍按实际模拟条件说明。
|
|
87
|
-
3.
|
|
87
|
+
3. 提交前逐项核对 `evidence.path`,以下字段只要本次工具已返回,就必须各有独立的 path/value 项:
|
|
88
|
+
- 行情:`get_quote.price`、`get_quote.data_as_of`。
|
|
89
|
+
- 财务:`get_financials.report_date`、`get_financials.roe`,以及历史 `periods` 中实际返回的 `report_date`、`roe`,路径含数字下标。
|
|
90
|
+
- 回测:`run_backtest.metrics.total_trades`、`run_backtest.metrics.win_rate`。
|
|
91
|
+
每项保留原始 value,并按第 2 项填写 source/as_of;正文中的数字及其他证据的 as_of 元数据不替代独立引用。漏项先补齐再提交。报价过期时保留原始价格与时间作为历史证据,说明时效限制,等待新报价后再制定当前数值交易计划。
|
|
88
92
|
4. 调用 `render_stock_report`:快速问答用 `brief`,完整研判用 `full`。
|
|
89
93
|
5. 输出渲染后的 Markdown;只在用户要求机器可读数据时附加结构化 JSON。
|
|
90
94
|
|
|
@@ -96,6 +100,10 @@ python3 scripts/gather.py <symbol>
|
|
|
96
100
|
|
|
97
101
|
## 注意事项
|
|
98
102
|
- `get_kline` 的 A 股股票/ETF 数据为前复权,每条记录 `adjusted="qfq"`;显式指数 `sh000xxx` / `sz399xxx` 为原始点位,`adjusted="none"`。复权数据源全部失败时说明数据缺失,不用未复权价格补算指标或信号。
|
|
103
|
+
- `get_quote` 的 PE 必须连同 `pe_basis` 解读;dynamic、trailing 与 unknown 不是同一口径,不能直接比较。
|
|
104
|
+
- `get_financials` 的 Yahoo 顶层快照按 `snapshot_units` 解读:`roe/profit_margin/dividend_yield=ratio`,`debt_to_equity=percent`,例如 150 表示 150%,不是 150 倍。
|
|
105
|
+
- `detect_market_regime` 用 `index.as_of` 核对实际日期并披露 `warnings`;`above_ma60=null` 表示历史不足,不能当作高于或低于 MA60。
|
|
106
|
+
- `get_technical_analysis` 的 RSI 全涨窗口为 100、全平为 50;预热不足的 RSI/量比不得解释为中性。量比是当根成交量除以前 5 根均量,不包含当根本身;不足时返回 unavailable/insufficient_data,不称为正常量价。
|
|
99
107
|
- 行情读取 `source/fetched_at/data_as_of`,`fetched_at` 是 UTC 采集时间;`as_of_basis=trading_calendar` 是日历推断,不能声称是提供方报价时间。提供方时间未知时明确说明时效性未核实。
|
|
100
108
|
- 始终提供风险提示
|
|
101
109
|
- 不做绝对化的涨跌预测
|
|
@@ -126,6 +134,6 @@ get_shareholder_structure 的 northbound 优先使用沪深官方季度总量;
|
|
|
126
134
|
|
|
127
135
|
实际披露股票持仓可用 get_etf_details(include_full_holdings=true) 获取半年度/年度表;按 as_of 解释,数量为股、市值为人民币元。默认不取大量明细;不是实时全资产组合,不与 PCF 对价数量混同。
|
|
128
136
|
|
|
129
|
-
|
|
137
|
+
信号价格使用原始报价口径,自动记录的默认 `record_date` 与 `price_date` 均按标的市场时区确定(显式 `date` 不变),并保存原始 `price_as_of`;`price_date` 晚于 `record_date` 时拒绝记录与结算。多头 target 必须高于 entry、stop 必须低于 entry,空头相反,否则拒绝记录。开盘先触 stop 按 open 结算,先触 target 按 target 保守结算;日内顺序未知的双触发仍 stop 优先。复权 K 线需有该报价日的可核实 adjustment_factor,才能换算入场/目标/止损及收益;缺失时 skipped_price_basis 并保持未结算,不得猜测拆股或除权比例,重复日期返回 skipped_no_data。记录日无 K 线时仅在前后因子一致(或已有明确报价日)时使用最近锚点;旧信号缺少报价时点且记录日因子发生变化时必须保持未结算。evaluate_signals 返回 complete/deferred/warnings;预算耗尽时已完成结果保存,未处理记录下次重试。当前仅日线 Tushare、Alpha Vantage 提供可验证换算系数,其余复权来源可能跳过结算。
|
|
130
138
|
|
|
131
139
|
自选股上下文异动检查失败时 anomaly_status=unavailable、anomaly_count=null,并提供 anomaly_error/warnings;summary.partial 不得写成无异常或完整成功。
|
|
@@ -17,7 +17,7 @@
|
|
|
17
17
|
|
|
18
18
|
工具输出精确到传入文本行号的变化片段、来源、截断标志和指标差异。文本差异本身不等于经营变化;Agent 要阅读上下文,说明发生了什么、与原预期的关系和可能反证,并引用原文。金额单位和 basis 一致才计算 delta;前期值大于0才计算普通增长率,亏损转盈另述。报告期可不同,但必须核实是可比同长期间(年度/同比单季等),累计季度不能直接当单季。
|
|
19
19
|
|
|
20
|
-
##
|
|
20
|
+
## 组合风险与压力测试:analyze_portfolio_risk
|
|
21
21
|
|
|
22
22
|
输入 `base_currency`、基准币种 `cash>=0`、`positions`(1..100项)。持仓 `{symbol, quantity, price, currency, cost?, stop_price?, sector?, as_of?}`,现货多头;重复标的先汇总。价格/数量为正,单位由调用方确认。
|
|
23
23
|
|
|
@@ -27,6 +27,20 @@
|
|
|
27
27
|
|
|
28
28
|
可选 `histories:[{symbol,prices:[{date,close}]}]`,工具按每对标的共同日期计算收益相关性;至少4个共同价格点、存在波动才有结果。不是组合收益率或汇率调整后的相关性;少样本、跨时区非同步收盘和缺交易日都应说明,不从相关性推断因果。缺历史时明确相关性未计算。
|
|
29
29
|
|
|
30
|
+
可选 `stress_scenarios`(1..20项)执行确定性压力测试。每项包含唯一 `name`,以及可选 `market_shock`、`sector_shocks:[{sector,shock}]`、`symbol_shocks:[{symbol,shock}]`、`currency_shocks:[{currency,shock}]`;shock 是 -1..1 的小数。个股冲击覆盖行业冲击,行业冲击覆盖市场冲击;汇率冲击独立乘算,不能与资产冲击重复相加。基准币种不能相对自身冲击,重复或当前组合中不存在的标的/行业/币种会报错。
|
|
31
|
+
|
|
32
|
+
`stress_tests` 返回每个情景的 `equity_before/equity_after/pnl_base/return_pct` 和逐持仓 `asset_shock/fx_shock/value_before/value_after/pnl_base`。这些是用户指定冲击下的 what-if 结果,不是预测、VaR 或最大亏损保证。
|
|
33
|
+
|
|
34
|
+
## 目标权重调仓:plan_portfolio_rebalance
|
|
35
|
+
|
|
36
|
+
输入 `base_currency`、基准币种 `cash>=0`、当前 `positions`(0..100项,纯现金可为空)和 `targets`(1..100项),汇率格式同上。当前持仓字段与组合风险一致,cost/stop_price 可保留但不参与调仓。
|
|
37
|
+
|
|
38
|
+
每个 target 包含 `{symbol,weight,price?,currency?,sector?,as_of?,lot_size?}`。已有标的可继承当前价格、币种、行业和时点;新标的必须提供 price/currency。已有标的覆盖 price/currency 时,该有效价格与汇率同时用于初始权益、目标数量和调后权益,不能把新旧价差异计为无交易成本。weight 为 0..1,所有目标权重之和不得超过1,未分配部分保留现金;weight>0 时必须提供用户或交易规则确认的 lot_size。未出现在 targets 的当前持仓按 weight=0 全部退出。正目标权重按初始权益、参考价格和汇率向下取整到交易单位,不足一个交易单位则报错,不向上凑整。
|
|
39
|
+
|
|
40
|
+
可选 `fee_rate`、`slippage_rate`(每边0..0.1)和 `max_turnover_fraction`(非负,默认不限制)。换手按买卖参考金额合计/初始权益计算,全仓换仓可超过1。计划先卖后买;卖出按 price×(1-slippage)×(1-fee) 估算回收,买入按 price×(1+slippage)×(1+fee) 估算成本。现金不足时所有买单按同一比例缩减并向下取整到各自交易单位,`cash_limited=true`。
|
|
41
|
+
|
|
42
|
+
输出 `orders` 是参考价下的计划订单,不是已提交委托或成交;`unfilled` 分别用 `reason=lot_rounding/cash` 标记整手差额和现金未满足数量。整手差额按未取整原始调整需求减去整手后的计划数量计算,现金缩减另按计划前数量减去最终数量计算,两者不得重复。`positions_after` 同时保留 `target_weight` 与计划后的实际 `weight`,并返回 `cash_after/equity_after/gross_turnover_fraction/estimated_cost_base`。全额退出允许卖出当前全部数量;部分买卖向下取整,不为了贴近目标而超出目标。工具不提交订单,实际成交、未提供税费/最低收费、结算和流动性仍需核实。
|
|
43
|
+
|
|
30
44
|
## 仓位预算:calculate_position_size
|
|
31
45
|
|
|
32
46
|
必需 `equity,cash,entry_price,stop_price,risk_fraction,lot_size`。风险比例0..1,止损正且低于入场价,现金0..equity,交易单位正整数。所有金额同币种。
|
|
@@ -43,7 +57,7 @@ lot_size 来自用户或可核实交易规则,尤其港股不能统一猜100
|
|
|
43
57
|
|
|
44
58
|
事件日映射到股票序列中不早于指定日期的首日;盘后事件应显式使用下一交易日。基点是该日前一个股票交易日收盘;horizon=0表示事件当日收盘。基准必须同市场,并在两个端点都有数据,缺失时不移动事件日期。收益差是股票与基准各自买入持有收益的差(百分点),不等于因果影响。
|
|
45
59
|
|
|
46
|
-
MUST
|
|
60
|
+
MUST 核实完整交易日、复权、币种和股息处理。工具无法从缺行判断是停牌、节假日还是数据故障。重叠事件标识意味着样本不独立;完全没有有效超额收益样本(包括股票窗口不足或基准端点缺失)的事件不参与重叠计算,不应误标相邻有效事件;部分 horizon 无效时,重叠区间只覆盖有效 horizon。少样本均值不能作为稳定预测。
|
|
47
61
|
|
|
48
62
|
## 回测稳健性:validate_backtest
|
|
49
63
|
|
|
@@ -70,6 +70,10 @@ python3 tools/screener.py screen --market A --top 20
|
|
|
70
70
|
|
|
71
71
|
每个候选必须读取 `factor_coverage.available/missing/ratio/effective_weights`。ratio 是已覆盖因子的原始权重之和;L1 与 L2 的 effective_weights 均按可用因子重归一化,缺失或非有限值不按零分计,排序前先按实际可用因子计算综合分,effective_scores 保留实际参与计算的各组分数;用 sum(effective_scores[g] × effective_weights[g]) × market_sentiment.multiplier 核对 scores.final(四舍五入至一位)。scores.momentum 仍保留 L1 参考值,L2 贡献以 effective_scores.momentum 为准。相同分数但缺失因子不同的候选不能视为同等证据,报告缺失项和覆盖度,不以 `enriched=true` 代替覆盖判断。`scores.final=null` 表示没有足够因子计算,不能作为高分候选推荐。
|
|
72
72
|
|
|
73
|
+
估值比较还需读取 `pe_basis`:dynamic、trailing 与 unknown 不得当成同一 PE 口径。筛选中的有限非正 PE/PB 价值子分为 0,不能因数值更低而获得最高价值分;缺失或非有限因子仍保持未知,不按零分处理。
|
|
74
|
+
|
|
75
|
+
L2 的 `vol20` 只使用恰好 20 个有效日收益,`factor_coverage.vol20_samples` 记录实际样本数,非正/非有限收盘价先剔除,空输入为 0;短样本为缺测。质量因子按 `report_date` 分组归一,年度累计与单季累计不得直接排名;资金流 5/10/20 日窗口不足时返回 null,不按 0 或完整窗口处理。
|
|
76
|
+
|
|
73
77
|
完成标准:列出实际生效的市场、过滤条件、排序口径和候选数量,且推荐理由只使用返回数据,并说明因子覆盖。
|
|
74
78
|
|
|
75
79
|
## 策略模板
|
|
@@ -57,12 +57,14 @@ simulation:
|
|
|
57
57
|
|
|
58
58
|
position:
|
|
59
59
|
size: 1.0 # 仓位比例
|
|
60
|
-
max_positions: 1 #
|
|
60
|
+
max_positions: 1 # 当前仅支持单持仓,其他值明确报错
|
|
61
61
|
```
|
|
62
62
|
|
|
63
63
|
**可用指标**:rsi, ma, ema, macd_dif, macd_dea, macd, volume_ratio, price_change, bollinger_position, close, volume
|
|
64
64
|
|
|
65
|
-
`
|
|
65
|
+
`rsi` 在预热不足时不可用,连续上涨窗口为 100,全平窗口为中性 50;不可用值不能满足条件或制造交叉。`volume_ratio` 是当根成交量除以前 N 根平均成交量,不包含当根本身。
|
|
66
|
+
|
|
67
|
+
`monthly_momentum` 是共享核心的月度观察对数收益:`period` 默认63,支持21/63/252等正整数;月初首根正成交量日K收盘计算并保持到下次月度观察,次日开盘才可能成交。零成交量记录不计回溯根数。MUST 读取 [多期限月度趋势](../bull-trend/references/trend-horizons.md),不能把单期限YAML等同三子策略组合。需要在观察日已有period+1根有效日K;回测按策略最大 lookback 增加取数,起点前历史仅用于指标预热,交易和权益仍限于请求区间;`warnings` 出现 `Entry indicator is unavailable` 时必须披露指标不可用及数据质量,提供方历史不足时不能声称完成预热。三期限同资金起点的完整研究复现使用参考里的研究脚本。
|
|
66
68
|
|
|
67
69
|
独立趋势强度可用 `trend_score`,默认 `(EMA20-EMA60)/ATR14`,ATR 为真实波幅简单平均。`fast_period/slow_period/period` 分别控制快 EMA、慢 EMA、ATR,要求正整数且快线小于慢线;默认 60 根预热,预热或零 ATR 不触发条件。解释七档显示、初始化与样本外验证前 MUST 读取 [独立趋势温度](../bull-trend/references/trend-temperature.md)。它不是星球温度或肥尾信号,原固定止损/止盈默认值仍生效。
|
|
68
70
|
|
|
@@ -70,6 +72,8 @@ position:
|
|
|
70
72
|
|
|
71
73
|
**可用运算符**:`>`, `<`, `>=`, `<=`, `==`, `cross_above`, `cross_below`
|
|
72
74
|
|
|
75
|
+
`entry/exit.logic` 仅允许 `all/any`,operator 仅限上表;period/fast_period/slow_period 仅接受正整数或整数字符串,非法输入明确报错,不静默替换默认值或截断。
|
|
76
|
+
|
|
73
77
|
### 第二步:运行回测
|
|
74
78
|
|
|
75
79
|
A 股股票/ETF 回测统一使用前复权 K 线(每条记录 `adjusted="qfq"`),显式指数使用原始点位(`adjusted="none"`)。复权源不可用时停止本次回测并说明缺失,不混用未复权历史价格。
|
|
@@ -85,7 +89,7 @@ python3 tools/backtest.py run <path.yaml> <symbol> --start <date> --end <date>
|
|
|
85
89
|
- `--start` / `--end`:回测时间范围(可选,默认近一年)
|
|
86
90
|
- 初始资金默认 100 万,可用 `--capital` 调整
|
|
87
91
|
|
|
88
|
-
默认 `simulation.execution=next_open`:信号在前一交易日收盘确定,下一有效交易日按开盘价加滑点成交;交易同时保留 `signal_date` 与实际 `date`。最后一天新信号没有后续开盘时不能成交。需要复现旧结果时显式使用 `same_close`,并说明它按信号日收盘成交,可能高估可执行收益。零/缺失成交量(已有 volume 字段时)阻止成交;一字涨跌停仅在输入提供同口径历史 `limit_up/limit_down` 时保守阻止,不猜 ST、IPO 或 ETF
|
|
92
|
+
默认 `simulation.execution=next_open`:信号在前一交易日收盘确定,下一有效交易日按开盘价加滑点成交;交易同时保留 `signal_date` 与实际 `date`。最后一天新信号没有后续开盘时不能成交。需要复现旧结果时显式使用 `same_close`,并说明它按信号日收盘成交,可能高估可执行收益。零/缺失成交量(已有 volume 字段时)阻止成交;一字涨跌停仅在输入提供同口径历史 `limit_up/limit_down` 时保守阻止,不猜 ST、IPO 或 ETF 限价。延迟的入场信号在新收盘失效时撤单,风险退出 pending 保留至成交。回测仅接受单一 `qfq`/`total_return`/`none` 复权口径,unknown 或混合口径明确报错。
|
|
89
93
|
|
|
90
94
|
读取 `execution.model/blocked_orders/unfilled_order/limitations` 并说明未成交情况。止损、止盈和移动止损均是收盘信号,不承诺盘中按阈值成交;次日跳空按实际开盘价计算。没有历史限价数据时,不能声称已验证涨跌停可成交性。
|
|
91
95
|
|
|
@@ -93,6 +97,7 @@ python3 tools/backtest.py run <path.yaml> <symbol> --start <date> --end <date>
|
|
|
93
97
|
|
|
94
98
|
回测完成后,按共享框架的风险单位和回测约束解释原始结果。针对本工具:
|
|
95
99
|
|
|
100
|
+
- 基准与策略使用相同首日执行口径,无预热时以策略首条权益日期为起点;覆盖不符或首末价格非法时读取 `benchmark.error`,不能输出超额。
|
|
96
101
|
- 从 `metrics` 和 `trades` 计算期望值并与盈亏比一起报告。
|
|
97
102
|
- 报告最大回撤、连续亏损、交易次数和平均持有期;结果未携带初始风险时,将 1R 分布标为不可计算。
|
|
98
103
|
- 使用用户指定的互斥日期区间分别运行样本内和样本外回测。
|