@v587d/capital-generation 2.31.8 → 2.32.1
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 +68 -0
- package/README.md +11 -7
- 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/sources/ftshare-rest.js +1 -1
- package/lib/sources/tencent-http.js +210 -53
- 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
|
@@ -12,7 +12,12 @@ this module only produces reproducible residuals plus the input values behind ea
|
|
|
12
12
|
"""
|
|
13
13
|
from __future__ import annotations
|
|
14
14
|
|
|
15
|
-
from
|
|
15
|
+
from lib import frames as _frames
|
|
16
|
+
from lib import gaps as gapvocab
|
|
17
|
+
from lib.errors import AnalysisInputError
|
|
18
|
+
from lib.frames import columns_of as _columns_of, number as _number, row_at as _row_at
|
|
19
|
+
from lib.jsonio import round_metric as _round
|
|
20
|
+
from lib.timeaxis import iso_date as _iso_date
|
|
16
21
|
|
|
17
22
|
MODULE_ID = "statement_integrity"
|
|
18
23
|
MODULE_VERSION = "1.0.0"
|
|
@@ -58,22 +63,6 @@ DIVIDEND_COLUMNS = ("dividends_paid", "dividends_declared")
|
|
|
58
63
|
DEFAULT_TOLERANCE_RATIO = 0.001
|
|
59
64
|
|
|
60
65
|
|
|
61
|
-
class AnalysisInputError(Exception):
|
|
62
|
-
"""The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
|
|
63
|
-
|
|
64
|
-
analysis_code = "analysis_input_invalid"
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
def _round(value):
|
|
68
|
-
rounded = round(float(value), 6)
|
|
69
|
-
return 0.0 if rounded == 0 else rounded
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
def _plain(value):
|
|
73
|
-
"""Integral floats as ints: the audit file then shows 100000000000, not 100000000000.0."""
|
|
74
|
-
return int(value) if isinstance(value, float) and value.is_integer() else value
|
|
75
|
-
|
|
76
|
-
|
|
77
66
|
def _amount(value):
|
|
78
67
|
"""Money keeps the source's integer form when it has one; otherwise 6 decimals."""
|
|
79
68
|
if value is None:
|
|
@@ -83,44 +72,12 @@ def _amount(value):
|
|
|
83
72
|
return _round(value)
|
|
84
73
|
|
|
85
74
|
|
|
86
|
-
def
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
number = float(value)
|
|
93
|
-
if number != number or number in (float("inf"), float("-inf")):
|
|
94
|
-
return None
|
|
95
|
-
return number
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
def _columns_of(view):
|
|
99
|
-
columns = view.get("columns") or []
|
|
100
|
-
names = {item.get("name") for item in columns if isinstance(item, dict)}
|
|
101
|
-
for row in (view.get("rows") or [])[:1]:
|
|
102
|
-
if isinstance(row, dict):
|
|
103
|
-
names |= set(row)
|
|
104
|
-
return names
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
def _read_datasets(request, context):
|
|
108
|
-
items = (request.get("inputs") or {}).get("datasets") or []
|
|
109
|
-
if not items:
|
|
110
|
-
raise AnalysisInputError("快照里没有任何 Dataset:先取齐三张报表再建快照")
|
|
111
|
-
views = {}
|
|
112
|
-
for item in items:
|
|
113
|
-
dataset_id = (item or {}).get("dataset_id")
|
|
114
|
-
if not isinstance(dataset_id, str) or not dataset_id:
|
|
115
|
-
raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
|
|
116
|
-
views[dataset_id] = context.read_dataset(dataset_id)
|
|
117
|
-
for dataset_id, view in views.items():
|
|
118
|
-
if view.get("shape") != "rows":
|
|
119
|
-
raise AnalysisInputError(
|
|
120
|
-
f"Dataset {dataset_id} 是 {view.get('shape')} 型:statement_integrity 只吃表格数据,"
|
|
121
|
-
"文档型输入请先走 profile 或证据"
|
|
122
|
-
)
|
|
123
|
-
return views
|
|
75
|
+
def _read_views(request, context):
|
|
76
|
+
return _frames.read_views(
|
|
77
|
+
request, context,
|
|
78
|
+
module_id=MODULE_ID,
|
|
79
|
+
empty_message="快照里没有任何 Dataset:先取齐三张报表再建快照",
|
|
80
|
+
)
|
|
124
81
|
|
|
125
82
|
|
|
126
83
|
def _resolve_roles(views, params):
|
|
@@ -159,30 +116,15 @@ def _resolve_roles(views, params):
|
|
|
159
116
|
|
|
160
117
|
|
|
161
118
|
def _join_key(roles, views):
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
"三张报表缺少共同的报告期键:需要 period_end_ms 或 period 列,否则无法对齐同一报告期"
|
|
119
|
+
return _frames.join_key(
|
|
120
|
+
views, roles,
|
|
121
|
+
period_keys=PERIOD_KEYS,
|
|
122
|
+
hint="三张报表缺少共同的报告期键:需要 period_end_ms 或 period 列,否则无法对齐同一报告期",
|
|
167
123
|
)
|
|
168
124
|
|
|
169
125
|
|
|
170
126
|
def _index_rows(view, column, role):
|
|
171
|
-
|
|
172
|
-
for row in view.get("rows") or []:
|
|
173
|
-
if not isinstance(row, dict):
|
|
174
|
-
raise AnalysisInputError(f"{LABELS[role]}的数据行不是对象:无法计算")
|
|
175
|
-
key = row.get(column)
|
|
176
|
-
if isinstance(key, bool) or not isinstance(key, (int, float, str)) or key == "":
|
|
177
|
-
raise AnalysisInputError(f"{LABELS[role]}的 {column} 列有空值:无法对齐报告期")
|
|
178
|
-
if key in indexed:
|
|
179
|
-
raise AnalysisInputError(f"{LABELS[role]}在报告期 {key} 出现多行:无法判断用哪一行(请先去重)")
|
|
180
|
-
indexed[key] = row
|
|
181
|
-
return indexed
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
def _iso_date(ms):
|
|
185
|
-
return datetime.fromtimestamp(float(ms) / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
|
|
127
|
+
return _frames.index_rows(view, column, LABELS[role])
|
|
186
128
|
|
|
187
129
|
|
|
188
130
|
def _period_text_is_informative(rows_by_role):
|
|
@@ -205,11 +147,6 @@ def _period_text_is_informative(rows_by_role):
|
|
|
205
147
|
return len(texts) == len(keys) and len(texts) > 0 and all(any(ch.isdigit() for ch in text) for text in texts)
|
|
206
148
|
|
|
207
149
|
|
|
208
|
-
def _row_at(rows_by_role, key, role):
|
|
209
|
-
row = rows_by_role.get(role, {}).get(key)
|
|
210
|
-
return row if isinstance(row, dict) else None
|
|
211
|
-
|
|
212
|
-
|
|
213
150
|
def _label(rows_by_role, key, key_column):
|
|
214
151
|
"""Human-facing period label: the source's own text when it actually varies, else the report date."""
|
|
215
152
|
if _period_text_is_informative(rows_by_role):
|
|
@@ -326,6 +263,17 @@ def _skip_pair(name, reason):
|
|
|
326
263
|
return _skipped(name, reason), {f"{name}_checked": False}
|
|
327
264
|
|
|
328
265
|
|
|
266
|
+
def _skip_gap(name, reason):
|
|
267
|
+
"""Classify a skipped check by what is actually missing: a whole statement is an unavailable
|
|
268
|
+
source, a row absent for the selected period is a period conflict, the rest is a missing field."""
|
|
269
|
+
text = f"{CHECK_LABELS[name]}未校验:{reason}"
|
|
270
|
+
if "数据集" in reason:
|
|
271
|
+
return gapvocab.source_unavailable(text)
|
|
272
|
+
if "数据行" in reason or "没有早于" in reason:
|
|
273
|
+
return gapvocab.period_conflict(text)
|
|
274
|
+
return gapvocab.field_missing(text)
|
|
275
|
+
|
|
276
|
+
|
|
329
277
|
def _money_text(value):
|
|
330
278
|
return str(_amount(value))
|
|
331
279
|
|
|
@@ -475,7 +423,7 @@ def _retained_earnings_check(rows_by_role, key, label, tolerance_ratio, toleranc
|
|
|
475
423
|
surplus_delta = _number(current, "surplus_reserve") - _number(previous, "surplus_reserve")
|
|
476
424
|
else:
|
|
477
425
|
surplus_note = f"{label} 资产负债表没有可比的 surplus_reserve 列:留存收益滚动未扣除盈余公积变动,差异可能包含该部分"
|
|
478
|
-
gaps.append(surplus_note)
|
|
426
|
+
gaps.append(gapvocab.field_missing(surplus_note))
|
|
479
427
|
inputs = {
|
|
480
428
|
"retained_earnings_end": re_end,
|
|
481
429
|
"retained_earnings_previous": re_prev,
|
|
@@ -496,7 +444,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
496
444
|
params = request.get("params") or {}
|
|
497
445
|
tolerance_ratio = _param_number(params, "tolerance_ratio", DEFAULT_TOLERANCE_RATIO)
|
|
498
446
|
tolerance_abs = _param_number(params, "tolerance_abs", 0.0)
|
|
499
|
-
views =
|
|
447
|
+
views = _read_views(request, context)
|
|
500
448
|
roles = _resolve_roles(views, params)
|
|
501
449
|
|
|
502
450
|
methodology = [
|
|
@@ -520,7 +468,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
520
468
|
|
|
521
469
|
for role in ("balance", "cashflow", "income"):
|
|
522
470
|
if role not in roles:
|
|
523
|
-
gaps.append(f"缺少{LABELS[role]}数据集:相关勾稽未校验")
|
|
471
|
+
gaps.append(gapvocab.source_unavailable(f"缺少{LABELS[role]}数据集:相关勾稽未校验"))
|
|
524
472
|
|
|
525
473
|
key_column = _join_key(roles, views)
|
|
526
474
|
if key_column == "period":
|
|
@@ -537,7 +485,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
537
485
|
check, check_metrics = _skip_pair("balance", "缺少资产负债表数据集")
|
|
538
486
|
metrics.update(check_metrics)
|
|
539
487
|
if check["status"] == "skipped":
|
|
540
|
-
gaps.append(
|
|
488
|
+
gaps.append(_skip_gap("balance", check["reason"]))
|
|
541
489
|
else:
|
|
542
490
|
methodology.append(
|
|
543
491
|
f"资产负债恒等式差异 {check['residual']},基准 {check['scale']},{'通过' if check['status'] == 'pass' else '未通过'}"
|
|
@@ -550,7 +498,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
550
498
|
check, check_metrics = _skip_pair("cash", "缺少现金流量表数据集")
|
|
551
499
|
metrics.update(check_metrics)
|
|
552
500
|
if check["status"] == "skipped":
|
|
553
|
-
gaps.append(
|
|
501
|
+
gaps.append(_skip_gap("cash", check["reason"]))
|
|
554
502
|
else:
|
|
555
503
|
methodology.append(
|
|
556
504
|
f"现金流对账差异 {check['residual']},基准 {check['scale']},{'通过' if check['status'] == 'pass' else '未通过'}"
|
|
@@ -564,7 +512,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
564
512
|
check, check_metrics = _retained_earnings_check(rows_by_role, selected, label, tolerance_ratio, tolerance_abs, gaps)
|
|
565
513
|
metrics.update(check_metrics)
|
|
566
514
|
if check["status"] == "skipped":
|
|
567
|
-
gaps.append(
|
|
515
|
+
gaps.append(_skip_gap("retained_earnings", check["reason"]))
|
|
568
516
|
else:
|
|
569
517
|
methodology.append(
|
|
570
518
|
f"留存收益滚动(上一期 {check['previous_period']})差异 {check['residual']},"
|
|
@@ -591,7 +539,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
591
539
|
methodology.append(f"执行 {len(ran)} 项勾稽,{len(failures)} 项未通过;{len(gaps)} 项缺口")
|
|
592
540
|
|
|
593
541
|
payload = {
|
|
594
|
-
"protocol": "capital.analysis/
|
|
542
|
+
"protocol": "capital.analysis/v2",
|
|
595
543
|
"module_id": MODULE_ID,
|
|
596
544
|
"module_version": MODULE_VERSION,
|
|
597
545
|
"analysis_id": request.get("analysis_id"),
|
|
@@ -14,8 +14,19 @@ Protocol: `docs/dev/senior-analysis.md` §1.9.
|
|
|
14
14
|
from __future__ import annotations
|
|
15
15
|
|
|
16
16
|
import math
|
|
17
|
-
|
|
18
|
-
from
|
|
17
|
+
|
|
18
|
+
from lib import frames as _frames
|
|
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 text as _text
|
|
24
|
+
from lib.jsonio import round_or_none as _round
|
|
25
|
+
from lib.prices import candidate as _candidate
|
|
26
|
+
from lib.prices import price_column as _price_column
|
|
27
|
+
from lib.timeaxis import parse_time as _parse_time
|
|
28
|
+
from lib.timeaxis import time_column as _time_column
|
|
29
|
+
from lib.timeaxis import timezone_of as _timezone
|
|
19
30
|
|
|
20
31
|
MODULE_ID = "technical_indicators"
|
|
21
32
|
MODULE_VERSION = "1.0.0"
|
|
@@ -43,32 +54,14 @@ LIMITATIONS = [
|
|
|
43
54
|
"不构成投资建议,也不产生评级、目标价或收益承诺",
|
|
44
55
|
]
|
|
45
56
|
|
|
46
|
-
PRICE_COLUMNS = ("close", "adj_close", "close_price", "price", "nav")
|
|
47
|
-
TIME_COLUMNS = ("trade_date_ms", "date_ms", "period_end_ms", "datetime", "date", "trade_date", "time")
|
|
48
57
|
OHLC_COLUMNS = ("high", "low")
|
|
49
|
-
ISO_DAY = re.compile(r"^(\d{4}-\d{2}-\d{2})")
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
class AnalysisInputError(Exception):
|
|
53
|
-
"""The input cannot be used at all; the host maps `analysis_code` to the stable protocol code."""
|
|
54
|
-
|
|
55
|
-
analysis_code = "analysis_input_invalid"
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
def _round(value):
|
|
59
|
-
"""Six decimals; `None` for a non-finite value so the JSON boundary never sees NaN/Infinity."""
|
|
60
|
-
number = float(value)
|
|
61
|
-
if number != number or number in (float("inf"), float("-inf")):
|
|
62
|
-
return None
|
|
63
|
-
rounded = round(number, 6)
|
|
64
|
-
return 0.0 if rounded == 0 else rounded
|
|
65
58
|
|
|
66
59
|
|
|
67
60
|
def _publish(metrics, computed, gaps, key, label, value):
|
|
68
61
|
"""Publish one latest indicator value; a non-finite one is a gap, not a NaN."""
|
|
69
62
|
rounded = _round(value)
|
|
70
63
|
if rounded is None:
|
|
71
|
-
gaps.append(f"{label} 最新值不是有限数字(价格量级导致数值溢出):未输出")
|
|
64
|
+
gaps.append(gapvocab.field_missing(f"{label} 最新值不是有限数字(价格量级导致数值溢出):未输出"))
|
|
72
65
|
return
|
|
73
66
|
metrics[key] = rounded
|
|
74
67
|
computed.append(key)
|
|
@@ -78,97 +71,6 @@ def _fmt4(value):
|
|
|
78
71
|
return f"{value:.4f}"
|
|
79
72
|
|
|
80
73
|
|
|
81
|
-
def _number(row, name):
|
|
82
|
-
if row is None:
|
|
83
|
-
return None
|
|
84
|
-
value = row.get(name)
|
|
85
|
-
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
86
|
-
return None
|
|
87
|
-
number = float(value)
|
|
88
|
-
if number != number or number in (float("inf"), float("-inf")):
|
|
89
|
-
return None
|
|
90
|
-
return number
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
def _columns_of(view):
|
|
94
|
-
columns = view.get("columns") or []
|
|
95
|
-
names = {item.get("name") for item in columns if isinstance(item, dict)}
|
|
96
|
-
for row in (view.get("rows") or [])[:1]:
|
|
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 之一"
|
|
132
|
-
)
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
def _price_column(view, override):
|
|
136
|
-
names = _columns_of(view)
|
|
137
|
-
if override is not None:
|
|
138
|
-
if override not in names:
|
|
139
|
-
raise AnalysisInputError(f"price_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
|
|
140
|
-
return override
|
|
141
|
-
for name in PRICE_COLUMNS:
|
|
142
|
-
if name in names:
|
|
143
|
-
return name
|
|
144
|
-
raise AnalysisInputError(
|
|
145
|
-
"找不到价格列:需要 close / adj_close / close_price / price / nav 之一(或用 price_column 指明)"
|
|
146
|
-
)
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
def _parse_time(value, tz):
|
|
150
|
-
"""Return `(sort_key, day_label)`; `None` when the value is not a usable time."""
|
|
151
|
-
if isinstance(value, bool):
|
|
152
|
-
return None
|
|
153
|
-
if isinstance(value, (int, float)):
|
|
154
|
-
number = float(value)
|
|
155
|
-
if number != number or number in (float("inf"), float("-inf")):
|
|
156
|
-
return None
|
|
157
|
-
stamp = datetime.fromtimestamp(number / 1000.0, tz=tz)
|
|
158
|
-
return number, stamp.strftime("%Y-%m-%d")
|
|
159
|
-
if isinstance(value, str):
|
|
160
|
-
match = ISO_DAY.match(value.strip())
|
|
161
|
-
if match is None:
|
|
162
|
-
return None
|
|
163
|
-
day = match.group(1)
|
|
164
|
-
try:
|
|
165
|
-
stamp = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
|
166
|
-
except ValueError:
|
|
167
|
-
return None
|
|
168
|
-
return stamp.timestamp() * 1000.0, day
|
|
169
|
-
return None
|
|
170
|
-
|
|
171
|
-
|
|
172
74
|
def _series(view, dataset_id, price_column, time_column, tz):
|
|
173
75
|
"""Positive prices on a time axis; bad rows are skipped and returned for `data_gaps`."""
|
|
174
76
|
rows = view.get("rows") or []
|
|
@@ -409,7 +311,7 @@ def _indicators(points, groups, names):
|
|
|
409
311
|
"formula": f"SMA({window}) = 最近 {window} 个收盘价的算术平均",
|
|
410
312
|
})
|
|
411
313
|
if count < window:
|
|
412
|
-
gaps.append(_window_gap(f"SMA({window})", f"{window} 根收盘价", count))
|
|
314
|
+
gaps.append(gapvocab.sample_insufficient(_window_gap(f"SMA({window})", f"{window} 根收盘价", count)))
|
|
413
315
|
continue
|
|
414
316
|
_publish(metrics, computed, gaps, key, f"SMA({window})", values[-1])
|
|
415
317
|
|
|
@@ -426,7 +328,7 @@ def _indicators(points, groups, names):
|
|
|
426
328
|
"formula": f"EMA({window}) = 前值 + 2/({window}+1)×(收盘 − 前值),首值取前 {window} 个收盘价均值",
|
|
427
329
|
})
|
|
428
330
|
if count < window:
|
|
429
|
-
gaps.append(_window_gap(f"EMA({window})", f"{window} 根收盘价", count))
|
|
331
|
+
gaps.append(gapvocab.sample_insufficient(_window_gap(f"EMA({window})", f"{window} 根收盘价", count)))
|
|
430
332
|
continue
|
|
431
333
|
_publish(metrics, computed, gaps, key, f"EMA({window})", values[-1])
|
|
432
334
|
|
|
@@ -446,7 +348,7 @@ def _indicators(points, groups, names):
|
|
|
446
348
|
),
|
|
447
349
|
})
|
|
448
350
|
if count < period + 1:
|
|
449
|
-
gaps.append(_window_gap(f"RSI({period})", f"{period + 1} 根(周期 + 1)", count))
|
|
351
|
+
gaps.append(gapvocab.sample_insufficient(_window_gap(f"RSI({period})", f"{period + 1} 根(周期 + 1)", count)))
|
|
450
352
|
else:
|
|
451
353
|
_publish(metrics, computed, gaps, key, f"RSI({period})", values[-1])
|
|
452
354
|
|
|
@@ -480,7 +382,7 @@ def _indicators(points, groups, names):
|
|
|
480
382
|
},
|
|
481
383
|
])
|
|
482
384
|
if count < slow + signal:
|
|
483
|
-
gaps.append(_window_gap(f"MACD({fast}/{slow}/{signal})", f"{slow + signal} 根(slow + signal)", count))
|
|
385
|
+
gaps.append(gapvocab.sample_insufficient(_window_gap(f"MACD({fast}/{slow}/{signal})", f"{slow + signal} 根(slow + signal)", count)))
|
|
484
386
|
else:
|
|
485
387
|
_publish(metrics, computed, gaps, "macd", "MACD", macd_values[-1])
|
|
486
388
|
_publish(metrics, computed, gaps, "macd_signal", "MACD signal", signal_values[-1])
|
|
@@ -517,7 +419,7 @@ def _indicators(points, groups, names):
|
|
|
517
419
|
},
|
|
518
420
|
])
|
|
519
421
|
if count < period:
|
|
520
|
-
gaps.append(_window_gap(f"BOLL({period})", f"{period} 根收盘价", count))
|
|
422
|
+
gaps.append(gapvocab.sample_insufficient(_window_gap(f"BOLL({period})", f"{period} 根收盘价", count)))
|
|
521
423
|
else:
|
|
522
424
|
_publish(metrics, computed, gaps, "boll_upper", "BOLL 上轨", upper[-1])
|
|
523
425
|
_publish(metrics, computed, gaps, "boll_middle", "BOLL 中轨", middle[-1])
|
|
@@ -541,15 +443,17 @@ def _indicators(points, groups, names):
|
|
|
541
443
|
invalid = sum(1 for point in points if point["high"] is None or point["low"] is None)
|
|
542
444
|
if missing:
|
|
543
445
|
series_values[key] = [None] * count
|
|
544
|
-
gaps.append(
|
|
446
|
+
gaps.append(gapvocab.field_missing(
|
|
545
447
|
f"ATR({period}) 未计算:需要 high / low / close 三列,Dataset 缺 {'、'.join(missing)}(ATR 要用真实波幅)"
|
|
546
|
-
)
|
|
448
|
+
))
|
|
547
449
|
elif invalid:
|
|
548
450
|
series_values[key] = [None] * count
|
|
549
|
-
gaps.append(
|
|
451
|
+
gaps.append(gapvocab.field_missing(
|
|
452
|
+
f"ATR({period}) 未计算:有 {invalid} 行 high/low 不是有限数字(按缺口处理,不填默认值)"
|
|
453
|
+
))
|
|
550
454
|
elif count < period + 1:
|
|
551
455
|
series_values[key] = [None] * count
|
|
552
|
-
gaps.append(_window_gap(f"ATR({period})", f"{period + 1} 根(周期 + 1)", count))
|
|
456
|
+
gaps.append(gapvocab.sample_insufficient(_window_gap(f"ATR({period})", f"{period + 1} 根(周期 + 1)", count)))
|
|
553
457
|
else:
|
|
554
458
|
values = _atr_series(points, period)
|
|
555
459
|
series_values[key] = values
|
|
@@ -684,35 +588,12 @@ def _result(status, summary, metrics, methodology, limitations, gaps, outputs):
|
|
|
684
588
|
|
|
685
589
|
|
|
686
590
|
def _read_views(request, context):
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
if not isinstance(dataset_id, str) or not dataset_id:
|
|
694
|
-
raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
|
|
695
|
-
views[dataset_id] = context.read_dataset(dataset_id)
|
|
696
|
-
for dataset_id, view in views.items():
|
|
697
|
-
if view.get("shape") != "rows":
|
|
698
|
-
raise AnalysisInputError(
|
|
699
|
-
f"Dataset {dataset_id} 是 {view.get('shape')} 型:technical_indicators 只吃表格价格序列(rows),"
|
|
700
|
-
"文档型输入请先走 profile 或证据"
|
|
701
|
-
)
|
|
702
|
-
return views
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
def _candidate(views, price_override, time_override):
|
|
706
|
-
"""Dataset ids that look like a price series (a time column plus a price column)."""
|
|
707
|
-
candidates = []
|
|
708
|
-
for dataset_id, view in sorted(views.items()):
|
|
709
|
-
try:
|
|
710
|
-
time_column = _time_column(view, time_override)
|
|
711
|
-
_price_column(view, price_override)
|
|
712
|
-
except AnalysisInputError:
|
|
713
|
-
continue
|
|
714
|
-
candidates.append((dataset_id, time_column))
|
|
715
|
-
return candidates
|
|
591
|
+
return _frames.read_views(
|
|
592
|
+
request,
|
|
593
|
+
context,
|
|
594
|
+
module_id=MODULE_ID,
|
|
595
|
+
empty_message="快照里没有任何 Dataset:先取价格序列再建快照",
|
|
596
|
+
)
|
|
716
597
|
|
|
717
598
|
|
|
718
599
|
def analyze(request: dict, context) -> dict:
|
|
@@ -755,7 +636,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
755
636
|
names = _columns_of(price_view)
|
|
756
637
|
metrics, series_values, metadata, gaps, computed = _indicators(points, groups, names)
|
|
757
638
|
if dropped:
|
|
758
|
-
gaps.insert(0, _skipped_gap(price_column, dropped))
|
|
639
|
+
gaps.insert(0, gapvocab.field_missing(_skipped_gap(price_column, dropped)))
|
|
759
640
|
_states(points, metrics, groups, series_values)
|
|
760
641
|
|
|
761
642
|
methodology = [
|
|
@@ -821,7 +702,7 @@ def analyze(request: dict, context) -> dict:
|
|
|
821
702
|
series_rows = series_rows[-MAX_SERIES_BARS:]
|
|
822
703
|
|
|
823
704
|
payload = {
|
|
824
|
-
"protocol": "capital.analysis/
|
|
705
|
+
"protocol": "capital.analysis/v2",
|
|
825
706
|
"module_id": MODULE_ID,
|
|
826
707
|
"module_version": MODULE_VERSION,
|
|
827
708
|
"analysis_id": request.get("analysis_id"),
|