@v587d/capital-generation 2.31.7 → 2.32.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 (75) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +14 -5
  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/artifact.d.ts +35 -0
  7. package/lib/analysis/artifact.js +250 -0
  8. package/lib/analysis/registry.d.ts +16 -2
  9. package/lib/analysis/registry.js +133 -23
  10. package/lib/analysis/runtime.d.ts +46 -19
  11. package/lib/analysis/runtime.js +485 -116
  12. package/lib/analysis/schemas.d.ts +46 -0
  13. package/lib/analysis/schemas.js +260 -7
  14. package/lib/analysis/snapshot.d.ts +10 -3
  15. package/lib/analysis/snapshot.js +298 -46
  16. package/lib/analysis/storage.d.ts +29 -1
  17. package/lib/analysis/storage.js +39 -6
  18. package/lib/analysis/tools.js +270 -29
  19. package/lib/analysis/types.d.ts +257 -3
  20. package/lib/analysis/types.js +31 -1
  21. package/lib/analysis/validation.d.ts +37 -1
  22. package/lib/analysis/validation.js +315 -1
  23. package/lib/chart/tool.js +1 -0
  24. package/lib/data-collector/store.d.ts +7 -1
  25. package/lib/data-collector/store.js +14 -0
  26. package/lib/python-runtime/child-env.d.ts +4 -2
  27. package/lib/python-runtime/child-env.js +21 -14
  28. package/lib/python-runtime/manager.d.ts +8 -0
  29. package/lib/python-runtime/manager.js +30 -14
  30. package/lib/sources/tencent-http.js +9 -3
  31. package/lib/web-retriever/local-fetch.d.ts +1 -1
  32. package/lib/web-retriever/local-fetch.js +1 -1
  33. package/lib/web-retriever/wind-client.d.ts +1 -1
  34. package/lib/web-retriever/wind-client.js +1 -1
  35. package/package.json +2 -1
  36. package/plugin-page/README.en.md +1 -1
  37. package/plugin-page/README.zh.md +1 -1
  38. package/preset/capital-generation/agent.patch.yml +1 -1
  39. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +15 -2
  40. package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +54 -9
  41. package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +41 -7
  42. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  43. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +20 -1
  44. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
  45. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +38 -8
  46. package/python/analysis/lib/__init__.py +9 -0
  47. package/python/analysis/lib/errors.py +12 -0
  48. package/python/analysis/lib/eventstudy.py +164 -0
  49. package/python/analysis/lib/frames.py +95 -0
  50. package/python/analysis/lib/gaps.py +54 -0
  51. package/python/analysis/lib/jsonio.py +61 -0
  52. package/python/analysis/lib/metrics.py +147 -0
  53. package/python/analysis/lib/pit.py +84 -0
  54. package/python/analysis/lib/prices.py +140 -0
  55. package/python/analysis/lib/timeaxis.py +142 -0
  56. package/python/analysis/lib/version.py +3 -0
  57. package/python/analysis/modules/comps_valuation/module.py +26 -59
  58. package/python/analysis/modules/earnings_bridge/module.py +20 -77
  59. package/python/analysis/modules/event_study/LICENSE +21 -0
  60. package/python/analysis/modules/event_study/module.json +217 -0
  61. package/python/analysis/modules/event_study/module.py +979 -0
  62. package/python/analysis/modules/financial_quality/module.py +25 -88
  63. package/python/analysis/modules/hello/module.py +4 -0
  64. package/python/analysis/modules/kline_quality/module.py +26 -132
  65. package/python/analysis/modules/portfolio_stress/module.py +27 -112
  66. package/python/analysis/modules/returns_risk/module.json +108 -25
  67. package/python/analysis/modules/returns_risk/module.py +68 -227
  68. package/python/analysis/modules/scenario_sensitivity/module.py +11 -44
  69. package/python/analysis/modules/simple_backtest/module.json +244 -36
  70. package/python/analysis/modules/simple_backtest/module.py +1146 -459
  71. package/python/analysis/modules/statement_integrity/module.py +35 -87
  72. package/python/analysis/modules/technical_indicators/module.py +33 -152
  73. package/python/analysis/modules/valuation_sensitivity/module.py +30 -61
  74. package/python/worker.py +5 -0
  75. package/watchlist/package.json +1 -1
@@ -0,0 +1,140 @@
1
+ """Price series: column discovery, ordered points, bad-row handling and period-in-time gate.
2
+
3
+ A bad row is skipped and reported; the return that would have bridged the hole is **not** computed,
4
+ because counting a multi-day jump as one daily return would silently inflate volatility and Sharpe.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from . import gaps
9
+ from .errors import AnalysisInputError
10
+ from .frames import columns_of, number
11
+ from .pit import require_bar_available
12
+ from .timeaxis import parse_time, temporal_of, time_column
13
+ PRICE_COLUMNS = ("close", "adj_close", "close_price", "price", "nav")
14
+ ADJUST_COLUMNS = ("adjust", "adjust_type", "adjustment", "price_adjust", "adjust_flag")
15
+ ADJUST_LABELS = {
16
+ "qfq": "qfq", "前复权": "qfq", "forward": "qfq",
17
+ "hfq": "hfq", "后复权": "hfq", "backward": "hfq",
18
+ "none": "none", "不复权": "none", "raw": "none", "": "none",
19
+ }
20
+
21
+
22
+ def price_column(view, override):
23
+ names = columns_of(view)
24
+ if override is not None:
25
+ if override not in names:
26
+ raise AnalysisInputError(f"price_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
27
+ return override
28
+ for name in PRICE_COLUMNS:
29
+ if name in names:
30
+ return name
31
+ raise AnalysisInputError(
32
+ "找不到价格列:需要 close / adj_close / close_price / price / nav 之一(或用 price_column 指明);"
33
+ f"现有列:{sorted(names)}"
34
+ )
35
+
36
+
37
+ def candidate(views, price_override, time_override):
38
+ """Dataset ids that look like a price series (a time column plus a price column)."""
39
+ candidates = []
40
+ for dataset_id, view in sorted(views.items()):
41
+ try:
42
+ time_column(view, time_override)
43
+ price_column(view, price_override)
44
+ except AnalysisInputError:
45
+ continue
46
+ candidates.append((dataset_id, time_column(view, time_override)))
47
+ return candidates
48
+
49
+
50
+ def adjustment_conflict(view):
51
+ """Mixed adjustment regimes in one series make every return ambiguous; refuse instead of guessing."""
52
+ names = columns_of(view)
53
+ column = next((name for name in ADJUST_COLUMNS if name in names), None)
54
+ if column is None:
55
+ return None
56
+ seen = set()
57
+ for row in view.get("rows") or []:
58
+ if not isinstance(row, dict):
59
+ continue
60
+ value = row.get(column)
61
+ if value is None:
62
+ continue
63
+ label = ADJUST_LABELS.get(str(value).strip().lower(), str(value).strip().lower())
64
+ seen.add(label)
65
+ if len(seen) <= 1:
66
+ return None
67
+ return f"Dataset 的 {column} 列混用了 {sorted(seen)}:同一序列不能混用复权口径({gaps.adjustment_unknown('请在取数时统一复权口径')})"
68
+
69
+
70
+ def series(view, dataset_id, price_column_name, time_column_name, tz, *, request=None, temporal=None):
71
+ """Ordered price points plus the raw values of the rows that were skipped.
72
+
73
+ Under `as_known_then` a bar whose day is after `as_of` is a hard input error: the snapshot
74
+ claims to be known-as-of that date, so using a later bar would leak the future into the result.
75
+ """
76
+ rows = view.get("rows") or []
77
+ if not rows:
78
+ raise AnalysisInputError(f"Dataset {dataset_id} 没有数据行:无法计算收益与风险")
79
+ conflict = adjustment_conflict(view)
80
+ if conflict is not None:
81
+ raise AnalysisInputError(conflict, code="analysis_adjustment_unknown")
82
+ resolved_temporal = temporal if temporal is not None else temporal_of(request or {})
83
+ points, dropped, kind = [], [], None
84
+ for index, row in enumerate(rows):
85
+ if not isinstance(row, dict):
86
+ raise AnalysisInputError(f"Dataset {dataset_id} 的数据行不是对象:无法计算")
87
+ raw_time = row.get(time_column_name)
88
+ row_kind = "ms" if isinstance(raw_time, (int, float)) and not isinstance(raw_time, bool) else "date"
89
+ if kind is None:
90
+ kind = row_kind
91
+ elif row_kind != kind:
92
+ raise AnalysisInputError(
93
+ f"Dataset {dataset_id} 的 {time_column_name} 列混用了数值时间戳与日期字符串:无法排序,请取数时统一"
94
+ )
95
+ parsed = parse_time(raw_time, tz)
96
+ price = number(row, price_column_name)
97
+ if parsed is None or price is None or price <= 0:
98
+ dropped.append(raw_time)
99
+ continue
100
+ key, day = parsed
101
+ require_bar_available(day, resolved_temporal, dataset_id)
102
+ points.append({"key": key, "day": day, "price": price, "row_index": index})
103
+ points.sort(key=lambda item: item["key"])
104
+ seen = set()
105
+ for point in points:
106
+ if point["day"] in seen:
107
+ raise AnalysisInputError(
108
+ f"Dataset {dataset_id} 在 {point['day']} 出现多行:无法判断用哪一行(请先去重)"
109
+ )
110
+ seen.add(point["day"])
111
+ return points, dropped
112
+
113
+
114
+ def pair_returns(points, trading_days=None):
115
+ """Adjacent-bar returns; a pair separated by a skipped row (or a missing calendar day) is a gap.
116
+
117
+ Returns `(pairs, holes)`: `pairs` are `(previous_point, current_point, value)`, `holes` are gap
118
+ strings for the returns that were deliberately not computed.
119
+ """
120
+ pairs, holes = [], []
121
+ for previous, current in zip(points, points[1:]):
122
+ if current["row_index"] != previous["row_index"] + 1:
123
+ holes.append(gaps.time_unavailable(
124
+ f"{previous['day']} 与 {current['day']} 之间有被跳过的行:这段收益未计入"
125
+ ))
126
+ continue
127
+ if trading_days is not None:
128
+ missing = sorted(
129
+ day for day in trading_days
130
+ if previous["day"] < day < current["day"]
131
+ )
132
+ if missing:
133
+ shown = "、".join(missing[:5])
134
+ more = f" 等 {len(missing)} 个交易日" if len(missing) > 5 else ""
135
+ holes.append(gaps.time_unavailable(
136
+ f"{previous['day']} 与 {current['day']} 之间缺少交易日 {shown}{more}:这段收益未计入"
137
+ ))
138
+ continue
139
+ pairs.append((previous, current, current["price"] / previous["price"] - 1.0))
140
+ return pairs, holes
@@ -0,0 +1,142 @@
1
+ """Time axis: IANA zones, epoch-ms/date-string parsing, day labels and trading-day sets.
2
+
3
+ Daily bars are labelled by their close day in the caller's zone (the dataset timezone is not
4
+ authoritative). `2024-01-01T16:00Z` under `Asia/Shanghai` is `2024-01-02` — the Shanghai-midnight
5
+ case that decides whether a bar is knowable before or after an `as_of` date.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import re
10
+ from datetime import datetime, timezone
11
+
12
+ from .errors import AnalysisInputError
13
+ from .frames import columns_of
14
+
15
+ ISO_DAY = re.compile(r"^(\d{4}-\d{2}-\d{2})")
16
+ TIME_COLUMNS = ("trade_date_ms", "date_ms", "period_end_ms", "datetime", "date", "trade_date", "time")
17
+ # Disclosure columns come before period columns: "when was this knowable" beats "what period".
18
+ DISCLOSURE_COLUMNS = (
19
+ "report_date_ms", "report_date", "announce_date_ms", "announce_date",
20
+ "disclosure_date", "notice_date", "publish_date", "pub_date",
21
+ )
22
+ PERIOD_COLUMNS = ("period_end_ms", "period_end", "period", "report_period", "fiscal_year")
23
+
24
+
25
+ def timezone_of(name):
26
+ """IANA zone when the caller names one; UTC otherwise (the dataset tz is not authoritative)."""
27
+ if name is None:
28
+ return timezone.utc
29
+ try:
30
+ from zoneinfo import ZoneInfo
31
+
32
+ return ZoneInfo(name)
33
+ except Exception as error: # noqa: BLE001 - any load failure is a caller error
34
+ raise AnalysisInputError(f"timezone={name!r} 无法加载(需要 IANA 时区名,如 Asia/Shanghai)") from error
35
+
36
+
37
+ def parse_time(value, tz):
38
+ """Return `(sort_key, day_label)`; `None` when the value is not a usable time."""
39
+ if isinstance(value, bool):
40
+ return None
41
+ if isinstance(value, (int, float)):
42
+ number = float(value)
43
+ if number != number or number in (float("inf"), float("-inf")):
44
+ return None
45
+ try:
46
+ stamp = datetime.fromtimestamp(number / 1000.0, tz=tz)
47
+ except (OverflowError, OSError, ValueError):
48
+ return None
49
+ return number, stamp.strftime("%Y-%m-%d")
50
+ if isinstance(value, str):
51
+ match = ISO_DAY.match(value.strip())
52
+ if match is None:
53
+ return None
54
+ day = match.group(1)
55
+ try:
56
+ stamp = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=timezone.utc)
57
+ except ValueError:
58
+ return None
59
+ return stamp.timestamp() * 1000.0, day
60
+ return None
61
+
62
+
63
+ def iso_date(ms):
64
+ return datetime.fromtimestamp(float(ms) / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
65
+
66
+
67
+ def day_of(value):
68
+ """ISO day of a date/timestamp cell, or `None` (disclosure dates may be ms or `YYYY-MM-DD`)."""
69
+ parsed = parse_time(value, timezone.utc)
70
+ return None if parsed is None else parsed[1]
71
+
72
+
73
+ def time_column(view, override):
74
+ names = columns_of(view)
75
+ if override is not None:
76
+ if override not in names:
77
+ raise AnalysisInputError(f"time_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
78
+ return override
79
+ axis = (view.get("time_axis") or {}).get("column")
80
+ if isinstance(axis, str) and axis in names:
81
+ return axis
82
+ for name in TIME_COLUMNS:
83
+ if name in names:
84
+ return name
85
+ raise AnalysisInputError(
86
+ "找不到时间列:需要 time_coverage 列,或 trade_date_ms / date_ms / period_end_ms / datetime / date / trade_date 之一"
87
+ )
88
+
89
+
90
+ def disclosure_column(columns):
91
+ for name in DISCLOSURE_COLUMNS:
92
+ if name in columns:
93
+ return name
94
+ return None
95
+
96
+
97
+ def period_column(columns):
98
+ for name in PERIOD_COLUMNS:
99
+ if name in columns:
100
+ return name
101
+ return None
102
+
103
+
104
+ def trading_days_from(view, column=None):
105
+ """ISO days of a trading-calendar view: one row per day (or one row per day with a flag)."""
106
+ names = columns_of(view)
107
+ selected = column
108
+ if selected is None:
109
+ for candidate in ("trade_date_ms", "date", "trade_date", "datetime", "time"):
110
+ if candidate in names:
111
+ selected = candidate
112
+ break
113
+ if selected is None:
114
+ raise AnalysisInputError("交易日历 Dataset 找不到日期列:需要 trade_date_ms / date / trade_date 之一")
115
+ days = set()
116
+ for row in view.get("rows") or []:
117
+ if not isinstance(row, dict):
118
+ continue
119
+ parsed = parse_time(row.get(selected), timezone.utc)
120
+ if parsed is not None:
121
+ days.add(parsed[1])
122
+ return days
123
+
124
+
125
+ def temporal_of(request):
126
+ """The snapshot's temporal contract as the module sees it (v1 requests default to `ex_post`)."""
127
+ temporal = request.get("temporal")
128
+ if not isinstance(temporal, dict):
129
+ return {"mode": "ex_post", "as_of": request.get("as_of"), "data_cutoff": None}
130
+ return {
131
+ "mode": temporal.get("mode") or "ex_post",
132
+ "as_of": temporal.get("as_of") or request.get("as_of"),
133
+ "data_cutoff": temporal.get("data_cutoff"),
134
+ }
135
+
136
+
137
+ def as_of_day(temporal):
138
+ raw = temporal.get("as_of") if isinstance(temporal, dict) else None
139
+ if not isinstance(raw, str):
140
+ return None
141
+ match = ISO_DAY.match(raw.strip())
142
+ return match.group(1) if match else None
@@ -0,0 +1,3 @@
1
+ """Version of the shared primitives. Bump it whenever a module-visible behaviour changes here."""
2
+
3
+ LIB_VERSION = "1.2.0"
@@ -11,6 +11,12 @@ this module only produces reproducible multiples plus the input values behind ea
11
11
  """
12
12
  from __future__ import annotations
13
13
 
14
+ from lib import frames as _frames
15
+ from lib import gaps as gapvocab
16
+ from lib.errors import AnalysisInputError
17
+ from lib.frames import columns_of as _columns_of, number as _number
18
+ from lib.jsonio import plain as _plain, round_metric as _round
19
+
14
20
  MODULE_ID = "comps_valuation"
15
21
  MODULE_VERSION = "1.0.0"
16
22
  OUTPUT_NAME = "comps"
@@ -42,59 +48,12 @@ MULTIPLES = (
42
48
  )
43
49
 
44
50
 
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
51
+ def _read_views(request, context):
52
+ return _frames.read_views(
53
+ request, context,
54
+ module_id=MODULE_ID,
55
+ empty_message="快照里没有任何 Dataset:comps_valuation 需要同行同期的 peers 横截面",
56
+ )
98
57
 
99
58
 
100
59
  def _select_datasets(views, params):
@@ -232,7 +191,7 @@ def _summary(peer_medians, subject_values, subject_premiums, excluded, gaps, sub
232
191
 
233
192
  def analyze(request: dict, context) -> dict:
234
193
  params = request.get("params") or {}
235
- views = _read_datasets(request, context)
194
+ views = _read_views(request, context)
236
195
  peers_id, subject_id = _select_datasets(views, params)
237
196
  methodology = [f"peers = {peers_id}" + (f";subject = {subject_id}" if subject_id else ";未提供 subject")]
238
197
  limitations = list(LIMITATIONS)
@@ -260,7 +219,9 @@ def analyze(request: dict, context) -> dict:
260
219
  label = str(ticker) if ticker is not None else f"row_{index + 1}"
261
220
  values, inputs = _multiples_of(row)
262
221
  if not values:
263
- gaps.append(f"{label} 没有可计算的倍数(market_cap / net_profit 或对应分母缺失或不可用)")
222
+ gaps.append(gapvocab.field_missing(
223
+ f"{label} 没有可计算的倍数(market_cap / net_profit 或对应分母缺失或不可用)"
224
+ ))
264
225
  for code, _, numerator, denominator in MULTIPLES:
265
226
  if code in values:
266
227
  peer_values[code].append(values[code])
@@ -277,7 +238,9 @@ def analyze(request: dict, context) -> dict:
277
238
  for code, label, _, _ in MULTIPLES:
278
239
  values = peer_values[code]
279
240
  if not values:
280
- gaps.append(f"{label} 未计算:peers 表没有可用的 {_multiple_name(code)} 样本(缺列、分母 ≤ 0 或全被剔除)")
241
+ gaps.append(gapvocab.field_missing(
242
+ f"{label} 未计算:peers 表没有可用的 {_multiple_name(code)} 样本(缺列、分母 ≤ 0 或全被剔除)"
243
+ ))
281
244
  metrics[f"{code}_count"] = 0
282
245
  continue
283
246
  median = _round(_median(values))
@@ -295,7 +258,9 @@ def analyze(request: dict, context) -> dict:
295
258
  raise AnalysisInputError(f"subject Dataset 必须只有一行(当前 {len(subject_rows)} 行):横截面口径一次只比一只标的")
296
259
  subject_values, subject_inputs = _multiples_of(subject_rows[0])
297
260
  if not subject_values:
298
- gaps.append("subject 没有可计算的倍数:缺 market_cap / net_profit 或分母不可用")
261
+ gaps.append(gapvocab.field_missing(
262
+ "subject 没有可计算的倍数:缺 market_cap / net_profit 或分母不可用"
263
+ ))
299
264
  for code, label, _, _ in MULTIPLES:
300
265
  if code in subject_values:
301
266
  metrics[f"{code}_subject"] = _round(subject_values[code])
@@ -305,7 +270,9 @@ def analyze(request: dict, context) -> dict:
305
270
  metrics[f"{code}_premium"] = premium
306
271
  methodology.append(f"{label}:标的 {_ratio_text(subject_values[code])},较中位数 {premium * 100:+.2f}%")
307
272
  else:
308
- gaps.append(f"{label} 的相对位置未计算:peers 侧没有可用中位数")
273
+ gaps.append(gapvocab.field_missing(
274
+ f"{label} 的相对位置未计算:peers 侧没有可用中位数"
275
+ ))
309
276
  methodology.append("subject 倍数:" + "、".join(f"{label} {_ratio_text(subject_values[code])}" for code, label, _, _ in MULTIPLES if code in subject_values))
310
277
  subject_payload = {
311
278
  "ticker": str(subject_rows[0].get(ticker_column)) if ticker_column and subject_rows[0].get(ticker_column) is not None else "subject",
@@ -328,7 +295,7 @@ def analyze(request: dict, context) -> dict:
328
295
  limitations.append("剔除的样本:" + "、".join(f"{label} {count} 家" for label, count in excluded.items()))
329
296
 
330
297
  payload = {
331
- "protocol": "capital.analysis/v1",
298
+ "protocol": "capital.analysis/v2",
332
299
  "module_id": MODULE_ID,
333
300
  "module_version": MODULE_VERSION,
334
301
  "analysis_id": request.get("analysis_id"),
@@ -17,7 +17,12 @@ this module only produces reproducible effects plus the input values behind each
17
17
  """
18
18
  from __future__ import annotations
19
19
 
20
- from datetime import datetime, timezone
20
+ from lib import frames as _frames
21
+ from lib import gaps as gapvocab
22
+ from lib.errors import AnalysisInputError
23
+ from lib.frames import columns_of as _columns_of, number as _number
24
+ from lib.jsonio import round_metric as _round
25
+ from lib.timeaxis import iso_date as _iso_date
21
26
 
22
27
  MODULE_ID = "earnings_bridge"
23
28
  MODULE_VERSION = "1.0.0"
@@ -41,22 +46,6 @@ LIMITATIONS = [
41
46
 
42
47
  SIGNATURE = ("operating_income", "net_profit")
43
48
  PERIOD_KEYS = ("period_end_ms", "period")
44
- ROUND = 6
45
-
46
-
47
- class AnalysisInputError(Exception):
48
- """The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
49
-
50
- analysis_code = "analysis_input_invalid"
51
-
52
-
53
- def _round(value):
54
- rounded = round(float(value), ROUND)
55
- return 0.0 if rounded == 0 else rounded
56
-
57
-
58
- def _plain(value):
59
- return int(value) if isinstance(value, float) and value.is_integer() else value
60
49
 
61
50
 
62
51
  def _amount(value):
@@ -69,44 +58,12 @@ def _amount(value):
69
58
  return _round(value)
70
59
 
71
60
 
72
- def _number(row, name):
73
- if row is None:
74
- return None
75
- value = row.get(name)
76
- if isinstance(value, bool) or not isinstance(value, (int, float)):
77
- return None
78
- number = float(value)
79
- if number != number or number in (float("inf"), float("-inf")):
80
- return None
81
- return number
82
-
83
-
84
- def _columns_of(view):
85
- columns = view.get("columns") or []
86
- names = {item.get("name") for item in columns if isinstance(item, dict)}
87
- for row in (view.get("rows") or [])[:1]:
88
- if isinstance(row, dict):
89
- names |= set(row)
90
- return names
91
-
92
-
93
- def _read_datasets(request, context):
94
- items = (request.get("inputs") or {}).get("datasets") or []
95
- if not items:
96
- raise AnalysisInputError("快照里没有任何 Dataset:earnings_bridge 需要一份利润表序列")
97
- views = {}
98
- for item in items:
99
- dataset_id = (item or {}).get("dataset_id")
100
- if not isinstance(dataset_id, str) or not dataset_id:
101
- raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
102
- views[dataset_id] = context.read_dataset(dataset_id)
103
- for dataset_id, view in views.items():
104
- if view.get("shape") != "rows":
105
- raise AnalysisInputError(
106
- f"Dataset {dataset_id} 是 {view.get('shape')} 型:earnings_bridge 只吃表格数据,"
107
- "文档型输入请先走 profile 或证据"
108
- )
109
- return views
61
+ def _read_views(request, context):
62
+ return _frames.read_views(
63
+ request, context,
64
+ module_id=MODULE_ID,
65
+ empty_message="快照里没有任何 Dataset:earnings_bridge 需要一份利润表序列",
66
+ )
110
67
 
111
68
 
112
69
  def _select_dataset(views, params):
@@ -142,21 +99,7 @@ def _join_key(view):
142
99
 
143
100
 
144
101
  def _index_rows(view, column):
145
- indexed = {}
146
- for row in view.get("rows") or []:
147
- if not isinstance(row, dict):
148
- raise AnalysisInputError("利润表的数据行不是对象:无法计算")
149
- key = row.get(column)
150
- if isinstance(key, bool) or not isinstance(key, (int, float, str)) or key == "":
151
- raise AnalysisInputError(f"利润表的 {column} 列有空值:无法对齐报告期")
152
- if key in indexed:
153
- raise AnalysisInputError(f"利润表在报告期 {key} 出现多行:无法判断用哪一行(请先去重)")
154
- indexed[key] = row
155
- return indexed
156
-
157
-
158
- def _iso_date(ms):
159
- return datetime.fromtimestamp(float(ms) / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
102
+ return _frames.index_rows(view, column, "利润表")
160
103
 
161
104
 
162
105
  def _label(rows, key, key_column):
@@ -292,7 +235,7 @@ def _summary(current_label, previous_label, nets, revenue_bridge, tax_bridge, ga
292
235
 
293
236
  def analyze(request: dict, context) -> dict:
294
237
  params = request.get("params") or {}
295
- views = _read_datasets(request, context)
238
+ views = _read_views(request, context)
296
239
  dataset_id = _select_dataset(views, params)
297
240
  view = views[dataset_id]
298
241
  methodology = [f"利润表 = {dataset_id}"]
@@ -313,13 +256,13 @@ def analyze(request: dict, context) -> dict:
313
256
  methodology.append(f"报告期键 {key_column};本期 {current_label}")
314
257
 
315
258
  if not previous_keys:
316
- gaps.append(f"没有早于 {current_label} 的报告期:两期归因无法计算")
259
+ gaps.append(gapvocab.period_conflict(f"没有早于 {current_label} 的报告期:两期归因无法计算"))
317
260
  current = rows[current_key]
318
261
  nets = (_number(current, "net_profit"), _number(current, "net_profit"), 0.0)
319
262
  status = "blocked"
320
263
  metrics = {"net_profit_current": _amount(nets[1])}
321
264
  payload = {
322
- "protocol": "capital.analysis/v1",
265
+ "protocol": "capital.analysis/v2",
323
266
  "module_id": MODULE_ID,
324
267
  "module_version": MODULE_VERSION,
325
268
  "analysis_id": request.get("analysis_id"),
@@ -357,7 +300,7 @@ def analyze(request: dict, context) -> dict:
357
300
  net_cur = _number(current, "net_profit")
358
301
  metrics = {}
359
302
  if net_prev is None or net_cur is None:
360
- gaps.append("两期净利润有空值(或非数字):差额无法计算")
303
+ gaps.append(gapvocab.field_missing("两期净利润有空值(或非数字):差额无法计算"))
361
304
  status = "blocked"
362
305
  nets = (None, None, None)
363
306
  else:
@@ -376,7 +319,7 @@ def analyze(request: dict, context) -> dict:
376
319
  revenue_bridge, revenue_gap = _revenue_bridge(previous, current)
377
320
  tax_bridge, tax_gap = _tax_bridge(previous, current)
378
321
  if revenue_gap:
379
- gaps.append(f"收入/净利率分解未执行:{revenue_gap}")
322
+ gaps.append(gapvocab.field_missing(f"收入/净利率分解未执行:{revenue_gap}"))
380
323
  else:
381
324
  metrics.update({
382
325
  "revenue_previous": revenue_bridge["revenue_previous"],
@@ -394,7 +337,7 @@ def analyze(request: dict, context) -> dict:
394
337
  f"三项合计与差额的残差 {revenue_bridge['bridge_residual']}"
395
338
  )
396
339
  if tax_gap:
397
- gaps.append(f"税前/税率分解未执行:{tax_gap}")
340
+ gaps.append(gapvocab.field_missing(f"税前/税率分解未执行:{tax_gap}"))
398
341
  else:
399
342
  metrics.update({
400
343
  "profit_total_previous": tax_bridge["profit_total_previous"],
@@ -422,7 +365,7 @@ def analyze(request: dict, context) -> dict:
422
365
  limitations.append("交互项不是误差项:它同时含两个因子的变化,报告时不要并入收入或净利率")
423
366
 
424
367
  payload = {
425
- "protocol": "capital.analysis/v1",
368
+ "protocol": "capital.analysis/v2",
426
369
  "module_id": MODULE_ID,
427
370
  "module_version": MODULE_VERSION,
428
371
  "analysis_id": request.get("analysis_id"),
@@ -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.