@v587d/capital-generation 2.30.0 → 2.31.0

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 (76) hide show
  1. package/CHANGELOG.md +99 -0
  2. package/README.md +4 -4
  3. package/THIRD_PARTY_NOTICES.md +1 -0
  4. package/automation/package.json +1 -1
  5. package/automation/storage.js +4 -0
  6. package/chart-ui/package.json +1 -1
  7. package/config/client.js +1 -1
  8. package/config/package.json +1 -1
  9. package/lib/agents/messaging-policy.d.ts +1 -1
  10. package/lib/agents/role-tool-policy.d.ts +3 -0
  11. package/lib/agents/role-tool-policy.js +12 -2
  12. package/lib/agents/selected-skills-provider.d.ts +1 -1
  13. package/lib/agents/selected-skills-provider.js +3 -1
  14. package/lib/analysis/registry.d.ts +12 -0
  15. package/lib/analysis/registry.js +76 -0
  16. package/lib/analysis/runtime.d.ts +87 -0
  17. package/lib/analysis/runtime.js +225 -0
  18. package/lib/analysis/schemas.d.ts +52 -0
  19. package/lib/analysis/schemas.js +270 -0
  20. package/lib/analysis/snapshot.d.ts +102 -0
  21. package/lib/analysis/snapshot.js +266 -0
  22. package/lib/analysis/storage.d.ts +64 -0
  23. package/lib/analysis/storage.js +96 -0
  24. package/lib/analysis/tools.d.ts +17 -0
  25. package/lib/analysis/tools.js +352 -0
  26. package/lib/analysis/types.d.ts +201 -0
  27. package/lib/analysis/types.js +44 -0
  28. package/lib/analysis/validation.d.ts +44 -0
  29. package/lib/analysis/validation.js +338 -0
  30. package/lib/analysis-entry.d.ts +10 -0
  31. package/lib/analysis-entry.js +7 -0
  32. package/lib/data-collector/dataset-tools.js +4 -2
  33. package/lib/data-collector/describe.d.ts +2 -0
  34. package/lib/data-collector/describe.js +2 -0
  35. package/lib/data-collector/store.d.ts +25 -1
  36. package/lib/data-collector/store.js +124 -1
  37. package/lib/data-collector/tools.d.ts +1 -1
  38. package/lib/data-collector/tools.js +3 -2
  39. package/lib/data-contract.d.ts +3 -2
  40. package/lib/data-contract.js +18 -2
  41. package/lib/preset-ids.d.ts +5 -0
  42. package/lib/preset-ids.js +7 -1
  43. package/lib/python-runtime/errors.d.ts +7 -1
  44. package/lib/python-runtime/errors.js +9 -1
  45. package/lib/python-runtime/manager.d.ts +30 -0
  46. package/lib/python-runtime/manager.js +88 -0
  47. package/lib/python-runtime/probe.js +5 -1
  48. package/lib/selected-skills-entry.js +1 -1
  49. package/lib/sources/tencent-http.js +1 -1
  50. package/lib/sources/ths-http.js +5 -2
  51. package/lib/time/tools.js +1 -1
  52. package/lib/web-retriever/local-fetch.d.ts +1 -1
  53. package/lib/web-retriever/local-fetch.js +1 -1
  54. package/lib/web-retriever/wind-client.d.ts +1 -1
  55. package/lib/web-retriever/wind-client.js +1 -1
  56. package/package.json +6 -1
  57. package/preset/capital-generation/README.md +5 -6
  58. package/preset/capital-generation/agent.patch.yml +47 -58
  59. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +99 -0
  60. package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +110 -0
  61. package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +93 -0
  62. package/preset/capital-generation/skills/capital-data-query/SKILL.md +1 -1
  63. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  64. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +1 -1
  65. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
  66. package/preset/capital-generation/skills/capital-portfolio-review/SKILL.md +1 -1
  67. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +100 -0
  68. package/python/analysis/modules/financial_quality/LICENSE +27 -0
  69. package/python/analysis/modules/financial_quality/module.json +65 -0
  70. package/python/analysis/modules/financial_quality/module.py +535 -0
  71. package/python/analysis/modules/hello/LICENSE +21 -0
  72. package/python/analysis/modules/hello/module.json +46 -0
  73. package/python/analysis/modules/hello/module.py +56 -0
  74. package/python/worker.py +152 -5
  75. package/selected-skills/routing.js +5 -2
  76. package/watchlist/package.json +1 -1
@@ -0,0 +1,535 @@
1
+ """Financial quality: margins, ROE/DuPont, cash conversion, leverage, coverage, working capital.
2
+
3
+ The input is the snapshot's datasets, not a pre-joined table: each of the three statements is
4
+ recognised by its column signature and joined on one period key (`period_end_ms`, else `period`).
5
+ A missing statement, column or period becomes a `data_gaps` entry; a ratio whose denominator has no
6
+ economic meaning is skipped rather than reported as zero. This module never fills a gap with a
7
+ default value, and it never emits a rating or a target price.
8
+
9
+ Protocol: `docs/dev/senior-analysis.md` §1.9. Conclusions and claims belong to the senior analyst;
10
+ this module only produces reproducible ratios plus the input values behind each one.
11
+ """
12
+ from __future__ import annotations
13
+
14
+ from datetime import datetime, timezone
15
+
16
+ MODULE_ID = "financial_quality"
17
+ MODULE_VERSION = "1.0.0"
18
+ OUTPUT_NAME = "ratios"
19
+
20
+ # Mirrors module.json `assumptions`: a result must state the same caveats the manifest promises.
21
+ ASSUMPTIONS = [
22
+ "EBIT 用「利润总额 + 利息费用」近似:中国会计准则下利息费用已在利润总额之前扣除",
23
+ "ROE、现金转换与周转率按期末余额计算,未使用期初期末平均值",
24
+ "total_debt 是资产负债表「负债合计」(全部负债),不是有息负债;净负债与有息负债率不在本模块口径内",
25
+ "报表期为累计口径(一季报/中报/三季报为年初至期末),不做年化或季度换算",
26
+ "金额按数据集原币计,不做币种换算;跨币种数据集不合并",
27
+ ]
28
+
29
+ LIMITATIONS = [
30
+ "未调整会计政策变更、并购与汇率折算影响",
31
+ "营运资本比率需要 total_current_liabilities 与 inventory 两列;缺列时按缺口处理,不用替代口径估算",
32
+ ]
33
+
34
+ # A dataset belongs to a statement role when it carries the whole signature. Signatures are
35
+ # disjoint on purpose: guessing from a name or from a single column would silently join the wrong
36
+ # table and produce numbers that look sourced.
37
+ SIGNATURES = {
38
+ "income": ("operating_income", "net_profit"),
39
+ "balance": ("assets_total", "holder_equity_total"),
40
+ "cashflow": ("act_cash_flow_net",),
41
+ }
42
+ LABELS = {"income": "利润表", "balance": "资产负债表", "cashflow": "现金流量表"}
43
+ REQUIRED_HINT = {
44
+ "income": "同时含 operating_income 与 net_profit 列",
45
+ "balance": "同时含 assets_total 与 holder_equity_total 列",
46
+ "cashflow": "含 act_cash_flow_net 列",
47
+ }
48
+ PERIOD_KEYS = ("period_end_ms", "period")
49
+ TREND_METRICS = ("gross_margin", "net_margin", "roe", "cash_conversion", "debt_ratio")
50
+ TREND_LABELS = {
51
+ "gross_margin_delta": ("毛利率", "pp"),
52
+ "net_margin_delta": ("净利率", "pp"),
53
+ "roe_delta": ("ROE", "pp"),
54
+ "debt_ratio_delta": ("资产负债率", "pp"),
55
+ "cash_conversion_delta": ("现金转换", "倍"),
56
+ }
57
+
58
+
59
+ class AnalysisInputError(Exception):
60
+ """The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
61
+
62
+ analysis_code = "analysis_input_invalid"
63
+
64
+
65
+ def _round(value):
66
+ rounded = round(float(value), 6)
67
+ return 0.0 if rounded == 0 else rounded
68
+
69
+
70
+ def _plain(value):
71
+ """Integral floats as ints: the audit file then shows 100000000000, not 100000000000.0."""
72
+ return int(value) if isinstance(value, float) and value.is_integer() else value
73
+
74
+
75
+ def _number(row, name):
76
+ if row is None:
77
+ return None
78
+ value = row.get(name)
79
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
80
+ return None
81
+ number = float(value)
82
+ if number != number or number in (float("inf"), float("-inf")):
83
+ return None
84
+ return number
85
+
86
+
87
+ def _columns_of(view):
88
+ columns = view.get("columns") or []
89
+ names = {item.get("name") for item in columns if isinstance(item, dict)}
90
+ for row in (view.get("rows") or [])[:1]:
91
+ if isinstance(row, dict):
92
+ names |= set(row)
93
+ return names
94
+
95
+
96
+ def _read_datasets(request, context):
97
+ items = (request.get("inputs") or {}).get("datasets") or []
98
+ if not items:
99
+ raise AnalysisInputError("快照里没有任何 Dataset:先取齐三张报表再建快照")
100
+ views = {}
101
+ for item in items:
102
+ dataset_id = (item or {}).get("dataset_id")
103
+ if not isinstance(dataset_id, str) or not dataset_id:
104
+ raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
105
+ views[dataset_id] = context.read_dataset(dataset_id)
106
+ for dataset_id, view in views.items():
107
+ if view.get("shape") != "rows":
108
+ raise AnalysisInputError(
109
+ f"Dataset {dataset_id} 是 {view.get('shape')} 型:financial_quality 只吃表格数据,"
110
+ "文档型输入请先走 profile 或证据"
111
+ )
112
+ return views
113
+
114
+
115
+ def _resolve_roles(views, params):
116
+ """Map each statement role to one dataset id: explicit param first, then the column signature."""
117
+ roles = {}
118
+ for role, signature in SIGNATURES.items():
119
+ explicit = params.get(f"{role}_dataset_id")
120
+ if isinstance(explicit, str) and explicit:
121
+ view = views.get(explicit)
122
+ if view is None:
123
+ raise AnalysisInputError(f"{role}_dataset_id={explicit} 不在本次快照的 Dataset 里")
124
+ missing = [name for name in signature if name not in _columns_of(view)]
125
+ if missing:
126
+ raise AnalysisInputError(
127
+ f"Dataset {explicit} 缺少{LABELS[role]}必需列:{'、'.join(missing)}(需要{REQUIRED_HINT[role]})"
128
+ )
129
+ roles[role] = explicit
130
+ continue
131
+ candidates = sorted(
132
+ dataset_id for dataset_id, view in views.items()
133
+ if all(name in _columns_of(view) for name in signature)
134
+ )
135
+ if len(candidates) > 1:
136
+ raise AnalysisInputError(
137
+ f"有 {len(candidates)} 份 Dataset 都像{LABELS[role]}({'、'.join(candidates)}):"
138
+ f"用 {role}_dataset_id 指明用哪一份"
139
+ )
140
+ if candidates:
141
+ roles[role] = candidates[0]
142
+ return roles
143
+
144
+
145
+ def _join_key(roles, views):
146
+ for column in PERIOD_KEYS:
147
+ if all(column in _columns_of(views[dataset_id]) for dataset_id in roles.values()):
148
+ return column
149
+ raise AnalysisInputError(
150
+ "三张报表缺少共同的报告期键:需要 period_end_ms 或 period 列,否则无法对齐同一报告期"
151
+ )
152
+
153
+
154
+ def _index_rows(view, column, role):
155
+ indexed = {}
156
+ for row in view.get("rows") or []:
157
+ if not isinstance(row, dict):
158
+ raise AnalysisInputError(f"{LABELS[role]}的数据行不是对象:无法计算")
159
+ key = row.get(column)
160
+ if isinstance(key, bool) or not isinstance(key, (int, float, str)) or key == "":
161
+ raise AnalysisInputError(f"{LABELS[role]}的 {column} 列有空值:无法对齐报告期")
162
+ if key in indexed:
163
+ raise AnalysisInputError(f"{LABELS[role]}在报告期 {key} 出现多行:无法判断用哪一行(请先去重)")
164
+ indexed[key] = row
165
+ return indexed
166
+
167
+
168
+ def _iso_date(ms):
169
+ return datetime.fromtimestamp(float(ms) / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
170
+
171
+
172
+ def _period_text_is_informative(rows_by_role):
173
+ """Trust the source's `period` text only when it identifies the period one-to-one.
174
+
175
+ Some sources put a constant there (fuyao A-share statements: every row says "annual"), which
176
+ makes the text useless as a label or a selection key; a single-period dataset is still fine.
177
+ """
178
+ keys = set()
179
+ for rows in rows_by_role.values():
180
+ keys |= set(rows)
181
+ texts = set()
182
+ for role in ("income", "balance", "cashflow"):
183
+ for key in keys:
184
+ row = _row_at(rows_by_role, key, role)
185
+ if row is not None and isinstance(row.get("period"), str) and row["period"]:
186
+ texts.add(row["period"])
187
+ return len(texts) == len(keys) and len(texts) > 0
188
+
189
+
190
+ def _row_at(rows_by_role, key, role):
191
+ row = rows_by_role.get(role, {}).get(key)
192
+ return row if isinstance(row, dict) else None
193
+
194
+
195
+ def _label(rows_by_role, key, key_column):
196
+ """Human-facing period label: the source's own text when it actually varies, else the report date.
197
+
198
+ Order matters: a constant text column (fuyao A-share: `annual` everywhere) must lose to the date,
199
+ while a varying one (`2024-4`) is the label the analyst already uses in reports.
200
+ """
201
+ if _period_text_is_informative(rows_by_role):
202
+ for role in ("income", "balance", "cashflow"):
203
+ row = _row_at(rows_by_role, key, role)
204
+ if row is not None and isinstance(row.get("period"), str) and row["period"]:
205
+ return row["period"]
206
+ if key_column == "period_end_ms" and isinstance(key, (int, float)) and not isinstance(key, bool):
207
+ return _iso_date(key)
208
+ return str(key)
209
+
210
+
211
+ def _period_candidates(rows_by_role, key, key_column):
212
+ """Every way a model may spell this period: the key itself, the date label, fiscal year and
213
+ `year-period` (e.g. `2024`, `2024-FY`), plus the text column only when it is informative."""
214
+ values = {str(key), _label(rows_by_role, key, key_column)}
215
+ informative = _period_text_is_informative(rows_by_role)
216
+ for role in ("income", "balance", "cashflow"):
217
+ row = _row_at(rows_by_role, key, role)
218
+ if row is None:
219
+ continue
220
+ year = row.get("fiscal_year")
221
+ if isinstance(year, int) and not isinstance(year, bool):
222
+ values.add(str(year))
223
+ period = row.get("fiscal_period")
224
+ if isinstance(period, str) and period:
225
+ values.add(f"{year}-{period}")
226
+ if informative and isinstance(row.get("period"), str) and row["period"]:
227
+ values.add(row["period"])
228
+ return values
229
+
230
+
231
+ def _select_period(rows_by_role, params, key_column):
232
+ keys = set()
233
+ for rows in rows_by_role.values():
234
+ keys |= set(rows)
235
+ if not keys:
236
+ raise AnalysisInputError("三张报表都没有数据行:无法计算")
237
+ requested = params.get("period")
238
+ if isinstance(requested, str) and requested.strip():
239
+ wanted = requested.strip()
240
+ matches = [key for key in keys if wanted in _period_candidates(rows_by_role, key, key_column)]
241
+ if not matches:
242
+ available = "、".join(_label(rows_by_role, key, key_column) for key in sorted(keys))
243
+ raise AnalysisInputError(f"报告期 {wanted} 不在这批数据集里;可选:{available}")
244
+ if len(matches) > 1:
245
+ labels = "、".join(_label(rows_by_role, key, key_column) for key in sorted(matches))
246
+ raise AnalysisInputError(f"报告期 {wanted} 同时匹配多个报告期({labels}):请写完整报告期,如 {_label(rows_by_role, matches[0], key_column)}")
247
+ return matches[0]
248
+ return max(keys)
249
+
250
+
251
+ def _compute(rows_by_role, key, label, wanted=None):
252
+ """One period's ratios. Returns (metrics, ratio rows, gaps); `wanted` narrows to a metric subset."""
253
+ income = rows_by_role.get("income", {}).get(key)
254
+ balance = rows_by_role.get("balance", {}).get(key)
255
+ cashflow = rows_by_role.get("cashflow", {}).get(key)
256
+ metrics, ratios, gaps = {}, [], []
257
+
258
+ def add(name, numerator, denominator, formula, inputs, *, positive_denominator=False, reason=None):
259
+ if wanted is not None and name not in wanted:
260
+ return
261
+ missing = [field for field, value in inputs.items() if value is None]
262
+ if missing:
263
+ gaps.append(f"{name} 未计算:{label} 缺 {'、'.join(missing)}")
264
+ return
265
+ if denominator == 0 or (positive_denominator and denominator < 0):
266
+ gaps.append(reason or f"{name} 未计算:{label} 分母为 0")
267
+ return
268
+ value = _round(numerator / denominator)
269
+ metrics[name] = value
270
+ ratios.append({
271
+ "metric": name,
272
+ "value": value,
273
+ "formula": formula,
274
+ "inputs": {field: _plain(raw) for field, raw in inputs.items()},
275
+ })
276
+
277
+ revenue = _number(income, "operating_income")
278
+ costs = _number(income, "operating_costs")
279
+ operating_profit = _number(income, "operating_profit")
280
+ profit_total = _number(income, "profit_total")
281
+ interest = _number(income, "interest_expenses")
282
+ net_profit = _number(income, "net_profit")
283
+ assets = _number(balance, "assets_total")
284
+ equity = _number(balance, "holder_equity_total")
285
+ liabilities = _number(balance, "total_debt")
286
+ current_assets = _number(balance, "total_current_assets")
287
+ current_liabilities = _number(balance, "total_current_liabilities")
288
+ inventory = _number(balance, "inventory")
289
+ receivables = _number(balance, "accounts_receivable")
290
+ ocf = _number(cashflow, "act_cash_flow_net")
291
+ capex = _number(cashflow, "pay_fixed_assets_etc_cash")
292
+
293
+ gross_profit = None if revenue is None or costs is None else revenue - costs
294
+ ebit = None if profit_total is None or interest is None else profit_total + interest
295
+ fcf = None if ocf is None or capex is None else ocf - capex
296
+ quick_assets = None if current_assets is None or inventory is None else current_assets - inventory
297
+
298
+ add("gross_margin", gross_profit, revenue, "(operating_income - operating_costs) / operating_income",
299
+ {"operating_income": revenue, "operating_costs": costs}, positive_denominator=True,
300
+ reason=f"gross_margin 未计算:{label} 营业收入 ≤ 0,毛利率无经济含义")
301
+ add("operating_margin", operating_profit, revenue, "operating_profit / operating_income",
302
+ {"operating_income": revenue, "operating_profit": operating_profit}, positive_denominator=True,
303
+ reason=f"operating_margin 未计算:{label} 营业收入 ≤ 0,营业利润率无经济含义")
304
+ add("net_margin", net_profit, revenue, "net_profit / operating_income",
305
+ {"operating_income": revenue, "net_profit": net_profit}, positive_denominator=True,
306
+ reason=f"net_margin 未计算:{label} 营业收入 ≤ 0,净利率无经济含义")
307
+ add("roe", net_profit, equity, "net_profit / holder_equity_total",
308
+ {"net_profit": net_profit, "holder_equity_total": equity}, positive_denominator=True,
309
+ reason=f"roe 未计算:{label} 期末净资产 ≤ 0,ROE 无经济含义")
310
+ add("roa", net_profit, assets, "net_profit / assets_total",
311
+ {"net_profit": net_profit, "assets_total": assets}, positive_denominator=True,
312
+ reason=f"roa 未计算:{label} 资产总计 ≤ 0")
313
+ add("asset_turnover", revenue, assets, "operating_income / assets_total",
314
+ {"operating_income": revenue, "assets_total": assets}, positive_denominator=True,
315
+ reason=f"asset_turnover 未计算:{label} 资产总计 ≤ 0")
316
+ add("equity_multiplier", assets, equity, "assets_total / holder_equity_total",
317
+ {"assets_total": assets, "holder_equity_total": equity}, positive_denominator=True,
318
+ reason=f"equity_multiplier 未计算:{label} 期末净资产 ≤ 0,权益乘数无经济含义")
319
+ add("cash_conversion", ocf, net_profit, "act_cash_flow_net / net_profit",
320
+ {"act_cash_flow_net": ocf, "net_profit": net_profit}, positive_denominator=True,
321
+ reason=f"cash_conversion 未计算:{label} 净利润 ≤ 0,现金转换倍数无意义")
322
+ add("ocf_margin", ocf, revenue, "act_cash_flow_net / operating_income",
323
+ {"act_cash_flow_net": ocf, "operating_income": revenue}, positive_denominator=True,
324
+ reason=f"ocf_margin 未计算:{label} 营业收入 ≤ 0")
325
+ add("fcf_amount", fcf, 1.0, "act_cash_flow_net - pay_fixed_assets_etc_cash",
326
+ {"act_cash_flow_net": ocf, "pay_fixed_assets_etc_cash": capex})
327
+ add("fcf_margin", fcf, revenue, "(act_cash_flow_net - pay_fixed_assets_etc_cash) / operating_income",
328
+ {"act_cash_flow_net": ocf, "pay_fixed_assets_etc_cash": capex, "operating_income": revenue},
329
+ positive_denominator=True, reason=f"fcf_margin 未计算:{label} 营业收入 ≤ 0")
330
+ add("debt_ratio", liabilities, assets, "total_debt / assets_total",
331
+ {"total_debt": liabilities, "assets_total": assets}, positive_denominator=True,
332
+ reason=f"debt_ratio 未计算:{label} 资产总计 ≤ 0")
333
+ add("debt_to_equity", liabilities, equity, "total_debt / holder_equity_total",
334
+ {"total_debt": liabilities, "holder_equity_total": equity}, positive_denominator=True,
335
+ reason=f"debt_to_equity 未计算:{label} 期末净资产 ≤ 0,产权比率无经济含义")
336
+ add("interest_coverage", ebit, interest, "(profit_total + interest_expenses) / interest_expenses",
337
+ {"profit_total": profit_total, "interest_expenses": interest}, positive_denominator=True,
338
+ reason=f"interest_coverage 未计算:{label} 利息费用 ≤ 0,利息保障倍数无意义")
339
+ add("current_ratio", current_assets, current_liabilities,
340
+ "total_current_assets / total_current_liabilities",
341
+ {"total_current_assets": current_assets, "total_current_liabilities": current_liabilities},
342
+ positive_denominator=True, reason=f"current_ratio 未计算:{label} 流动负债合计 ≤ 0")
343
+ add("quick_ratio", quick_assets, current_liabilities,
344
+ "(total_current_assets - inventory) / total_current_liabilities",
345
+ {"total_current_assets": current_assets, "inventory": inventory,
346
+ "total_current_liabilities": current_liabilities},
347
+ positive_denominator=True, reason=f"quick_ratio 未计算:{label} 流动负债合计 ≤ 0")
348
+ add("receivable_days", None if receivables is None or revenue is None else receivables * 365, revenue,
349
+ "accounts_receivable / operating_income * 365",
350
+ {"accounts_receivable": receivables, "operating_income": revenue}, positive_denominator=True,
351
+ reason=f"receivable_days 未计算:{label} 营业收入 ≤ 0")
352
+ return metrics, ratios, gaps
353
+
354
+
355
+ def _result(status, summary, metrics, methodology, limitations, gaps, outputs):
356
+ return {
357
+ "status": status,
358
+ "summary": summary,
359
+ "metrics": metrics,
360
+ "claims": [],
361
+ "assumptions": list(ASSUMPTIONS),
362
+ "methodology_log": methodology,
363
+ "sensitivity": {},
364
+ "limitations": limitations,
365
+ "data_gaps": gaps,
366
+ "outputs": outputs,
367
+ }
368
+
369
+
370
+ def _times(value):
371
+ """Multiples keep 5 decimals: a 2-decimal form would sit outside the default anchor tolerance."""
372
+ text = f"{value:.5f}".rstrip("0").rstrip(".")
373
+ return text if text not in ("", "-0") else "0"
374
+
375
+
376
+ def _summary(label, metrics, trend_rows, gaps):
377
+ # Rounding here is deliberate: 2-decimal percentages are always inside the host's percentage
378
+ # tolerance, and 5-decimal multiples inside the default anchor precision. The summary is the most
379
+ # likely thing a model copies into a claim, so every number in it must be anchorable as written.
380
+ parts = []
381
+ if "gross_margin" in metrics:
382
+ parts.append(f"毛利率 {metrics['gross_margin'] * 100:.2f}%")
383
+ if "net_margin" in metrics:
384
+ parts.append(f"净利率 {metrics['net_margin'] * 100:.2f}%")
385
+ if "roe" in metrics:
386
+ parts.append(f"ROE {metrics['roe'] * 100:.2f}%")
387
+ if "cash_conversion" in metrics:
388
+ parts.append(f"现金转换 {_times(metrics['cash_conversion'])} 倍")
389
+ if "debt_ratio" in metrics:
390
+ parts.append(f"资产负债率 {metrics['debt_ratio'] * 100:.2f}%")
391
+ if "interest_coverage" in metrics:
392
+ parts.append(f"利息保障 {_times(metrics['interest_coverage'])} 倍")
393
+ head = f"{label} 财务质量:" + ("、".join(parts) if parts else "没有可计算的指标")
394
+ if trend_rows:
395
+ changes = []
396
+ for row in trend_rows:
397
+ name, unit = TREND_LABELS[row["metric"]]
398
+ if unit == "pp":
399
+ changes.append(f"{name} {row['value'] * 100:+.2f}%")
400
+ else:
401
+ prefix = "+" if row["value"] > 0 else ""
402
+ changes.append(f"{name} {prefix}{_times(row['value'])} 倍")
403
+ head += ";环比 " + "、".join(changes)
404
+ if gaps:
405
+ head += "(有缺口未计算,见 data_gaps)"
406
+ return head + "。"
407
+
408
+
409
+ def analyze(request: dict, context) -> dict:
410
+ params = request.get("params") or {}
411
+ views = _read_datasets(request, context)
412
+ roles = _resolve_roles(views, params)
413
+ ignored = sorted(set(views) - set(roles.values()))
414
+ methodology = [
415
+ "按列签名识别报表:" + ("、".join(f"{role}={dataset_id}" for role, dataset_id in sorted(roles.items())) or "一份都没识别到"),
416
+ ]
417
+ limitations = list(LIMITATIONS)
418
+ gaps = []
419
+
420
+ for dataset_id in ignored:
421
+ limitations.append(f"Dataset {dataset_id} 不属于三张报表(列签名不匹配),未参与计算")
422
+ for role, dataset_id in sorted(roles.items()):
423
+ view = views[dataset_id]
424
+ if view.get("truncated"):
425
+ limitations.append(
426
+ f"{LABELS[role]} {dataset_id} 被截断到 {len(view.get('rows') or [])} 行(max_input_rows),"
427
+ "结论只覆盖截断后的样本"
428
+ )
429
+
430
+ if "income" not in roles:
431
+ gaps.append("缺少利润表数据集(需要同时含 operating_income 与 net_profit 列):利润率、ROE、现金转换都无法计算")
432
+ context.log(f"{MODULE_ID}: 缺利润表,返回 blocked")
433
+ return _result(
434
+ "blocked",
435
+ "缺少利润表数据集:无法计算财务质量指标,请补齐利润表后重跑。",
436
+ {},
437
+ methodology + ["未执行比率计算:利润表缺失"],
438
+ limitations + ["没有任何指标可用,不能据此判断财务质量"],
439
+ gaps,
440
+ [],
441
+ )
442
+
443
+ for role in ("balance", "cashflow"):
444
+ if role not in roles:
445
+ gaps.append(f"缺少{LABELS[role]}数据集(需要{REQUIRED_HINT[role]}):相关指标未计算")
446
+
447
+ key_column = _join_key(roles, views)
448
+ if key_column == "period":
449
+ limitations.append("报告期按 period 字符串排序取最新期(没有 period_end_ms 列):格式不一致时可能选错报告期")
450
+ rows_by_role = {role: _index_rows(views[dataset_id], key_column, role) for role, dataset_id in roles.items()}
451
+ selected = _select_period(rows_by_role, params, key_column)
452
+ label = _label(rows_by_role, selected, key_column)
453
+ methodology.append(f"报告期键 {key_column};选中 {label}")
454
+
455
+ currency = None
456
+ for role in ("income", "balance", "cashflow"):
457
+ row = rows_by_role.get(role, {}).get(selected)
458
+ if isinstance(row, dict) and isinstance(row.get("currency"), str) and row["currency"]:
459
+ currency = row["currency"]
460
+ break
461
+
462
+ metrics, ratios, period_gaps = _compute(rows_by_role, selected, label)
463
+ gaps.extend(period_gaps)
464
+ if currency:
465
+ metrics = {"currency": currency, **metrics}
466
+
467
+ trend_rows = []
468
+ previous_label = None
469
+ if params.get("compare_previous", True) is not False:
470
+ candidates = [key for key in set().union(*[set(rows) for rows in rows_by_role.values()]) if key < selected]
471
+ if not candidates:
472
+ gaps.append(f"未计算趋势:这批数据集没有早于 {label} 的报告期")
473
+ limitations.append("只有一期报表,没有环比趋势")
474
+ else:
475
+ previous = max(candidates)
476
+ previous_label = _label(rows_by_role, previous, key_column)
477
+ previous_metrics, _, _ = _compute(rows_by_role, previous, previous_label, wanted=TREND_METRICS)
478
+ for name in TREND_METRICS:
479
+ if name in metrics and name in previous_metrics:
480
+ delta = _round(metrics[name] - previous_metrics[name])
481
+ metrics[f"{name}_delta"] = delta
482
+ trend_rows.append({
483
+ "metric": f"{name}_delta",
484
+ "value": delta,
485
+ "current": metrics[name],
486
+ "previous": previous_metrics[name],
487
+ "formula": f"{name}({label}) - {name}({previous_label})",
488
+ })
489
+ else:
490
+ gaps.append(f"{name}_delta 未计算:{previous_label} 缺少可比指标")
491
+ methodology.append(f"上一期 {previous_label}:计算 {len(trend_rows)} 项环比变化")
492
+ else:
493
+ limitations.append("按参数关闭了环比趋势")
494
+
495
+ if all(name in metrics for name in ("net_margin", "asset_turnover", "equity_multiplier", "roe")):
496
+ residual = _round(
497
+ metrics["net_margin"] * metrics["asset_turnover"] * metrics["equity_multiplier"] - metrics["roe"]
498
+ )
499
+ methodology.append(
500
+ f"DuPont 三因子乘积与 roe 一致(差 {residual:+.6f})" if abs(residual) <= 1e-5
501
+ else f"DuPont 三因子乘积与 roe 不一致(差 {residual:+.6f}):输入可能存在口径混用"
502
+ )
503
+
504
+ status = "partial" if gaps else "completed"
505
+ methodology.append(
506
+ f"计算 {len([name for name in metrics if name != 'currency'])} 项指标、{len(trend_rows)} 项环比;{len(gaps)} 项缺口"
507
+ )
508
+
509
+ payload = {
510
+ "protocol": "capital.analysis/v1",
511
+ "module_id": MODULE_ID,
512
+ "module_version": MODULE_VERSION,
513
+ "analysis_id": request.get("analysis_id"),
514
+ "module_run_id": request.get("module_run_id"),
515
+ "period": label,
516
+ "period_key": key_column,
517
+ "previous_period": previous_label,
518
+ "currency": currency,
519
+ "statements": {role: dataset_id for role, dataset_id in sorted(roles.items())},
520
+ "ratios": ratios,
521
+ "trend": trend_rows,
522
+ "data_gaps": gaps,
523
+ }
524
+ ref = context.write_output(OUTPUT_NAME, payload)
525
+ context.log(f"{MODULE_ID}: {status} period={label} metrics={len(metrics)} gaps={len(gaps)}")
526
+
527
+ return _result(
528
+ status,
529
+ _summary(label, metrics, trend_rows, gaps),
530
+ metrics,
531
+ methodology,
532
+ limitations,
533
+ gaps,
534
+ [{"name": OUTPUT_NAME, "ref": ref}],
535
+ )
@@ -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,46 @@
1
+ {
2
+ "id": "hello",
3
+ "version": "1.0.0",
4
+ "entrypoint": "module.py",
5
+ "runtime": "python",
6
+ "description": "分析环境自检:回显输入形状与参数,不产出任何结论",
7
+ "roles": ["senior_analyst"],
8
+ "capabilities": ["dataset.read", "profile.read"],
9
+ "required_fields": [],
10
+ "input_schema": {
11
+ "type": "object",
12
+ "properties": {
13
+ "note": { "type": "string", "maxLength": 200 }
14
+ },
15
+ "additionalProperties": false
16
+ },
17
+ "output_schema": {
18
+ "type": "object",
19
+ "properties": {
20
+ "status": { "type": "string", "enum": ["completed", "partial", "blocked", "failed"] },
21
+ "summary": { "type": "string" },
22
+ "metrics": { "type": "object" },
23
+ "claims": { "type": "array" },
24
+ "assumptions": { "type": "array" },
25
+ "methodology_log": { "type": "array" },
26
+ "sensitivity": { "type": "object" },
27
+ "limitations": { "type": "array" },
28
+ "data_gaps": { "type": "array" },
29
+ "outputs": { "type": "array" }
30
+ },
31
+ "required": [
32
+ "status", "summary", "metrics", "claims", "assumptions", "methodology_log",
33
+ "sensitivity", "limitations", "data_gaps", "outputs"
34
+ ],
35
+ "additionalProperties": false
36
+ },
37
+ "assumptions": ["自检模块只回显输入形状,不解释数据含义"],
38
+ "applicability": ["仅用于验证分析环境与模块协议;不要用它回答研究问题"],
39
+ "limits": {
40
+ "timeout_ms": 15000,
41
+ "max_input_rows": 200000,
42
+ "max_output_bytes": 1048576,
43
+ "max_log_bytes": 65536
44
+ },
45
+ "provenance": { "source_type": "original", "license": "MIT" }
46
+ }
@@ -0,0 +1,56 @@
1
+ """Analysis-environment self-check module.
2
+
3
+ It reads the staged inputs through `context`, echoes their shape and writes a result that satisfies
4
+ the protocol. It produces no analytical conclusion on purpose: its only job is to prove that the
5
+ module protocol, the input staging and the result contract all work end to end.
6
+
7
+ Protocol: `docs/dev/senior-analysis.md` §1.9. Do not add conclusions here; add a real module instead.
8
+ """
9
+ from __future__ import annotations
10
+
11
+
12
+ def analyze(request: dict, context) -> dict:
13
+ datasets = []
14
+ for item in request.get("inputs", {}).get("datasets", []):
15
+ view = context.read_dataset(item["dataset_id"])
16
+ datasets.append({
17
+ "dataset_id": view["source"]["dataset_id"],
18
+ "shape": view["shape"],
19
+ "row_count": view["row_count"],
20
+ "column_count": len(view["columns"]),
21
+ "time_axis": (view.get("time_axis") or {}).get("column"),
22
+ "truncated": view["truncated"],
23
+ })
24
+
25
+ profiles = []
26
+ for item in request.get("inputs", {}).get("profiles", []):
27
+ loaded = context.read_profile(item["profile_id"])
28
+ profiles.append({
29
+ "profile_id": loaded["ref"]["profile_id"],
30
+ "dataset_id": loaded["ref"]["dataset_id"],
31
+ "row_count": loaded["profile"]["row_count"],
32
+ })
33
+
34
+ note = request.get("params", {}).get("note")
35
+ context.log(f"hello: {len(datasets)} dataset(s), {len(profiles)} profile(s), note={note!r}")
36
+
37
+ return {
38
+ "status": "completed",
39
+ "summary": "分析环境自检通过:模块协议、输入读取与结果回写均可用(本模块不产出结论)。",
40
+ "metrics": {
41
+ "dataset_count": len(datasets),
42
+ "profile_count": len(profiles),
43
+ "dataset_rows": sum(item["row_count"] for item in datasets),
44
+ },
45
+ "claims": [],
46
+ "assumptions": ["自检模块只回显输入形状,不解释数据含义"],
47
+ "methodology_log": [
48
+ "读取 request.inputs 里声明的 Dataset 与 profile",
49
+ "按 §8.5 的视图形状回显行数、列数与时间轴",
50
+ "回写结果,交由宿主校验",
51
+ ],
52
+ "sensitivity": {},
53
+ "limitations": ["自检模块不产出分析结论,不能用于任何研究判断"],
54
+ "data_gaps": [],
55
+ "outputs": [],
56
+ }