@v587d/capital-generation 2.31.3 → 2.31.5

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 (48) hide show
  1. package/CHANGELOG.md +74 -0
  2. package/README.md +46 -8
  3. package/automation/package.json +1 -1
  4. package/chart-ui/package.json +1 -1
  5. package/config/package.json +1 -1
  6. package/lib/analysis/registry.js +6 -1
  7. package/lib/collector-runtime.js +8 -0
  8. package/lib/data-collector/catalog-taxonomy.js +11 -0
  9. package/lib/sources/eastmoney-http.js +274 -0
  10. package/lib/sources/sec-http.d.ts +9 -0
  11. package/lib/sources/sec-http.js +643 -0
  12. package/lib/sources/us-official-http.d.ts +4 -0
  13. package/lib/sources/us-official-http.js +654 -0
  14. package/lib/time/tools.js +6 -0
  15. package/lib/web-retriever/local-fetch.d.ts +1 -1
  16. package/lib/web-retriever/local-fetch.js +1 -1
  17. package/lib/web-retriever/wind-client.d.ts +1 -1
  18. package/lib/web-retriever/wind-client.js +1 -1
  19. package/package.json +1 -1
  20. package/plugin-page/README.en.md +7 -0
  21. package/plugin-page/README.zh.md +7 -0
  22. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +47 -37
  23. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +4 -2
  24. package/python/analysis/modules/comps_valuation/LICENSE +21 -0
  25. package/python/analysis/modules/comps_valuation/module.json +61 -0
  26. package/python/analysis/modules/comps_valuation/module.py +360 -0
  27. package/python/analysis/modules/earnings_bridge/LICENSE +21 -0
  28. package/python/analysis/modules/earnings_bridge/module.json +58 -0
  29. package/python/analysis/modules/earnings_bridge/module.py +452 -0
  30. package/python/analysis/modules/kline_quality/LICENSE +21 -0
  31. package/python/analysis/modules/kline_quality/module.json +61 -0
  32. package/python/analysis/modules/kline_quality/module.py +538 -0
  33. package/python/analysis/modules/portfolio_stress/LICENSE +21 -0
  34. package/python/analysis/modules/portfolio_stress/module.json +89 -0
  35. package/python/analysis/modules/portfolio_stress/module.py +537 -0
  36. package/python/analysis/modules/simple_backtest/LICENSE +21 -0
  37. package/python/analysis/modules/simple_backtest/module.json +66 -0
  38. package/python/analysis/modules/simple_backtest/module.py +648 -0
  39. package/python/analysis/modules/statement_integrity/LICENSE +21 -0
  40. package/python/analysis/modules/statement_integrity/module.json +62 -0
  41. package/python/analysis/modules/statement_integrity/module.py +621 -0
  42. package/python/analysis/modules/technical_indicators/LICENSE +21 -0
  43. package/python/analysis/modules/technical_indicators/module.json +170 -0
  44. package/python/analysis/modules/technical_indicators/module.py +854 -0
  45. package/python/analysis/modules/valuation_sensitivity/LICENSE +21 -0
  46. package/python/analysis/modules/valuation_sensitivity/module.json +73 -0
  47. package/python/analysis/modules/valuation_sensitivity/module.py +589 -0
  48. package/watchlist/package.json +1 -1
@@ -0,0 +1,589 @@
1
+ """DCF model value plus WACC x terminal-growth sensitivity, from caller-stated assumptions only.
2
+
3
+ This is the "explicit valuation assumptions" shape of the module protocol: parameters only, no
4
+ Dataset. The caller supplies the projection-period FCFs, either WACC or the six CAPM inputs, the
5
+ perpetual growth rate, net debt, minority interest and diluted shares. The module discounts those
6
+ cash flows, builds the EV -> equity bridge and evaluates the caller's (or a default) WACC x growth
7
+ grid. It does not estimate FCF, pick a discount rate, forecast a price, rate the company or treat
8
+ the grid as a confidence interval: every number is arithmetic over the stated assumptions.
9
+
10
+ Pure standard library, so the arithmetic is auditable line by line and the module runs on the
11
+ minimal analysis runtime.
12
+
13
+ Protocol: `docs/dev/senior-analysis.md` §1.9. Conclusions and claims belong to the senior analyst;
14
+ this module only produces reproducible model values plus the assumptions behind them.
15
+ """
16
+ from __future__ import annotations
17
+
18
+ import math
19
+
20
+ MODULE_ID = "valuation_sensitivity"
21
+ MODULE_VERSION = "1.0.0"
22
+ OUTPUT_NAME = "dcf_sensitivity"
23
+
24
+ MAX_PROJECTION_YEARS = 20
25
+ MAX_GRID_VALUES = 9
26
+ DEFAULT_GRID_STEP = 0.01
27
+ VALUE_DECIMALS = 6
28
+ CAPM_FIELDS = (
29
+ "risk_free_rate", "beta", "equity_risk_premium",
30
+ "cost_of_debt", "tax_rate", "debt_weight",
31
+ )
32
+
33
+ ASSUMPTIONS = [
34
+ "预测期自由现金流与全部假设由调用方显式给出:模块只做折现与终值算术,不估计 FCF、增长率、WACC 或市场价格",
35
+ "终值用戈登永续:TV_n = FCF_n × (1 + terminal_growth) / (wacc − terminal_growth),再折现 n 期;wacc ≤ terminal_growth 直接拒绝",
36
+ "企业价值 EV = Σ FCF_t/(1+wacc)^t + TV_n/(1+wacc)^n;mid_year 时每期指数为 t − 0.5,否则为 t",
37
+ "股权价值 = EV − net_debt − minority_interest;每股模型值 = 股权价值 / shares_outstanding",
38
+ "CAPM 路径:Ke = risk_free_rate + beta × equity_risk_premium;WACC = (1 − debt_weight) × Ke + debt_weight × cost_of_debt × (1 − tax_rate);只作为 wacc 的推导口径,不代替市场利率",
39
+ "输出是「给定假设下的模型值」:不是目标价、不是概率,也不代表市场价格应到哪;敏感性网格只是假设区间,不是置信区间",
40
+ ]
41
+
42
+ LIMITATIONS = [
43
+ "模型值是给定假设的算术结果:FCF、增长率与折现率换一组假设就会得出另一组数,不能当作价格预测",
44
+ "Gordon 终值对 wacc − terminal_growth 极敏感;两者接近时模型值急剧放大,网格里的高低值不代表概率",
45
+ "只做单阶段永续增长,不外推预测期、不做多阶段或退出倍数估值,也不处理周期性极强或亏损企业的转折",
46
+ "不做跨币种换算、通胀调整、控制权溢价、流动性折价或税务重构;金额口径必须与预测 FCF 一致",
47
+ "不构成投资建议,也不产生评级、目标价或收益承诺",
48
+ ]
49
+
50
+
51
+ class AnalysisInputError(Exception):
52
+ """The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
53
+
54
+ analysis_code = "analysis_input_invalid"
55
+
56
+
57
+ def _round(value):
58
+ rounded = round(float(value), VALUE_DECIMALS)
59
+ if rounded == 0:
60
+ return 0
61
+ return int(rounded) if float(rounded).is_integer() else rounded
62
+
63
+
64
+ def _maybe(value):
65
+ return None if value is None else _round(value)
66
+
67
+
68
+ def _number(value, label):
69
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
70
+ raise AnalysisInputError(f"{label} 必须是数字,实际是 {value!r}")
71
+ number = float(value)
72
+ if number != number or number in (float("inf"), float("-inf")):
73
+ raise AnalysisInputError(f"{label} 必须是有限数字,实际是 {value!r}")
74
+ return number
75
+
76
+
77
+ def _finite(value, label):
78
+ number = float(value)
79
+ if number != number or number in (float("inf"), float("-inf")):
80
+ raise AnalysisInputError(f"{label} 不是有限数:请检查 wacc、terminal_growth 与预测期 FCF 的量级")
81
+ return number
82
+
83
+
84
+ def _fmt6(value):
85
+ """Six decimals with trailing zeros trimmed: the display shape of every rounded number."""
86
+ text = f"{_round(value):.6f}".rstrip("0").rstrip(".")
87
+ return text if text not in ("", "-0") else "0"
88
+
89
+
90
+ def _pct(value):
91
+ return f"{value * 100:.2f}%"
92
+
93
+
94
+ def _text(value, label):
95
+ if value is None:
96
+ return None
97
+ if not isinstance(value, str) or not value.strip():
98
+ raise AnalysisInputError(f"{label} 必须是非空字符串")
99
+ return value.strip()
100
+
101
+
102
+ def _projections(params):
103
+ raw = params.get("projections")
104
+ if not isinstance(raw, list) or not raw:
105
+ raise AnalysisInputError("projections 必须是非空数组:至少给出 1 期预测期自由现金流(模块不估计 FCF)")
106
+ if len(raw) > MAX_PROJECTION_YEARS:
107
+ raise AnalysisInputError(f"projections 最多 {MAX_PROJECTION_YEARS} 期,实际 {len(raw)} 期")
108
+ return [_number(item, f"projections[{index}]") for index, item in enumerate(raw)]
109
+
110
+
111
+ def _required_number(params, name, note):
112
+ if params.get(name) is None:
113
+ raise AnalysisInputError(f"{name} 缺失:{note}")
114
+ return _number(params.get(name), name)
115
+
116
+
117
+ def _optional_number(params, name):
118
+ if params.get(name) is None:
119
+ return None
120
+ return _number(params.get(name), name)
121
+
122
+
123
+ def _capm(params):
124
+ """Derive WACC from the six CAPM inputs; only used when `wacc` itself is absent."""
125
+ missing = [name for name in CAPM_FIELDS if params.get(name) is None]
126
+ if missing:
127
+ raise AnalysisInputError(
128
+ f"未给 wacc,CAPM 推导缺少 {'、'.join(missing)};"
129
+ f"要么直接给 wacc,要么把 {' / '.join(CAPM_FIELDS)} 六个参数给全"
130
+ )
131
+ values = {name: _number(params[name], f"CAPM {name}") for name in CAPM_FIELDS}
132
+ if not 0.0 <= values["debt_weight"] <= 1.0:
133
+ raise AnalysisInputError(f"CAPM debt_weight 必须在 0..1,实际是 {values['debt_weight']!r}")
134
+ if not 0.0 <= values["tax_rate"] <= 1.0:
135
+ raise AnalysisInputError(f"CAPM tax_rate 必须在 0..1,实际是 {values['tax_rate']!r}")
136
+ if values["cost_of_debt"] < 0:
137
+ raise AnalysisInputError(f"CAPM cost_of_debt 不能为负,实际是 {values['cost_of_debt']!r}")
138
+ cost_of_equity = values["risk_free_rate"] + values["beta"] * values["equity_risk_premium"]
139
+ cost_of_equity = _finite(cost_of_equity, "CAPM 推导的 Ke")
140
+ debt_weight = values["debt_weight"]
141
+ wacc = _finite(
142
+ (1.0 - debt_weight) * cost_of_equity
143
+ + debt_weight * values["cost_of_debt"] * (1.0 - values["tax_rate"]),
144
+ "CAPM 推导的 WACC",
145
+ )
146
+ return wacc, {
147
+ "cost_of_equity": _round(cost_of_equity),
148
+ "wacc": _round(wacc),
149
+ **{name: _round(values[name]) for name in CAPM_FIELDS},
150
+ }
151
+
152
+
153
+ def _resolve_wacc(params):
154
+ wacc_raw = params.get("wacc")
155
+ capm_given = any(params.get(name) is not None for name in CAPM_FIELDS)
156
+ if wacc_raw is not None:
157
+ return _number(wacc_raw, "wacc"), "param", None, capm_given
158
+ wacc, capm = _capm(params)
159
+ return wacc, "capm", capm, False
160
+
161
+
162
+ def _axis(params, key, *, floor, inclusive):
163
+ """Explicit grid axis (sorted, de-duplicated) or None when the caller omitted it."""
164
+ raw = params.get(key)
165
+ if raw is None:
166
+ return None
167
+ if not isinstance(raw, list) or not raw:
168
+ raise AnalysisInputError(f"{key} 必须是非空数组(省略即围绕基准值取默认标准点)")
169
+ if len(raw) > MAX_GRID_VALUES:
170
+ raise AnalysisInputError(f"{key} 最多 {MAX_GRID_VALUES} 个值,实际 {len(raw)} 个")
171
+ values = []
172
+ for index, item in enumerate(raw):
173
+ value = _round(_number(item, f"{key}[{index}]"))
174
+ if inclusive:
175
+ if value < floor:
176
+ raise AnalysisInputError(f"{key} 里的值必须 ≥ {_fmt6(floor)},实际是 {_fmt6(value)}")
177
+ elif value <= floor:
178
+ raise AnalysisInputError(f"{key} 里的值必须 > {_fmt6(floor)},实际是 {_fmt6(value)}")
179
+ if value in values:
180
+ raise AnalysisInputError(f"{key} 有重复值 {_fmt6(value)}:同一网格轴只能出现一次")
181
+ values.append(value)
182
+ return sorted(values)
183
+
184
+
185
+ def _default_axis(center, *, floor, inclusive, upper_exclusive=None):
186
+ """Caller omitted the axis: center ±1pp, dropping points that would be out of range."""
187
+ center = _round(center)
188
+ values = []
189
+ for candidate in (center - DEFAULT_GRID_STEP, center, center + DEFAULT_GRID_STEP):
190
+ candidate = _round(candidate)
191
+ if inclusive:
192
+ if candidate < floor:
193
+ continue
194
+ elif candidate <= floor:
195
+ continue
196
+ if upper_exclusive is not None and candidate >= upper_exclusive:
197
+ continue
198
+ if candidate not in values:
199
+ values.append(candidate)
200
+ return sorted(values)
201
+
202
+
203
+ def _dcf(projections, wacc, terminal_growth, mid_year):
204
+ """Explicit-period PVs, Gordon terminal value and enterprise value; all from the input assumptions."""
205
+ rows, present_values = [], []
206
+ for period, fcf in enumerate(projections, start=1):
207
+ exponent = period - 0.5 if mid_year else float(period)
208
+ try:
209
+ discount_factor = 1.0 / (1.0 + wacc) ** exponent
210
+ except OverflowError as error:
211
+ raise AnalysisInputError(
212
+ f"wacc={_fmt6(wacc)} 的折现因子溢出:请检查折现率与预测期期数"
213
+ ) from error
214
+ present_value = _finite(fcf * discount_factor, f"第 {period} 期现值")
215
+ present_values.append(present_value)
216
+ rows.append({
217
+ "period": period,
218
+ "fcf": _round(fcf),
219
+ "exponent": exponent,
220
+ "discount_factor": _round(discount_factor),
221
+ "present_value": _round(present_value),
222
+ })
223
+ present_value_explicit = math.fsum(present_values)
224
+ denominator = wacc - terminal_growth
225
+ if denominator <= 0:
226
+ raise AnalysisInputError(
227
+ f"wacc({_fmt6(wacc)})必须大于 terminal_growth({_fmt6(terminal_growth)}):"
228
+ "否则 Gordon 终值分母 ≤ 0,模型无经济含义"
229
+ )
230
+ try:
231
+ terminal_value = projections[-1] * (1.0 + terminal_growth) / denominator
232
+ except OverflowError as error:
233
+ raise AnalysisInputError(
234
+ f"终值溢出:wacc={_fmt6(wacc)} 与 terminal_growth={_fmt6(terminal_growth)} 过于接近"
235
+ ) from error
236
+ terminal_value = _finite(terminal_value, "Gordon 终值")
237
+ exponent = len(projections) - 0.5 if mid_year else float(len(projections))
238
+ try:
239
+ terminal_present_value = terminal_value / (1.0 + wacc) ** exponent
240
+ except OverflowError as error:
241
+ raise AnalysisInputError(f"终值折现因子溢出:wacc={_fmt6(wacc)} 过大") from error
242
+ terminal_present_value = _finite(terminal_present_value, "终值现值")
243
+ enterprise_value = _finite(
244
+ math.fsum([present_value_explicit, terminal_present_value]),
245
+ "企业价值",
246
+ )
247
+ return {
248
+ "rows": rows,
249
+ "present_value_explicit": present_value_explicit,
250
+ "terminal_value": terminal_value,
251
+ "terminal_present_value": terminal_present_value,
252
+ "terminal_exponent": exponent,
253
+ "enterprise_value": enterprise_value,
254
+ }
255
+
256
+
257
+ def _equity_value(model, net_debt, minority_interest):
258
+ return model["enterprise_value"] - net_debt - minority_interest
259
+
260
+
261
+ def _fit(axis, target):
262
+ for index, value in enumerate(axis):
263
+ if abs(value - target) <= 1e-9:
264
+ return index
265
+ return None
266
+
267
+
268
+ def _grid(projections, wacc_axis, growth_axis, net_debt, minority_interest, shares_outstanding, mid_year, gaps):
269
+ """Evaluate every cell; a cell whose Gordon denominator is ≤ 0 stays null and is named in gaps."""
270
+ rows, cells, null_cells = [], [], 0
271
+ for terminal_growth in growth_axis:
272
+ row = []
273
+ for wacc in wacc_axis:
274
+ value = None
275
+ if wacc <= terminal_growth:
276
+ gaps.append(
277
+ f"敏感性网格格点无定义:wacc={_fmt6(wacc)} ≤ terminal_growth={_fmt6(terminal_growth)},"
278
+ "Gordon 终值分母 ≤ 0,该格写 null"
279
+ )
280
+ else:
281
+ if net_debt is None or shares_outstanding is None:
282
+ # The bridge-level gap already explains why every cell is null here.
283
+ value = None
284
+ else:
285
+ try:
286
+ model = _dcf(projections, wacc, terminal_growth, mid_year)
287
+ equity = _equity_value(model, net_debt, minority_interest)
288
+ value = _finite(equity / shares_outstanding, "每股模型值")
289
+ except AnalysisInputError as error:
290
+ gaps.append(
291
+ f"敏感性网格格点无法计算:wacc={_fmt6(wacc)}、terminal_growth={_fmt6(terminal_growth)}:{error}"
292
+ )
293
+ cells.append({
294
+ "wacc": _round(wacc),
295
+ "terminal_growth": _round(terminal_growth),
296
+ "value_per_share": None if value is None else _round(value),
297
+ })
298
+ if value is None:
299
+ null_cells += 1
300
+ row.append(value)
301
+ rows.append(row)
302
+ return cells, rows, null_cells
303
+
304
+
305
+ def _sensitivity(wacc_axis, growth_axis, rows, center_wacc, center_growth, gaps):
306
+ """Center cell plus the one-standard-point differences the summary quotes."""
307
+ center_column = _fit(wacc_axis, center_wacc)
308
+ center_row = _fit(growth_axis, center_growth)
309
+ center = {
310
+ "wacc": _round(center_wacc),
311
+ "terminal_growth": _round(center_growth),
312
+ "value_per_share": None,
313
+ }
314
+ wacc_plus = growth_plus = None
315
+ wacc_delta = growth_delta = None
316
+ if center_column is None or center_row is None:
317
+ gaps.append(
318
+ f"敏感性摘要未计算:网格里没有中心格(wacc={_fmt6(center_wacc)}、"
319
+ f"terminal_growth={_fmt6(center_growth)})"
320
+ )
321
+ else:
322
+ center_value = rows[center_row][center_column]
323
+ center["value_per_share"] = None if center_value is None else _round(center_value)
324
+ wacc_column = _fit(wacc_axis, _round(center_wacc + DEFAULT_GRID_STEP))
325
+ if wacc_column is None:
326
+ gaps.append(
327
+ f"敏感性摘要未计算:网格没有 wacc+1pp 标准点(wacc={_fmt6(center_wacc + DEFAULT_GRID_STEP)}),"
328
+ "wacc_1pp_value_per_share 写 null"
329
+ )
330
+ elif center_value is not None and rows[center_row][wacc_column] is not None:
331
+ wacc_plus = _round(rows[center_row][wacc_column])
332
+ wacc_delta = _round(rows[center_row][wacc_column] - center_value)
333
+ growth_row = _fit(growth_axis, _round(center_growth + DEFAULT_GRID_STEP))
334
+ if growth_row is None:
335
+ gaps.append(
336
+ f"敏感性摘要未计算:网格没有 g+1pp 标准点(g={_fmt6(center_growth + DEFAULT_GRID_STEP)}),"
337
+ "growth_1pp_value_per_share 写 null"
338
+ )
339
+ elif center_value is not None and rows[growth_row][center_column] is not None:
340
+ growth_plus = _round(rows[growth_row][center_column])
341
+ growth_delta = _round(rows[growth_row][center_column] - center_value)
342
+ return {
343
+ "center": center,
344
+ # Deltas between the center cell and the adjacent +1pp cell, not probabilities.
345
+ "wacc_1pp_value_per_share": wacc_delta,
346
+ "growth_1pp_value_per_share": growth_delta,
347
+ "wacc_plus_1pp_cell_value_per_share": wacc_plus,
348
+ "growth_plus_1pp_cell_value_per_share": growth_plus,
349
+ "wacc_grid": [_round(value) for value in wacc_axis],
350
+ "terminal_growth_grid": [_round(value) for value in growth_axis],
351
+ "cells": len(wacc_axis) * len(growth_axis),
352
+ "null_cells": sum(1 for row in rows for value in row if value is None),
353
+ }
354
+
355
+
356
+ def _result(status, summary, metrics, sensitivity, methodology, limitations, gaps, outputs):
357
+ return {
358
+ "status": status,
359
+ "summary": summary,
360
+ "metrics": metrics,
361
+ "claims": [],
362
+ "assumptions": list(ASSUMPTIONS),
363
+ "methodology_log": methodology,
364
+ "sensitivity": sensitivity,
365
+ "limitations": limitations,
366
+ "data_gaps": gaps,
367
+ "outputs": outputs,
368
+ }
369
+
370
+
371
+ def analyze(request: dict, context) -> dict:
372
+ params = request.get("params") or {}
373
+ projections = _projections(params)
374
+ terminal_growth = _required_number(
375
+ params, "terminal_growth", "Gordon 终值需要永续增长率(小数);模块不估计增长率"
376
+ )
377
+ net_debt = _optional_number(params, "net_debt")
378
+ shares_outstanding = _optional_number(params, "shares_outstanding")
379
+ minority_interest = _optional_number(params, "minority_interest")
380
+ if minority_interest is None:
381
+ minority_interest = 0.0
382
+ elif minority_interest < 0:
383
+ raise AnalysisInputError("minority_interest 不能为负:少数股东权益从 EV 里扣除,负值没有经济含义")
384
+ mid_year = params.get("mid_year", False)
385
+ if not isinstance(mid_year, bool):
386
+ raise AnalysisInputError(f"mid_year 必须是布尔值,实际是 {mid_year!r}")
387
+ currency = _text(params.get("currency"), "currency")
388
+
389
+ if terminal_growth < 0:
390
+ raise AnalysisInputError(f"terminal_growth 不能为负,实际是 {_fmt6(terminal_growth)}")
391
+ wacc, wacc_source, capm, capm_given = _resolve_wacc(params)
392
+ if wacc <= 0:
393
+ raise AnalysisInputError(f"wacc 必须 > 0,实际是 {_fmt6(wacc)}")
394
+ if wacc <= terminal_growth:
395
+ raise AnalysisInputError(
396
+ f"wacc({_fmt6(wacc)})必须大于 terminal_growth({_fmt6(terminal_growth)}):"
397
+ "否则 Gordon 终值分母 ≤ 0,模型无经济含义"
398
+ )
399
+ if shares_outstanding is not None and shares_outstanding <= 0:
400
+ raise AnalysisInputError(f"shares_outstanding 必须 > 0,实际是 {_fmt6(shares_outstanding)}")
401
+
402
+ wacc_axis = _axis(params, "wacc_grid", floor=0.0, inclusive=False)
403
+ growth_axis = _axis(params, "terminal_growth_grid", floor=0.0, inclusive=True)
404
+ wacc_defaulted = wacc_axis is None
405
+ growth_defaulted = growth_axis is None
406
+ if wacc_defaulted:
407
+ wacc_axis = _default_axis(wacc, floor=0.0, inclusive=False)
408
+ if growth_defaulted:
409
+ growth_axis = _default_axis(terminal_growth, floor=0.0, inclusive=True, upper_exclusive=wacc)
410
+
411
+ gaps = []
412
+ model = _dcf(projections, wacc, terminal_growth, mid_year)
413
+ enterprise_value = model["enterprise_value"]
414
+ equity_value = None if net_debt is None else _equity_value(model, net_debt, minority_interest)
415
+ value_per_share = None
416
+ if equity_value is not None and shares_outstanding is not None:
417
+ value_per_share = _finite(equity_value / shares_outstanding, "每股模型值")
418
+ if net_debt is None:
419
+ gaps.append("net_debt 缺失:只算到企业价值,股权价值与每股模型值未计算(不按 0 处理)")
420
+ if shares_outstanding is None:
421
+ gaps.append("shares_outstanding 缺失:每股模型值与敏感性网格未计算(不猜股本)")
422
+ terminal_share = None
423
+ if enterprise_value > 0:
424
+ terminal_share = model["terminal_present_value"] / enterprise_value
425
+ else:
426
+ gaps.append(
427
+ f"企业价值非正({_fmt6(enterprise_value)}):终值占比无定义,terminal_value_share 写 null"
428
+ )
429
+
430
+ cells, rows, null_cells = _grid(
431
+ projections, wacc_axis, growth_axis, net_debt, minority_interest, shares_outstanding, mid_year, gaps
432
+ )
433
+ sensitivity = _sensitivity(wacc_axis, growth_axis, rows, wacc, terminal_growth, gaps)
434
+
435
+ metrics = {
436
+ "enterprise_value": _round(enterprise_value),
437
+ "equity_value": _maybe(equity_value),
438
+ "value_per_share": _maybe(value_per_share),
439
+ "terminal_value": _round(model["terminal_present_value"]),
440
+ "terminal_value_nominal": _round(model["terminal_value"]),
441
+ "terminal_value_share": None if terminal_share is None else _round(terminal_share),
442
+ "wacc": _round(wacc),
443
+ "terminal_growth": _round(terminal_growth),
444
+ "projection_years": len(projections),
445
+ "net_debt": _maybe(net_debt),
446
+ "minority_interest": _round(minority_interest),
447
+ "shares_outstanding": _maybe(shares_outstanding),
448
+ }
449
+
450
+ exponent_text = "t − 0.5" if mid_year else "t"
451
+ terminal_exponent_text = f"n − 0.5({_fmt6(model['terminal_exponent'])})" if mid_year \
452
+ else f"n({_fmt6(model['terminal_exponent'])})"
453
+ bridge_text = (
454
+ f"股权价值 = EV − net_debt − minority_interest = {_fmt6(equity_value)};"
455
+ f"每股模型值 = 股权价值 / shares_outstanding = {_fmt6(value_per_share)}"
456
+ if equity_value is not None and value_per_share is not None
457
+ else "股权价值与每股模型值未计算(缺 net_debt 或 shares_outstanding,见 data_gaps)"
458
+ )
459
+ methodology = [
460
+ f"预测期 {len(projections)} 期;{'年中' if mid_year else '年末'}折现:第 t 期指数 {exponent_text},"
461
+ f"终值指数 {terminal_exponent_text}(终值与最后一期同口径,不额外提前一期)",
462
+ f"Gordon 终值:TV_n = FCF_n × (1 + g)/(wacc − g) = {_fmt6(model['terminal_value'])};"
463
+ f"折现后 TV 现值 {_fmt6(model['terminal_present_value'])}",
464
+ f"EV = Σ PV_t + PV_TV = {_fmt6(enterprise_value)};{bridge_text}",
465
+ ]
466
+ if wacc_source == "capm":
467
+ methodology.append(
468
+ f"CAPM 推 WACC:Ke = risk_free_rate + beta × equity_risk_premium = {_fmt6(capm['cost_of_equity'])};"
469
+ f"WACC = (1 − debt_weight) × Ke + debt_weight × cost_of_debt × (1 − tax_rate) = {_fmt6(wacc)}"
470
+ )
471
+ elif capm_given:
472
+ methodology.append("调用方同时给了 CAPM 参数:按约定以显式 wacc 为准,CAPM 未参与本次计算")
473
+ else:
474
+ methodology.append(f"WACC 来源:调用方显式给定 wacc={_fmt6(wacc)},未使用 CAPM 推导")
475
+ if minority_interest == 0 and params.get("minority_interest") is None:
476
+ methodology.append("minority_interest 省略:EV→股权桥按 0 扣除,这是披露的缺省口径,不是从数据估出")
477
+ methodology.append(
478
+ f"敏感性网格:wacc_grid({'默认标准点' if wacc_defaulted else '调用方给定'})"
479
+ f"{[_fmt6(value) for value in wacc_axis]} × terminal_growth_grid"
480
+ f"({'默认标准点' if growth_defaulted else '调用方给定'})"
481
+ f"{[_fmt6(value) for value in growth_axis]};"
482
+ f"共 {len(cells)} 格、{null_cells} 格 null;标准点只是假设区间,不是置信区间"
483
+ )
484
+ methodology.append(
485
+ f"sensitivity.wacc_1pp_value_per_share / growth_1pp_value_per_share 是中心格与 +1pp 相邻格的每股模型值差分;"
486
+ f"金额与每股保留 {VALUE_DECIMALS} 位小数,{len(gaps)} 项缺口"
487
+ )
488
+
489
+ parts = [
490
+ f"{len(projections)} 期预测、wacc {_pct(wacc)}"
491
+ f"{'(CAPM 推导)' if wacc_source == 'capm' else ''}、终值增长 {_pct(terminal_growth)}"
492
+ f"({'年中' if mid_year else '年末'}折现)",
493
+ ]
494
+ if value_per_share is not None:
495
+ parts.append(
496
+ f"EV {_fmt6(enterprise_value)}、股权价值 {_fmt6(equity_value)}、"
497
+ f"每股模型值 {_fmt6(value_per_share)}"
498
+ )
499
+ else:
500
+ parts.append(f"EV {_fmt6(enterprise_value)}")
501
+ parts.append("股权桥 / 每股模型值未计算(见 data_gaps)")
502
+ if terminal_share is not None:
503
+ parts.append(f"终值现值占 EV {_pct(terminal_share)}")
504
+ has_deltas = (
505
+ sensitivity["wacc_1pp_value_per_share"] is not None
506
+ and sensitivity["growth_1pp_value_per_share"] is not None
507
+ )
508
+ if has_deltas:
509
+ parts.append(
510
+ f"WACC +1pp 每股模型值差分 {_fmt6(sensitivity['wacc_1pp_value_per_share'])}、"
511
+ f"g +1pp {_fmt6(sensitivity['growth_1pp_value_per_share'])}"
512
+ )
513
+ summary = ";".join(parts) + "。"
514
+ if gaps:
515
+ summary += "(有缺口未计算,见 data_gaps)"
516
+ summary += "这是给定假设下的模型值,不是目标价、不是预测。"
517
+
518
+ payload = {
519
+ "protocol": "capital.analysis/v1",
520
+ "module_id": MODULE_ID,
521
+ "module_version": MODULE_VERSION,
522
+ "analysis_id": request.get("analysis_id"),
523
+ "module_run_id": request.get("module_run_id"),
524
+ "parameters": {
525
+ "projections": [_round(value) for value in projections],
526
+ "wacc": _round(wacc),
527
+ "wacc_source": wacc_source,
528
+ "terminal_growth": _round(terminal_growth),
529
+ "net_debt": _maybe(net_debt),
530
+ "minority_interest": _round(minority_interest),
531
+ "minority_interest_source": "param" if params.get("minority_interest") is not None else "default_zero",
532
+ "shares_outstanding": _maybe(shares_outstanding),
533
+ "mid_year": mid_year,
534
+ "currency": currency,
535
+ "wacc_grid": [_round(value) for value in wacc_axis],
536
+ "wacc_grid_source": "default" if wacc_defaulted else "explicit",
537
+ "terminal_growth_grid": [_round(value) for value in growth_axis],
538
+ "terminal_growth_grid_source": "default" if growth_defaulted else "explicit",
539
+ },
540
+ "capm": capm,
541
+ "discounting": {
542
+ "mid_year": mid_year,
543
+ "exponent_rule": "t - 0.5" if mid_year else "t",
544
+ "terminal_value_exponent": model["terminal_exponent"],
545
+ "terminal_value_rule": "same n / n - 0.5 convention as the projection period",
546
+ },
547
+ "projections": model["rows"],
548
+ "terminal_value": {
549
+ "method": "gordon",
550
+ "terminal_fcf": _round(projections[-1]),
551
+ "growth": _round(terminal_growth),
552
+ "wacc": _round(wacc),
553
+ "value": _round(model["terminal_value"]),
554
+ "present_value": _round(model["terminal_present_value"]),
555
+ "discount_exponent": model["terminal_exponent"],
556
+ },
557
+ "enterprise_value": _round(enterprise_value),
558
+ "bridge": {
559
+ "enterprise_value": _round(enterprise_value),
560
+ "net_debt": _maybe(net_debt),
561
+ "minority_interest": _round(minority_interest),
562
+ "equity_value": _maybe(equity_value),
563
+ "shares_outstanding": _maybe(shares_outstanding),
564
+ "value_per_share": _maybe(value_per_share),
565
+ },
566
+ "sensitivity": {
567
+ "wacc_grid": [_round(value) for value in wacc_axis],
568
+ "terminal_growth_grid": [_round(value) for value in growth_axis],
569
+ "cells": cells,
570
+ "null_cells": null_cells,
571
+ },
572
+ "assumptions": list(ASSUMPTIONS),
573
+ "data_gaps": gaps,
574
+ }
575
+ ref = context.write_output(OUTPUT_NAME, payload)
576
+ context.log(
577
+ f"{MODULE_ID}: {len(projections)} periods wacc={_fmt6(wacc)} g={_fmt6(terminal_growth)} "
578
+ f"grid={len(cells)} null={null_cells} gaps={len(gaps)}"
579
+ )
580
+ return _result(
581
+ "partial" if gaps else "completed",
582
+ summary,
583
+ metrics,
584
+ sensitivity,
585
+ methodology,
586
+ list(LIMITATIONS),
587
+ gaps,
588
+ [{"name": OUTPUT_NAME, "ref": ref}],
589
+ )
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@v587d/watchlist",
3
- "version": "2.31.3",
3
+ "version": "2.31.5",
4
4
  "description": "自动模式的用户自选股(宿主级清单 + Fuyao 报价快照 + /capital-watchlist 路由 + 输入框菜单弹窗):由 @v587d/capital-generation 随包携带并作为 host 平面行挂载。",
5
5
  "license": "MIT",
6
6
  "type": "module",