@v587d/capital-generation 2.31.1 → 2.31.4

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.
Files changed (49) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +45 -7
  3. package/automation/package.json +1 -1
  4. package/chart-ui/package.json +1 -1
  5. package/config/package.json +1 -1
  6. package/lib/analysis/registry.js +6 -1
  7. package/lib/analysis/validation.js +13 -3
  8. package/lib/web-retriever/local-fetch.d.ts +1 -1
  9. package/lib/web-retriever/local-fetch.js +1 -1
  10. package/lib/web-retriever/wind-client.d.ts +1 -1
  11. package/lib/web-retriever/wind-client.js +1 -1
  12. package/package.json +1 -1
  13. package/plugin-page/README.en.md +7 -0
  14. package/plugin-page/README.zh.md +7 -0
  15. package/preset/capital-generation/agent.patch.yml +11 -9
  16. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +47 -16
  17. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +2 -2
  18. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +5 -0
  19. package/python/analysis/modules/comps_valuation/LICENSE +21 -0
  20. package/python/analysis/modules/comps_valuation/module.json +61 -0
  21. package/python/analysis/modules/comps_valuation/module.py +360 -0
  22. package/python/analysis/modules/earnings_bridge/LICENSE +21 -0
  23. package/python/analysis/modules/earnings_bridge/module.json +58 -0
  24. package/python/analysis/modules/earnings_bridge/module.py +452 -0
  25. package/python/analysis/modules/kline_quality/LICENSE +21 -0
  26. package/python/analysis/modules/kline_quality/module.json +61 -0
  27. package/python/analysis/modules/kline_quality/module.py +538 -0
  28. package/python/analysis/modules/portfolio_stress/LICENSE +21 -0
  29. package/python/analysis/modules/portfolio_stress/module.json +89 -0
  30. package/python/analysis/modules/portfolio_stress/module.py +537 -0
  31. package/python/analysis/modules/returns_risk/LICENSE +21 -0
  32. package/python/analysis/modules/returns_risk/module.json +66 -0
  33. package/python/analysis/modules/returns_risk/module.py +517 -0
  34. package/python/analysis/modules/scenario_sensitivity/LICENSE +21 -0
  35. package/python/analysis/modules/scenario_sensitivity/module.json +105 -0
  36. package/python/analysis/modules/scenario_sensitivity/module.py +379 -0
  37. package/python/analysis/modules/simple_backtest/LICENSE +21 -0
  38. package/python/analysis/modules/simple_backtest/module.json +66 -0
  39. package/python/analysis/modules/simple_backtest/module.py +648 -0
  40. package/python/analysis/modules/statement_integrity/LICENSE +21 -0
  41. package/python/analysis/modules/statement_integrity/module.json +62 -0
  42. package/python/analysis/modules/statement_integrity/module.py +621 -0
  43. package/python/analysis/modules/technical_indicators/LICENSE +21 -0
  44. package/python/analysis/modules/technical_indicators/module.json +170 -0
  45. package/python/analysis/modules/technical_indicators/module.py +854 -0
  46. package/python/analysis/modules/valuation_sensitivity/LICENSE +21 -0
  47. package/python/analysis/modules/valuation_sensitivity/module.json +73 -0
  48. package/python/analysis/modules/valuation_sensitivity/module.py +589 -0
  49. package/watchlist/package.json +1 -1
@@ -0,0 +1,379 @@
1
+ """Scenario sensitivity: evaluate one explicit arithmetic identity over an assumption grid.
2
+
3
+ This is the "assumption grid" input shape of the module protocol. The caller supplies base values
4
+ for 1-4 factors, the identity that relates them (`product` = Π factor^exponent, or `sum` =
5
+ Σ factor×exponent), an optional grid of factor values and optional named scenarios. The module only
6
+ evaluates that identity at the points the caller chose: it does not invent assumptions, fit a
7
+ distribution, extrapolate, or forecast anything. Every row is traceable to the base values and the
8
+ explicit override that produced it.
9
+
10
+ Pure standard library (no numpy/pandas); the arithmetic is visible line by line and the module runs
11
+ on the minimal analysis runtime.
12
+
13
+ Protocol: `docs/dev/senior-analysis.md` §1.9. Conclusions and claims belong to the senior analyst;
14
+ this module only produces reproducible scenario values plus the assumptions behind each one.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import itertools
19
+ import math
20
+
21
+ MODULE_ID = "scenario_sensitivity"
22
+ MODULE_VERSION = "1.0.0"
23
+ OUTPUT_NAME = "scenarios"
24
+
25
+ MAX_FACTORS = 4
26
+ MAX_GRID_VALUES = 32
27
+ MAX_GRID_CELLS = 256
28
+ MAX_SCENARIOS = 12
29
+
30
+ ASSUMPTIONS = [
31
+ "目标是显式算术恒等式:product 模型 target = Π factor^exponent;sum 模型 target = Σ factor×exponent",
32
+ "因子基准值由调用方给出,本模块不判断其来源、口径或是否来自同一期",
33
+ "情景值由调用方给出;未在情景里出现的因子继承基准,并在 trace 里标 inherited",
34
+ "网格是单因子扫描(oat)或网格因子笛卡尔积(full),不做随机采样、不插值",
35
+ "输出只是同一恒等式在不同假设下的取值,不是预测、不是概率,也不构成收益承诺",
36
+ "product 模型下负基准值只允许整数指数;零基准值不允许负指数",
37
+ ]
38
+
39
+ LIMITATIONS = [
40
+ "恒等式是调用方给的:模块不验证因子之间是否独立、口径是否一致或假设是否合理",
41
+ "情景与网格的边界由调用方给定;模块不生成假设,也不把格点区间当置信区间",
42
+ "不做概率分布、反馈回路或非线性模型;需要这些时本模块不适用",
43
+ "不构成投资建议,也不产生评级、目标价或收益承诺",
44
+ ]
45
+
46
+
47
+ class AnalysisInputError(Exception):
48
+ """The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
49
+
50
+ analysis_code = "analysis_input_invalid"
51
+
52
+
53
+ def _round(value):
54
+ rounded = round(float(value), 6)
55
+ return 0.0 if rounded == 0 else rounded
56
+
57
+
58
+ def _number(value, label):
59
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
60
+ raise AnalysisInputError(f"{label} 必须是数字,实际是 {value!r}")
61
+ number = float(value)
62
+ if number != number or number in (float("inf"), float("-inf")):
63
+ raise AnalysisInputError(f"{label} 必须是有限数字,实际是 {value!r}")
64
+ return number
65
+
66
+
67
+ def _fmt6(value):
68
+ """Six decimals, trailing zeros trimmed: the same shape the metrics are rounded to."""
69
+ text = f"{_round(value):.6f}".rstrip("0").rstrip(".")
70
+ return text if text not in ("", "-0") else "0"
71
+
72
+
73
+ def _pct(value):
74
+ return f"{value * 100:.2f}%"
75
+
76
+
77
+ def _text(value, label, *, required=False):
78
+ if value is None and not required:
79
+ return None
80
+ if not isinstance(value, str) or not value.strip():
81
+ raise AnalysisInputError(f"{label} 必须是非空字符串")
82
+ return value.strip()
83
+
84
+
85
+ def _factors(params):
86
+ raw = params.get("factors")
87
+ if not isinstance(raw, list) or not raw:
88
+ raise AnalysisInputError("factors 必须是非空数组:至少给出一个因子与基准值")
89
+ if len(raw) > MAX_FACTORS:
90
+ raise AnalysisInputError(f"factors 最多 {MAX_FACTORS} 个,实际 {len(raw)} 个")
91
+ factors, seen = [], set()
92
+ for index, item in enumerate(raw):
93
+ if not isinstance(item, dict):
94
+ raise AnalysisInputError(f"factors[{index}] 必须是对象")
95
+ name = _text(item.get("name"), f"factors[{index}].name", required=True)
96
+ if name in seen:
97
+ raise AnalysisInputError(f"因子名重复:{name};同一因子只能出现一次")
98
+ seen.add(name)
99
+ base = _number(item.get("base"), f"factors[{index}].base")
100
+ exponent = _number(item.get("exponent", 1.0), f"factors[{index}].exponent")
101
+ unit = _text(item.get("unit"), f"factors[{index}].unit")
102
+ factors.append({"name": name, "base": base, "unit": unit, "exponent": exponent})
103
+ return factors
104
+
105
+
106
+ def _model(params):
107
+ model = params.get("model", "product")
108
+ if model not in ("product", "sum"):
109
+ raise AnalysisInputError(f"model 只能是 product 或 sum,实际是 {model!r}")
110
+ return model
111
+
112
+
113
+ def _check_bases(model, factors):
114
+ if model == "sum":
115
+ return
116
+ for factor in factors:
117
+ base, exponent = factor["base"], factor["exponent"]
118
+ if base == 0 and exponent < 0:
119
+ raise AnalysisInputError(f"因子 {factor['name']} 的基准值为 0,不允许负指数(0^-1 无定义)")
120
+ if base < 0 and not exponent.is_integer():
121
+ raise AnalysisInputError(
122
+ f"因子 {factor['name']} 的基准值为负({base}),product 模型只允许整数指数,实际是 {exponent}"
123
+ )
124
+
125
+
126
+ def _evaluate(model, factors, values):
127
+ if model == "product":
128
+ result = 1.0
129
+ for factor in factors:
130
+ base = values[factor["name"]]
131
+ exponent = factor["exponent"]
132
+ if base == 0 and exponent < 0:
133
+ raise AnalysisInputError(f"因子 {factor['name']} 取 0 时不允许负指数")
134
+ if base < 0 and not exponent.is_integer():
135
+ raise AnalysisInputError(f"因子 {factor['name']} 取负值({base})时只允许整数指数")
136
+ result *= base ** exponent
137
+ else:
138
+ result = math.fsum(values[factor["name"]] * factor["exponent"] for factor in factors)
139
+ if isinstance(result, complex) or result != result or result in (float("inf"), float("-inf")):
140
+ raise AnalysisInputError("目标值不是有限实数:检查因子的基准值、指数与情景取值")
141
+ return float(result)
142
+
143
+
144
+ def _grid(params, factors, model, base_values, base_target):
145
+ raw = params.get("grid")
146
+ if raw is None:
147
+ return None, [], []
148
+ if not isinstance(raw, list) or not raw:
149
+ raise AnalysisInputError("grid 必须是非空数组(或省略);空数组请直接省略")
150
+ if len(raw) > MAX_FACTORS:
151
+ raise AnalysisInputError(f"grid 最多覆盖 {MAX_FACTORS} 个因子,实际 {len(raw)} 个")
152
+ known = {factor["name"] for factor in factors}
153
+ entries, seen = [], set()
154
+ for index, item in enumerate(raw):
155
+ if not isinstance(item, dict):
156
+ raise AnalysisInputError(f"grid[{index}] 必须是对象")
157
+ name = _text(item.get("factor"), f"grid[{index}].factor", required=True)
158
+ if name not in known:
159
+ raise AnalysisInputError(f"grid[{index}].factor={name!r} 不是已声明的因子")
160
+ if name in seen:
161
+ raise AnalysisInputError(f"grid 里因子 {name} 出现了两次;每个因子只能有一组扫描值")
162
+ seen.add(name)
163
+ values = item.get("values")
164
+ if not isinstance(values, list) or not values:
165
+ raise AnalysisInputError(f"grid[{index}].values 必须是非空数组")
166
+ if len(values) > MAX_GRID_VALUES:
167
+ raise AnalysisInputError(f"grid[{index}].values 最多 {MAX_GRID_VALUES} 个值,实际 {len(values)} 个")
168
+ entries.append({"factor": name, "values": [_number(value, f"grid[{index}].values") for value in values]})
169
+ mode = params.get("grid_mode", "oat")
170
+ if mode not in ("oat", "full"):
171
+ raise AnalysisInputError(f"grid_mode 只能是 oat 或 full,实际是 {mode!r}")
172
+
173
+ rows = []
174
+ if mode == "full":
175
+ cells = math.prod(len(entry["values"]) for entry in entries)
176
+ if cells > MAX_GRID_CELLS:
177
+ raise AnalysisInputError(f"full 网格 {cells} 格超过 {MAX_GRID_CELLS} 格上限:减少因子或取值")
178
+ names = [entry["factor"] for entry in entries]
179
+ for combo in itertools.product(*[entry["values"] for entry in entries]):
180
+ values = dict(base_values)
181
+ values.update(dict(zip(names, combo)))
182
+ target = _evaluate(model, factors, values)
183
+ rows.append(_row({"values": {name: _round(value) for name, value in zip(names, combo)}, "target": target}, base_target))
184
+ else:
185
+ for entry in entries:
186
+ for value in entry["values"]:
187
+ values = dict(base_values)
188
+ values[entry["factor"]] = value
189
+ target = _evaluate(model, factors, values)
190
+ rows.append(_row({"factor": entry["factor"], "value": _round(value), "target": target}, base_target))
191
+ summary = {
192
+ "mode": mode,
193
+ "cells": len(rows),
194
+ "min": min(row["target"] for row in rows),
195
+ "max": max(row["target"] for row in rows),
196
+ "rows": rows,
197
+ }
198
+ return summary, rows, [row["target"] for row in rows]
199
+
200
+
201
+ def _row(row, base_target):
202
+ target = row.pop("target")
203
+ delta = _round(target - base_target)
204
+ pct = None if base_target == 0 else _round(target / base_target - 1)
205
+ row.update({"target": _round(target), "delta": delta, "delta_pct": pct})
206
+ return row
207
+
208
+
209
+ def _scenarios(params, factors, model, base_values, base_target):
210
+ raw = params.get("scenarios")
211
+ if raw is None:
212
+ return [], []
213
+ if not isinstance(raw, list) or not raw:
214
+ raise AnalysisInputError("scenarios 必须是非空数组(或省略);空数组请直接省略")
215
+ if len(raw) > MAX_SCENARIOS:
216
+ raise AnalysisInputError(f"scenarios 最多 {MAX_SCENARIOS} 个,实际 {len(raw)} 个")
217
+ known = {factor["name"] for factor in factors}
218
+ rows, names = [], set()
219
+ for index, item in enumerate(raw):
220
+ if not isinstance(item, dict):
221
+ raise AnalysisInputError(f"scenarios[{index}] 必须是对象")
222
+ name = _text(item.get("name"), f"scenarios[{index}].name", required=True)
223
+ if name in names:
224
+ raise AnalysisInputError(f"情景名重复:{name}")
225
+ names.add(name)
226
+ overrides = item.get("values")
227
+ if not isinstance(overrides, dict):
228
+ raise AnalysisInputError(f"scenarios[{index}].values 必须是对象")
229
+ values = dict(base_values)
230
+ inherited = []
231
+ for key, value in overrides.items():
232
+ if key not in known:
233
+ raise AnalysisInputError(f"scenarios[{index}].values 里的 {key!r} 不是已声明的因子")
234
+ values[key] = _number(value, f"scenarios[{index}].values.{key}")
235
+ for factor in factors:
236
+ if factor["name"] not in overrides:
237
+ inherited.append(factor["name"])
238
+ target = _evaluate(model, factors, values)
239
+ rows.append(_row({"name": name, "values": {factor["name"]: _round(values[factor["name"]]) for factor in factors},
240
+ "inherited": inherited, "target": target}, base_target))
241
+ return rows, [row["target"] for row in rows]
242
+
243
+
244
+ def _expression(model, factors):
245
+ if model == "product":
246
+ parts = [factor["name"] if factor["exponent"] == 1 else f"{factor['name']}^{_fmt6(factor['exponent'])}"
247
+ for factor in factors]
248
+ return " × ".join(parts)
249
+ text = ""
250
+ for index, factor in enumerate(factors):
251
+ exponent = factor["exponent"]
252
+ magnitude = factor["name"] if abs(exponent) == 1 else f"{_fmt6(abs(exponent))}×{factor['name']}"
253
+ if index == 0:
254
+ text = f"-{magnitude}" if exponent < 0 else magnitude
255
+ else:
256
+ text += f" {'-' if exponent < 0 else '+'} {magnitude}"
257
+ return text
258
+
259
+
260
+ def _result(status, summary, metrics, sensitivity, methodology, limitations, gaps, outputs):
261
+ return {
262
+ "status": status,
263
+ "summary": summary,
264
+ "metrics": metrics,
265
+ "claims": [],
266
+ "assumptions": list(ASSUMPTIONS),
267
+ "methodology_log": methodology,
268
+ "sensitivity": sensitivity,
269
+ "limitations": limitations,
270
+ "data_gaps": gaps,
271
+ "outputs": outputs,
272
+ }
273
+
274
+
275
+ def analyze(request: dict, context) -> dict:
276
+ params = request.get("params") or {}
277
+ target_name = _text(params.get("target_name"), "target_name", required=True)
278
+ target_unit = _text(params.get("target_unit"), "target_unit")
279
+ model = _model(params)
280
+ factors = _factors(params)
281
+ _check_bases(model, factors)
282
+ base_values = {factor["name"]: factor["base"] for factor in factors}
283
+ base_target = _evaluate(model, factors, base_values)
284
+
285
+ grid_summary, grid_rows, grid_targets = _grid(params, factors, model, base_values, base_target)
286
+ scenario_rows, scenario_targets = _scenarios(params, factors, model, base_values, base_target)
287
+ if grid_summary is None and not scenario_rows:
288
+ raise AnalysisInputError("至少给出 grid 或 scenarios 之一:否则只有基准值,没有可比较的假设")
289
+
290
+ gaps = []
291
+ if base_target == 0:
292
+ gaps.append("基准目标值为 0:变化率(delta_pct)无定义,只给绝对值")
293
+ metrics = {"base_target": _round(base_target), "factor_count": len(factors)}
294
+ if scenario_rows:
295
+ metrics.update({
296
+ "scenario_count": len(scenario_rows),
297
+ "scenario_min": _round(min(scenario_targets)),
298
+ "scenario_max": _round(max(scenario_targets)),
299
+ })
300
+ if grid_summary is not None:
301
+ metrics.update({
302
+ "grid_cells": grid_summary["cells"],
303
+ "grid_min": _round(grid_summary["min"]),
304
+ "grid_max": _round(grid_summary["max"]),
305
+ })
306
+
307
+ expression = _expression(model, factors)
308
+ unit = target_unit or ""
309
+ parts = [f"{target_name} 基准 {_fmt6(base_target)}{unit}({model}:{expression})"]
310
+ if scenario_rows:
311
+ parts.append(
312
+ f"情景 {len(scenario_rows)} 个,目标区间 {_fmt6(min(scenario_targets))}–{_fmt6(max(scenario_targets))}{unit}"
313
+ )
314
+ if grid_summary is not None:
315
+ parts.append(
316
+ f"网格 {grid_summary['cells']} 格({grid_summary['mode']}),"
317
+ f"目标区间 {_fmt6(grid_summary['min'])}–{_fmt6(grid_summary['max'])}{unit}"
318
+ )
319
+ summary = ";".join(parts) + "。这是调用方给出的恒等式在不同假设下的取值,不是预测。"
320
+
321
+ methodology = [
322
+ f"因子 {len(factors)} 个、模型 {model}:{expression}",
323
+ f"基准目标值 {_fmt6(base_target)}(由因子基准值直接求值)",
324
+ ]
325
+ if grid_summary is not None:
326
+ methodology.append(
327
+ f"网格模式 {grid_summary['mode']}:{grid_summary['cells']} 格;"
328
+ f"区间 {_fmt6(grid_summary['min'])}–{_fmt6(grid_summary['max'])}"
329
+ )
330
+ if scenario_rows:
331
+ inherited = [name for row in scenario_rows for name in row["inherited"]]
332
+ methodology.append(
333
+ f"情景 {len(scenario_rows)} 个;继承基准的因子值 {len(inherited)} 处(trace 里标 inherited)"
334
+ )
335
+ methodology.append(f"{len(gaps)} 项缺口")
336
+
337
+ sensitivity = {
338
+ "model": model,
339
+ "expression": expression,
340
+ "scenarios": scenario_rows,
341
+ "grid": None if grid_summary is None else {
342
+ "mode": grid_summary["mode"],
343
+ "cells": grid_summary["cells"],
344
+ "rows": grid_rows,
345
+ },
346
+ }
347
+ payload = {
348
+ "protocol": "capital.analysis/v1",
349
+ "module_id": MODULE_ID,
350
+ "module_version": MODULE_VERSION,
351
+ "analysis_id": request.get("analysis_id"),
352
+ "module_run_id": request.get("module_run_id"),
353
+ "target": {"name": target_name, "unit": target_unit, "model": model, "expression": expression},
354
+ "factors": factors,
355
+ "parameters": {"grid_mode": params.get("grid_mode", "oat") if grid_summary is not None else None},
356
+ "base_target": _round(base_target),
357
+ "scenarios": scenario_rows,
358
+ "grid": None if grid_summary is None else {
359
+ "mode": grid_summary["mode"],
360
+ "cells": grid_summary["cells"],
361
+ "rows": grid_rows,
362
+ },
363
+ "data_gaps": gaps,
364
+ }
365
+ ref = context.write_output(OUTPUT_NAME, payload)
366
+ context.log(
367
+ f"{MODULE_ID}: {len(factors)} factors model={model} grid={0 if grid_summary is None else grid_summary['cells']} "
368
+ f"scenarios={len(scenario_rows)}"
369
+ )
370
+ return _result(
371
+ "partial" if gaps else "completed",
372
+ summary,
373
+ metrics,
374
+ sensitivity,
375
+ methodology,
376
+ list(LIMITATIONS),
377
+ gaps,
378
+ [{"name": OUTPUT_NAME, "ref": ref}],
379
+ )
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 v587d
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,66 @@
1
+ {
2
+ "id": "simple_backtest",
3
+ "version": "1.0.0",
4
+ "entrypoint": "module.py",
5
+ "runtime": "python",
6
+ "description": "单标的均线规则的历史回测:按下一根收盘执行、默认含手续费,输出净值曲线、交易记录与区间统计;只说明历史上发生了什么,不预测、不评级",
7
+ "roles": ["senior_analyst"],
8
+ "capabilities": ["dataset.read"],
9
+ "required_fields": [],
10
+ "input_schema": {
11
+ "type": "object",
12
+ "properties": {
13
+ "price_dataset_id": { "type": "string", "maxLength": 128, "description": "价格序列 Dataset;只有一份像日线序列时可省略" },
14
+ "price_column": { "type": "string", "maxLength": 64, "description": "价格列名;省略按 close / adj_close / close_price / price 识别" },
15
+ "time_column": { "type": "string", "maxLength": 64, "description": "时间列名;省略优先用 time_coverage 列,再按 trade_date_ms / date 等识别" },
16
+ "timezone": { "type": "string", "maxLength": 64, "description": "数值时间轴(epoch 毫秒)标注日期用的 IANA 时区;省略按 UTC" },
17
+ "rule": { "type": "string", "enum": ["sma_cross", "price_above_sma"], "description": "sma_cross = 快线上穿慢线持有、下穿空仓;price_above_sma = 收盘价高于均线持有、否则空仓" },
18
+ "fast_window": { "type": "integer", "minimum": 2, "description": "快线 / 单均线窗口(如 5)" },
19
+ "slow_window": { "type": "integer", "minimum": 2, "description": "慢线窗口(仅 sma_cross 需要,如 20;必须大于 fast_window)" },
20
+ "initial_capital": { "type": "number", "minimum": 1, "description": "初始资金(原币),默认 1;只影响金额规模,不影响收益率" },
21
+ "fee_rate": { "type": "number", "minimum": 0, "description": "单边手续费率(小数,0.001 = 0.1%),默认 0 并在结果里披露" }
22
+ },
23
+ "required": ["rule", "fast_window"],
24
+ "additionalProperties": false
25
+ },
26
+ "output_schema": {
27
+ "type": "object",
28
+ "properties": {
29
+ "status": { "type": "string", "enum": ["completed", "partial", "blocked", "failed"] },
30
+ "summary": { "type": "string" },
31
+ "metrics": { "type": "object" },
32
+ "claims": { "type": "array" },
33
+ "assumptions": { "type": "array" },
34
+ "methodology_log": { "type": "array" },
35
+ "sensitivity": { "type": "object" },
36
+ "limitations": { "type": "array" },
37
+ "data_gaps": { "type": "array" },
38
+ "outputs": { "type": "array" }
39
+ },
40
+ "required": [
41
+ "status", "summary", "metrics", "claims", "assumptions", "methodology_log",
42
+ "sensitivity", "limitations", "data_gaps", "outputs"
43
+ ],
44
+ "additionalProperties": false
45
+ },
46
+ "assumptions": [
47
+ "信号在第 t 根收盘算出、按第 t+1 根收盘执行:不使用未来数据,也不假设盘中成交",
48
+ "只做多、空仓二态:持有期收益按收盘价到收盘价,卖出后空仓收益为 0",
49
+ "手续费按单边 fee_rate 从每次买入与卖出金额中扣除;默认 0 时必须原样披露“未扣手续费”",
50
+ "回测使用样本内价格:参数是调用方给的,模块不做参数寻优、不选择最佳窗口,也不做样本外检验",
51
+ "结果只描述这段历史上该规则发生了什么;不构成策略推荐、收益预测或评级"
52
+ ],
53
+ "applicability": [
54
+ "单只标的的日频或周频价格序列:一行一个时间点,价格为正数;有效观测至少为 max(窗口) + 2",
55
+ "只支持 sma_cross 与 price_above_sma 两条规则;需要其他规则时本模块不适用",
56
+ "A 股、港股、美股与指数均可;复权口径由调用方选定,跨口径比较不适用",
57
+ "不适用于高频、做空、杠杆、组合层回测或需要交易成本模型的场景"
58
+ ],
59
+ "limits": {
60
+ "timeout_ms": 30000,
61
+ "max_input_rows": 200000,
62
+ "max_output_bytes": 1048576,
63
+ "max_log_bytes": 65536
64
+ },
65
+ "provenance": { "source_type": "original", "license": "MIT" }
66
+ }