@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.
- package/CHANGELOG.md +125 -0
- package/README.md +45 -7
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/package.json +1 -1
- package/lib/analysis/registry.js +6 -1
- package/lib/analysis/validation.js +13 -3
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +1 -1
- package/plugin-page/README.en.md +7 -0
- package/plugin-page/README.zh.md +7 -0
- package/preset/capital-generation/agent.patch.yml +11 -9
- package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +47 -16
- package/preset/capital-generation/skills/capital-orchestration/SKILL.md +2 -2
- package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +5 -0
- package/python/analysis/modules/comps_valuation/LICENSE +21 -0
- package/python/analysis/modules/comps_valuation/module.json +61 -0
- package/python/analysis/modules/comps_valuation/module.py +360 -0
- package/python/analysis/modules/earnings_bridge/LICENSE +21 -0
- package/python/analysis/modules/earnings_bridge/module.json +58 -0
- package/python/analysis/modules/earnings_bridge/module.py +452 -0
- package/python/analysis/modules/kline_quality/LICENSE +21 -0
- package/python/analysis/modules/kline_quality/module.json +61 -0
- package/python/analysis/modules/kline_quality/module.py +538 -0
- package/python/analysis/modules/portfolio_stress/LICENSE +21 -0
- package/python/analysis/modules/portfolio_stress/module.json +89 -0
- package/python/analysis/modules/portfolio_stress/module.py +537 -0
- package/python/analysis/modules/returns_risk/LICENSE +21 -0
- package/python/analysis/modules/returns_risk/module.json +66 -0
- package/python/analysis/modules/returns_risk/module.py +517 -0
- package/python/analysis/modules/scenario_sensitivity/LICENSE +21 -0
- package/python/analysis/modules/scenario_sensitivity/module.json +105 -0
- package/python/analysis/modules/scenario_sensitivity/module.py +379 -0
- package/python/analysis/modules/simple_backtest/LICENSE +21 -0
- package/python/analysis/modules/simple_backtest/module.json +66 -0
- package/python/analysis/modules/simple_backtest/module.py +648 -0
- package/python/analysis/modules/statement_integrity/LICENSE +21 -0
- package/python/analysis/modules/statement_integrity/module.json +62 -0
- package/python/analysis/modules/statement_integrity/module.py +621 -0
- package/python/analysis/modules/technical_indicators/LICENSE +21 -0
- package/python/analysis/modules/technical_indicators/module.json +170 -0
- package/python/analysis/modules/technical_indicators/module.py +854 -0
- package/python/analysis/modules/valuation_sensitivity/LICENSE +21 -0
- package/python/analysis/modules/valuation_sensitivity/module.json +73 -0
- package/python/analysis/modules/valuation_sensitivity/module.py +589 -0
- package/watchlist/package.json +1 -1
|
@@ -0,0 +1,621 @@
|
|
|
1
|
+
"""Statement integrity: balance identity, cash-flow reconciliation, retained-earnings roll-forward.
|
|
2
|
+
|
|
3
|
+
The input is the snapshot's datasets, not a pre-joined table: the three statements are recognised
|
|
4
|
+
by column signature and joined on one period key (`period_end_ms`, else `period`). Every check is
|
|
5
|
+
an explicit identity with the same two sides; the module reports the residual, the scale it is
|
|
6
|
+
compared against and the tolerance the caller passed. A missing statement, column or period becomes
|
|
7
|
+
a `data_gaps` entry — the module never fills a gap with a default value, never decides that a
|
|
8
|
+
residual means fraud, and never emits a rating.
|
|
9
|
+
|
|
10
|
+
Protocol: `docs/dev/senior-analysis.md` §1.9. Conclusions and claims belong to the senior analyst;
|
|
11
|
+
this module only produces reproducible residuals plus the input values behind each one.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from datetime import datetime, timezone
|
|
16
|
+
|
|
17
|
+
MODULE_ID = "statement_integrity"
|
|
18
|
+
MODULE_VERSION = "1.0.0"
|
|
19
|
+
OUTPUT_NAME = "integrity_checks"
|
|
20
|
+
|
|
21
|
+
# Mirrors module.json `assumptions`: a result must state the same caveats the manifest promises.
|
|
22
|
+
ASSUMPTIONS = [
|
|
23
|
+
"资产负债恒等式按 assets_total = total_debt + holder_equity_total 校验;total_debt 是「负债合计」,不区分有息与无息",
|
|
24
|
+
"现金流对账按 act_cash_flow_net + invest_cash_flow_net + financing_cash_flow_net = cash_equivalents_net_addition;只有数据集含 effect_of_exchange_rate_changes 列时才把汇率影响计入左边",
|
|
25
|
+
"留存收益滚动只在资产负债表有 retained_earnings 列且找到上一期时校验:RE_end = RE_prev + net_profit - dividends_paid - 盈余公积增加(balance 有 surplus_reserve 列时扣除其增量)",
|
|
26
|
+
"容差由参数显式给出:|差异| ≤ tolerance_abs + tolerance_ratio × 对账基准;基准取同一恒等式两边绝对值中的较大者,不按行业或规模另设阈值",
|
|
27
|
+
"差异是数据质量信号,不是投资结论:本模块不判断报表是否造假、不评级,也不给目标价",
|
|
28
|
+
]
|
|
29
|
+
|
|
30
|
+
LIMITATIONS = [
|
|
31
|
+
"勾稽成立不代表报表真实或完整:本模块不校验会计政策、科目口径、合并范围与附注披露",
|
|
32
|
+
"三张报表来自不同 Dataset 时,本模块只按报告期键对齐,不检查它们是否同一个合并口径或同一币种",
|
|
33
|
+
"留存收益滚动对盈余公积与现金分红的处理取决于列是否披露;缺列按缺口处理,不用默认值补齐",
|
|
34
|
+
"容差是调用方给的参数:调宽容差只会让差异更容易通过,不改变差异本身",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
SIGNATURES = {
|
|
38
|
+
"balance": ("assets_total", "holder_equity_total"),
|
|
39
|
+
"income": ("net_profit",),
|
|
40
|
+
"cashflow": ("act_cash_flow_net",),
|
|
41
|
+
}
|
|
42
|
+
LABELS = {"balance": "资产负债表", "income": "利润表", "cashflow": "现金流量表"}
|
|
43
|
+
CHECK_LABELS = {
|
|
44
|
+
"balance": "资产负债恒等式",
|
|
45
|
+
"cash": "现金流对账",
|
|
46
|
+
"retained_earnings": "留存收益滚动",
|
|
47
|
+
}
|
|
48
|
+
CHECK_FORMULAS = {
|
|
49
|
+
"balance": "assets_total = total_debt + holder_equity_total",
|
|
50
|
+
"cash": "act_cash_flow_net + invest_cash_flow_net + financing_cash_flow_net (+ 汇率影响) = cash_equivalents_net_addition",
|
|
51
|
+
"retained_earnings": "retained_earnings(end) = retained_earnings(prev) + net_profit - dividends_paid - Δsurplus_reserve",
|
|
52
|
+
}
|
|
53
|
+
PERIOD_KEYS = ("period_end_ms", "period")
|
|
54
|
+
CASH_COMPONENTS = ("act_cash_flow_net", "invest_cash_flow_net", "financing_cash_flow_net")
|
|
55
|
+
CASH_TOTAL = "cash_equivalents_net_addition"
|
|
56
|
+
FX_COLUMN = "effect_of_exchange_rate_changes"
|
|
57
|
+
DIVIDEND_COLUMNS = ("dividends_paid", "dividends_declared")
|
|
58
|
+
DEFAULT_TOLERANCE_RATIO = 0.001
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class AnalysisInputError(Exception):
|
|
62
|
+
"""The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
|
|
63
|
+
|
|
64
|
+
analysis_code = "analysis_input_invalid"
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def _round(value):
|
|
68
|
+
rounded = round(float(value), 6)
|
|
69
|
+
return 0.0 if rounded == 0 else rounded
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _plain(value):
|
|
73
|
+
"""Integral floats as ints: the audit file then shows 100000000000, not 100000000000.0."""
|
|
74
|
+
return int(value) if isinstance(value, float) and value.is_integer() else value
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def _amount(value):
|
|
78
|
+
"""Money keeps the source's integer form when it has one; otherwise 6 decimals."""
|
|
79
|
+
if value is None:
|
|
80
|
+
return None
|
|
81
|
+
if float(value).is_integer():
|
|
82
|
+
return int(value)
|
|
83
|
+
return _round(value)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _number(row, name):
|
|
87
|
+
if row is None:
|
|
88
|
+
return None
|
|
89
|
+
value = row.get(name)
|
|
90
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
91
|
+
return None
|
|
92
|
+
number = float(value)
|
|
93
|
+
if number != number or number in (float("inf"), float("-inf")):
|
|
94
|
+
return None
|
|
95
|
+
return number
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _columns_of(view):
|
|
99
|
+
columns = view.get("columns") or []
|
|
100
|
+
names = {item.get("name") for item in columns if isinstance(item, dict)}
|
|
101
|
+
for row in (view.get("rows") or [])[:1]:
|
|
102
|
+
if isinstance(row, dict):
|
|
103
|
+
names |= set(row)
|
|
104
|
+
return names
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _read_datasets(request, context):
|
|
108
|
+
items = (request.get("inputs") or {}).get("datasets") or []
|
|
109
|
+
if not items:
|
|
110
|
+
raise AnalysisInputError("快照里没有任何 Dataset:先取齐三张报表再建快照")
|
|
111
|
+
views = {}
|
|
112
|
+
for item in items:
|
|
113
|
+
dataset_id = (item or {}).get("dataset_id")
|
|
114
|
+
if not isinstance(dataset_id, str) or not dataset_id:
|
|
115
|
+
raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
|
|
116
|
+
views[dataset_id] = context.read_dataset(dataset_id)
|
|
117
|
+
for dataset_id, view in views.items():
|
|
118
|
+
if view.get("shape") != "rows":
|
|
119
|
+
raise AnalysisInputError(
|
|
120
|
+
f"Dataset {dataset_id} 是 {view.get('shape')} 型:statement_integrity 只吃表格数据,"
|
|
121
|
+
"文档型输入请先走 profile 或证据"
|
|
122
|
+
)
|
|
123
|
+
return views
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _resolve_roles(views, params):
|
|
127
|
+
"""Map each statement role to one dataset id: explicit param first, then the column signature."""
|
|
128
|
+
roles = {}
|
|
129
|
+
for role, signature in SIGNATURES.items():
|
|
130
|
+
explicit = params.get(f"{role}_dataset_id")
|
|
131
|
+
if isinstance(explicit, str) and explicit:
|
|
132
|
+
view = views.get(explicit)
|
|
133
|
+
if view is None:
|
|
134
|
+
raise AnalysisInputError(f"{role}_dataset_id={explicit} 不在本次快照的 Dataset 里")
|
|
135
|
+
missing = [name for name in signature if name not in _columns_of(view)]
|
|
136
|
+
if missing:
|
|
137
|
+
raise AnalysisInputError(
|
|
138
|
+
f"Dataset {explicit} 缺少{LABELS[role]}识别列:{'、'.join(missing)}"
|
|
139
|
+
)
|
|
140
|
+
roles[role] = explicit
|
|
141
|
+
continue
|
|
142
|
+
candidates = sorted(
|
|
143
|
+
dataset_id for dataset_id, view in views.items()
|
|
144
|
+
if all(name in _columns_of(view) for name in signature)
|
|
145
|
+
)
|
|
146
|
+
if len(candidates) > 1:
|
|
147
|
+
raise AnalysisInputError(
|
|
148
|
+
f"有 {len(candidates)} 份 Dataset 都像{LABELS[role]}({'、'.join(candidates)}):"
|
|
149
|
+
f"用 {role}_dataset_id 指明用哪一份"
|
|
150
|
+
)
|
|
151
|
+
if candidates:
|
|
152
|
+
roles[role] = candidates[0]
|
|
153
|
+
if not roles:
|
|
154
|
+
raise AnalysisInputError(
|
|
155
|
+
"快照里没有任何三张报表的 Dataset:需要资产负债表(assets_total + holder_equity_total)、"
|
|
156
|
+
"利润表(net_profit)或现金流量表(act_cash_flow_net)"
|
|
157
|
+
)
|
|
158
|
+
return roles
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _join_key(roles, views):
|
|
162
|
+
for column in PERIOD_KEYS:
|
|
163
|
+
if all(column in _columns_of(views[dataset_id]) for dataset_id in roles.values()):
|
|
164
|
+
return column
|
|
165
|
+
raise AnalysisInputError(
|
|
166
|
+
"三张报表缺少共同的报告期键:需要 period_end_ms 或 period 列,否则无法对齐同一报告期"
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def _index_rows(view, column, role):
|
|
171
|
+
indexed = {}
|
|
172
|
+
for row in view.get("rows") or []:
|
|
173
|
+
if not isinstance(row, dict):
|
|
174
|
+
raise AnalysisInputError(f"{LABELS[role]}的数据行不是对象:无法计算")
|
|
175
|
+
key = row.get(column)
|
|
176
|
+
if isinstance(key, bool) or not isinstance(key, (int, float, str)) or key == "":
|
|
177
|
+
raise AnalysisInputError(f"{LABELS[role]}的 {column} 列有空值:无法对齐报告期")
|
|
178
|
+
if key in indexed:
|
|
179
|
+
raise AnalysisInputError(f"{LABELS[role]}在报告期 {key} 出现多行:无法判断用哪一行(请先去重)")
|
|
180
|
+
indexed[key] = row
|
|
181
|
+
return indexed
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _iso_date(ms):
|
|
185
|
+
return datetime.fromtimestamp(float(ms) / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _period_text_is_informative(rows_by_role):
|
|
189
|
+
"""Trust the source's `period` text only when it identifies the period one-to-one.
|
|
190
|
+
|
|
191
|
+
Some sources put a constant there (fuyao A-share statements: every row says "annual"), which
|
|
192
|
+
makes the text useless as a label or a selection key.
|
|
193
|
+
"""
|
|
194
|
+
keys = set()
|
|
195
|
+
for rows in rows_by_role.values():
|
|
196
|
+
keys |= set(rows)
|
|
197
|
+
texts = set()
|
|
198
|
+
for keys_by_role in rows_by_role.values():
|
|
199
|
+
for key in keys:
|
|
200
|
+
row = keys_by_role.get(key)
|
|
201
|
+
if isinstance(row, dict) and isinstance(row.get("period"), str) and row["period"]:
|
|
202
|
+
texts.add(row["period"])
|
|
203
|
+
# A bare periodicity word (`annual`, `FY`) does not identify a period even when only one row
|
|
204
|
+
# exists: labels derived from it ("annual 缺 ...") are not something a reader can check.
|
|
205
|
+
return len(texts) == len(keys) and len(texts) > 0 and all(any(ch.isdigit() for ch in text) for text in texts)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
def _row_at(rows_by_role, key, role):
|
|
209
|
+
row = rows_by_role.get(role, {}).get(key)
|
|
210
|
+
return row if isinstance(row, dict) else None
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def _label(rows_by_role, key, key_column):
|
|
214
|
+
"""Human-facing period label: the source's own text when it actually varies, else the report date."""
|
|
215
|
+
if _period_text_is_informative(rows_by_role):
|
|
216
|
+
for role in ("balance", "income", "cashflow"):
|
|
217
|
+
row = _row_at(rows_by_role, key, role)
|
|
218
|
+
if row is not None and isinstance(row.get("period"), str) and row["period"]:
|
|
219
|
+
return row["period"]
|
|
220
|
+
if key_column == "period_end_ms" and isinstance(key, (int, float)) and not isinstance(key, bool):
|
|
221
|
+
return _iso_date(key)
|
|
222
|
+
return str(key)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def _period_candidates(rows_by_role, key, key_column):
|
|
226
|
+
"""Every way a model may spell this period: the key, its date label, fiscal year and `year-period`."""
|
|
227
|
+
values = {str(key), _label(rows_by_role, key, key_column)}
|
|
228
|
+
informative = _period_text_is_informative(rows_by_role)
|
|
229
|
+
for role in ("balance", "income", "cashflow"):
|
|
230
|
+
row = _row_at(rows_by_role, key, role)
|
|
231
|
+
if row is None:
|
|
232
|
+
continue
|
|
233
|
+
year = row.get("fiscal_year")
|
|
234
|
+
if isinstance(year, int) and not isinstance(year, bool):
|
|
235
|
+
values.add(str(year))
|
|
236
|
+
period = row.get("fiscal_period")
|
|
237
|
+
if isinstance(period, str) and period:
|
|
238
|
+
values.add(f"{year}-{period}")
|
|
239
|
+
if informative and isinstance(row.get("period"), str) and row["period"]:
|
|
240
|
+
values.add(row["period"])
|
|
241
|
+
return values
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def _select_period(rows_by_role, params, key_column):
|
|
245
|
+
keys = set()
|
|
246
|
+
for rows in rows_by_role.values():
|
|
247
|
+
keys |= set(rows)
|
|
248
|
+
if not keys:
|
|
249
|
+
raise AnalysisInputError("三张报表都没有数据行:无法计算")
|
|
250
|
+
requested = params.get("period")
|
|
251
|
+
if isinstance(requested, str) and requested.strip():
|
|
252
|
+
wanted = requested.strip()
|
|
253
|
+
matches = [key for key in keys if wanted in _period_candidates(rows_by_role, key, key_column)]
|
|
254
|
+
if not matches:
|
|
255
|
+
available = "、".join(_label(rows_by_role, key, key_column) for key in sorted(keys))
|
|
256
|
+
raise AnalysisInputError(f"报告期 {wanted} 不在这批数据集里;可选:{available}")
|
|
257
|
+
if len(matches) > 1:
|
|
258
|
+
labels = "、".join(_label(rows_by_role, key, key_column) for key in sorted(matches))
|
|
259
|
+
raise AnalysisInputError(
|
|
260
|
+
f"报告期 {wanted} 同时匹配多个报告期({labels}):请写完整报告期,如 {_label(rows_by_role, matches[0], key_column)}"
|
|
261
|
+
)
|
|
262
|
+
return matches[0]
|
|
263
|
+
return max(keys)
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
def _param_number(params, name, default):
|
|
267
|
+
value = params.get(name, default)
|
|
268
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
269
|
+
raise AnalysisInputError(f"{name} 必须是数字,实际是 {value!r}")
|
|
270
|
+
number = float(value)
|
|
271
|
+
if number != number or number in (float("inf"), float("-inf")):
|
|
272
|
+
raise AnalysisInputError(f"{name} 必须是有限数字")
|
|
273
|
+
if number < 0:
|
|
274
|
+
raise AnalysisInputError(f"{name} 必须 ≥ 0,实际是 {number}")
|
|
275
|
+
return number
|
|
276
|
+
|
|
277
|
+
|
|
278
|
+
def _tolerance(tolerance_ratio, tolerance_abs, scale):
|
|
279
|
+
return tolerance_abs + tolerance_ratio * scale
|
|
280
|
+
|
|
281
|
+
|
|
282
|
+
def _check(name, left, right, inputs, tolerance_ratio, tolerance_abs, reason=None):
|
|
283
|
+
"""Compare the two sides of one identity and return the audit row plus its metrics."""
|
|
284
|
+
residual = float(left) - float(right)
|
|
285
|
+
scale = max(abs(float(left)), abs(float(right)))
|
|
286
|
+
tolerance = _tolerance(tolerance_ratio, tolerance_abs, scale)
|
|
287
|
+
row = {
|
|
288
|
+
"check": name,
|
|
289
|
+
"label": CHECK_LABELS[name],
|
|
290
|
+
"formula": CHECK_FORMULAS[name],
|
|
291
|
+
"status": "pass" if abs(residual) <= tolerance else "fail",
|
|
292
|
+
"residual": _amount(residual),
|
|
293
|
+
"scale": _amount(scale),
|
|
294
|
+
"tolerance": _amount(tolerance),
|
|
295
|
+
"residual_ratio": None if scale == 0 else _round(residual / scale),
|
|
296
|
+
"inputs": {field: _amount(value) for field, value in inputs.items()},
|
|
297
|
+
}
|
|
298
|
+
if reason:
|
|
299
|
+
row["reason"] = reason
|
|
300
|
+
metrics = {
|
|
301
|
+
f"{name}_checked": True,
|
|
302
|
+
f"{name}_residual": _amount(residual),
|
|
303
|
+
f"{name}_scale": _amount(scale),
|
|
304
|
+
f"{name}_residual_ratio": row["residual_ratio"],
|
|
305
|
+
f"{name}_within_tolerance": row["status"] == "pass",
|
|
306
|
+
}
|
|
307
|
+
return row, metrics
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _skipped(name, reason):
|
|
311
|
+
return {
|
|
312
|
+
"check": name,
|
|
313
|
+
"label": CHECK_LABELS[name],
|
|
314
|
+
"formula": CHECK_FORMULAS[name],
|
|
315
|
+
"status": "skipped",
|
|
316
|
+
"residual": None,
|
|
317
|
+
"scale": None,
|
|
318
|
+
"tolerance": None,
|
|
319
|
+
"residual_ratio": None,
|
|
320
|
+
"inputs": {},
|
|
321
|
+
"reason": reason,
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def _skip_pair(name, reason):
|
|
326
|
+
return _skipped(name, reason), {f"{name}_checked": False}
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def _money_text(value):
|
|
330
|
+
return str(_amount(value))
|
|
331
|
+
|
|
332
|
+
|
|
333
|
+
def _summary(label, checks, gaps, tolerance_ratio, tolerance_abs):
|
|
334
|
+
ran = [row for row in checks if row["status"] in ("pass", "fail")]
|
|
335
|
+
if not ran:
|
|
336
|
+
return f"三表勾稽没有可执行的校验:{len(gaps)} 项缺口,见 data_gaps。"
|
|
337
|
+
parts = []
|
|
338
|
+
for row in ran:
|
|
339
|
+
amount = _money_text(row["residual"])
|
|
340
|
+
tolerance_text = f"{tolerance_ratio * 100:.2f}%"
|
|
341
|
+
if tolerance_abs:
|
|
342
|
+
tolerance_text += f" + {tolerance_abs:g}"
|
|
343
|
+
if row["status"] == "pass":
|
|
344
|
+
parts.append(f"{row['label']}差异 {amount}(容差 {tolerance_text},通过)")
|
|
345
|
+
else:
|
|
346
|
+
ratio = 0.0 if row["residual_ratio"] is None else row["residual_ratio"] * 100
|
|
347
|
+
parts.append(f"{row['label']}差异 {amount}(占基准 {ratio:.2f}%,容差 {tolerance_text},未通过)")
|
|
348
|
+
failed = sum(1 for row in ran if row["status"] == "fail")
|
|
349
|
+
tail = f"共 {len(ran)} 项校验,{failed} 项未通过"
|
|
350
|
+
if gaps:
|
|
351
|
+
tail += f";另有 {len(gaps)} 项缺口"
|
|
352
|
+
return f"{label} 三表勾稽:" + ";".join(parts) + "。" + tail + "。"
|
|
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 _currency(rows_by_role, key):
|
|
371
|
+
for role in ("balance", "income", "cashflow"):
|
|
372
|
+
row = _row_at(rows_by_role, key, role)
|
|
373
|
+
if isinstance(row, dict) and isinstance(row.get("currency"), str) and row["currency"]:
|
|
374
|
+
return row["currency"]
|
|
375
|
+
return None
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _balance_check(rows_by_role, key, label, tolerance_ratio, tolerance_abs):
|
|
379
|
+
row = _row_at(rows_by_role, key, "balance")
|
|
380
|
+
if row is None:
|
|
381
|
+
return _skip_pair("balance", f"{label} 没有资产负债表数据行")
|
|
382
|
+
assets = _number(row, "assets_total")
|
|
383
|
+
liabilities = _number(row, "total_debt")
|
|
384
|
+
equity = _number(row, "holder_equity_total")
|
|
385
|
+
missing = []
|
|
386
|
+
if assets is None:
|
|
387
|
+
missing.append("assets_total")
|
|
388
|
+
if liabilities is None:
|
|
389
|
+
missing.append("total_debt")
|
|
390
|
+
if equity is None:
|
|
391
|
+
missing.append("holder_equity_total")
|
|
392
|
+
if missing:
|
|
393
|
+
return _skip_pair("balance", f"{label} 资产负债表缺 {'、'.join(missing)}(空值或非数字),恒等式无法校验")
|
|
394
|
+
return _check(
|
|
395
|
+
"balance", assets, liabilities + equity,
|
|
396
|
+
{"assets_total": assets, "total_debt": liabilities, "holder_equity_total": equity},
|
|
397
|
+
tolerance_ratio, tolerance_abs,
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def _cash_check(rows_by_role, key, label, views, roles, tolerance_ratio, tolerance_abs):
|
|
402
|
+
row = _row_at(rows_by_role, key, "cashflow")
|
|
403
|
+
if row is None:
|
|
404
|
+
return _skip_pair("cash", f"{label} 没有现金流量表数据行")
|
|
405
|
+
missing = [name for name in (*CASH_COMPONENTS, CASH_TOTAL) if _number(row, name) is None]
|
|
406
|
+
if missing:
|
|
407
|
+
return _skip_pair("cash", f"{label} 现金流量表缺 {'、'.join(missing)}(空值或非数字),对账无法校验")
|
|
408
|
+
left = sum(_number(row, name) for name in CASH_COMPONENTS)
|
|
409
|
+
fx_used = False
|
|
410
|
+
fx_column_present = FX_COLUMN in _columns_of(views[roles["cashflow"]])
|
|
411
|
+
fx = _number(row, FX_COLUMN)
|
|
412
|
+
if fx_column_present and fx is not None:
|
|
413
|
+
left += fx
|
|
414
|
+
fx_used = True
|
|
415
|
+
inputs = {name: _number(row, name) for name in CASH_COMPONENTS}
|
|
416
|
+
inputs[CASH_TOTAL] = _number(row, CASH_TOTAL)
|
|
417
|
+
if fx_used:
|
|
418
|
+
inputs[FX_COLUMN] = fx
|
|
419
|
+
result, metrics = _check(
|
|
420
|
+
"cash", left, _number(row, CASH_TOTAL), inputs,
|
|
421
|
+
tolerance_ratio, tolerance_abs,
|
|
422
|
+
)
|
|
423
|
+
result["foreign_exchange_included"] = fx_used
|
|
424
|
+
return result, metrics
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def _dividends(rows_by_role, key):
|
|
428
|
+
"""Cash dividends actually paid: an explicit column, never the combined dividend/interest line."""
|
|
429
|
+
for role in ("cashflow", "balance", "income"):
|
|
430
|
+
row = _row_at(rows_by_role, key, role)
|
|
431
|
+
if row is None:
|
|
432
|
+
continue
|
|
433
|
+
for column in DIVIDEND_COLUMNS:
|
|
434
|
+
value = _number(row, column)
|
|
435
|
+
if value is not None:
|
|
436
|
+
return value, f"{role}.{column}"
|
|
437
|
+
return None, None
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def _retained_earnings_check(rows_by_role, key, label, tolerance_ratio, tolerance_abs, gaps):
|
|
441
|
+
balance = rows_by_role.get("balance") or {}
|
|
442
|
+
current = _row_at(rows_by_role, key, "balance")
|
|
443
|
+
if current is None:
|
|
444
|
+
return _skip_pair("retained_earnings", f"{label} 没有资产负债表数据行")
|
|
445
|
+
if "retained_earnings" not in current:
|
|
446
|
+
return _skip_pair("retained_earnings", f"{label} 资产负债表没有 retained_earnings 列,无法核对留存收益滚动")
|
|
447
|
+
re_end = _number(current, "retained_earnings")
|
|
448
|
+
if re_end is None:
|
|
449
|
+
return _skip_pair("retained_earnings", f"{label} retained_earnings 为空值,无法核对留存收益滚动")
|
|
450
|
+
previous_keys = [candidate for candidate in balance if candidate < key]
|
|
451
|
+
if not previous_keys:
|
|
452
|
+
return _skip_pair("retained_earnings", f"没有早于 {label} 的资产负债表报告期,无法核对留存收益滚动")
|
|
453
|
+
previous_key = max(previous_keys)
|
|
454
|
+
previous = balance[previous_key]
|
|
455
|
+
previous_label = _label(rows_by_role, previous_key, "period_end_ms" if isinstance(previous_key, (int, float)) else "period")
|
|
456
|
+
re_prev = _number(previous, "retained_earnings")
|
|
457
|
+
income = _row_at(rows_by_role, key, "income")
|
|
458
|
+
net_profit = _number(income, "net_profit")
|
|
459
|
+
missing = []
|
|
460
|
+
if re_prev is None:
|
|
461
|
+
missing.append(f"{previous_label} retained_earnings")
|
|
462
|
+
if net_profit is None:
|
|
463
|
+
missing.append(f"{label} net_profit")
|
|
464
|
+
if missing:
|
|
465
|
+
return _skip_pair("retained_earnings", f"留存收益滚动缺 {'、'.join(missing)}(空值或非数字)")
|
|
466
|
+
dividends, dividends_source = _dividends(rows_by_role, key)
|
|
467
|
+
if dividends is None:
|
|
468
|
+
return _skip_pair(
|
|
469
|
+
"retained_earnings",
|
|
470
|
+
f"{label} 没有 dividends_paid / dividends_declared 列:分配股利口径缺失,无法核对留存收益滚动",
|
|
471
|
+
)
|
|
472
|
+
surplus_delta = 0.0
|
|
473
|
+
surplus_note = None
|
|
474
|
+
if _number(current, "surplus_reserve") is not None and _number(previous, "surplus_reserve") is not None:
|
|
475
|
+
surplus_delta = _number(current, "surplus_reserve") - _number(previous, "surplus_reserve")
|
|
476
|
+
else:
|
|
477
|
+
surplus_note = f"{label} 资产负债表没有可比的 surplus_reserve 列:留存收益滚动未扣除盈余公积变动,差异可能包含该部分"
|
|
478
|
+
gaps.append(surplus_note)
|
|
479
|
+
inputs = {
|
|
480
|
+
"retained_earnings_end": re_end,
|
|
481
|
+
"retained_earnings_previous": re_prev,
|
|
482
|
+
"net_profit": net_profit,
|
|
483
|
+
"dividends_paid": dividends,
|
|
484
|
+
"surplus_reserve_delta": surplus_delta,
|
|
485
|
+
}
|
|
486
|
+
right = re_prev + net_profit - dividends - surplus_delta
|
|
487
|
+
result, metrics = _check("retained_earnings", re_end, right, inputs, tolerance_ratio, tolerance_abs)
|
|
488
|
+
result["previous_period"] = previous_label
|
|
489
|
+
result["dividends_source"] = dividends_source
|
|
490
|
+
if surplus_note:
|
|
491
|
+
result["surplus_reserve_missing"] = True
|
|
492
|
+
return result, metrics
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def analyze(request: dict, context) -> dict:
|
|
496
|
+
params = request.get("params") or {}
|
|
497
|
+
tolerance_ratio = _param_number(params, "tolerance_ratio", DEFAULT_TOLERANCE_RATIO)
|
|
498
|
+
tolerance_abs = _param_number(params, "tolerance_abs", 0.0)
|
|
499
|
+
views = _read_datasets(request, context)
|
|
500
|
+
roles = _resolve_roles(views, params)
|
|
501
|
+
|
|
502
|
+
methodology = [
|
|
503
|
+
"按列签名识别报表:" + "、".join(f"{role}={dataset_id}" for role, dataset_id in sorted(roles.items())),
|
|
504
|
+
f"容差:|差异| ≤ {tolerance_abs:g} + {tolerance_ratio:g} × 对账基准(基准 = 恒等式两边绝对值较大者)",
|
|
505
|
+
]
|
|
506
|
+
limitations = list(LIMITATIONS)
|
|
507
|
+
gaps = []
|
|
508
|
+
checks = []
|
|
509
|
+
|
|
510
|
+
ignored = sorted(set(views) - set(roles.values()))
|
|
511
|
+
for dataset_id in ignored:
|
|
512
|
+
limitations.append(f"Dataset {dataset_id} 不是三张报表(列签名不匹配),未参与勾稽")
|
|
513
|
+
for role, dataset_id in sorted(roles.items()):
|
|
514
|
+
view = views[dataset_id]
|
|
515
|
+
if view.get("truncated"):
|
|
516
|
+
limitations.append(
|
|
517
|
+
f"{LABELS[role]} {dataset_id} 被截断到 {len(view.get('rows') or [])} 行(max_input_rows),"
|
|
518
|
+
"勾稽只覆盖截断后的样本"
|
|
519
|
+
)
|
|
520
|
+
|
|
521
|
+
for role in ("balance", "cashflow", "income"):
|
|
522
|
+
if role not in roles:
|
|
523
|
+
gaps.append(f"缺少{LABELS[role]}数据集:相关勾稽未校验")
|
|
524
|
+
|
|
525
|
+
key_column = _join_key(roles, views)
|
|
526
|
+
if key_column == "period":
|
|
527
|
+
limitations.append("报告期按 period 字符串排序取最新期(没有 period_end_ms 列):格式不一致时可能选错报告期")
|
|
528
|
+
rows_by_role = {role: _index_rows(views[dataset_id], key_column, role) for role, dataset_id in roles.items()}
|
|
529
|
+
selected = _select_period(rows_by_role, params, key_column)
|
|
530
|
+
label = _label(rows_by_role, selected, key_column)
|
|
531
|
+
methodology.append(f"报告期键 {key_column};选中 {label}")
|
|
532
|
+
|
|
533
|
+
metrics = {}
|
|
534
|
+
if "balance" in roles:
|
|
535
|
+
check, check_metrics = _balance_check(rows_by_role, selected, label, tolerance_ratio, tolerance_abs)
|
|
536
|
+
else:
|
|
537
|
+
check, check_metrics = _skip_pair("balance", "缺少资产负债表数据集")
|
|
538
|
+
metrics.update(check_metrics)
|
|
539
|
+
if check["status"] == "skipped":
|
|
540
|
+
gaps.append(f"{CHECK_LABELS['balance']}未校验:{check['reason']}")
|
|
541
|
+
else:
|
|
542
|
+
methodology.append(
|
|
543
|
+
f"资产负债恒等式差异 {check['residual']},基准 {check['scale']},{'通过' if check['status'] == 'pass' else '未通过'}"
|
|
544
|
+
)
|
|
545
|
+
checks.append(check)
|
|
546
|
+
|
|
547
|
+
if "cashflow" in roles:
|
|
548
|
+
check, check_metrics = _cash_check(rows_by_role, selected, label, views, roles, tolerance_ratio, tolerance_abs)
|
|
549
|
+
else:
|
|
550
|
+
check, check_metrics = _skip_pair("cash", "缺少现金流量表数据集")
|
|
551
|
+
metrics.update(check_metrics)
|
|
552
|
+
if check["status"] == "skipped":
|
|
553
|
+
gaps.append(f"{CHECK_LABELS['cash']}未校验:{check['reason']}")
|
|
554
|
+
else:
|
|
555
|
+
methodology.append(
|
|
556
|
+
f"现金流对账差异 {check['residual']},基准 {check['scale']},{'通过' if check['status'] == 'pass' else '未通过'}"
|
|
557
|
+
)
|
|
558
|
+
if check.get("foreign_exchange_included"):
|
|
559
|
+
methodology.append(f"现金流对账已计入 {FX_COLUMN}(汇率变动影响)")
|
|
560
|
+
else:
|
|
561
|
+
limitations.append(f"数据集没有 {FX_COLUMN} 列:现金流对账未计入汇率变动影响")
|
|
562
|
+
checks.append(check)
|
|
563
|
+
|
|
564
|
+
check, check_metrics = _retained_earnings_check(rows_by_role, selected, label, tolerance_ratio, tolerance_abs, gaps)
|
|
565
|
+
metrics.update(check_metrics)
|
|
566
|
+
if check["status"] == "skipped":
|
|
567
|
+
gaps.append(f"{CHECK_LABELS['retained_earnings']}未校验:{check['reason']}")
|
|
568
|
+
else:
|
|
569
|
+
methodology.append(
|
|
570
|
+
f"留存收益滚动(上一期 {check['previous_period']})差异 {check['residual']},"
|
|
571
|
+
f"基准 {check['scale']},{'通过' if check['status'] == 'pass' else '未通过'}"
|
|
572
|
+
)
|
|
573
|
+
checks.append(check)
|
|
574
|
+
|
|
575
|
+
currency = _currency(rows_by_role, selected)
|
|
576
|
+
metrics["checks_run"] = sum(1 for row in checks if row["status"] in ("pass", "fail"))
|
|
577
|
+
metrics["checks_failed"] = sum(1 for row in checks if row["status"] == "fail")
|
|
578
|
+
metrics["tolerance_ratio"] = tolerance_ratio
|
|
579
|
+
metrics["tolerance_abs"] = tolerance_abs
|
|
580
|
+
if currency:
|
|
581
|
+
metrics["currency"] = currency
|
|
582
|
+
|
|
583
|
+
ran = [row for row in checks if row["status"] in ("pass", "fail")]
|
|
584
|
+
status = "blocked" if not ran else ("partial" if gaps else "completed")
|
|
585
|
+
findings = [
|
|
586
|
+
f"{row['label']}差异 {_money_text(row['residual'])} 超过容差 {_money_text(row['tolerance'])}(占基准 "
|
|
587
|
+
f"{(0.0 if row['residual_ratio'] is None else row['residual_ratio']) * 100:.2f}%)"
|
|
588
|
+
for row in ran if row["status"] == "fail"
|
|
589
|
+
]
|
|
590
|
+
failures = [row["check"] for row in ran if row["status"] == "fail"]
|
|
591
|
+
methodology.append(f"执行 {len(ran)} 项勾稽,{len(failures)} 项未通过;{len(gaps)} 项缺口")
|
|
592
|
+
|
|
593
|
+
payload = {
|
|
594
|
+
"protocol": "capital.analysis/v1",
|
|
595
|
+
"module_id": MODULE_ID,
|
|
596
|
+
"module_version": MODULE_VERSION,
|
|
597
|
+
"analysis_id": request.get("analysis_id"),
|
|
598
|
+
"module_run_id": request.get("module_run_id"),
|
|
599
|
+
"period": label,
|
|
600
|
+
"period_key": key_column,
|
|
601
|
+
"statements": {role: dataset_id for role, dataset_id in sorted(roles.items())},
|
|
602
|
+
"parameters": {
|
|
603
|
+
"tolerance_ratio": tolerance_ratio,
|
|
604
|
+
"tolerance_abs": tolerance_abs,
|
|
605
|
+
},
|
|
606
|
+
"checks": checks,
|
|
607
|
+
"findings": findings,
|
|
608
|
+
"data_gaps": gaps,
|
|
609
|
+
}
|
|
610
|
+
ref = context.write_output(OUTPUT_NAME, payload)
|
|
611
|
+
context.log(f"{MODULE_ID}: {status} period={label} checks={len(ran)} failed={len(failures)} gaps={len(gaps)}")
|
|
612
|
+
|
|
613
|
+
return _result(
|
|
614
|
+
status,
|
|
615
|
+
_summary(label, checks, gaps, tolerance_ratio, tolerance_abs),
|
|
616
|
+
metrics,
|
|
617
|
+
methodology,
|
|
618
|
+
limitations,
|
|
619
|
+
gaps,
|
|
620
|
+
[{"name": OUTPUT_NAME, "ref": ref}],
|
|
621
|
+
)
|
|
@@ -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.
|