@v587d/capital-generation 2.31.8 → 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.
- package/CHANGELOG.md +44 -0
- package/README.md +14 -5
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/package.json +1 -1
- package/lib/analysis/artifact.d.ts +35 -0
- package/lib/analysis/artifact.js +250 -0
- package/lib/analysis/registry.d.ts +16 -2
- package/lib/analysis/registry.js +133 -23
- package/lib/analysis/runtime.d.ts +46 -19
- package/lib/analysis/runtime.js +485 -116
- package/lib/analysis/schemas.d.ts +46 -0
- package/lib/analysis/schemas.js +260 -7
- package/lib/analysis/snapshot.d.ts +10 -3
- package/lib/analysis/snapshot.js +298 -46
- package/lib/analysis/storage.d.ts +29 -1
- package/lib/analysis/storage.js +39 -6
- package/lib/analysis/tools.js +270 -29
- package/lib/analysis/types.d.ts +257 -3
- package/lib/analysis/types.js +31 -1
- package/lib/analysis/validation.d.ts +37 -1
- package/lib/analysis/validation.js +315 -1
- package/lib/chart/tool.js +1 -0
- package/lib/data-collector/store.d.ts +7 -1
- package/lib/data-collector/store.js +14 -0
- package/lib/python-runtime/child-env.d.ts +4 -2
- package/lib/python-runtime/child-env.js +21 -14
- package/lib/python-runtime/manager.d.ts +8 -0
- package/lib/python-runtime/manager.js +30 -14
- 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 +2 -1
- package/plugin-page/README.en.md +1 -1
- package/plugin-page/README.zh.md +1 -1
- package/preset/capital-generation/agent.patch.yml +1 -1
- package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +15 -2
- package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +54 -9
- package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +41 -7
- package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-event-impact/SKILL.md +20 -1
- package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +38 -8
- package/python/analysis/lib/__init__.py +9 -0
- package/python/analysis/lib/errors.py +12 -0
- package/python/analysis/lib/eventstudy.py +164 -0
- package/python/analysis/lib/frames.py +95 -0
- package/python/analysis/lib/gaps.py +54 -0
- package/python/analysis/lib/jsonio.py +61 -0
- package/python/analysis/lib/metrics.py +147 -0
- package/python/analysis/lib/pit.py +84 -0
- package/python/analysis/lib/prices.py +140 -0
- package/python/analysis/lib/timeaxis.py +142 -0
- package/python/analysis/lib/version.py +3 -0
- package/python/analysis/modules/comps_valuation/module.py +26 -59
- package/python/analysis/modules/earnings_bridge/module.py +20 -77
- package/python/analysis/modules/event_study/LICENSE +21 -0
- package/python/analysis/modules/event_study/module.json +217 -0
- package/python/analysis/modules/event_study/module.py +979 -0
- package/python/analysis/modules/financial_quality/module.py +25 -88
- package/python/analysis/modules/hello/module.py +4 -0
- package/python/analysis/modules/kline_quality/module.py +26 -132
- package/python/analysis/modules/portfolio_stress/module.py +27 -112
- package/python/analysis/modules/returns_risk/module.json +108 -25
- package/python/analysis/modules/returns_risk/module.py +68 -227
- package/python/analysis/modules/scenario_sensitivity/module.py +11 -44
- package/python/analysis/modules/simple_backtest/module.json +244 -36
- package/python/analysis/modules/simple_backtest/module.py +1146 -459
- package/python/analysis/modules/statement_integrity/module.py +35 -87
- package/python/analysis/modules/technical_indicators/module.py +33 -152
- package/python/analysis/modules/valuation_sensitivity/module.py +30 -61
- package/python/worker.py +5 -0
- package/watchlist/package.json +1 -1
|
@@ -11,7 +11,12 @@ this module only produces reproducible ratios plus the input values behind each
|
|
|
11
11
|
"""
|
|
12
12
|
from __future__ import annotations
|
|
13
13
|
|
|
14
|
-
from
|
|
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, row_at as _row_at
|
|
18
|
+
from lib.jsonio import plain as _plain, round_metric as _round
|
|
19
|
+
from lib.timeaxis import iso_date as _iso_date
|
|
15
20
|
|
|
16
21
|
MODULE_ID = "financial_quality"
|
|
17
22
|
MODULE_VERSION = "1.0.0"
|
|
@@ -56,60 +61,12 @@ TREND_LABELS = {
|
|
|
56
61
|
}
|
|
57
62
|
|
|
58
63
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
def _round(value):
|
|
66
|
-
rounded = round(float(value), 6)
|
|
67
|
-
return 0.0 if rounded == 0 else rounded
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
def _plain(value):
|
|
71
|
-
"""Integral floats as ints: the audit file then shows 100000000000, not 100000000000.0."""
|
|
72
|
-
return int(value) if isinstance(value, float) and value.is_integer() else value
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
def _number(row, name):
|
|
76
|
-
if row is None:
|
|
77
|
-
return None
|
|
78
|
-
value = row.get(name)
|
|
79
|
-
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
80
|
-
return None
|
|
81
|
-
number = float(value)
|
|
82
|
-
if number != number or number in (float("inf"), float("-inf")):
|
|
83
|
-
return None
|
|
84
|
-
return number
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
def _columns_of(view):
|
|
88
|
-
columns = view.get("columns") or []
|
|
89
|
-
names = {item.get("name") for item in columns if isinstance(item, dict)}
|
|
90
|
-
for row in (view.get("rows") or [])[:1]:
|
|
91
|
-
if isinstance(row, dict):
|
|
92
|
-
names |= set(row)
|
|
93
|
-
return names
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
def _read_datasets(request, context):
|
|
97
|
-
items = (request.get("inputs") or {}).get("datasets") or []
|
|
98
|
-
if not items:
|
|
99
|
-
raise AnalysisInputError("快照里没有任何 Dataset:先取齐三张报表再建快照")
|
|
100
|
-
views = {}
|
|
101
|
-
for item in items:
|
|
102
|
-
dataset_id = (item or {}).get("dataset_id")
|
|
103
|
-
if not isinstance(dataset_id, str) or not dataset_id:
|
|
104
|
-
raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
|
|
105
|
-
views[dataset_id] = context.read_dataset(dataset_id)
|
|
106
|
-
for dataset_id, view in views.items():
|
|
107
|
-
if view.get("shape") != "rows":
|
|
108
|
-
raise AnalysisInputError(
|
|
109
|
-
f"Dataset {dataset_id} 是 {view.get('shape')} 型:financial_quality 只吃表格数据,"
|
|
110
|
-
"文档型输入请先走 profile 或证据"
|
|
111
|
-
)
|
|
112
|
-
return views
|
|
64
|
+
def _read_views(request, context):
|
|
65
|
+
return _frames.read_views(
|
|
66
|
+
request, context,
|
|
67
|
+
module_id=MODULE_ID,
|
|
68
|
+
empty_message="快照里没有任何 Dataset:先取齐三张报表再建快照",
|
|
69
|
+
)
|
|
113
70
|
|
|
114
71
|
|
|
115
72
|
def _resolve_roles(views, params):
|
|
@@ -143,30 +100,15 @@ def _resolve_roles(views, params):
|
|
|
143
100
|
|
|
144
101
|
|
|
145
102
|
def _join_key(roles, views):
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
"三张报表缺少共同的报告期键:需要 period_end_ms 或 period 列,否则无法对齐同一报告期"
|
|
103
|
+
return _frames.join_key(
|
|
104
|
+
views, roles,
|
|
105
|
+
period_keys=PERIOD_KEYS,
|
|
106
|
+
hint="三张报表缺少共同的报告期键:需要 period_end_ms 或 period 列,否则无法对齐同一报告期",
|
|
151
107
|
)
|
|
152
108
|
|
|
153
109
|
|
|
154
110
|
def _index_rows(view, column, role):
|
|
155
|
-
|
|
156
|
-
for row in view.get("rows") or []:
|
|
157
|
-
if not isinstance(row, dict):
|
|
158
|
-
raise AnalysisInputError(f"{LABELS[role]}的数据行不是对象:无法计算")
|
|
159
|
-
key = row.get(column)
|
|
160
|
-
if isinstance(key, bool) or not isinstance(key, (int, float, str)) or key == "":
|
|
161
|
-
raise AnalysisInputError(f"{LABELS[role]}的 {column} 列有空值:无法对齐报告期")
|
|
162
|
-
if key in indexed:
|
|
163
|
-
raise AnalysisInputError(f"{LABELS[role]}在报告期 {key} 出现多行:无法判断用哪一行(请先去重)")
|
|
164
|
-
indexed[key] = row
|
|
165
|
-
return indexed
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
def _iso_date(ms):
|
|
169
|
-
return datetime.fromtimestamp(float(ms) / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
|
|
111
|
+
return _frames.index_rows(view, column, LABELS[role])
|
|
170
112
|
|
|
171
113
|
|
|
172
114
|
def _period_text_is_informative(rows_by_role):
|
|
@@ -187,11 +129,6 @@ def _period_text_is_informative(rows_by_role):
|
|
|
187
129
|
return len(texts) == len(keys) and len(texts) > 0
|
|
188
130
|
|
|
189
131
|
|
|
190
|
-
def _row_at(rows_by_role, key, role):
|
|
191
|
-
row = rows_by_role.get(role, {}).get(key)
|
|
192
|
-
return row if isinstance(row, dict) else None
|
|
193
|
-
|
|
194
|
-
|
|
195
132
|
def _label(rows_by_role, key, key_column):
|
|
196
133
|
"""Human-facing period label: the source's own text when it actually varies, else the report date.
|
|
197
134
|
|
|
@@ -260,10 +197,10 @@ def _compute(rows_by_role, key, label, wanted=None):
|
|
|
260
197
|
return
|
|
261
198
|
missing = [field for field, value in inputs.items() if value is None]
|
|
262
199
|
if missing:
|
|
263
|
-
gaps.append(f"{name} 未计算:{label} 缺 {'、'.join(missing)}")
|
|
200
|
+
gaps.append(gapvocab.field_missing(f"{name} 未计算:{label} 缺 {'、'.join(missing)}"))
|
|
264
201
|
return
|
|
265
202
|
if denominator == 0 or (positive_denominator and denominator < 0):
|
|
266
|
-
gaps.append(reason or f"{name} 未计算:{label} 分母为 0")
|
|
203
|
+
gaps.append(gapvocab.field_missing(reason or f"{name} 未计算:{label} 分母为 0"))
|
|
267
204
|
return
|
|
268
205
|
value = _round(numerator / denominator)
|
|
269
206
|
metrics[name] = value
|
|
@@ -408,7 +345,7 @@ def _summary(label, metrics, trend_rows, gaps):
|
|
|
408
345
|
|
|
409
346
|
def analyze(request: dict, context) -> dict:
|
|
410
347
|
params = request.get("params") or {}
|
|
411
|
-
views =
|
|
348
|
+
views = _read_views(request, context)
|
|
412
349
|
roles = _resolve_roles(views, params)
|
|
413
350
|
ignored = sorted(set(views) - set(roles.values()))
|
|
414
351
|
methodology = [
|
|
@@ -428,7 +365,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
428
365
|
)
|
|
429
366
|
|
|
430
367
|
if "income" not in roles:
|
|
431
|
-
gaps.append("缺少利润表数据集(需要同时含 operating_income 与 net_profit 列):利润率、ROE、现金转换都无法计算")
|
|
368
|
+
gaps.append(gapvocab.source_unavailable("缺少利润表数据集(需要同时含 operating_income 与 net_profit 列):利润率、ROE、现金转换都无法计算"))
|
|
432
369
|
context.log(f"{MODULE_ID}: 缺利润表,返回 blocked")
|
|
433
370
|
return _result(
|
|
434
371
|
"blocked",
|
|
@@ -442,7 +379,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
442
379
|
|
|
443
380
|
for role in ("balance", "cashflow"):
|
|
444
381
|
if role not in roles:
|
|
445
|
-
gaps.append(f"缺少{LABELS[role]}数据集(需要{REQUIRED_HINT[role]}):相关指标未计算")
|
|
382
|
+
gaps.append(gapvocab.source_unavailable(f"缺少{LABELS[role]}数据集(需要{REQUIRED_HINT[role]}):相关指标未计算"))
|
|
446
383
|
|
|
447
384
|
key_column = _join_key(roles, views)
|
|
448
385
|
if key_column == "period":
|
|
@@ -469,7 +406,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
469
406
|
if params.get("compare_previous", True) is not False:
|
|
470
407
|
candidates = [key for key in set().union(*[set(rows) for rows in rows_by_role.values()]) if key < selected]
|
|
471
408
|
if not candidates:
|
|
472
|
-
gaps.append(f"未计算趋势:这批数据集没有早于 {label} 的报告期")
|
|
409
|
+
gaps.append(gapvocab.period_conflict(f"未计算趋势:这批数据集没有早于 {label} 的报告期"))
|
|
473
410
|
limitations.append("只有一期报表,没有环比趋势")
|
|
474
411
|
else:
|
|
475
412
|
previous = max(candidates)
|
|
@@ -487,7 +424,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
487
424
|
"formula": f"{name}({label}) - {name}({previous_label})",
|
|
488
425
|
})
|
|
489
426
|
else:
|
|
490
|
-
gaps.append(f"{name}_delta 未计算:{previous_label} 缺少可比指标")
|
|
427
|
+
gaps.append(gapvocab.field_missing(f"{name}_delta 未计算:{previous_label} 缺少可比指标"))
|
|
491
428
|
methodology.append(f"上一期 {previous_label}:计算 {len(trend_rows)} 项环比变化")
|
|
492
429
|
else:
|
|
493
430
|
limitations.append("按参数关闭了环比趋势")
|
|
@@ -507,7 +444,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
507
444
|
)
|
|
508
445
|
|
|
509
446
|
payload = {
|
|
510
|
-
"protocol": "capital.analysis/
|
|
447
|
+
"protocol": "capital.analysis/v2",
|
|
511
448
|
"module_id": MODULE_ID,
|
|
512
449
|
"module_version": MODULE_VERSION,
|
|
513
450
|
"analysis_id": request.get("analysis_id"),
|
|
@@ -8,6 +8,8 @@ Protocol: `docs/dev/senior-analysis.md` §1.9. Do not add conclusions here; add
|
|
|
8
8
|
"""
|
|
9
9
|
from __future__ import annotations
|
|
10
10
|
|
|
11
|
+
from lib.version import LIB_VERSION
|
|
12
|
+
|
|
11
13
|
|
|
12
14
|
def analyze(request: dict, context) -> dict:
|
|
13
15
|
datasets = []
|
|
@@ -38,6 +40,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
38
40
|
"status": "completed",
|
|
39
41
|
"summary": "分析环境自检通过:模块协议、输入读取与结果回写均可用(本模块不产出结论)。",
|
|
40
42
|
"metrics": {
|
|
43
|
+
"lib_version": LIB_VERSION,
|
|
41
44
|
"dataset_count": len(datasets),
|
|
42
45
|
"profile_count": len(profiles),
|
|
43
46
|
"dataset_rows": sum(item["row_count"] for item in datasets),
|
|
@@ -47,6 +50,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
47
50
|
"methodology_log": [
|
|
48
51
|
"读取 request.inputs 里声明的 Dataset 与 profile",
|
|
49
52
|
"按 §8.5 的视图形状回显行数、列数与时间轴",
|
|
53
|
+
f"共享原语包版本 {LIB_VERSION}(打包完整性自检)",
|
|
50
54
|
"回写结果,交由宿主校验",
|
|
51
55
|
],
|
|
52
56
|
"sensitivity": {},
|
|
@@ -14,8 +14,18 @@ this module only produces the cleaned series plus the evidence behind every reje
|
|
|
14
14
|
"""
|
|
15
15
|
from __future__ import annotations
|
|
16
16
|
|
|
17
|
-
import
|
|
18
|
-
from
|
|
17
|
+
from lib import frames as _frames
|
|
18
|
+
from lib import gaps as gapvocab
|
|
19
|
+
from lib.errors import AnalysisInputError
|
|
20
|
+
from lib.frames import columns_of as _columns_of
|
|
21
|
+
from lib.frames import number as _number
|
|
22
|
+
from lib.frames import text as _text
|
|
23
|
+
from lib.jsonio import fmt6 as _fmt6
|
|
24
|
+
from lib.jsonio import pct as _pct
|
|
25
|
+
from lib.jsonio import round_metric as _round
|
|
26
|
+
from lib.timeaxis import parse_time as _parse_time
|
|
27
|
+
from lib.timeaxis import time_column as _time_column
|
|
28
|
+
from lib.timeaxis import timezone_of as _timezone
|
|
19
29
|
|
|
20
30
|
MODULE_ID = "kline_quality"
|
|
21
31
|
MODULE_VERSION = "1.0.0"
|
|
@@ -23,8 +33,6 @@ OUTPUT_NAME = "kline_quality"
|
|
|
23
33
|
|
|
24
34
|
JUMP_THRESHOLD_DEFAULT = 0.5
|
|
25
35
|
OHLC_COLUMNS = ("open", "high", "low", "close")
|
|
26
|
-
TIME_COLUMNS = ("trade_date_ms", "date_ms", "period_end_ms", "datetime", "date", "trade_date", "time")
|
|
27
|
-
ISO_DAY = re.compile(r"^(\d{4}-\d{2}-\d{2})")
|
|
28
36
|
|
|
29
37
|
REJECT_TIME = "time_unparseable"
|
|
30
38
|
REJECT_PRICE = "price_invalid"
|
|
@@ -52,86 +60,6 @@ LIMITATIONS = [
|
|
|
52
60
|
]
|
|
53
61
|
|
|
54
62
|
|
|
55
|
-
class AnalysisInputError(Exception):
|
|
56
|
-
"""The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
|
|
57
|
-
|
|
58
|
-
analysis_code = "analysis_input_invalid"
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
def _round(value):
|
|
62
|
-
rounded = round(float(value), 6)
|
|
63
|
-
return 0.0 if rounded == 0 else rounded
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
def _fmt6(value):
|
|
67
|
-
"""Six decimals, trailing zeros trimmed: readable in prose, still the stored precision."""
|
|
68
|
-
text = f"{_round(value):.6f}".rstrip("0").rstrip(".")
|
|
69
|
-
return text if text not in ("", "-0") else "0"
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def _pct(value):
|
|
73
|
-
return f"{value * 100:.2f}%"
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
def _number(row, name):
|
|
77
|
-
if row is None:
|
|
78
|
-
return None
|
|
79
|
-
value = row.get(name)
|
|
80
|
-
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
81
|
-
return None
|
|
82
|
-
number = float(value)
|
|
83
|
-
if number != number or number in (float("inf"), float("-inf")):
|
|
84
|
-
return None
|
|
85
|
-
return number
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
def _columns_of(view):
|
|
89
|
-
"""Declared columns plus the keys of every row: a sampled schema can miss a late volume column."""
|
|
90
|
-
names = set()
|
|
91
|
-
for item in view.get("columns") or []:
|
|
92
|
-
if isinstance(item, dict):
|
|
93
|
-
name = item.get("name")
|
|
94
|
-
if isinstance(name, str):
|
|
95
|
-
names.add(name)
|
|
96
|
-
for row in view.get("rows") or []:
|
|
97
|
-
if isinstance(row, dict):
|
|
98
|
-
names |= set(row)
|
|
99
|
-
return names
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
def _text(value):
|
|
103
|
-
return value if isinstance(value, str) and value.strip() else None
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
def _timezone(name):
|
|
107
|
-
"""IANA zone when the caller names one; UTC otherwise (the dataset tz is not authoritative)."""
|
|
108
|
-
if name is None:
|
|
109
|
-
return timezone.utc
|
|
110
|
-
try:
|
|
111
|
-
from zoneinfo import ZoneInfo
|
|
112
|
-
|
|
113
|
-
return ZoneInfo(name)
|
|
114
|
-
except Exception as error: # noqa: BLE001 - any load failure is a caller error
|
|
115
|
-
raise AnalysisInputError(f"timezone={name!r} 无法加载(需要 IANA 时区名,如 Asia/Shanghai)") from error
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
def _time_column(view, override):
|
|
119
|
-
names = _columns_of(view)
|
|
120
|
-
if override is not None:
|
|
121
|
-
if override not in names:
|
|
122
|
-
raise AnalysisInputError(f"time_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
|
|
123
|
-
return override
|
|
124
|
-
axis = (view.get("time_axis") or {}).get("column")
|
|
125
|
-
if isinstance(axis, str) and axis in names:
|
|
126
|
-
return axis
|
|
127
|
-
for name in TIME_COLUMNS:
|
|
128
|
-
if name in names:
|
|
129
|
-
return name
|
|
130
|
-
raise AnalysisInputError(
|
|
131
|
-
"找不到时间列:需要 time_coverage 列,或 trade_date_ms / date_ms / period_end_ms / datetime / date / trade_date / time 之一"
|
|
132
|
-
)
|
|
133
|
-
|
|
134
|
-
|
|
135
63
|
def _require_ohlc(view, dataset_id):
|
|
136
64
|
names = _columns_of(view)
|
|
137
65
|
missing = [name for name in OHLC_COLUMNS if name not in names]
|
|
@@ -153,32 +81,6 @@ def _threshold(value):
|
|
|
153
81
|
return number
|
|
154
82
|
|
|
155
83
|
|
|
156
|
-
def _parse_time(value, tz):
|
|
157
|
-
"""Return `(sort_key, day_label)`; `None` when the value is not a usable time."""
|
|
158
|
-
if isinstance(value, bool):
|
|
159
|
-
return None
|
|
160
|
-
if isinstance(value, (int, float)):
|
|
161
|
-
number = float(value)
|
|
162
|
-
if number != number or number in (float("inf"), float("-inf")):
|
|
163
|
-
return None
|
|
164
|
-
try:
|
|
165
|
-
stamp = datetime.fromtimestamp(number / 1000.0, tz=tz)
|
|
166
|
-
except (OverflowError, OSError, ValueError):
|
|
167
|
-
return None
|
|
168
|
-
return number, stamp.strftime("%Y-%m-%d")
|
|
169
|
-
if isinstance(value, str):
|
|
170
|
-
match = ISO_DAY.match(value.strip())
|
|
171
|
-
if match is None:
|
|
172
|
-
return None
|
|
173
|
-
day = match.group(1)
|
|
174
|
-
try:
|
|
175
|
-
stamp = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
|
176
|
-
except ValueError:
|
|
177
|
-
return None
|
|
178
|
-
return stamp.timestamp() * 1000.0, day
|
|
179
|
-
return None
|
|
180
|
-
|
|
181
|
-
|
|
182
84
|
def _raw_values(row, names):
|
|
183
85
|
"""Original cell values for the audit trail; a missing cell simply omits its key (no nulls)."""
|
|
184
86
|
values = {}
|
|
@@ -351,22 +253,12 @@ def _result(status, summary, metrics, methodology, limitations, gaps, outputs):
|
|
|
351
253
|
|
|
352
254
|
|
|
353
255
|
def _read_views(request, context):
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
if not isinstance(dataset_id, str) or not dataset_id:
|
|
361
|
-
raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
|
|
362
|
-
views[dataset_id] = context.read_dataset(dataset_id)
|
|
363
|
-
for dataset_id, view in views.items():
|
|
364
|
-
if view.get("shape") != "rows":
|
|
365
|
-
raise AnalysisInputError(
|
|
366
|
-
f"Dataset {dataset_id} 是 {view.get('shape')} 型:kline_quality 只吃表格数据,"
|
|
367
|
-
"文档型输入请先走 profile 或证据"
|
|
368
|
-
)
|
|
369
|
-
return views
|
|
256
|
+
return _frames.read_views(
|
|
257
|
+
request,
|
|
258
|
+
context,
|
|
259
|
+
module_id=MODULE_ID,
|
|
260
|
+
empty_message="快照里没有任何 Dataset:先取一份日 K 行情再建快照",
|
|
261
|
+
)
|
|
370
262
|
|
|
371
263
|
|
|
372
264
|
def _candidates(views, time_override):
|
|
@@ -469,17 +361,19 @@ def analyze(request: dict, context) -> dict:
|
|
|
469
361
|
|
|
470
362
|
gaps = []
|
|
471
363
|
if not bars:
|
|
472
|
-
gaps.append(
|
|
364
|
+
gaps.append(gapvocab.sample_insufficient(
|
|
473
365
|
f"清洗后没有合法 bar:{len(rows)} 行全部被拒绝({_breakdown(counts)}):"
|
|
474
366
|
f"明细见 outputs/{OUTPUT_NAME}.json"
|
|
475
|
-
)
|
|
367
|
+
))
|
|
476
368
|
elif rejected:
|
|
477
|
-
gaps.append(
|
|
369
|
+
gaps.append(gapvocab.field_missing(
|
|
370
|
+
f"硬校验拒绝 {len(rejected)} 行({_breakdown(counts)}):明细见 outputs/{OUTPUT_NAME}.json"
|
|
371
|
+
))
|
|
478
372
|
if suspects:
|
|
479
|
-
gaps.append(
|
|
373
|
+
gaps.append(gapvocab.assumption_missing(
|
|
480
374
|
f"相邻收盘涨跌幅超过阈值 {_pct(threshold)} 的 bar {len(suspects)} 行"
|
|
481
375
|
f"(最大 {_pct(max_change)}):已标 suspect_jump,保留在清洗序列"
|
|
482
|
-
)
|
|
376
|
+
))
|
|
483
377
|
|
|
484
378
|
if not bars:
|
|
485
379
|
status = "blocked"
|
|
@@ -489,7 +383,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
489
383
|
status = "completed"
|
|
490
384
|
|
|
491
385
|
payload = {
|
|
492
|
-
"protocol": "capital.analysis/
|
|
386
|
+
"protocol": "capital.analysis/v2",
|
|
493
387
|
"module_id": MODULE_ID,
|
|
494
388
|
"module_version": MODULE_VERSION,
|
|
495
389
|
"analysis_id": request.get("analysis_id"),
|
|
@@ -14,7 +14,19 @@ from __future__ import annotations
|
|
|
14
14
|
|
|
15
15
|
import math
|
|
16
16
|
import re
|
|
17
|
-
from datetime import datetime
|
|
17
|
+
from datetime import datetime
|
|
18
|
+
|
|
19
|
+
from lib import gaps as gapvocab
|
|
20
|
+
from lib.errors import AnalysisInputError
|
|
21
|
+
from lib.frames import columns_of as _columns_of
|
|
22
|
+
from lib.frames import number as _number
|
|
23
|
+
from lib.frames import require_text as _text
|
|
24
|
+
from lib.jsonio import fmt6_fixed as _fmt6, pct as _pct
|
|
25
|
+
from lib.jsonio import ratio as _ratio
|
|
26
|
+
from lib.jsonio import require_number as _finite_number
|
|
27
|
+
from lib.jsonio import round_metric as _round
|
|
28
|
+
from lib.timeaxis import parse_time as _parse_time
|
|
29
|
+
from lib.timeaxis import timezone_of as _timezone
|
|
18
30
|
|
|
19
31
|
MODULE_ID = "portfolio_stress"
|
|
20
32
|
MODULE_VERSION = "1.0.0"
|
|
@@ -43,51 +55,9 @@ LIMITATIONS = [
|
|
|
43
55
|
|
|
44
56
|
PRICE_COLUMNS = ("close", "adj_close", "close_price", "price", "nav")
|
|
45
57
|
TIME_COLUMNS = ("trade_date_ms", "date_ms", "period_end_ms", "datetime", "date", "trade_date", "time")
|
|
46
|
-
ISO_DAY = re.compile(r"^(\d{4}-\d{2}-\d{2})")
|
|
47
58
|
DAY = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
48
59
|
|
|
49
60
|
|
|
50
|
-
class AnalysisInputError(Exception):
|
|
51
|
-
"""The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
|
|
52
|
-
|
|
53
|
-
analysis_code = "analysis_input_invalid"
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
def _round(value):
|
|
57
|
-
rounded = round(float(value), 6)
|
|
58
|
-
return 0.0 if rounded == 0 else rounded
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
def _finite_number(value, label):
|
|
62
|
-
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
63
|
-
raise AnalysisInputError(f"{label} 必须是数字,实际是 {value!r}")
|
|
64
|
-
number = float(value)
|
|
65
|
-
if number != number or number in (float("inf"), float("-inf")):
|
|
66
|
-
raise AnalysisInputError(f"{label} 必须是有限数字,实际是 {value!r}")
|
|
67
|
-
return number
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
def _number(row, name):
|
|
71
|
-
"""A finite positive/negative price cell; `None` means "not usable" (the row is skipped)."""
|
|
72
|
-
if row is None:
|
|
73
|
-
return None
|
|
74
|
-
value = row.get(name)
|
|
75
|
-
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
76
|
-
return None
|
|
77
|
-
number = float(value)
|
|
78
|
-
if number != number or number in (float("inf"), float("-inf")):
|
|
79
|
-
return None
|
|
80
|
-
return number
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
def _text(value, label, *, required=False):
|
|
84
|
-
if value is None and not required:
|
|
85
|
-
return None
|
|
86
|
-
if not isinstance(value, str) or not value.strip():
|
|
87
|
-
raise AnalysisInputError(f"{label} 必须是非空字符串")
|
|
88
|
-
return value.strip()
|
|
89
|
-
|
|
90
|
-
|
|
91
61
|
def _day(value, label):
|
|
92
62
|
if not isinstance(value, str) or DAY.match(value.strip()) is None:
|
|
93
63
|
raise AnalysisInputError(f"{label} 必须是 YYYY-MM-DD 日期,实际是 {value!r}")
|
|
@@ -99,39 +69,6 @@ def _day(value, label):
|
|
|
99
69
|
return text
|
|
100
70
|
|
|
101
71
|
|
|
102
|
-
def _pct(value):
|
|
103
|
-
return f"{value * 100:.2f}%"
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
def _ratio(value):
|
|
107
|
-
return f"{value:.4f}"
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
def _fmt6(value):
|
|
111
|
-
return f"{value:.6f}"
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
def _columns_of(view):
|
|
115
|
-
columns = view.get("columns") or []
|
|
116
|
-
names = {item.get("name") for item in columns if isinstance(item, dict)}
|
|
117
|
-
for row in (view.get("rows") or [])[:1]:
|
|
118
|
-
if isinstance(row, dict):
|
|
119
|
-
names |= set(row)
|
|
120
|
-
return names
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
def _timezone(name):
|
|
124
|
-
"""IANA zone when the caller names one; UTC otherwise (the dataset tz is not authoritative)."""
|
|
125
|
-
if name is None:
|
|
126
|
-
return timezone.utc
|
|
127
|
-
try:
|
|
128
|
-
from zoneinfo import ZoneInfo
|
|
129
|
-
|
|
130
|
-
return ZoneInfo(name)
|
|
131
|
-
except Exception as error: # noqa: BLE001 - any load failure is a caller error
|
|
132
|
-
raise AnalysisInputError(f"timezone={name!r} 无法加载(需要 IANA 时区名,如 Asia/Shanghai)") from error
|
|
133
|
-
|
|
134
|
-
|
|
135
72
|
def _time_column(view, dataset_id, override):
|
|
136
73
|
names = _columns_of(view)
|
|
137
74
|
if override is not None:
|
|
@@ -169,32 +106,6 @@ def _price_column(view, dataset_id, override):
|
|
|
169
106
|
)
|
|
170
107
|
|
|
171
108
|
|
|
172
|
-
def _parse_time(value, tz):
|
|
173
|
-
"""Return `(sort_key, day_label)`; `None` when the value is not a usable time."""
|
|
174
|
-
if isinstance(value, bool):
|
|
175
|
-
return None
|
|
176
|
-
if isinstance(value, (int, float)):
|
|
177
|
-
number = float(value)
|
|
178
|
-
if number != number or number in (float("inf"), float("-inf")):
|
|
179
|
-
return None
|
|
180
|
-
try:
|
|
181
|
-
stamp = datetime.fromtimestamp(number / 1000.0, tz=tz)
|
|
182
|
-
except (OverflowError, OSError, ValueError):
|
|
183
|
-
return None
|
|
184
|
-
return number, stamp.strftime("%Y-%m-%d")
|
|
185
|
-
if isinstance(value, str):
|
|
186
|
-
match = ISO_DAY.match(value.strip())
|
|
187
|
-
if match is None:
|
|
188
|
-
return None
|
|
189
|
-
day = match.group(1)
|
|
190
|
-
try:
|
|
191
|
-
stamp = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
|
192
|
-
except ValueError:
|
|
193
|
-
return None
|
|
194
|
-
return stamp.timestamp() * 1000.0, day
|
|
195
|
-
return None
|
|
196
|
-
|
|
197
|
-
|
|
198
109
|
def _series(view, dataset_id, time_column, price_column, tz):
|
|
199
110
|
"""Time-ordered usable closes; bad rows are dropped and reported, ambiguity is an input error."""
|
|
200
111
|
rows = view.get("rows") or []
|
|
@@ -319,21 +230,25 @@ def _evaluate_window(window, positions, series_by_id):
|
|
|
319
230
|
"return": None,
|
|
320
231
|
"contribution": None,
|
|
321
232
|
}
|
|
322
|
-
reason = None
|
|
233
|
+
reason, gap_of = None, None
|
|
323
234
|
if not points:
|
|
324
|
-
reason = f"{dataset_id} 没有可用价格"
|
|
235
|
+
gap_of, reason = gapvocab.field_missing, f"{dataset_id} 没有可用价格"
|
|
325
236
|
elif window["start"] < points[0]["day"]:
|
|
237
|
+
gap_of = gapvocab.period_conflict
|
|
326
238
|
reason = f"{dataset_id} 起点 {window['start']} 早于序列覆盖(首日 {points[0]['day']})"
|
|
327
239
|
elif window["end"] > points[-1]["day"]:
|
|
240
|
+
gap_of = gapvocab.period_conflict
|
|
328
241
|
reason = f"{dataset_id} 终点 {window['end']} 晚于序列覆盖(末日 {points[-1]['day']})"
|
|
329
242
|
else:
|
|
330
243
|
inside = [point for point in points if window["start"] <= point["day"] <= window["end"]]
|
|
331
244
|
if len(inside) < 2:
|
|
245
|
+
gap_of = gapvocab.sample_insufficient
|
|
332
246
|
reason = f"{dataset_id} 窗口内只有 {len(inside)} 个可用价格(至少 2 个才能算收益)"
|
|
333
247
|
else:
|
|
334
248
|
first, last = inside[0], inside[-1]
|
|
335
249
|
exact = last["price"] / first["price"] - 1.0
|
|
336
250
|
if not math.isfinite(exact):
|
|
251
|
+
gap_of = gapvocab.field_missing
|
|
337
252
|
reason = f"{dataset_id} 的区间收益不是有限数:检查价格量级"
|
|
338
253
|
else:
|
|
339
254
|
entry.update({
|
|
@@ -347,7 +262,7 @@ def _evaluate_window(window, positions, series_by_id):
|
|
|
347
262
|
})
|
|
348
263
|
weighted.append(position["weight"] * exact)
|
|
349
264
|
if reason is not None:
|
|
350
|
-
reasons.append(reason)
|
|
265
|
+
reasons.append((gap_of, reason))
|
|
351
266
|
rows.append(entry)
|
|
352
267
|
if reasons:
|
|
353
268
|
return rows, reasons, None, None
|
|
@@ -425,9 +340,9 @@ def analyze(request: dict, context) -> dict:
|
|
|
425
340
|
points, dropped = _series(view, dataset_id, time_column, price_column, tz)
|
|
426
341
|
series_by_id[dataset_id] = {"points": points}
|
|
427
342
|
if dropped:
|
|
428
|
-
gaps.append(
|
|
343
|
+
gaps.append(gapvocab.field_missing(
|
|
429
344
|
f"Dataset {dataset_id}:跳过 {len(dropped)} 行(时间无法解析、价格缺失或非正):{_sample(dropped)}"
|
|
430
|
-
)
|
|
345
|
+
))
|
|
431
346
|
coverage = None
|
|
432
347
|
if points:
|
|
433
348
|
coverage = {
|
|
@@ -455,13 +370,13 @@ def analyze(request: dict, context) -> dict:
|
|
|
455
370
|
for window in windows:
|
|
456
371
|
rows, reasons, portfolio_return, contribution_sum = _evaluate_window(window, positions, series_by_id)
|
|
457
372
|
prefix = f"窗口 {window['name']}({window['start']}..{window['end']})"
|
|
458
|
-
for reason in reasons:
|
|
459
|
-
gaps.append(f"{prefix}:{reason}")
|
|
373
|
+
for gap_of, reason in reasons:
|
|
374
|
+
gaps.append(gap_of(f"{prefix}:{reason}"))
|
|
460
375
|
if reasons:
|
|
461
|
-
gaps.append(
|
|
376
|
+
gaps.append(gapvocab.field_missing(
|
|
462
377
|
f"{prefix}:{len(reasons)}/{len(positions)} 个持仓缺区间收益,"
|
|
463
378
|
"组合收益未计算(不按剩余权重重归一化)"
|
|
464
|
-
)
|
|
379
|
+
))
|
|
465
380
|
window_rows.append({
|
|
466
381
|
"name": window["name"],
|
|
467
382
|
"start": window["start"],
|
|
@@ -509,7 +424,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
509
424
|
return _result(status, summary, metrics, methodology, limitations, gaps, [])
|
|
510
425
|
|
|
511
426
|
payload = {
|
|
512
|
-
"protocol": "capital.analysis/
|
|
427
|
+
"protocol": "capital.analysis/v2",
|
|
513
428
|
"module_id": MODULE_ID,
|
|
514
429
|
"module_version": MODULE_VERSION,
|
|
515
430
|
"analysis_id": request.get("analysis_id"),
|