@v587d/capital-generation 2.31.3 → 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 (40) hide show
  1. package/CHANGELOG.md +44 -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/web-retriever/local-fetch.d.ts +1 -1
  8. package/lib/web-retriever/local-fetch.js +1 -1
  9. package/lib/web-retriever/wind-client.d.ts +1 -1
  10. package/lib/web-retriever/wind-client.js +1 -1
  11. package/package.json +1 -1
  12. package/plugin-page/README.en.md +7 -0
  13. package/plugin-page/README.zh.md +7 -0
  14. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +47 -37
  15. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +4 -2
  16. package/python/analysis/modules/comps_valuation/LICENSE +21 -0
  17. package/python/analysis/modules/comps_valuation/module.json +61 -0
  18. package/python/analysis/modules/comps_valuation/module.py +360 -0
  19. package/python/analysis/modules/earnings_bridge/LICENSE +21 -0
  20. package/python/analysis/modules/earnings_bridge/module.json +58 -0
  21. package/python/analysis/modules/earnings_bridge/module.py +452 -0
  22. package/python/analysis/modules/kline_quality/LICENSE +21 -0
  23. package/python/analysis/modules/kline_quality/module.json +61 -0
  24. package/python/analysis/modules/kline_quality/module.py +538 -0
  25. package/python/analysis/modules/portfolio_stress/LICENSE +21 -0
  26. package/python/analysis/modules/portfolio_stress/module.json +89 -0
  27. package/python/analysis/modules/portfolio_stress/module.py +537 -0
  28. package/python/analysis/modules/simple_backtest/LICENSE +21 -0
  29. package/python/analysis/modules/simple_backtest/module.json +66 -0
  30. package/python/analysis/modules/simple_backtest/module.py +648 -0
  31. package/python/analysis/modules/statement_integrity/LICENSE +21 -0
  32. package/python/analysis/modules/statement_integrity/module.json +62 -0
  33. package/python/analysis/modules/statement_integrity/module.py +621 -0
  34. package/python/analysis/modules/technical_indicators/LICENSE +21 -0
  35. package/python/analysis/modules/technical_indicators/module.json +170 -0
  36. package/python/analysis/modules/technical_indicators/module.py +854 -0
  37. package/python/analysis/modules/valuation_sensitivity/LICENSE +21 -0
  38. package/python/analysis/modules/valuation_sensitivity/module.json +73 -0
  39. package/python/analysis/modules/valuation_sensitivity/module.py +589 -0
  40. package/watchlist/package.json +1 -1
@@ -0,0 +1,648 @@
1
+ """Moving-average backtest of one price series (the "price series" input shape of the module protocol).
2
+
3
+ Input is one Dataset with a time column and a positive price column. The caller picks one of two
4
+ long-only rules (`sma_cross` = fast/slow SMA crossover, `price_above_sma` = close above one SMA),
5
+ and the module reports what that rule did on that sample: a close-to-close equity curve, one record
6
+ per round trip, and the standard interval statistics. The signal is computed from bar t's close and
7
+ executed at bar t+1's close, so no close is used before it is knowable; nothing is optimised,
8
+ forecast, rated or recommended.
9
+
10
+ Pure standard library on purpose: no numpy/pandas, so the arithmetic is auditable line by line and
11
+ the module runs on the minimal analysis runtime.
12
+
13
+ Protocol: `docs/dev/senior-analysis.md` §1.9. `module.json` `assumptions` is repeated verbatim in
14
+ ASSUMPTIONS so describe_analysis_module and run_analysis cannot contradict each other.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from datetime import datetime, timezone
20
+
21
+ MODULE_ID = "simple_backtest"
22
+ MODULE_VERSION = "1.0.0"
23
+ OUTPUT_NAME = "simple_backtest"
24
+
25
+ RULES = ("sma_cross", "price_above_sma")
26
+ PRICE_COLUMNS = ("close", "adj_close", "close_price", "price", "nav")
27
+ TIME_COLUMNS = ("trade_date_ms", "date_ms", "period_end_ms", "datetime", "date", "trade_date", "time")
28
+ ISO_DAY = re.compile(r"^(\d{4}-\d{2}-\d{2})")
29
+ MIN_OBSERVATIONS_FOR_STABLE = 20
30
+
31
+ ASSUMPTIONS = [
32
+ "信号在第 t 根收盘算出、按第 t+1 根收盘执行:不使用未来数据,也不假设盘中成交",
33
+ "只做多、空仓二态:持有期收益按收盘价到收盘价,卖出后空仓收益为 0",
34
+ "手续费按单边 fee_rate 从每次买入与卖出金额中扣除;默认 0 时必须原样披露“未扣手续费”",
35
+ "回测使用样本内价格:参数是调用方给的,模块不做参数寻优、不选择最佳窗口,也不做样本外检验",
36
+ "结果只描述这段历史上该规则发生了什么;不构成策略推荐、收益预测或评级",
37
+ ]
38
+
39
+ LIMITATIONS = [
40
+ "信号按收盘价成交:不模拟盘中价格、滑点、冲击成本、涨跌停买不到卖不掉与停牌无法成交的情形",
41
+ "价格口径沿用 Dataset 的取数参数(qfq / hfq / none);本模块不检测也不做复权调整,除权跳变会原样进入净值",
42
+ "只做多、空仓二态,不做空、杠杆、组合或仓位管理;initial_capital 只缩放净值规模,不改变收益率",
43
+ "回测是样本内的:参数由调用方给定,不做参数寻优、窗口选择、样本外检验或统计显著性检验",
44
+ "未计分红再投资、融资融券费用、税费与借券成本;fee_rate=0 时结果是未扣手续费的名义净值",
45
+ "历史结果不预测未来;不构成投资建议,也不产生评级、目标价或收益承诺",
46
+ ]
47
+
48
+
49
+ class AnalysisInputError(Exception):
50
+ """The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
51
+
52
+ analysis_code = "analysis_input_invalid"
53
+
54
+
55
+ def _round(value):
56
+ rounded = round(float(value), 6)
57
+ return 0.0 if rounded == 0 else rounded
58
+
59
+
60
+ def _fmt6(value):
61
+ """Six decimals with trailing zeros trimmed: the same shape the metrics are rounded to."""
62
+ text = f"{_round(value):.6f}".rstrip("0").rstrip(".")
63
+ return text if text not in ("", "-0") else "0"
64
+
65
+
66
+ def _pct(value):
67
+ return f"{value * 100:.2f}%"
68
+
69
+
70
+ def _number(row, name):
71
+ if row is None:
72
+ return None
73
+ value = row.get(name)
74
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
75
+ return None
76
+ number = float(value)
77
+ if number != number or number in (float("inf"), float("-inf")):
78
+ return None
79
+ return number
80
+
81
+
82
+ def _columns_of(view):
83
+ names = set()
84
+ for item in view.get("columns") or []:
85
+ if isinstance(item, dict):
86
+ name = item.get("name")
87
+ if isinstance(name, str):
88
+ names.add(name)
89
+ for row in view.get("rows") or []:
90
+ if isinstance(row, dict):
91
+ names |= set(row)
92
+ return names
93
+
94
+
95
+ def _text(value):
96
+ return value if isinstance(value, str) and value.strip() else None
97
+
98
+
99
+ def _timezone(name):
100
+ """IANA zone when the caller names one; UTC otherwise (the dataset tz is not authoritative)."""
101
+ if name is None:
102
+ return timezone.utc
103
+ try:
104
+ from zoneinfo import ZoneInfo
105
+
106
+ return ZoneInfo(name)
107
+ except Exception as error: # noqa: BLE001 - any load failure is a caller error
108
+ raise AnalysisInputError(f"timezone={name!r} 无法加载(需要 IANA 时区名,如 Asia/Shanghai)") from error
109
+
110
+
111
+ def _time_column(view, override):
112
+ names = _columns_of(view)
113
+ if override is not None:
114
+ if override not in names:
115
+ raise AnalysisInputError(f"time_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
116
+ return override
117
+ axis = (view.get("time_axis") or {}).get("column")
118
+ if isinstance(axis, str) and axis in names:
119
+ return axis
120
+ for name in TIME_COLUMNS:
121
+ if name in names:
122
+ return name
123
+ raise AnalysisInputError(
124
+ "找不到时间列:需要 time_coverage 列,或 trade_date_ms / date_ms / period_end_ms / datetime / date / trade_date / time 之一"
125
+ )
126
+
127
+
128
+ def _price_column(view, override):
129
+ names = _columns_of(view)
130
+ if override is not None:
131
+ if override not in names:
132
+ raise AnalysisInputError(f"price_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
133
+ return override
134
+ for name in PRICE_COLUMNS:
135
+ if name in names:
136
+ return name
137
+ raise AnalysisInputError(
138
+ "找不到价格列:需要 close / adj_close / close_price / price / nav 之一(或用 price_column 指明);"
139
+ f"现有列:{sorted(names)}"
140
+ )
141
+
142
+
143
+ def _parse_time(value, tz):
144
+ """Return `(sort_key, day_label)`; `None` when the value is not a usable time."""
145
+ if isinstance(value, bool):
146
+ return None
147
+ if isinstance(value, (int, float)):
148
+ number = float(value)
149
+ if number != number or number in (float("inf"), float("-inf")):
150
+ return None
151
+ try:
152
+ stamp = datetime.fromtimestamp(number / 1000.0, tz=tz)
153
+ except (OverflowError, OSError, ValueError):
154
+ return None
155
+ return number, stamp.strftime("%Y-%m-%d")
156
+ if isinstance(value, str):
157
+ match = ISO_DAY.match(value.strip())
158
+ if match is None:
159
+ return None
160
+ day = match.group(1)
161
+ try:
162
+ stamp = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=timezone.utc)
163
+ except ValueError:
164
+ return None
165
+ return stamp.timestamp() * 1000.0, day
166
+ return None
167
+
168
+
169
+ def _sample(values):
170
+ shown = "、".join(str(value) for value in values[:5])
171
+ return shown if len(values) <= 5 else f"{shown} 等 {len(values)} 行"
172
+
173
+
174
+ def _series(view, dataset_id, price_column, time_column, tz):
175
+ rows = view.get("rows") or []
176
+ if not rows:
177
+ raise AnalysisInputError(f"Dataset {dataset_id} 没有数据行:无法回测")
178
+ points, dropped, kind = [], [], None
179
+ for row in rows:
180
+ if not isinstance(row, dict):
181
+ raise AnalysisInputError(f"Dataset {dataset_id} 的数据行不是对象:无法回测")
182
+ raw_time = row.get(time_column)
183
+ row_kind = "ms" if isinstance(raw_time, (int, float)) and not isinstance(raw_time, bool) else "date"
184
+ if kind is None:
185
+ kind = row_kind
186
+ elif row_kind != kind:
187
+ raise AnalysisInputError(
188
+ f"Dataset {dataset_id} 的 {time_column} 列混用了数值时间戳与日期字符串:无法排序,请取数时统一"
189
+ )
190
+ parsed = _parse_time(raw_time, tz)
191
+ price = _number(row, price_column)
192
+ if parsed is None or price is None or price <= 0:
193
+ dropped.append(raw_time)
194
+ continue
195
+ key, day = parsed
196
+ points.append({"key": key, "day": day, "price": price})
197
+ points.sort(key=lambda item: item["key"])
198
+ seen = set()
199
+ for point in points:
200
+ if point["day"] in seen:
201
+ raise AnalysisInputError(
202
+ f"Dataset {dataset_id} 在 {point['day']} 出现多行:无法判断用哪一行(请先去重)"
203
+ )
204
+ seen.add(point["day"])
205
+ return points, dropped
206
+
207
+
208
+ def _window(params, name, required):
209
+ value = params.get(name)
210
+ if value is None:
211
+ if required:
212
+ raise AnalysisInputError(f"sma_cross 需要 {name}(且必须大于 fast_window)")
213
+ return None
214
+ if isinstance(value, bool) or not isinstance(value, int):
215
+ raise AnalysisInputError(f"{name}={value!r} 必须是整数")
216
+ if value < 2:
217
+ raise AnalysisInputError(f"{name}={value} 至少为 2(均线窗口不能是 1)")
218
+ return value
219
+
220
+
221
+ def _capital(params):
222
+ value = params.get("initial_capital", 1.0)
223
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
224
+ raise AnalysisInputError(f"initial_capital={value!r} 必须是数字")
225
+ number = float(value)
226
+ if number != number or number in (float("inf"), float("-inf")) or number <= 0:
227
+ raise AnalysisInputError(f"initial_capital={value!r} 必须是正的有限数字")
228
+ return number
229
+
230
+
231
+ def _fee(params):
232
+ value = params.get("fee_rate", 0.0)
233
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
234
+ raise AnalysisInputError(f"fee_rate={value!r} 必须是数字(小数,0.001 = 0.1%)")
235
+ number = float(value)
236
+ if number != number or number in (float("inf"), float("-inf")) or not 0 <= number < 1:
237
+ raise AnalysisInputError(f"fee_rate={value!r} 必须在 [0, 1) 内(单边费率,0.001 = 0.1%)")
238
+ return number
239
+
240
+
241
+ def _parameters(params):
242
+ rule = params.get("rule")
243
+ if rule not in RULES:
244
+ raise AnalysisInputError(f"rule={rule!r} 只能是 sma_cross 或 price_above_sma")
245
+ fast = _window(params, "fast_window", required=True)
246
+ slow = _window(params, "slow_window", required=rule == "sma_cross")
247
+ if rule == "sma_cross" and slow <= fast:
248
+ raise AnalysisInputError(f"slow_window={slow} 必须大于 fast_window={fast}:快慢线不能相等或反置")
249
+ return {
250
+ "rule": rule,
251
+ "fast_window": fast,
252
+ "slow_window": slow if rule == "sma_cross" else None,
253
+ "initial_capital": _capital(params),
254
+ "fee_rate": _fee(params),
255
+ }
256
+
257
+
258
+ def _sma(closes, window):
259
+ n = len(closes)
260
+ prefix, total = [], 0.0
261
+ for close in closes:
262
+ total += close
263
+ prefix.append(total)
264
+ values = [None] * n
265
+ for index in range(window - 1, n):
266
+ before = prefix[index - window] if index >= window else 0.0
267
+ values[index] = (prefix[index] - before) / window
268
+ return values
269
+
270
+
271
+ def _targets(closes, rule, fast, slow):
272
+ """Desired state at each bar's close; `None` while a window is not yet full."""
273
+ n = len(closes)
274
+ fast_sma = _sma(closes, fast)
275
+ slow_sma = _sma(closes, slow) if slow is not None else None
276
+ targets = [None] * n
277
+ if rule == "price_above_sma":
278
+ for index in range(fast - 1, n):
279
+ targets[index] = 1 if closes[index] > fast_sma[index] else 0
280
+ return targets, fast_sma, slow_sma
281
+ state = 0
282
+ for index in range(slow - 1, n):
283
+ if fast_sma[index] > slow_sma[index]:
284
+ state = 1
285
+ elif fast_sma[index] < slow_sma[index]:
286
+ state = 0
287
+ targets[index] = state
288
+ return targets, fast_sma, slow_sma
289
+
290
+
291
+ def _backtest(points, targets, fee_rate, initial_capital):
292
+ """Walk the bars once. A signal at t is executed at t+1's close; a held bar earns close-to-close."""
293
+ closes = [point["price"] for point in points]
294
+ n = len(closes)
295
+ equity = [initial_capital]
296
+ position = [0]
297
+ trades, current = [], None
298
+ for bar in range(1, n):
299
+ value = equity[bar - 1]
300
+ if position[bar - 1] == 1:
301
+ value *= closes[bar] / closes[bar - 1]
302
+ action = targets[bar - 1]
303
+ still = position[bar - 1]
304
+ if action == 1 and still == 0:
305
+ value *= 1.0 - fee_rate
306
+ still = 1
307
+ current = {"entry_index": bar, "entry_price": closes[bar], "equity_before": equity[bar - 1]}
308
+ elif action == 0 and still == 1:
309
+ value *= 1.0 - fee_rate
310
+ still = 0
311
+ trades.append({
312
+ "open": False,
313
+ "entry_index": current["entry_index"],
314
+ "entry_price": current["entry_price"],
315
+ "exit_index": bar,
316
+ "exit_price": closes[bar],
317
+ "bars": bar - current["entry_index"],
318
+ "price_return": closes[bar] / current["entry_price"] - 1.0,
319
+ "net_return": value / current["equity_before"] - 1.0,
320
+ })
321
+ current = None
322
+ equity.append(value)
323
+ position.append(still)
324
+ if current is not None:
325
+ trades.append({
326
+ "open": True,
327
+ "entry_index": current["entry_index"],
328
+ "entry_price": current["entry_price"],
329
+ "last_index": n - 1,
330
+ "last_price": closes[-1],
331
+ "bars": n - current["entry_index"],
332
+ "price_return": closes[-1] / current["entry_price"] - 1.0,
333
+ })
334
+ for trade in trades:
335
+ trade["win"] = (not trade["open"]) and trade["net_return"] > 0
336
+ return closes, equity, position, trades
337
+
338
+
339
+ def _metrics(equity, closes, position, trades, initial_capital):
340
+ peak, max_drawdown = equity[0], 0.0
341
+ for value in equity:
342
+ peak = max(peak, value)
343
+ max_drawdown = min(max_drawdown, value / peak - 1.0)
344
+ closed = [trade for trade in trades if not trade["open"]]
345
+ bars = sum(position)
346
+ metrics = {
347
+ "observations": len(closes),
348
+ "total_return": _round(equity[-1] / initial_capital - 1.0),
349
+ "buy_and_hold_return": _round(closes[-1] / closes[0] - 1.0),
350
+ "max_drawdown": _round(max_drawdown),
351
+ "final_equity": _round(equity[-1]),
352
+ "trade_count": len(closed),
353
+ "exposure_bars": bars,
354
+ "exposure_ratio": _round(bars / len(closes)),
355
+ }
356
+ if closed:
357
+ metrics["win_rate"] = _round(sum(1 for trade in closed if trade["win"]) / len(closed))
358
+ return metrics
359
+
360
+
361
+ def _trade_rows(trades, points):
362
+ rows = []
363
+ for number, trade in enumerate(trades, start=1):
364
+ entry = points[trade["entry_index"]]
365
+ if trade["open"]:
366
+ rows.append({
367
+ "trade": number,
368
+ "open": True,
369
+ "entry_date": entry["day"],
370
+ "entry_price": _round(trade["entry_price"]),
371
+ "entry_index": trade["entry_index"],
372
+ "last_date": points[trade["last_index"]]["day"],
373
+ "last_price": _round(trade["last_price"]),
374
+ "bars": trade["bars"],
375
+ "price_return": _round(trade["price_return"]),
376
+ })
377
+ continue
378
+ exit_ = points[trade["exit_index"]]
379
+ rows.append({
380
+ "trade": number,
381
+ "open": False,
382
+ "entry_date": entry["day"],
383
+ "entry_price": _round(trade["entry_price"]),
384
+ "entry_index": trade["entry_index"],
385
+ "exit_date": exit_["day"],
386
+ "exit_price": _round(trade["exit_price"]),
387
+ "exit_index": trade["exit_index"],
388
+ "bars": trade["bars"],
389
+ "price_return": _round(trade["price_return"]),
390
+ "net_return": _round(trade["net_return"]),
391
+ "win": trade["win"],
392
+ })
393
+ return rows
394
+
395
+
396
+ def _result(status, summary, metrics, methodology, limitations, gaps, outputs):
397
+ return {
398
+ "status": status,
399
+ "summary": summary,
400
+ "metrics": metrics,
401
+ "claims": [],
402
+ "assumptions": list(ASSUMPTIONS),
403
+ "methodology_log": methodology,
404
+ "sensitivity": {},
405
+ "limitations": limitations,
406
+ "data_gaps": gaps,
407
+ "outputs": outputs,
408
+ }
409
+
410
+
411
+ def _rule_text(rule, fast, slow):
412
+ if rule == "sma_cross":
413
+ return f"sma_cross(fast {fast} / slow {slow})"
414
+ return f"price_above_sma(close 对 SMA{fast})"
415
+
416
+
417
+ def _fee_text(fee_rate):
418
+ if fee_rate == 0:
419
+ return "单边手续费 0(未扣手续费)"
420
+ return f"单边手续费 {_pct(fee_rate)}"
421
+
422
+
423
+ DISCLAIMER = "样本内回测、参数由调用方给定、未做参数寻优;不预测、不构成策略推荐。"
424
+
425
+
426
+ def _summary(metrics, rule, fast, slow, fee_rate, points, dropped, gaps, open_trades):
427
+ start, end = points[0]["day"], points[-1]["day"]
428
+ head = f"{start}..{end}(有效观测 {len(points)} 个"
429
+ head += f",跳过 {len(dropped)} 行)" if dropped else ")"
430
+ rule_text = _rule_text(rule, fast, slow)
431
+ parts = [
432
+ f"区间收益 {_pct(metrics['total_return'])}",
433
+ f"买入持有 {_pct(metrics['buy_and_hold_return'])}",
434
+ f"最大回撤 {_pct(metrics['max_drawdown'])}",
435
+ f"期末净值 {_fmt6(metrics['final_equity'])}",
436
+ ]
437
+ trade_text = f"完整往返 {metrics['trade_count']} 笔"
438
+ if "win_rate" in metrics:
439
+ trade_text += f"、胜率 {_pct(metrics['win_rate'])}"
440
+ else:
441
+ trade_text += "(没有平仓交易,胜率无定义)"
442
+ if open_trades:
443
+ trade_text += f"、未平仓 {open_trades} 笔"
444
+ parts.append(trade_text)
445
+ parts.append(f"持有占比 {_pct(metrics['exposure_ratio'])}({metrics['exposure_bars']}/{len(points)} 根)")
446
+ parts.append(_fee_text(fee_rate))
447
+ body = f"{head},{rule_text}:" + ";".join(parts) + "。"
448
+ if gaps:
449
+ body += f"有 {len(gaps)} 项缺口,见 data_gaps。"
450
+ return body + DISCLAIMER
451
+
452
+
453
+ def _blocked_summary(rule, fast, slow, points, required):
454
+ start, end = points[0]["day"], points[-1]["day"]
455
+ head = f"{start}..{end}(有效观测 {len(points)} 个)"
456
+ return (
457
+ f"{head}:{_rule_text(rule, fast, slow)} 样本不足,未回测"
458
+ f"(需要 max 窗口 + 2 = {required} 个有效观测,实际 {len(points)} 个)。" + DISCLAIMER
459
+ )
460
+
461
+
462
+ def _read_views(request, context):
463
+ items = (request.get("inputs") or {}).get("datasets") or []
464
+ if not items:
465
+ raise AnalysisInputError("快照里没有任何 Dataset:先取价格序列再建快照")
466
+ views = {}
467
+ for item in items:
468
+ dataset_id = (item or {}).get("dataset_id")
469
+ if not isinstance(dataset_id, str) or not dataset_id:
470
+ raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
471
+ views[dataset_id] = context.read_dataset(dataset_id)
472
+ for dataset_id, view in views.items():
473
+ if view.get("shape") != "rows":
474
+ raise AnalysisInputError(
475
+ f"Dataset {dataset_id} 是 {view.get('shape')} 型:simple_backtest 只吃价格表格,"
476
+ "文档型输入请先走 profile 或证据"
477
+ )
478
+ return views
479
+
480
+
481
+ def _candidate(views, price_override, time_override):
482
+ """Dataset ids that look like a price series (a time column plus a price column)."""
483
+ candidates = []
484
+ for dataset_id, view in sorted(views.items()):
485
+ try:
486
+ time_column = _time_column(view, time_override)
487
+ _price_column(view, price_override)
488
+ except AnalysisInputError:
489
+ continue
490
+ candidates.append((dataset_id, time_column))
491
+ return candidates
492
+
493
+
494
+ def analyze(request: dict, context) -> dict:
495
+ params = request.get("params") or {}
496
+ settings = _parameters(params)
497
+ rule, fast, slow = settings["rule"], settings["fast_window"], settings["slow_window"]
498
+ fee_rate = settings["fee_rate"]
499
+
500
+ views = _read_views(request, context)
501
+ price_override = _text(params.get("price_column"))
502
+ time_override = _text(params.get("time_column"))
503
+ price_dataset_id = _text(params.get("price_dataset_id"))
504
+ if price_dataset_id is not None:
505
+ if price_dataset_id not in views:
506
+ raise AnalysisInputError(f"price_dataset_id={price_dataset_id} 不在本次快照的 Dataset 里")
507
+ price_view = views[price_dataset_id]
508
+ else:
509
+ candidates = _candidate(views, price_override, time_override)
510
+ if len(candidates) > 1:
511
+ raise AnalysisInputError(
512
+ f"有 {len(candidates)} 份 Dataset 都像价格序列({'、'.join(item[0] for item in candidates)}):"
513
+ "用 price_dataset_id 指明用哪一份"
514
+ )
515
+ if not candidates:
516
+ detail = f"(time_column={time_override} 不在任何 Dataset 里)" if time_override else ""
517
+ raise AnalysisInputError(
518
+ f"没有可识别的价格序列 Dataset{detail}:需要时间列 + close/adj_close/close_price/price/nav 之一"
519
+ )
520
+ price_dataset_id = candidates[0][0]
521
+ price_view = views[price_dataset_id]
522
+
523
+ time_column = _time_column(price_view, time_override)
524
+ price_column = _price_column(price_view, price_override)
525
+ tz_name = _text(params.get("timezone")) or "UTC"
526
+ tz = _timezone(_text(params.get("timezone")))
527
+ points, dropped = _series(price_view, price_dataset_id, price_column, time_column, tz)
528
+ if not points:
529
+ raise AnalysisInputError(f"Dataset {price_dataset_id} 没有有效价格观测:无法回测")
530
+
531
+ n = len(points)
532
+ max_window = max(fast, slow if slow is not None else 0)
533
+ required = max_window + 2
534
+ methodology = [
535
+ f"价格 Dataset {price_dataset_id}:时间列 {time_column}、价格列 {price_column};数值时间轴按 {tz_name} 标注日历日",
536
+ f"按时间升序 {n} 个有效观测" + (f";跳过 {len(dropped)} 行(时间无法解析或价格非正)" if dropped else ";无跳过行"),
537
+ f"规则 {_rule_text(rule, fast, slow)};initial_capital={_fmt6(settings['initial_capital'])}、"
538
+ f"fee_rate={fee_rate:g}({_fee_text(fee_rate)})",
539
+ "信号在第 t 根收盘用截至 t 的收盘价算出,第 t+1 根收盘成交;净值按收盘到收盘,空仓日不变",
540
+ ]
541
+ if rule != "sma_cross" and params.get("slow_window") is not None:
542
+ methodology.append("price_above_sma 是单均线规则:传入的 slow_window 未生效(结果里记为 null)")
543
+ limitations = list(LIMITATIONS)
544
+ gaps = []
545
+ if dropped:
546
+ gaps.append(
547
+ f"价格列 {price_column} 有 {len(dropped)} 行不是正数或时间无法解析(已跳过):{_sample(dropped)}"
548
+ )
549
+ limitations.append(f"跳过 {len(dropped)} 行后按剩余观测重排 bar 序号,均线窗口因此跨过被跳过的日期")
550
+
551
+ if n < required:
552
+ gaps.insert(0, (
553
+ f"有效观测不足 {required} 个(实际 {n} 个):{rule} 用 fast_window={fast}"
554
+ + (f" / slow_window={slow}" if slow is not None else "")
555
+ + f",需要 max 窗口 + 2 = {required} 个有效观测(填满窗口才出信号、下一根才成交)"
556
+ ))
557
+ methodology.append(f"有效观测 {n} < {required}:未计算净值曲线、交易与统计")
558
+ return _result(
559
+ "blocked",
560
+ _blocked_summary(rule, fast, slow, points, required),
561
+ {},
562
+ methodology,
563
+ limitations,
564
+ gaps,
565
+ [],
566
+ )
567
+
568
+ closes = [point["price"] for point in points]
569
+ targets, fast_sma, slow_sma = _targets(closes, rule, fast, slow)
570
+ closes, equity, position, trades = _backtest(points, targets, fee_rate, settings["initial_capital"])
571
+ metrics = _metrics(equity, closes, position, trades, settings["initial_capital"])
572
+ closed = [trade for trade in trades if not trade["open"]]
573
+ open_trades = len(trades) - len(closed)
574
+ if not closed:
575
+ gaps.append("没有已平仓交易:win_rate 无定义(不写 0)")
576
+ limitations.append("没有已平仓交易:win_rate 缺省,交易层面的统计给不出来,不是 0%")
577
+ if open_trades:
578
+ limitations.append(f"期末仍有 {open_trades} 笔未平仓交易:total_return 含未实现浮动盈亏,net_return 只对已平仓交易给")
579
+ if fee_rate == 0:
580
+ limitations.append("本次 fee_rate=0(未扣手续费):净值不含任何交易成本,不是策略本身没有成本")
581
+ if n < MIN_OBSERVATIONS_FOR_STABLE:
582
+ limitations.append(f"只有 {n} 个有效观测:样本很短,胜率与净值对个别交易日敏感,只能作方向性参考")
583
+ status = "partial" if gaps else "completed"
584
+ methodology.append(
585
+ f"完整往返 {len(closed)} 笔、未平仓 {open_trades} 笔;"
586
+ f"持有占比 {metrics['exposure_bars']}/{n} = {_fmt6(metrics['exposure_ratio'])}"
587
+ )
588
+ methodology.append(f"{len(gaps)} 项缺口")
589
+
590
+ series = []
591
+ for index, point in enumerate(points):
592
+ row = {
593
+ "date": point["day"],
594
+ "close": _round(closes[index]),
595
+ "sma_fast": None if fast_sma[index] is None else _round(fast_sma[index]),
596
+ }
597
+ if slow_sma is not None:
598
+ row["sma_slow"] = None if slow_sma[index] is None else _round(slow_sma[index])
599
+ row.update({
600
+ "signal": targets[index],
601
+ "position": position[index],
602
+ "equity": _round(equity[index]),
603
+ })
604
+ series.append(row)
605
+
606
+ payload = {
607
+ "protocol": "capital.analysis/v1",
608
+ "module_id": MODULE_ID,
609
+ "module_version": MODULE_VERSION,
610
+ "analysis_id": request.get("analysis_id"),
611
+ "module_run_id": request.get("module_run_id"),
612
+ "price_dataset_id": price_dataset_id,
613
+ "time_column": time_column,
614
+ "price_column": price_column,
615
+ "rule": rule,
616
+ "parameters": {
617
+ "rule": rule,
618
+ "fast_window": fast,
619
+ "slow_window": slow,
620
+ "initial_capital": settings["initial_capital"],
621
+ "fee_rate": fee_rate,
622
+ "timezone": tz_name,
623
+ },
624
+ "window": {
625
+ "start": points[0]["day"],
626
+ "end": points[-1]["day"],
627
+ "observations": n,
628
+ "skipped_rows": len(dropped),
629
+ },
630
+ "statistics": metrics,
631
+ "series": series,
632
+ "trades": _trade_rows(trades, points),
633
+ "data_gaps": gaps,
634
+ }
635
+ ref = context.write_output(OUTPUT_NAME, payload)
636
+ context.log(
637
+ f"{MODULE_ID}: {status} observations={n} trades={metrics['trade_count']} "
638
+ f"open={open_trades} gaps={len(gaps)}"
639
+ )
640
+ return _result(
641
+ status,
642
+ _summary(metrics, rule, fast, slow, fee_rate, points, dropped, gaps, open_trades),
643
+ metrics,
644
+ methodology,
645
+ limitations,
646
+ gaps,
647
+ [{"name": OUTPUT_NAME, "ref": ref}],
648
+ )
@@ -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.