@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,61 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "comps_valuation",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"entrypoint": "module.py",
|
|
5
|
+
"runtime": "python",
|
|
6
|
+
"description": "可比倍数横截面:按同口径 peers 表算 P/E、P/B、P/S、EV/EBITDA 的截面中位数与计数,可选一只标的做相对溢价/折价;不评级、不给目标价",
|
|
7
|
+
"roles": ["senior_analyst"],
|
|
8
|
+
"capabilities": ["dataset.read"],
|
|
9
|
+
"required_fields": [],
|
|
10
|
+
"input_schema": {
|
|
11
|
+
"type": "object",
|
|
12
|
+
"properties": {
|
|
13
|
+
"peers_dataset_id": { "type": "string", "maxLength": 128, "description": "可比公司横截面 Dataset(一行一家);只有一份像 peers 表时可省略" },
|
|
14
|
+
"subject_dataset_id": { "type": "string", "maxLength": 128, "description": "可选:被比较标的的横截面 Dataset(一行);不给就只报 peers 中位数" },
|
|
15
|
+
"ticker_column": { "type": "string", "maxLength": 64, "description": "公司标识列名;省略按 ticker / thscode / code 识别,找不到就用行号" },
|
|
16
|
+
"period_note": { "type": "string", "maxLength": 64, "description": "口径备注(如 2024-TTM / 2024-12-31);只写入结果,不参与计算" }
|
|
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
|
+
"一行是一家公司的一个同口径截面:市值、净利润、净资产、营收、企业价值与 EBITDA 必须同为同一报告期、同一币种;模块不检查跨期或跨币种混用",
|
|
42
|
+
"P/E = market_cap / net_profit,只对净利润 > 0 的公司计算;亏损公司的 P/E 无经济含义,剔除并计数,不用负值参与中位数",
|
|
43
|
+
"P/B = market_cap / equity、P/S = market_cap / revenue 只对分母 > 0 的公司计算",
|
|
44
|
+
"EV/EBITDA 使用数据集自带的 enterprise_value 与 ebitda 两列;缺任一一列就不算,不用 market_cap + net_debt 反推",
|
|
45
|
+
"截面统计只报中位数与有效样本数:样本 < 3 时中位数没有横截面意义,写进 limitations;不把均值或最高/最低值当估值结论",
|
|
46
|
+
"可选标的的相对位置只是 same-period 截面上的溢价/折价,不构成目标价、评级或买卖建议"
|
|
47
|
+
],
|
|
48
|
+
"applicability": [
|
|
49
|
+
"peers 表至少 2 列:market_cap 与 net_profit;equity / revenue / enterprise_value / ebitda 为可选列,缺列只影响对应倍数",
|
|
50
|
+
"同一行的所有金额列必须同币种、同报告期;一行一家公司,ticker 重复视为输入错误",
|
|
51
|
+
"适用成熟上市公司之间的相对估值;亏损、金融企业、重组或跨行业混用会显著削弱可比性,需调用方自行披露",
|
|
52
|
+
"不适用于绝对估值、DCF、交易可比(并购溢价)或需要调整报表口径的场景"
|
|
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
|
+
}
|
|
@@ -0,0 +1,360 @@
|
|
|
1
|
+
"""Comparable multiples across one same-period cross-section.
|
|
2
|
+
|
|
3
|
+
The input is a peers table: one row per company, all money columns already on the same reporting
|
|
4
|
+
period and currency. The module computes P/E, P/B, P/S and EV/EBITDA per row, reports the
|
|
5
|
+
cross-sectional median with its valid sample count, and optionally places a subject company against
|
|
6
|
+
that median. It never fills a missing multiple with a default, never uses a negative-earnings P/E in
|
|
7
|
+
the median, and never turns the median into 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 multiples plus the input values behind each one.
|
|
11
|
+
"""
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
MODULE_ID = "comps_valuation"
|
|
15
|
+
MODULE_VERSION = "1.0.0"
|
|
16
|
+
OUTPUT_NAME = "comps"
|
|
17
|
+
|
|
18
|
+
# Mirrors module.json `assumptions`: a result must state the same caveats the manifest promises.
|
|
19
|
+
ASSUMPTIONS = [
|
|
20
|
+
"一行是一家公司的一个同口径截面:市值、净利润、净资产、营收、企业价值与 EBITDA 必须同为同一报告期、同一币种;模块不检查跨期或跨币种混用",
|
|
21
|
+
"P/E = market_cap / net_profit,只对净利润 > 0 的公司计算;亏损公司的 P/E 无经济含义,剔除并计数,不用负值参与中位数",
|
|
22
|
+
"P/B = market_cap / equity、P/S = market_cap / revenue 只对分母 > 0 的公司计算",
|
|
23
|
+
"EV/EBITDA 使用数据集自带的 enterprise_value 与 ebitda 两列;缺任一一列就不算,不用 market_cap + net_debt 反推",
|
|
24
|
+
"截面统计只报中位数与有效样本数:样本 < 3 时中位数没有横截面意义,写进 limitations;不把均值或最高/最低值当估值结论",
|
|
25
|
+
"可选标的的相对位置只是 same-period 截面上的溢价/折价,不构成目标价、评级或买卖建议",
|
|
26
|
+
]
|
|
27
|
+
|
|
28
|
+
LIMITATIONS = [
|
|
29
|
+
"可比性是调用方选的:同行业、同商业模式与同会计口径不在本模块的校验范围内",
|
|
30
|
+
"亏损、负净资产、零营收与缺失 EBITDA 的公司会退出对应倍数的样本;每项的剔除数在 metrics 里单独列出",
|
|
31
|
+
"中位数只描述这一组 peer 的截面,不推断合理估值区间,也不代表市场价格应当回归中位数",
|
|
32
|
+
"不构成投资建议,也不产生评级、目标价或收益承诺",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
SIGNATURE = ("market_cap", "net_profit")
|
|
36
|
+
TICKER_COLUMNS = ("ticker", "thscode", "code")
|
|
37
|
+
MULTIPLES = (
|
|
38
|
+
("pe", "P/E", "market_cap", "net_profit"),
|
|
39
|
+
("pb", "P/B", "market_cap", "equity"),
|
|
40
|
+
("ps", "P/S", "market_cap", "revenue"),
|
|
41
|
+
("ev_ebitda", "EV/EBITDA", "enterprise_value", "ebitda"),
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class AnalysisInputError(Exception):
|
|
46
|
+
"""The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
|
|
47
|
+
|
|
48
|
+
analysis_code = "analysis_input_invalid"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _round(value):
|
|
52
|
+
rounded = round(float(value), 6)
|
|
53
|
+
return 0.0 if rounded == 0 else rounded
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _plain(value):
|
|
57
|
+
return int(value) if isinstance(value, float) and value.is_integer() else value
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def _number(row, name):
|
|
61
|
+
if row is None:
|
|
62
|
+
return None
|
|
63
|
+
value = row.get(name)
|
|
64
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
65
|
+
return None
|
|
66
|
+
number = float(value)
|
|
67
|
+
if number != number or number in (float("inf"), float("-inf")):
|
|
68
|
+
return None
|
|
69
|
+
return number
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _columns_of(view):
|
|
73
|
+
columns = view.get("columns") or []
|
|
74
|
+
names = {item.get("name") for item in columns if isinstance(item, dict)}
|
|
75
|
+
for row in (view.get("rows") or [])[:1]:
|
|
76
|
+
if isinstance(row, dict):
|
|
77
|
+
names |= set(row)
|
|
78
|
+
return names
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _read_datasets(request, context):
|
|
82
|
+
items = (request.get("inputs") or {}).get("datasets") or []
|
|
83
|
+
if not items:
|
|
84
|
+
raise AnalysisInputError("快照里没有任何 Dataset:comps_valuation 需要同行同期的 peers 横截面")
|
|
85
|
+
views = {}
|
|
86
|
+
for item in items:
|
|
87
|
+
dataset_id = (item or {}).get("dataset_id")
|
|
88
|
+
if not isinstance(dataset_id, str) or not dataset_id:
|
|
89
|
+
raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
|
|
90
|
+
views[dataset_id] = context.read_dataset(dataset_id)
|
|
91
|
+
for dataset_id, view in views.items():
|
|
92
|
+
if view.get("shape") != "rows":
|
|
93
|
+
raise AnalysisInputError(
|
|
94
|
+
f"Dataset {dataset_id} 是 {view.get('shape')} 型:comps_valuation 只吃表格数据,"
|
|
95
|
+
"文档型输入请先走 profile 或证据"
|
|
96
|
+
)
|
|
97
|
+
return views
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _select_datasets(views, params):
|
|
101
|
+
peers_id = params.get("peers_dataset_id")
|
|
102
|
+
subject_id = params.get("subject_dataset_id")
|
|
103
|
+
candidates = sorted(
|
|
104
|
+
dataset_id for dataset_id, view in views.items()
|
|
105
|
+
if all(name in _columns_of(view) for name in SIGNATURE)
|
|
106
|
+
)
|
|
107
|
+
if isinstance(peers_id, str) and peers_id:
|
|
108
|
+
if peers_id not in views:
|
|
109
|
+
raise AnalysisInputError(f"peers_dataset_id={peers_id} 不在本次快照的 Dataset 里")
|
|
110
|
+
missing = [name for name in SIGNATURE if name not in _columns_of(views[peers_id])]
|
|
111
|
+
if missing:
|
|
112
|
+
raise AnalysisInputError(f"peers Dataset {peers_id} 缺少 {'、'.join(missing)} 列:不是可比倍数表")
|
|
113
|
+
peers = peers_id
|
|
114
|
+
else:
|
|
115
|
+
if not candidates:
|
|
116
|
+
raise AnalysisInputError(
|
|
117
|
+
"没有任何 Dataset 同时含 market_cap 与 net_profit:comps_valuation 需要同行同期的 peers 横截面"
|
|
118
|
+
)
|
|
119
|
+
if len(candidates) > 1:
|
|
120
|
+
raise AnalysisInputError(
|
|
121
|
+
f"有 {len(candidates)} 份 Dataset 都像 peers 表({'、'.join(candidates)}):"
|
|
122
|
+
"用 peers_dataset_id 指明 peers、subject_dataset_id 指明标的"
|
|
123
|
+
)
|
|
124
|
+
peers = candidates[0]
|
|
125
|
+
subject = None
|
|
126
|
+
if isinstance(subject_id, str) and subject_id:
|
|
127
|
+
if subject_id not in views:
|
|
128
|
+
raise AnalysisInputError(f"subject_dataset_id={subject_id} 不在本次快照的 Dataset 里")
|
|
129
|
+
missing = [name for name in ("market_cap", "net_profit") if name not in _columns_of(views[subject_id])]
|
|
130
|
+
if missing:
|
|
131
|
+
raise AnalysisInputError(f"subject Dataset {subject_id} 缺少 {'、'.join(missing)} 列:无法计算标的倍数")
|
|
132
|
+
subject = subject_id
|
|
133
|
+
elif len(candidates) > 1 and peers in candidates:
|
|
134
|
+
raise AnalysisInputError("有多份 Dataset 像 peers 表:请同时用 subject_dataset_id 指明标的,避免把另一份误当 peers")
|
|
135
|
+
return peers, subject
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
def _rows_of(view, role):
|
|
139
|
+
rows = view.get("rows") or []
|
|
140
|
+
if not rows:
|
|
141
|
+
raise AnalysisInputError(f"{role} Dataset 没有任何数据行")
|
|
142
|
+
for index, row in enumerate(rows):
|
|
143
|
+
if not isinstance(row, dict):
|
|
144
|
+
raise AnalysisInputError(f"{role} Dataset 第 {index + 1} 行不是对象:无法计算")
|
|
145
|
+
return rows
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _ticker_column(view, params):
|
|
149
|
+
explicit = params.get("ticker_column")
|
|
150
|
+
if isinstance(explicit, str) and explicit:
|
|
151
|
+
if explicit not in _columns_of(view):
|
|
152
|
+
raise AnalysisInputError(f"ticker_column={explicit} 不在 peers Dataset 的列里")
|
|
153
|
+
return explicit
|
|
154
|
+
for name in TICKER_COLUMNS:
|
|
155
|
+
if name in _columns_of(view):
|
|
156
|
+
return name
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def _multiple_name(code):
|
|
161
|
+
for candidate, label, _, _ in MULTIPLES:
|
|
162
|
+
if candidate == code:
|
|
163
|
+
return label
|
|
164
|
+
return code
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
def _multiples_of(row):
|
|
168
|
+
"""Every multiple this row can support; denominators must be economically meaningful."""
|
|
169
|
+
market_cap = _number(row, "market_cap")
|
|
170
|
+
net_profit = _number(row, "net_profit")
|
|
171
|
+
equity = _number(row, "equity")
|
|
172
|
+
revenue = _number(row, "revenue")
|
|
173
|
+
enterprise_value = _number(row, "enterprise_value")
|
|
174
|
+
ebitda = _number(row, "ebitda")
|
|
175
|
+
values = {}
|
|
176
|
+
if market_cap is not None and net_profit is not None and net_profit > 0:
|
|
177
|
+
values["pe"] = market_cap / net_profit
|
|
178
|
+
if market_cap is not None and equity is not None and equity > 0:
|
|
179
|
+
values["pb"] = market_cap / equity
|
|
180
|
+
if market_cap is not None and revenue is not None and revenue > 0:
|
|
181
|
+
values["ps"] = market_cap / revenue
|
|
182
|
+
if enterprise_value is not None and ebitda is not None and ebitda > 0:
|
|
183
|
+
values["ev_ebitda"] = enterprise_value / ebitda
|
|
184
|
+
return values, {
|
|
185
|
+
"market_cap": market_cap,
|
|
186
|
+
"net_profit": net_profit,
|
|
187
|
+
"equity": equity,
|
|
188
|
+
"revenue": revenue,
|
|
189
|
+
"enterprise_value": enterprise_value,
|
|
190
|
+
"ebitda": ebitda,
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _median(values):
|
|
195
|
+
ordered = sorted(values)
|
|
196
|
+
middle = len(ordered) // 2
|
|
197
|
+
if len(ordered) % 2:
|
|
198
|
+
return ordered[middle]
|
|
199
|
+
return (ordered[middle - 1] + ordered[middle]) / 2
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _ratio_text(value):
|
|
203
|
+
text = f"{value:.4f}".rstrip("0").rstrip(".")
|
|
204
|
+
return text if text not in ("", "-0") else "0"
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _summary(peer_medians, subject_values, subject_premiums, excluded, gaps, subject_available):
|
|
208
|
+
parts = []
|
|
209
|
+
for code, label in ((item[0], item[1]) for item in MULTIPLES):
|
|
210
|
+
if code not in peer_medians:
|
|
211
|
+
continue
|
|
212
|
+
count = peer_medians[code]["count"]
|
|
213
|
+
median = peer_medians[code]["median"]
|
|
214
|
+
text = f"{label} 中位数 {_ratio_text(median)}({count} 家)"
|
|
215
|
+
if subject_available and code in subject_values:
|
|
216
|
+
premium = subject_premiums[code]
|
|
217
|
+
sign = "+" if premium >= 0 else ""
|
|
218
|
+
text += f",标的 {_ratio_text(subject_values[code])}({sign}{premium * 100:.2f}%)"
|
|
219
|
+
parts.append(text)
|
|
220
|
+
if not parts:
|
|
221
|
+
return "可比倍数没有可计算的样本:所有 peer 的对应分母都不可用,见 data_gaps。"
|
|
222
|
+
head = "可比公司截面:" + ";".join(parts)
|
|
223
|
+
notes = []
|
|
224
|
+
if excluded:
|
|
225
|
+
notes.append("剔除 " + "、".join(f"{label} {count} 家" for label, count in excluded.items()))
|
|
226
|
+
if gaps:
|
|
227
|
+
notes.append(f"{len(gaps)} 项缺口")
|
|
228
|
+
if notes:
|
|
229
|
+
head += "。" + ";".join(notes)
|
|
230
|
+
return head + "。"
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def analyze(request: dict, context) -> dict:
|
|
234
|
+
params = request.get("params") or {}
|
|
235
|
+
views = _read_datasets(request, context)
|
|
236
|
+
peers_id, subject_id = _select_datasets(views, params)
|
|
237
|
+
methodology = [f"peers = {peers_id}" + (f";subject = {subject_id}" if subject_id else ";未提供 subject")]
|
|
238
|
+
limitations = list(LIMITATIONS)
|
|
239
|
+
gaps = []
|
|
240
|
+
|
|
241
|
+
peers_view = views[peers_id]
|
|
242
|
+
if peers_view.get("truncated"):
|
|
243
|
+
limitations.append(
|
|
244
|
+
f"peers Dataset 被截断到 {len(peers_view.get('rows') or [])} 行(max_input_rows):中位数只覆盖截断后的样本"
|
|
245
|
+
)
|
|
246
|
+
peers_rows = _rows_of(peers_view, "peers")
|
|
247
|
+
ticker_column = _ticker_column(peers_view, params)
|
|
248
|
+
|
|
249
|
+
seen_tickers = set()
|
|
250
|
+
peer_records = []
|
|
251
|
+
peer_values = {code: [] for code, _, _, _ in MULTIPLES}
|
|
252
|
+
excluded = {}
|
|
253
|
+
for index, row in enumerate(peers_rows):
|
|
254
|
+
ticker = row.get(ticker_column) if ticker_column else None
|
|
255
|
+
if ticker is not None:
|
|
256
|
+
ticker_text = str(ticker)
|
|
257
|
+
if ticker_text in seen_tickers:
|
|
258
|
+
raise AnalysisInputError(f"peers 表里 ticker {ticker_text} 出现多行:一行只能是一家公司")
|
|
259
|
+
seen_tickers.add(ticker_text)
|
|
260
|
+
label = str(ticker) if ticker is not None else f"row_{index + 1}"
|
|
261
|
+
values, inputs = _multiples_of(row)
|
|
262
|
+
if not values:
|
|
263
|
+
gaps.append(f"{label} 没有可计算的倍数(market_cap / net_profit 或对应分母缺失或不可用)")
|
|
264
|
+
for code, _, numerator, denominator in MULTIPLES:
|
|
265
|
+
if code in values:
|
|
266
|
+
peer_values[code].append(values[code])
|
|
267
|
+
elif _number(row, numerator) is not None and _number(row, denominator) is not None:
|
|
268
|
+
excluded[_multiple_name(code)] = excluded.get(_multiple_name(code), 0) + 1
|
|
269
|
+
peer_records.append({
|
|
270
|
+
"ticker": label,
|
|
271
|
+
"multiples": {code: _round(value) for code, value in values.items()},
|
|
272
|
+
"inputs": {name: _plain(value) if value is not None else None for name, value in inputs.items()},
|
|
273
|
+
})
|
|
274
|
+
|
|
275
|
+
peer_medians = {}
|
|
276
|
+
metrics = {"peers_rows": len(peers_rows), "peers_used": sum(1 for record in peer_records if record["multiples"])}
|
|
277
|
+
for code, label, _, _ in MULTIPLES:
|
|
278
|
+
values = peer_values[code]
|
|
279
|
+
if not values:
|
|
280
|
+
gaps.append(f"{label} 未计算:peers 表没有可用的 {_multiple_name(code)} 样本(缺列、分母 ≤ 0 或全被剔除)")
|
|
281
|
+
metrics[f"{code}_count"] = 0
|
|
282
|
+
continue
|
|
283
|
+
median = _round(_median(values))
|
|
284
|
+
peer_medians[code] = {"median": median, "count": len(values)}
|
|
285
|
+
metrics[f"{code}_count"] = len(values)
|
|
286
|
+
metrics[f"{code}_median"] = median
|
|
287
|
+
methodology.append(f"{label}:{len(values)} 个有效样本,中位数 {_ratio_text(median)}")
|
|
288
|
+
|
|
289
|
+
subject_available = subject_id is not None
|
|
290
|
+
subject_values = {}
|
|
291
|
+
subject_premiums = {}
|
|
292
|
+
if subject_available:
|
|
293
|
+
subject_rows = _rows_of(views[subject_id], "subject")
|
|
294
|
+
if len(subject_rows) != 1:
|
|
295
|
+
raise AnalysisInputError(f"subject Dataset 必须只有一行(当前 {len(subject_rows)} 行):横截面口径一次只比一只标的")
|
|
296
|
+
subject_values, subject_inputs = _multiples_of(subject_rows[0])
|
|
297
|
+
if not subject_values:
|
|
298
|
+
gaps.append("subject 没有可计算的倍数:缺 market_cap / net_profit 或分母不可用")
|
|
299
|
+
for code, label, _, _ in MULTIPLES:
|
|
300
|
+
if code in subject_values:
|
|
301
|
+
metrics[f"{code}_subject"] = _round(subject_values[code])
|
|
302
|
+
if code in peer_medians:
|
|
303
|
+
premium = _round(subject_values[code] / peer_medians[code]["median"] - 1)
|
|
304
|
+
subject_premiums[code] = premium
|
|
305
|
+
metrics[f"{code}_premium"] = premium
|
|
306
|
+
methodology.append(f"{label}:标的 {_ratio_text(subject_values[code])},较中位数 {premium * 100:+.2f}%")
|
|
307
|
+
else:
|
|
308
|
+
gaps.append(f"{label} 的相对位置未计算:peers 侧没有可用中位数")
|
|
309
|
+
methodology.append("subject 倍数:" + "、".join(f"{label} {_ratio_text(subject_values[code])}" for code, label, _, _ in MULTIPLES if code in subject_values))
|
|
310
|
+
subject_payload = {
|
|
311
|
+
"ticker": str(subject_rows[0].get(ticker_column)) if ticker_column and subject_rows[0].get(ticker_column) is not None else "subject",
|
|
312
|
+
"multiples": {code: _round(value) for code, value in subject_values.items()},
|
|
313
|
+
"inputs": {name: _plain(value) if value is not None else None for name, value in subject_inputs.items()},
|
|
314
|
+
}
|
|
315
|
+
else:
|
|
316
|
+
subject_payload = None
|
|
317
|
+
metrics["subject_available"] = subject_available
|
|
318
|
+
|
|
319
|
+
if metrics["peers_used"] == 0 and not subject_values:
|
|
320
|
+
status = "blocked"
|
|
321
|
+
elif gaps:
|
|
322
|
+
status = "partial"
|
|
323
|
+
else:
|
|
324
|
+
status = "completed"
|
|
325
|
+
if metrics["peers_used"] < 3:
|
|
326
|
+
limitations.append(f"peers 有效样本只有 {metrics['peers_used']} 家:中位数没有横截面意义")
|
|
327
|
+
if excluded:
|
|
328
|
+
limitations.append("剔除的样本:" + "、".join(f"{label} {count} 家" for label, count in excluded.items()))
|
|
329
|
+
|
|
330
|
+
payload = {
|
|
331
|
+
"protocol": "capital.analysis/v1",
|
|
332
|
+
"module_id": MODULE_ID,
|
|
333
|
+
"module_version": MODULE_VERSION,
|
|
334
|
+
"analysis_id": request.get("analysis_id"),
|
|
335
|
+
"module_run_id": request.get("module_run_id"),
|
|
336
|
+
"period_note": params.get("period_note"),
|
|
337
|
+
"peers_dataset_id": peers_id,
|
|
338
|
+
"subject_dataset_id": subject_id,
|
|
339
|
+
"ticker_column": ticker_column,
|
|
340
|
+
"peers": peer_records,
|
|
341
|
+
"subject": subject_payload,
|
|
342
|
+
"medians": {code: peer_medians[code] for code in peer_medians},
|
|
343
|
+
"excluded": excluded,
|
|
344
|
+
"data_gaps": gaps,
|
|
345
|
+
}
|
|
346
|
+
ref = context.write_output(OUTPUT_NAME, payload)
|
|
347
|
+
context.log(f"{MODULE_ID}: {status} peers={len(peers_rows)} multiples={len(peer_medians)} gaps={len(gaps)}")
|
|
348
|
+
|
|
349
|
+
return {
|
|
350
|
+
"status": status,
|
|
351
|
+
"summary": _summary(peer_medians, subject_values, subject_premiums, excluded, gaps, subject_available),
|
|
352
|
+
"metrics": metrics,
|
|
353
|
+
"claims": [],
|
|
354
|
+
"assumptions": list(ASSUMPTIONS),
|
|
355
|
+
"methodology_log": methodology,
|
|
356
|
+
"sensitivity": {},
|
|
357
|
+
"limitations": limitations,
|
|
358
|
+
"data_gaps": gaps,
|
|
359
|
+
"outputs": [{"name": OUTPUT_NAME, "ref": ref}],
|
|
360
|
+
}
|
|
@@ -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,58 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "earnings_bridge",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"entrypoint": "module.py",
|
|
5
|
+
"runtime": "python",
|
|
6
|
+
"description": "净利润变动归因(两期收入/净利率分解 + 税前利润/税率分解):把两期净利润差拆成可复算的效应,逐项校验加总回到原差额;不预测、不评级",
|
|
7
|
+
"roles": ["senior_analyst"],
|
|
8
|
+
"capabilities": ["dataset.read"],
|
|
9
|
+
"required_fields": [],
|
|
10
|
+
"input_schema": {
|
|
11
|
+
"type": "object",
|
|
12
|
+
"properties": {
|
|
13
|
+
"period": { "type": "string", "maxLength": 32, "description": "本期报告期:2024 / 2024-FY / 2024-12-30 都认,缺省取最新一期;上一期取早于它的最近一期" },
|
|
14
|
+
"income_dataset_id": { "type": "string", "maxLength": 128, "description": "利润表序列 Dataset;只有一份像利润表时可省略" }
|
|
15
|
+
},
|
|
16
|
+
"additionalProperties": false
|
|
17
|
+
},
|
|
18
|
+
"output_schema": {
|
|
19
|
+
"type": "object",
|
|
20
|
+
"properties": {
|
|
21
|
+
"status": { "type": "string", "enum": ["completed", "partial", "blocked", "failed"] },
|
|
22
|
+
"summary": { "type": "string" },
|
|
23
|
+
"metrics": { "type": "object" },
|
|
24
|
+
"claims": { "type": "array" },
|
|
25
|
+
"assumptions": { "type": "array" },
|
|
26
|
+
"methodology_log": { "type": "array" },
|
|
27
|
+
"sensitivity": { "type": "object" },
|
|
28
|
+
"limitations": { "type": "array" },
|
|
29
|
+
"data_gaps": { "type": "array" },
|
|
30
|
+
"outputs": { "type": "array" }
|
|
31
|
+
},
|
|
32
|
+
"required": [
|
|
33
|
+
"status", "summary", "metrics", "claims", "assumptions", "methodology_log",
|
|
34
|
+
"sensitivity", "limitations", "data_gaps", "outputs"
|
|
35
|
+
],
|
|
36
|
+
"additionalProperties": false
|
|
37
|
+
},
|
|
38
|
+
"assumptions": [
|
|
39
|
+
"收入/净利率分解:net_profit = operating_income × net_margin,差额拆成收入效应、净利率效应与两者交互项,三项之和必须等于净利润差额",
|
|
40
|
+
"税前/税率分解:net_profit = profit_total × (1 − tax_rate),tax_rate = income_tax_expense / profit_total,只对 profit_total > 0 的两期计算;三期效应之和必须等于净利润差额",
|
|
41
|
+
"两期必须来自同一份利润表 Dataset、同一币种与同一合并口径;模块不检查会计政策变更或追溯调整",
|
|
42
|
+
"效应为正表示对净利润变动是正贡献;交互项是两因子同时变动的交叉部分,不小到可以忽略时不得略去",
|
|
43
|
+
"不输出评级、目标价或预测:归因只解释已经发生的差额,不外推下一期"
|
|
44
|
+
],
|
|
45
|
+
"applicability": [
|
|
46
|
+
"利润表序列至少两期,含 operating_income 与 net_profit 两列;税前/税率分解另需 profit_total 与 income_tax_expense 列",
|
|
47
|
+
"报告期键为 period_end_ms 或 period;同一报告期只能一行,报告期格式需一致",
|
|
48
|
+
"A 股与美股利润表均可;累计口径(一季报/中报/三季报)只能与同口径的上期比,本模块不换算年度化",
|
|
49
|
+
"不适用于跨币种、跨合并范围、金融企业专用口径或需要调整一次性项目的场景"
|
|
50
|
+
],
|
|
51
|
+
"limits": {
|
|
52
|
+
"timeout_ms": 30000,
|
|
53
|
+
"max_input_rows": 200000,
|
|
54
|
+
"max_output_bytes": 1048576,
|
|
55
|
+
"max_log_bytes": 65536
|
|
56
|
+
},
|
|
57
|
+
"provenance": { "source_type": "original", "license": "MIT" }
|
|
58
|
+
}
|