@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,538 @@
1
+ """Daily K-line cleaning and quality audit (the "OHLC series" input shape of the module protocol).
2
+
3
+ Input is one Dataset whose rows are one bar per trading day. Every row is checked against the hard
4
+ rules spelled out in the manifest assumptions; a failing row is rejected with a stable reason code,
5
+ and the surviving bars form the cleaned series. Soft flags (a close-to-close move above the caller's
6
+ `jump_threshold`, missing or zero volume) never remove a bar — they are marked, counted and handed to
7
+ the auditor. Nothing here forecasts, rates or recommends, and a missing volume is never read as zero.
8
+
9
+ Pure standard library on purpose: no numpy/pandas, so every rule is auditable line by line and the
10
+ module runs on the minimal analysis runtime.
11
+
12
+ Protocol: `docs/dev/senior-analysis.md` §1.9. Conclusions and claims belong to the senior analyst;
13
+ this module only produces the cleaned series plus the evidence behind every rejection.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from datetime import datetime, timezone
19
+
20
+ MODULE_ID = "kline_quality"
21
+ MODULE_VERSION = "1.0.0"
22
+ OUTPUT_NAME = "kline_quality"
23
+
24
+ JUMP_THRESHOLD_DEFAULT = 0.5
25
+ OHLC_COLUMNS = ("open", "high", "low", "close")
26
+ TIME_COLUMNS = ("trade_date_ms", "date_ms", "period_end_ms", "datetime", "date", "trade_date", "time")
27
+ ISO_DAY = re.compile(r"^(\d{4}-\d{2}-\d{2})")
28
+
29
+ REJECT_TIME = "time_unparseable"
30
+ REJECT_PRICE = "price_invalid"
31
+ REJECT_HIGH = "high_below_max"
32
+ REJECT_LOW = "low_above_min"
33
+ REJECT_DUPLICATE = "duplicate_date"
34
+ REJECT_REASONS = (REJECT_TIME, REJECT_PRICE, REJECT_HIGH, REJECT_LOW, REJECT_DUPLICATE)
35
+
36
+ ASSUMPTIONS = [
37
+ "一根 bar 合法当且仅当:时间可解析、open/high/low/close 都是正数、high ≥ max(open, close, low)、low ≤ min(open, close, high)",
38
+ "时间列是 ISO 日期(YYYY-MM-DD)或 epoch 毫秒;同一交易日出现多行时保留第一行时间,其余行以 duplicate_date 拒绝并计数",
39
+ "成交量缺失或为 0 不当作 0 参与统计:只标 volume_missing,价格 bar 仍进清洗序列",
40
+ "价格口径沿用 Dataset 的取数参数(qfq / hfq / none);本模块不检测也不做复权调整,除权日的跳变可能被标成可疑",
41
+ "jump_threshold 只用于标记可疑 bar,不删除、不改写价格;阈值由调用方给出并写进结果,不是涨跌预测",
42
+ "清洗序列只是通过硬校验的 bar:不代表数据完整,也不代表可以据此交易",
43
+ ]
44
+
45
+ LIMITATIONS = [
46
+ "清洗序列只代表通过硬校验的 bar,不代表数据完整,也不构成交易建议",
47
+ "价格口径沿用 Dataset 的取数参数(qfq / hfq / none);本模块不检测也不做复权调整,除权日的跳变可能被标成可疑",
48
+ "时间列是 ISO 日期(YYYY-MM-DD)或 epoch 毫秒;数值时间轴按参数 timezone 标注日历日(省略按 UTC)",
49
+ "成交量缺失或为 0 的 bar 只标记、不剔除,也不当作 0 参与任何统计",
50
+ "jump_threshold 只标记可疑 bar,不猜原因:除权、停牌复牌与数据错误都可能呈现同一形态",
51
+ "不构成投资建议,也不产生评级、目标价或收益承诺",
52
+ ]
53
+
54
+
55
+ class AnalysisInputError(Exception):
56
+ """The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
57
+
58
+ analysis_code = "analysis_input_invalid"
59
+
60
+
61
+ def _round(value):
62
+ rounded = round(float(value), 6)
63
+ return 0.0 if rounded == 0 else rounded
64
+
65
+
66
+ def _fmt6(value):
67
+ """Six decimals, trailing zeros trimmed: readable in prose, still the stored precision."""
68
+ text = f"{_round(value):.6f}".rstrip("0").rstrip(".")
69
+ return text if text not in ("", "-0") else "0"
70
+
71
+
72
+ def _pct(value):
73
+ return f"{value * 100:.2f}%"
74
+
75
+
76
+ def _number(row, name):
77
+ if row is None:
78
+ return None
79
+ value = row.get(name)
80
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
81
+ return None
82
+ number = float(value)
83
+ if number != number or number in (float("inf"), float("-inf")):
84
+ return None
85
+ return number
86
+
87
+
88
+ def _columns_of(view):
89
+ """Declared columns plus the keys of every row: a sampled schema can miss a late volume column."""
90
+ names = set()
91
+ for item in view.get("columns") or []:
92
+ if isinstance(item, dict):
93
+ name = item.get("name")
94
+ if isinstance(name, str):
95
+ names.add(name)
96
+ for row in view.get("rows") or []:
97
+ if isinstance(row, dict):
98
+ names |= set(row)
99
+ return names
100
+
101
+
102
+ def _text(value):
103
+ return value if isinstance(value, str) and value.strip() else None
104
+
105
+
106
+ def _timezone(name):
107
+ """IANA zone when the caller names one; UTC otherwise (the dataset tz is not authoritative)."""
108
+ if name is None:
109
+ return timezone.utc
110
+ try:
111
+ from zoneinfo import ZoneInfo
112
+
113
+ return ZoneInfo(name)
114
+ except Exception as error: # noqa: BLE001 - any load failure is a caller error
115
+ raise AnalysisInputError(f"timezone={name!r} 无法加载(需要 IANA 时区名,如 Asia/Shanghai)") from error
116
+
117
+
118
+ def _time_column(view, override):
119
+ names = _columns_of(view)
120
+ if override is not None:
121
+ if override not in names:
122
+ raise AnalysisInputError(f"time_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
123
+ return override
124
+ axis = (view.get("time_axis") or {}).get("column")
125
+ if isinstance(axis, str) and axis in names:
126
+ return axis
127
+ for name in TIME_COLUMNS:
128
+ if name in names:
129
+ return name
130
+ raise AnalysisInputError(
131
+ "找不到时间列:需要 time_coverage 列,或 trade_date_ms / date_ms / period_end_ms / datetime / date / trade_date / time 之一"
132
+ )
133
+
134
+
135
+ def _require_ohlc(view, dataset_id):
136
+ names = _columns_of(view)
137
+ missing = [name for name in OHLC_COLUMNS if name not in names]
138
+ if missing:
139
+ raise AnalysisInputError(
140
+ f"Dataset {dataset_id} 缺少 OHLC 列:缺 {'、'.join(missing)};"
141
+ f"K 线清洗需要 open/high/low/close 四列(volume 可选)。现有列:{sorted(names)}"
142
+ )
143
+
144
+
145
+ def _threshold(value):
146
+ if value is None:
147
+ return JUMP_THRESHOLD_DEFAULT
148
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
149
+ raise AnalysisInputError(f"jump_threshold={value!r} 必须是数字(小数,0.5 = 50%)")
150
+ number = float(value)
151
+ if number != number or number in (float("inf"), float("-inf")) or number < 0:
152
+ raise AnalysisInputError(f"jump_threshold={value!r} 必须是非负有限数字(小数,0.5 = 50%)")
153
+ return number
154
+
155
+
156
+ def _parse_time(value, tz):
157
+ """Return `(sort_key, day_label)`; `None` when the value is not a usable time."""
158
+ if isinstance(value, bool):
159
+ return None
160
+ if isinstance(value, (int, float)):
161
+ number = float(value)
162
+ if number != number or number in (float("inf"), float("-inf")):
163
+ return None
164
+ try:
165
+ stamp = datetime.fromtimestamp(number / 1000.0, tz=tz)
166
+ except (OverflowError, OSError, ValueError):
167
+ return None
168
+ return number, stamp.strftime("%Y-%m-%d")
169
+ if isinstance(value, str):
170
+ match = ISO_DAY.match(value.strip())
171
+ if match is None:
172
+ return None
173
+ day = match.group(1)
174
+ try:
175
+ stamp = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=timezone.utc)
176
+ except ValueError:
177
+ return None
178
+ return stamp.timestamp() * 1000.0, day
179
+ return None
180
+
181
+
182
+ def _raw_values(row, names):
183
+ """Original cell values for the audit trail; a missing cell simply omits its key (no nulls)."""
184
+ values = {}
185
+ for name in names:
186
+ if name in row:
187
+ values[name] = row[name]
188
+ return values
189
+
190
+
191
+ def _rejected(index, day, reason, raw):
192
+ entry = {"index": index, "reason": reason, "values": raw}
193
+ if day is not None:
194
+ entry["date"] = day
195
+ return entry
196
+
197
+
198
+ def _clean(rows, dataset_id, time_column, volume_column, tz, threshold):
199
+ """One pass: hard rules reject, soft flags mark. Returns cleaned bars plus the audit trail."""
200
+ raw_names = (time_column,) + OHLC_COLUMNS + ((volume_column,) if volume_column is not None else ())
201
+ bars, rejected, suspects, volume_missing = [], [], [], []
202
+ seen_days = set()
203
+ time_kinds = set()
204
+ max_change = 0.0
205
+ for index, row in enumerate(rows):
206
+ if not isinstance(row, dict):
207
+ raise AnalysisInputError(f"Dataset {dataset_id} 的数据行不是对象:无法清洗")
208
+ raw_time = row.get(time_column)
209
+ if isinstance(raw_time, (int, float)) and not isinstance(raw_time, bool):
210
+ time_kinds.add("epoch_ms")
211
+ elif isinstance(raw_time, str):
212
+ time_kinds.add("iso_date")
213
+ raw = _raw_values(row, raw_names)
214
+ parsed = _parse_time(raw_time, tz)
215
+ if parsed is None:
216
+ rejected.append(_rejected(index, None, REJECT_TIME, raw))
217
+ continue
218
+ key, day = parsed
219
+ prices = {name: _number(row, name) for name in OHLC_COLUMNS}
220
+ if any(value is None or value <= 0 for value in prices.values()):
221
+ rejected.append(_rejected(index, day, REJECT_PRICE, raw))
222
+ continue
223
+ open_, high, low, close = (prices[name] for name in OHLC_COLUMNS)
224
+ if high < max(open_, close, low):
225
+ rejected.append(_rejected(index, day, REJECT_HIGH, raw))
226
+ continue
227
+ if low > min(open_, close, high):
228
+ rejected.append(_rejected(index, day, REJECT_LOW, raw))
229
+ continue
230
+ if day in seen_days:
231
+ rejected.append(_rejected(index, day, REJECT_DUPLICATE, raw))
232
+ continue
233
+ seen_days.add(day)
234
+ bar = {
235
+ "index": index,
236
+ "key": key,
237
+ "date": day,
238
+ "open": open_,
239
+ "high": high,
240
+ "low": low,
241
+ "close": close,
242
+ "volume_checked": volume_column is not None,
243
+ "volume_ok": True,
244
+ }
245
+ if volume_column is not None:
246
+ volume = _number(row, volume_column)
247
+ if volume is None or volume <= 0:
248
+ bar["volume_ok"] = False
249
+ if volume_column in row:
250
+ bar["volume_raw"] = row[volume_column]
251
+ else:
252
+ bar["volume"] = volume
253
+ bars.append(bar)
254
+
255
+ bars.sort(key=lambda bar: (bar["key"], bar["index"]))
256
+ for position, bar in enumerate(bars):
257
+ if position > 0:
258
+ change = bar["close"] / bars[position - 1]["close"] - 1.0
259
+ max_change = max(max_change, abs(change))
260
+ if abs(change) > threshold:
261
+ suspects.append({
262
+ "index": position,
263
+ "date": bar["date"],
264
+ "previous_close": _round(bars[position - 1]["close"]),
265
+ "close": _round(bar["close"]),
266
+ "change": _round(change),
267
+ })
268
+ if bar["volume_checked"] and not bar["volume_ok"]:
269
+ entry = {"index": position, "date": bar["date"]}
270
+ if "volume_raw" in bar:
271
+ entry["volume"] = bar["volume_raw"]
272
+ volume_missing.append(entry)
273
+
274
+ if time_kinds == {"epoch_ms"}:
275
+ time_format = "epoch_ms"
276
+ elif time_kinds == {"iso_date"}:
277
+ time_format = "iso_date"
278
+ elif time_kinds:
279
+ time_format = "mixed"
280
+ else:
281
+ time_format = "unknown"
282
+ return bars, rejected, suspects, volume_missing, max_change, time_format
283
+
284
+
285
+ def _series_row(bar):
286
+ row = {
287
+ "date": bar["date"],
288
+ "open": _round(bar["open"]),
289
+ "high": _round(bar["high"]),
290
+ "low": _round(bar["low"]),
291
+ "close": _round(bar["close"]),
292
+ }
293
+ if bar["volume_ok"] and "volume" in bar:
294
+ row["volume"] = _round(bar["volume"])
295
+ return row
296
+
297
+
298
+ def _breakdown(counts):
299
+ parts = [f"{reason} {counts[reason]}" for reason in REJECT_REASONS if counts[reason] > 0]
300
+ return "、".join(parts) if parts else "无"
301
+
302
+
303
+ def _summary(metrics, counts):
304
+ parts = []
305
+ if metrics["rows_cleaned"] > 0:
306
+ parts.append(
307
+ f"{metrics['first_date']}..{metrics['last_date']},共 {metrics['rows_total']} 行、"
308
+ f"清洗后 {metrics['rows_cleaned']} 根 bar({metrics['trading_days']} 个交易日)"
309
+ )
310
+ if metrics["rejected_rows"] > 0:
311
+ parts.append(f"拒绝 {metrics['rejected_rows']} 行({_breakdown(counts)})")
312
+ else:
313
+ parts.append("无硬校验拒绝")
314
+ if metrics["suspect_rows"] > 0:
315
+ parts.append(
316
+ f"可疑跳变 {metrics['suspect_rows']} 行(阈值 {_pct(metrics['jump_threshold'])},"
317
+ f"最大相邻涨跌幅 {_pct(metrics['max_abs_daily_change'])})"
318
+ )
319
+ else:
320
+ parts.append(f"无超过 {_pct(metrics['jump_threshold'])} 的相邻跳变")
321
+ else:
322
+ parts.append(
323
+ f"共 {metrics['rows_total']} 行,清洗后没有合法 bar:拒绝 {metrics['rejected_rows']} 行"
324
+ f"({_breakdown(counts)})"
325
+ )
326
+ if metrics["rows_cleaned"] > 0:
327
+ if metrics["volume_missing_rows"] > 0:
328
+ parts.append(f"成交量缺失或为 0 的 bar {metrics['volume_missing_rows']} 行(不当 0 参与统计)")
329
+ else:
330
+ parts.append("成交量无缺失标记")
331
+ parts.append(f"区间收盘 {_fmt6(metrics['first_close'])}..{_fmt6(metrics['last_close'])}")
332
+ else:
333
+ parts.append(f"jump_threshold={_fmt6(metrics['jump_threshold'])}")
334
+ head = ";".join(parts) + "。"
335
+ return head + "清洗序列只代表通过硬校验,不是数据完整或交易建议。"
336
+
337
+
338
+ def _result(status, summary, metrics, methodology, limitations, gaps, outputs):
339
+ return {
340
+ "status": status,
341
+ "summary": summary,
342
+ "metrics": metrics,
343
+ "claims": [],
344
+ "assumptions": list(ASSUMPTIONS),
345
+ "methodology_log": methodology,
346
+ "sensitivity": {},
347
+ "limitations": limitations,
348
+ "data_gaps": gaps,
349
+ "outputs": outputs,
350
+ }
351
+
352
+
353
+ def _read_views(request, context):
354
+ items = (request.get("inputs") or {}).get("datasets") or []
355
+ if not items:
356
+ raise AnalysisInputError("快照里没有任何 Dataset:先取一份日 K 行情再建快照")
357
+ views = {}
358
+ for item in items:
359
+ dataset_id = (item or {}).get("dataset_id")
360
+ if not isinstance(dataset_id, str) or not dataset_id:
361
+ raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
362
+ views[dataset_id] = context.read_dataset(dataset_id)
363
+ for dataset_id, view in views.items():
364
+ if view.get("shape") != "rows":
365
+ raise AnalysisInputError(
366
+ f"Dataset {dataset_id} 是 {view.get('shape')} 型:kline_quality 只吃表格数据,"
367
+ "文档型输入请先走 profile 或证据"
368
+ )
369
+ return views
370
+
371
+
372
+ def _candidates(views, time_override):
373
+ """Dataset ids that look like a daily OHLC table: a time column plus all four OHLC columns."""
374
+ candidates = []
375
+ for dataset_id, view in sorted(views.items()):
376
+ names = _columns_of(view)
377
+ if any(name not in names for name in OHLC_COLUMNS):
378
+ continue
379
+ try:
380
+ time_column = _time_column(view, time_override)
381
+ except AnalysisInputError:
382
+ continue
383
+ candidates.append((dataset_id, time_column))
384
+ return candidates
385
+
386
+
387
+ def analyze(request: dict, context) -> dict:
388
+ params = request.get("params") or {}
389
+ views = _read_views(request, context)
390
+ time_override = _text(params.get("time_column"))
391
+
392
+ price_dataset_id = _text(params.get("price_dataset_id"))
393
+ if price_dataset_id is not None:
394
+ if price_dataset_id not in views:
395
+ raise AnalysisInputError(f"price_dataset_id={price_dataset_id} 不在本次快照的 Dataset 里")
396
+ price_view = views[price_dataset_id]
397
+ else:
398
+ candidates = _candidates(views, time_override)
399
+ if len(candidates) > 1:
400
+ raise AnalysisInputError(
401
+ f"有 {len(candidates)} 份 Dataset 都像日 K 表({'、'.join(item[0] for item in candidates)}):"
402
+ "用 price_dataset_id 指明用哪一份"
403
+ )
404
+ if not candidates:
405
+ detail = f"(time_column={time_override} 不在任何 Dataset 里)" if time_override else ""
406
+ raise AnalysisInputError(
407
+ f"没有可识别的日 K Dataset{detail}:需要 open/high/low/close 四列 + 时间列"
408
+ "(time_coverage 或 trade_date_ms / date / time 等)"
409
+ )
410
+ price_dataset_id = candidates[0][0]
411
+ price_view = views[price_dataset_id]
412
+
413
+ rows = price_view.get("rows") or []
414
+ if not rows:
415
+ raise AnalysisInputError(f"Dataset {price_dataset_id} 没有数据行:没有可清洗的 K 线")
416
+
417
+ time_column = _time_column(price_view, time_override)
418
+ _require_ohlc(price_view, price_dataset_id)
419
+ volume_column = "volume" if "volume" in _columns_of(price_view) else None
420
+ tz = _timezone(_text(params.get("timezone")))
421
+ threshold = _threshold(params.get("jump_threshold"))
422
+
423
+ bars, rejected, suspects, volume_missing, max_change, time_format = _clean(
424
+ rows, price_dataset_id, time_column, volume_column, tz, threshold
425
+ )
426
+ counts = {reason: 0 for reason in REJECT_REASONS}
427
+ for entry in rejected:
428
+ counts[entry["reason"]] += 1
429
+
430
+ metrics = {
431
+ "rows_total": len(rows),
432
+ "rows_cleaned": len(bars),
433
+ "rejected_rows": len(rejected),
434
+ "suspect_rows": len(suspects),
435
+ "volume_missing_rows": len(volume_missing),
436
+ "duplicate_dates": counts[REJECT_DUPLICATE],
437
+ "trading_days": len(bars),
438
+ "jump_threshold": threshold,
439
+ "max_abs_daily_change": _round(max_change),
440
+ }
441
+ for reason in REJECT_REASONS:
442
+ metrics[f"rejected_{reason}"] = counts[reason]
443
+ if bars:
444
+ metrics["first_date"] = bars[0]["date"]
445
+ metrics["last_date"] = bars[-1]["date"]
446
+ metrics["first_close"] = _round(bars[0]["close"])
447
+ metrics["last_close"] = _round(bars[-1]["close"])
448
+
449
+ limitations = list(LIMITATIONS)
450
+ if volume_column is None:
451
+ limitations.append("Dataset 没有 volume 列:本次未做成交量体检(成交量缺失不计入 volume_missing_rows)")
452
+ if time_format == "mixed":
453
+ limitations.append("时间列混用了 epoch 毫秒与 ISO 日期:按各自解析后的时间排序,跨时区比较前先对齐口径")
454
+ if price_view.get("truncated"):
455
+ limitations.append(
456
+ f"输入超过 max_input_rows 被截断:只清洗了前 {len(rows)} 行,不能据此判断整段序列的质量"
457
+ )
458
+
459
+ methodology = [
460
+ f"行情 Dataset {price_dataset_id}:时间列 {time_column}、OHLC 列 open/high/low/close、"
461
+ + (f"成交量列 {volume_column}" if volume_column is not None else "无成交量列"),
462
+ f"时间轴 {time_format},日期按 {_text(params.get('timezone')) or 'UTC'} 标注;"
463
+ f"输入 {len(rows)} 行,清洗后 {len(bars)} 根 bar",
464
+ f"硬校验拒绝 {len(rejected)} 行({_breakdown(counts)});"
465
+ f"软标记 suspect_jump {len(suspects)} 行、volume_missing {len(volume_missing)} 行",
466
+ f"相邻收盘涨跌幅 = 清洗序列相邻两根 bar 的 close 比值 − 1,绝对值严格大于 {_fmt6(threshold)} 才标记;"
467
+ f"{max(len(bars) - 1, 0)} 个相邻变化,最大绝对 {_fmt6(max_change)}",
468
+ ]
469
+
470
+ gaps = []
471
+ if not bars:
472
+ gaps.append(
473
+ f"清洗后没有合法 bar:{len(rows)} 行全部被拒绝({_breakdown(counts)}):"
474
+ f"明细见 outputs/{OUTPUT_NAME}.json"
475
+ )
476
+ elif rejected:
477
+ gaps.append(f"硬校验拒绝 {len(rejected)} 行({_breakdown(counts)}):明细见 outputs/{OUTPUT_NAME}.json")
478
+ if suspects:
479
+ gaps.append(
480
+ f"相邻收盘涨跌幅超过阈值 {_pct(threshold)} 的 bar {len(suspects)} 行"
481
+ f"(最大 {_pct(max_change)}):已标 suspect_jump,保留在清洗序列"
482
+ )
483
+
484
+ if not bars:
485
+ status = "blocked"
486
+ elif rejected or suspects:
487
+ status = "partial"
488
+ else:
489
+ status = "completed"
490
+
491
+ payload = {
492
+ "protocol": "capital.analysis/v1",
493
+ "module_id": MODULE_ID,
494
+ "module_version": MODULE_VERSION,
495
+ "analysis_id": request.get("analysis_id"),
496
+ "module_run_id": request.get("module_run_id"),
497
+ "price_dataset_id": price_dataset_id,
498
+ "columns": {
499
+ "time": time_column,
500
+ **{name: name for name in OHLC_COLUMNS},
501
+ **({"volume": volume_column} if volume_column is not None else {}),
502
+ },
503
+ "time_axis": {
504
+ "column": time_column,
505
+ "format": time_format,
506
+ "timezone": _text(params.get("timezone")) or "UTC",
507
+ },
508
+ "parameters": {
509
+ "jump_threshold": threshold,
510
+ "timezone": _text(params.get("timezone")) or "UTC",
511
+ },
512
+ "window": {
513
+ "rows_total": len(rows),
514
+ "rows_cleaned": len(bars),
515
+ **({"start": bars[0]["date"], "end": bars[-1]["date"]} if bars else {}),
516
+ },
517
+ "statistics": metrics,
518
+ "rejected": rejected,
519
+ "suspects": suspects,
520
+ "volume_missing": volume_missing,
521
+ "series": [_series_row(bar) for bar in bars],
522
+ "data_gaps": gaps,
523
+ }
524
+ ref = context.write_output(OUTPUT_NAME, payload)
525
+ context.log(
526
+ f"{MODULE_ID}: {status} rows={len(rows)} cleaned={len(bars)} rejected={len(rejected)} "
527
+ f"suspect={len(suspects)} volume_missing={len(volume_missing)}"
528
+ )
529
+
530
+ return _result(
531
+ status,
532
+ _summary(metrics, counts),
533
+ metrics,
534
+ methodology,
535
+ limitations,
536
+ gaps,
537
+ [{"name": OUTPUT_NAME, "ref": ref}],
538
+ )
@@ -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,89 @@
1
+ {
2
+ "id": "portfolio_stress",
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
+ "positions": {
14
+ "type": "array",
15
+ "maxItems": 30,
16
+ "items": {
17
+ "type": "object",
18
+ "properties": {
19
+ "dataset_id": { "type": "string", "maxLength": 128, "description": "该持仓的价格序列 Dataset" },
20
+ "weight": { "type": "number", "minimum": 0, "description": "权重(小数,0.25 = 25%);所有持仓权重之和必须为 1" }
21
+ },
22
+ "required": ["dataset_id", "weight"],
23
+ "additionalProperties": false
24
+ },
25
+ "description": "持仓列表:每个元素一份价格序列 Dataset + 权重"
26
+ },
27
+ "windows": {
28
+ "type": "array",
29
+ "maxItems": 12,
30
+ "items": {
31
+ "type": "object",
32
+ "properties": {
33
+ "name": { "type": "string", "maxLength": 64, "description": "窗口名称,如 2024-回调 / Q3-2024" },
34
+ "start": { "type": "string", "maxLength": 10, "description": "窗口起始日 YYYY-MM-DD" },
35
+ "end": { "type": "string", "maxLength": 10, "description": "窗口结束日 YYYY-MM-DD(含)" }
36
+ },
37
+ "required": ["name", "start", "end"],
38
+ "additionalProperties": false
39
+ },
40
+ "description": "历史窗口列表:只回放已发生的区间,不接受未来日期"
41
+ },
42
+ "price_column": { "type": "string", "maxLength": 64, "description": "价格列名;省略按 close / adj_close / close_price / price / nav 识别" },
43
+ "time_column": { "type": "string", "maxLength": 64, "description": "时间列名;省略优先用 time_coverage 列,再按 trade_date_ms / date 等识别" },
44
+ "timezone": { "type": "string", "maxLength": 64, "description": "数值时间轴(epoch 毫秒)标注日期用的 IANA 时区;省略按 UTC" }
45
+ },
46
+ "required": ["positions", "windows"],
47
+ "additionalProperties": false
48
+ },
49
+ "output_schema": {
50
+ "type": "object",
51
+ "properties": {
52
+ "status": { "type": "string", "enum": ["completed", "partial", "blocked", "failed"] },
53
+ "summary": { "type": "string" },
54
+ "metrics": { "type": "object" },
55
+ "claims": { "type": "array" },
56
+ "assumptions": { "type": "array" },
57
+ "methodology_log": { "type": "array" },
58
+ "sensitivity": { "type": "object" },
59
+ "limitations": { "type": "array" },
60
+ "data_gaps": { "type": "array" },
61
+ "outputs": { "type": "array" }
62
+ },
63
+ "required": [
64
+ "status", "summary", "metrics", "claims", "assumptions", "methodology_log",
65
+ "sensitivity", "limitations", "data_gaps", "outputs"
66
+ ],
67
+ "additionalProperties": false
68
+ },
69
+ "assumptions": [
70
+ "权重是调用方给的静态组合权重:回放期间不再平衡,也不考虑现金流出入、分红与税费",
71
+ "组合窗口收益 = Σ 权重 × 该持仓窗口收益;持仓收益按窗口内首个与最后一个可用收盘价计算",
72
+ "窗口是已发生的历史区间:start 必须早于 end,且两端的交易日必须落在价格序列覆盖范围内;越界写缺口,不向前/向后找替代日期",
73
+ "集中度只用调用方权重计算(HHI = Σ w²、最大单持仓权重),与价格数据无关",
74
+ "历史情景回放只说明这些窗口里组合会怎样;不是压力测试的假设情景,不预测、不评级,也不给仓位建议"
75
+ ],
76
+ "applicability": [
77
+ "1–30 个持仓,每个持仓一份价格序列 Dataset;权重非负且合计为 1(容差 1e-6)",
78
+ "窗口 1–12 个,日期为 YYYY-MM-DD,且全部落在数据覆盖范围内;同一窗口内所有持仓都必须有起止价格",
79
+ "只支持多资产静态权重组合;需要动态调仓、汇率换算或期权敞口时不适用",
80
+ "不适用于未来情景假设(用 scenario_sensitivity)、归因或业绩基准比较"
81
+ ],
82
+ "limits": {
83
+ "timeout_ms": 30000,
84
+ "max_input_rows": 200000,
85
+ "max_output_bytes": 1048576,
86
+ "max_log_bytes": 65536
87
+ },
88
+ "provenance": { "source_type": "original", "license": "MIT" }
89
+ }