@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,452 @@
1
+ """Earnings bridge: decompose the change in net profit into reproducible effects.
2
+
3
+ Two exact decompositions over adjacent periods, both of which must add back up to the net-profit
4
+ difference:
5
+
6
+ - revenue / margin: NP = revenue × net_margin, so ΔNP splits into a revenue effect, a margin effect
7
+ and their interaction;
8
+ - pre-tax / tax rate: NP = profit_total × (1 − tax_rate), so ΔNP splits into a pre-tax effect, a
9
+ tax-rate effect and their interaction.
10
+
11
+ The input is one income-statement Dataset with at least two periods. The module only explains the
12
+ difference that already happened: it does not forecast the next period, does not label an effect as
13
+ good or bad, and never emits a rating or a target price.
14
+
15
+ Protocol: `docs/dev/senior-analysis.md` §1.9. Conclusions and claims belong to the senior analyst;
16
+ this module only produces reproducible effects plus the input values behind each one.
17
+ """
18
+ from __future__ import annotations
19
+
20
+ from datetime import datetime, timezone
21
+
22
+ MODULE_ID = "earnings_bridge"
23
+ MODULE_VERSION = "1.0.0"
24
+ OUTPUT_NAME = "earnings_bridge"
25
+
26
+ # Mirrors module.json `assumptions`: a result must state the same caveats the manifest promises.
27
+ ASSUMPTIONS = [
28
+ "收入/净利率分解:net_profit = operating_income × net_margin,差额拆成收入效应、净利率效应与两者交互项,三项之和必须等于净利润差额",
29
+ "税前/税率分解:net_profit = profit_total × (1 − tax_rate),tax_rate = income_tax_expense / profit_total,只对 profit_total > 0 的两期计算;三期效应之和必须等于净利润差额",
30
+ "两期必须来自同一份利润表 Dataset、同一币种与同一合并口径;模块不检查会计政策变更或追溯调整",
31
+ "效应为正表示对净利润变动是正贡献;交互项是两因子同时变动的交叉部分,不小到可以忽略时不得略去",
32
+ "不输出评级、目标价或预测:归因只解释已经发生的差额,不外推下一期",
33
+ ]
34
+
35
+ LIMITATIONS = [
36
+ "归因是恒等式分解,不说明变动的原因:收入为什么变、净利率为什么变不在本模块的回答范围内",
37
+ "两期口径不一致(如合并范围变化、会计政策变更、追溯重述)会让效应失真,模块无法自动识别",
38
+ "交互项同时包含收入与净利率的变化,不能单独归给任一方;报告时必须保留三项,不许合并或略去",
39
+ "不构成投资建议,也不产生评级、目标价或收益承诺",
40
+ ]
41
+
42
+ SIGNATURE = ("operating_income", "net_profit")
43
+ PERIOD_KEYS = ("period_end_ms", "period")
44
+ ROUND = 6
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), ROUND)
55
+ return 0.0 if rounded == 0 else rounded
56
+
57
+
58
+ def _plain(value):
59
+ return int(value) if isinstance(value, float) and value.is_integer() else value
60
+
61
+
62
+ def _amount(value):
63
+ """Money is integer yuan in the source; binary float noise below 0.00001 is not a real amount."""
64
+ if value is None:
65
+ return None
66
+ nearest = round(float(value))
67
+ if abs(float(value) - nearest) <= 1e-5:
68
+ return int(nearest)
69
+ return _round(value)
70
+
71
+
72
+ def _number(row, name):
73
+ if row is None:
74
+ return None
75
+ value = row.get(name)
76
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
77
+ return None
78
+ number = float(value)
79
+ if number != number or number in (float("inf"), float("-inf")):
80
+ return None
81
+ return number
82
+
83
+
84
+ def _columns_of(view):
85
+ columns = view.get("columns") or []
86
+ names = {item.get("name") for item in columns if isinstance(item, dict)}
87
+ for row in (view.get("rows") or [])[:1]:
88
+ if isinstance(row, dict):
89
+ names |= set(row)
90
+ return names
91
+
92
+
93
+ def _read_datasets(request, context):
94
+ items = (request.get("inputs") or {}).get("datasets") or []
95
+ if not items:
96
+ raise AnalysisInputError("快照里没有任何 Dataset:earnings_bridge 需要一份利润表序列")
97
+ views = {}
98
+ for item in items:
99
+ dataset_id = (item or {}).get("dataset_id")
100
+ if not isinstance(dataset_id, str) or not dataset_id:
101
+ raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
102
+ views[dataset_id] = context.read_dataset(dataset_id)
103
+ for dataset_id, view in views.items():
104
+ if view.get("shape") != "rows":
105
+ raise AnalysisInputError(
106
+ f"Dataset {dataset_id} 是 {view.get('shape')} 型:earnings_bridge 只吃表格数据,"
107
+ "文档型输入请先走 profile 或证据"
108
+ )
109
+ return views
110
+
111
+
112
+ def _select_dataset(views, params):
113
+ explicit = params.get("income_dataset_id")
114
+ if isinstance(explicit, str) and explicit:
115
+ if explicit not in views:
116
+ raise AnalysisInputError(f"income_dataset_id={explicit} 不在本次快照的 Dataset 里")
117
+ missing = [name for name in SIGNATURE if name not in _columns_of(views[explicit])]
118
+ if missing:
119
+ raise AnalysisInputError(f"income Dataset {explicit} 缺少 {'、'.join(missing)} 列:不是利润表")
120
+ return explicit
121
+ candidates = sorted(
122
+ dataset_id for dataset_id, view in views.items()
123
+ if all(name in _columns_of(view) for name in SIGNATURE)
124
+ )
125
+ if not candidates:
126
+ raise AnalysisInputError(
127
+ "没有 Dataset 同时含 operating_income 与 net_profit:earnings_bridge 需要一份利润表序列"
128
+ )
129
+ if len(candidates) > 1:
130
+ raise AnalysisInputError(
131
+ f"有 {len(candidates)} 份 Dataset 都像利润表({'、'.join(candidates)}):用 income_dataset_id 指明用哪一份"
132
+ )
133
+ return candidates[0]
134
+
135
+
136
+ def _join_key(view):
137
+ columns = _columns_of(view)
138
+ for name in PERIOD_KEYS:
139
+ if name in columns:
140
+ return name
141
+ raise AnalysisInputError("利润表缺少报告期键:需要 period_end_ms 或 period 列,否则无法对齐两期")
142
+
143
+
144
+ def _index_rows(view, column):
145
+ indexed = {}
146
+ for row in view.get("rows") or []:
147
+ if not isinstance(row, dict):
148
+ raise AnalysisInputError("利润表的数据行不是对象:无法计算")
149
+ key = row.get(column)
150
+ if isinstance(key, bool) or not isinstance(key, (int, float, str)) or key == "":
151
+ raise AnalysisInputError(f"利润表的 {column} 列有空值:无法对齐报告期")
152
+ if key in indexed:
153
+ raise AnalysisInputError(f"利润表在报告期 {key} 出现多行:无法判断用哪一行(请先去重)")
154
+ indexed[key] = row
155
+ return indexed
156
+
157
+
158
+ def _iso_date(ms):
159
+ return datetime.fromtimestamp(float(ms) / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
160
+
161
+
162
+ def _label(rows, key, key_column):
163
+ row = rows.get(key)
164
+ text = row.get("period") if isinstance(row, dict) else None
165
+ if isinstance(text, str) and text and any(ch.isdigit() for ch in text):
166
+ return text
167
+ if key_column == "period_end_ms" and isinstance(key, (int, float)) and not isinstance(key, bool):
168
+ return _iso_date(key)
169
+ return str(key)
170
+
171
+
172
+ def _period_candidates(rows, key, key_column):
173
+ values = {str(key), _label(rows, key, key_column)}
174
+ row = rows.get(key)
175
+ if isinstance(row, dict):
176
+ year = row.get("fiscal_year")
177
+ if isinstance(year, int) and not isinstance(year, bool):
178
+ values.add(str(year))
179
+ period = row.get("fiscal_period")
180
+ if isinstance(period, str) and period:
181
+ values.add(f"{year}-{period}")
182
+ return values
183
+
184
+
185
+ def _select_period(rows, params, key_column):
186
+ if not rows:
187
+ raise AnalysisInputError("利润表没有数据行:无法计算两期归因")
188
+ requested = params.get("period")
189
+ if isinstance(requested, str) and requested.strip():
190
+ wanted = requested.strip()
191
+ matches = [key for key in rows if wanted in _period_candidates(rows, key, key_column)]
192
+ if not matches:
193
+ available = "、".join(_label(rows, key, key_column) for key in sorted(rows))
194
+ raise AnalysisInputError(f"报告期 {wanted} 不在这份利润表里;可选:{available}")
195
+ if len(matches) > 1:
196
+ labels = "、".join(_label(rows, key, key_column) for key in sorted(matches))
197
+ raise AnalysisInputError(f"报告期 {wanted} 同时匹配多个报告期({labels}):请写完整报告期")
198
+ return matches[0]
199
+ return max(rows)
200
+
201
+
202
+ def _signed(value):
203
+ return f"+{value}" if value > 0 else str(value)
204
+
205
+
206
+ def _revenue_bridge(previous, current):
207
+ revenue_prev = _number(previous, "operating_income")
208
+ revenue_cur = _number(current, "operating_income")
209
+ net_prev = _number(previous, "net_profit")
210
+ net_cur = _number(current, "net_profit")
211
+ if revenue_prev is None or revenue_cur is None or net_prev is None or net_cur is None:
212
+ return None, "两期营业收入或净利润有空值(或非数字):收入/净利率分解无法计算"
213
+ if revenue_prev <= 0 or revenue_cur <= 0:
214
+ return None, "两期营业收入存在 ≤ 0:净利率没有经济含义,收入/净利率分解无法计算"
215
+ margin_prev = net_prev / revenue_prev
216
+ margin_cur = net_cur / revenue_cur
217
+ change = net_cur - net_prev
218
+ delta_revenue = revenue_cur - revenue_prev
219
+ delta_margin = margin_cur - margin_prev
220
+ revenue_effect = delta_revenue * margin_prev
221
+ margin_effect = revenue_prev * delta_margin
222
+ interaction = delta_revenue * delta_margin
223
+ residual = change - (revenue_effect + margin_effect + interaction)
224
+ return {
225
+ "revenue_previous": _amount(revenue_prev),
226
+ "revenue_current": _amount(revenue_cur),
227
+ "net_margin_previous": _round(margin_prev),
228
+ "net_margin_current": _round(margin_cur),
229
+ "revenue_effect": _amount(revenue_effect),
230
+ "margin_effect": _amount(margin_effect),
231
+ "interaction_effect": _amount(interaction),
232
+ "bridge_residual": _amount(residual),
233
+ "formula": "ΔNP = ΔRevenue × margin_prev + Revenue_prev × Δmargin + ΔRevenue × Δmargin",
234
+ }, None
235
+
236
+
237
+ def _tax_bridge(previous, current):
238
+ profit_prev = _number(previous, "profit_total")
239
+ profit_cur = _number(current, "profit_total")
240
+ tax_prev = _number(previous, "income_tax_expense")
241
+ tax_cur = _number(current, "income_tax_expense")
242
+ net_prev = _number(previous, "net_profit")
243
+ net_cur = _number(current, "net_profit")
244
+ if None in (profit_prev, profit_cur, tax_prev, tax_cur, net_prev, net_cur):
245
+ return None, "两期利润总额、所得税费用或净利润有空值(或非数字):税前/税率分解无法计算"
246
+ if profit_prev <= 0 or profit_cur <= 0:
247
+ return None, "两期利润总额存在 ≤ 0:税率没有经济含义,税前/税率分解无法计算"
248
+ rate_prev = tax_prev / profit_prev
249
+ rate_cur = tax_cur / profit_cur
250
+ change = net_cur - net_prev
251
+ delta_profit = profit_cur - profit_prev
252
+ delta_rate = rate_cur - rate_prev
253
+ pretax_effect = delta_profit * (1 - rate_prev)
254
+ tax_effect = profit_prev * (-delta_rate)
255
+ interaction = delta_profit * (-delta_rate)
256
+ residual = change - (pretax_effect + tax_effect + interaction)
257
+ return {
258
+ "profit_total_previous": _amount(profit_prev),
259
+ "profit_total_current": _amount(profit_cur),
260
+ "tax_rate_previous": _round(rate_prev),
261
+ "tax_rate_current": _round(rate_cur),
262
+ "pretax_effect": _amount(pretax_effect),
263
+ "tax_rate_effect": _amount(tax_effect),
264
+ "tax_interaction_effect": _amount(interaction),
265
+ "tax_bridge_residual": _amount(residual),
266
+ "formula": "ΔNP = ΔProfit_total × (1 − tax_prev) − Profit_total_prev × Δtax − ΔProfit_total × Δtax",
267
+ }, None
268
+
269
+
270
+ def _summary(current_label, previous_label, nets, revenue_bridge, tax_bridge, gaps):
271
+ net_prev, net_cur, change = nets
272
+ if net_prev is None or net_cur is None:
273
+ return f"{current_label} 较 {previous_label}:两期净利润有空值,无法计算差额与归因(见 data_gaps)。"
274
+ head = f"{current_label} 较 {previous_label}:净利润 {_amount(net_prev)} → {_amount(net_cur)}({_signed(_amount(change))})。"
275
+ parts = []
276
+ if revenue_bridge:
277
+ parts.append(
278
+ f"收入效应 {_signed(revenue_bridge['revenue_effect'])}、净利率效应 {_signed(revenue_bridge['margin_effect'])}、"
279
+ f"交互 {_signed(revenue_bridge['interaction_effect'])}(合计校验 {_signed(revenue_bridge['bridge_residual'])})"
280
+ )
281
+ else:
282
+ parts.append("收入/净利率分解未执行")
283
+ if tax_bridge:
284
+ parts.append(
285
+ f"税前效应 {_signed(tax_bridge['pretax_effect'])}、税率效应 {_signed(tax_bridge['tax_rate_effect'])}、"
286
+ f"交互 {_signed(tax_bridge['tax_interaction_effect'])}(合计校验 {_signed(tax_bridge['tax_bridge_residual'])})"
287
+ )
288
+ if gaps:
289
+ parts.append(f"{len(gaps)} 项缺口")
290
+ return head + "归因:" + ";".join(parts) + "。"
291
+
292
+
293
+ def analyze(request: dict, context) -> dict:
294
+ params = request.get("params") or {}
295
+ views = _read_datasets(request, context)
296
+ dataset_id = _select_dataset(views, params)
297
+ view = views[dataset_id]
298
+ methodology = [f"利润表 = {dataset_id}"]
299
+ limitations = list(LIMITATIONS)
300
+ gaps = []
301
+
302
+ if view.get("truncated"):
303
+ limitations.append(
304
+ f"利润表被截断到 {len(view.get('rows') or [])} 行(max_input_rows):归因只覆盖截断后的样本"
305
+ )
306
+ key_column = _join_key(view)
307
+ if key_column == "period":
308
+ limitations.append("报告期按 period 字符串排序(没有 period_end_ms 列):格式不一致时可能选错两期")
309
+ rows = _index_rows(view, key_column)
310
+ current_key = _select_period(rows, params, key_column)
311
+ current_label = _label(rows, current_key, key_column)
312
+ previous_keys = [key for key in rows if key < current_key]
313
+ methodology.append(f"报告期键 {key_column};本期 {current_label}")
314
+
315
+ if not previous_keys:
316
+ gaps.append(f"没有早于 {current_label} 的报告期:两期归因无法计算")
317
+ current = rows[current_key]
318
+ nets = (_number(current, "net_profit"), _number(current, "net_profit"), 0.0)
319
+ status = "blocked"
320
+ metrics = {"net_profit_current": _amount(nets[1])}
321
+ payload = {
322
+ "protocol": "capital.analysis/v1",
323
+ "module_id": MODULE_ID,
324
+ "module_version": MODULE_VERSION,
325
+ "analysis_id": request.get("analysis_id"),
326
+ "module_run_id": request.get("module_run_id"),
327
+ "income_dataset_id": dataset_id,
328
+ "period": current_label,
329
+ "previous_period": None,
330
+ "metrics": metrics,
331
+ "revenue_bridge": None,
332
+ "tax_bridge": None,
333
+ "data_gaps": gaps,
334
+ }
335
+ ref = context.write_output(OUTPUT_NAME, payload)
336
+ context.log(f"{MODULE_ID}: blocked period={current_label} gaps={len(gaps)}")
337
+ return {
338
+ "status": status,
339
+ "summary": f"{current_label} 只有一期利润表:无法计算两期归因(见 data_gaps)。",
340
+ "metrics": metrics,
341
+ "claims": [],
342
+ "assumptions": list(ASSUMPTIONS),
343
+ "methodology_log": methodology,
344
+ "sensitivity": {},
345
+ "limitations": limitations,
346
+ "data_gaps": gaps,
347
+ "outputs": [{"name": OUTPUT_NAME, "ref": ref}],
348
+ }
349
+
350
+ previous_key = max(previous_keys)
351
+ previous_label = _label(rows, previous_key, key_column)
352
+ previous = rows[previous_key]
353
+ current = rows[current_key]
354
+ methodology.append(f"上一期 {previous_label}")
355
+
356
+ net_prev = _number(previous, "net_profit")
357
+ net_cur = _number(current, "net_profit")
358
+ metrics = {}
359
+ if net_prev is None or net_cur is None:
360
+ gaps.append("两期净利润有空值(或非数字):差额无法计算")
361
+ status = "blocked"
362
+ nets = (None, None, None)
363
+ else:
364
+ change = net_cur - net_prev
365
+ nets = (net_prev, net_cur, change)
366
+ metrics.update({
367
+ "net_profit_previous": _amount(net_prev),
368
+ "net_profit_current": _amount(net_cur),
369
+ "net_profit_change": _amount(change),
370
+ })
371
+ status = "completed"
372
+
373
+ revenue_bridge, revenue_gap = (None, "两期净利润不可用")
374
+ tax_bridge, tax_gap = (None, None)
375
+ if nets[0] is not None:
376
+ revenue_bridge, revenue_gap = _revenue_bridge(previous, current)
377
+ tax_bridge, tax_gap = _tax_bridge(previous, current)
378
+ if revenue_gap:
379
+ gaps.append(f"收入/净利率分解未执行:{revenue_gap}")
380
+ else:
381
+ metrics.update({
382
+ "revenue_previous": revenue_bridge["revenue_previous"],
383
+ "revenue_current": revenue_bridge["revenue_current"],
384
+ "net_margin_previous": revenue_bridge["net_margin_previous"],
385
+ "net_margin_current": revenue_bridge["net_margin_current"],
386
+ "revenue_effect": revenue_bridge["revenue_effect"],
387
+ "margin_effect": revenue_bridge["margin_effect"],
388
+ "interaction_effect": revenue_bridge["interaction_effect"],
389
+ "bridge_residual": revenue_bridge["bridge_residual"],
390
+ })
391
+ methodology.append(
392
+ f"收入/净利率分解:ΔRevenue={_amount(revenue_bridge['revenue_current'] - revenue_bridge['revenue_previous'])},"
393
+ f"Δmargin={_round(revenue_bridge['net_margin_current'] - revenue_bridge['net_margin_previous'])},"
394
+ f"三项合计与差额的残差 {revenue_bridge['bridge_residual']}"
395
+ )
396
+ if tax_gap:
397
+ gaps.append(f"税前/税率分解未执行:{tax_gap}")
398
+ else:
399
+ metrics.update({
400
+ "profit_total_previous": tax_bridge["profit_total_previous"],
401
+ "profit_total_current": tax_bridge["profit_total_current"],
402
+ "tax_rate_previous": tax_bridge["tax_rate_previous"],
403
+ "tax_rate_current": tax_bridge["tax_rate_current"],
404
+ "pretax_effect": tax_bridge["pretax_effect"],
405
+ "tax_rate_effect": tax_bridge["tax_rate_effect"],
406
+ "tax_interaction_effect": tax_bridge["tax_interaction_effect"],
407
+ "tax_bridge_residual": tax_bridge["tax_bridge_residual"],
408
+ })
409
+ methodology.append(
410
+ f"税前/税率分解:ΔProfit_total={_amount(tax_bridge['profit_total_current'] - tax_bridge['profit_total_previous'])},"
411
+ f"Δtax_rate={_round(tax_bridge['tax_rate_current'] - tax_bridge['tax_rate_previous'])},"
412
+ f"三项合计与差额的残差 {tax_bridge['tax_bridge_residual']}"
413
+ )
414
+
415
+ if revenue_gap and tax_gap:
416
+ status = "blocked"
417
+ elif gaps:
418
+ status = "partial"
419
+ elif status != "blocked":
420
+ status = "completed"
421
+ if nets[0] is not None:
422
+ limitations.append("交互项不是误差项:它同时含两个因子的变化,报告时不要并入收入或净利率")
423
+
424
+ payload = {
425
+ "protocol": "capital.analysis/v1",
426
+ "module_id": MODULE_ID,
427
+ "module_version": MODULE_VERSION,
428
+ "analysis_id": request.get("analysis_id"),
429
+ "module_run_id": request.get("module_run_id"),
430
+ "income_dataset_id": dataset_id,
431
+ "period": current_label,
432
+ "previous_period": previous_label,
433
+ "period_key": key_column,
434
+ "metrics": metrics,
435
+ "revenue_bridge": revenue_bridge,
436
+ "tax_bridge": tax_bridge,
437
+ "data_gaps": gaps,
438
+ }
439
+ ref = context.write_output(OUTPUT_NAME, payload)
440
+ context.log(f"{MODULE_ID}: {status} period={current_label} previous={previous_label} gaps={len(gaps)}")
441
+ return {
442
+ "status": status,
443
+ "summary": _summary(current_label, previous_label, nets, revenue_bridge, tax_bridge, gaps),
444
+ "metrics": metrics,
445
+ "claims": [],
446
+ "assumptions": list(ASSUMPTIONS),
447
+ "methodology_log": methodology,
448
+ "sensitivity": {},
449
+ "limitations": limitations,
450
+ "data_gaps": gaps,
451
+ "outputs": [{"name": OUTPUT_NAME, "ref": ref}],
452
+ }
@@ -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,61 @@
1
+ {
2
+ "id": "kline_quality",
3
+ "version": "1.0.0",
4
+ "entrypoint": "module.py",
5
+ "runtime": "python",
6
+ "description": "日 K 线清洗与体检:OHLC 关系、非正价格、重复日期、缺失成交量与异常跳变逐行留痕,输出可直接用于下游的清洗序列;不预测、不评级",
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": "K 线 Dataset;只有一份像 OHLC 表时可省略" },
14
+ "time_column": { "type": "string", "maxLength": 64, "description": "时间列名;省略时优先用 Dataset 的 time_coverage 列,再按 trade_date_ms / date / time 等识别" },
15
+ "timezone": { "type": "string", "maxLength": 64, "description": "数值时间轴(epoch 毫秒)标注日期用的 IANA 时区,如 Asia/Shanghai;省略按 UTC 标注" },
16
+ "jump_threshold": { "type": "number", "minimum": 0, "description": "相邻收盘价涨跌幅超过该值(小数,默认 0.5 = 50%)标为可疑 bar;只标记不删除,阈值原样写进结果" }
17
+ },
18
+ "additionalProperties": false
19
+ },
20
+ "output_schema": {
21
+ "type": "object",
22
+ "properties": {
23
+ "status": { "type": "string", "enum": ["completed", "partial", "blocked", "failed"] },
24
+ "summary": { "type": "string" },
25
+ "metrics": { "type": "object" },
26
+ "claims": { "type": "array" },
27
+ "assumptions": { "type": "array" },
28
+ "methodology_log": { "type": "array" },
29
+ "sensitivity": { "type": "object" },
30
+ "limitations": { "type": "array" },
31
+ "data_gaps": { "type": "array" },
32
+ "outputs": { "type": "array" }
33
+ },
34
+ "required": [
35
+ "status", "summary", "metrics", "claims", "assumptions", "methodology_log",
36
+ "sensitivity", "limitations", "data_gaps", "outputs"
37
+ ],
38
+ "additionalProperties": false
39
+ },
40
+ "assumptions": [
41
+ "一根 bar 合法当且仅当:时间可解析、open/high/low/close 都是正数、high ≥ max(open, close, low)、low ≤ min(open, close, high)",
42
+ "时间列是 ISO 日期(YYYY-MM-DD)或 epoch 毫秒;同一交易日出现多行时保留第一行时间,其余行以 duplicate_date 拒绝并计数",
43
+ "成交量缺失或为 0 不当作 0 参与统计:只标 volume_missing,价格 bar 仍进清洗序列",
44
+ "价格口径沿用 Dataset 的取数参数(qfq / hfq / none);本模块不检测也不做复权调整,除权日的跳变可能被标成可疑",
45
+ "jump_threshold 只用于标记可疑 bar,不删除、不改写价格;阈值由调用方给出并写进结果,不是涨跌预测",
46
+ "清洗序列只是通过硬校验的 bar:不代表数据完整,也不代表可以据此交易"
47
+ ],
48
+ "applicability": [
49
+ "单只标的的日频 K 线:一行一个交易日,含 open/high/low/close(volume 可选)",
50
+ "A 股、港股、美股与指数的日 K 均可;分钟级、跨市场拼接或缺失整段时间的数据不适用",
51
+ "停牌日若源端给的是重复收盘价,按正常 bar 保留,只在摘要里提示成交量为 0",
52
+ "不适用于检测财务造假、不复权序列的公司行为还原或 tick 级数据清洗"
53
+ ],
54
+ "limits": {
55
+ "timeout_ms": 30000,
56
+ "max_input_rows": 200000,
57
+ "max_output_bytes": 1048576,
58
+ "max_log_bytes": 65536
59
+ },
60
+ "provenance": { "source_type": "original", "license": "MIT" }
61
+ }