@v587d/capital-generation 2.31.0 → 2.31.3
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 +129 -0
- package/README.md +2 -2
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/package.json +1 -1
- package/lib/agents/messaging-policy.d.ts +23 -6
- package/lib/agents/messaging-policy.js +64 -9
- package/lib/agents/role-tool-policy.js +3 -3
- package/lib/analysis/registry.js +1 -1
- package/lib/analysis/schemas.d.ts +8 -2
- package/lib/analysis/schemas.js +8 -2
- package/lib/analysis/tools.js +5 -0
- package/lib/analysis/validation.js +72 -19
- package/lib/data-collector/store.js +3 -1
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +1 -1
- package/preset/capital-generation/agent.patch.yml +23 -21
- package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +22 -1
- package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +9 -6
- package/preset/capital-generation/skills/capital-orchestration/SKILL.md +33 -28
- package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +16 -8
- package/python/analysis/modules/returns_risk/LICENSE +21 -0
- package/python/analysis/modules/returns_risk/module.json +66 -0
- package/python/analysis/modules/returns_risk/module.py +517 -0
- package/python/analysis/modules/scenario_sensitivity/LICENSE +21 -0
- package/python/analysis/modules/scenario_sensitivity/module.json +105 -0
- package/python/analysis/modules/scenario_sensitivity/module.py +379 -0
- package/watchlist/package.json +1 -1
|
@@ -0,0 +1,517 @@
|
|
|
1
|
+
"""Returns and risk for one price series (the "series" input shape of the module protocol).
|
|
2
|
+
|
|
3
|
+
Input is one Dataset with a time column and a positive price column, plus an optional benchmark
|
|
4
|
+
series. Every output is a stated formula over those rows — the module does not forecast, score,
|
|
5
|
+
rate or recommend, and it never fills a missing observation with zero. A bad price row is skipped
|
|
6
|
+
and reported as a gap; a duplicate or mixed-format time axis is an input error, because silently
|
|
7
|
+
picking one row would make every downstream number look sourced when it is not.
|
|
8
|
+
|
|
9
|
+
Pure standard library on purpose: no numpy/pandas, so the arithmetic is auditable line by line and
|
|
10
|
+
the module runs on the minimal analysis runtime.
|
|
11
|
+
|
|
12
|
+
Protocol: `docs/dev/senior-analysis.md` §1.9. Conclusions and claims belong to the senior analyst;
|
|
13
|
+
this module only produces reproducible risk figures plus the inputs behind each one.
|
|
14
|
+
"""
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import math
|
|
18
|
+
import re
|
|
19
|
+
from datetime import datetime, timezone
|
|
20
|
+
|
|
21
|
+
MODULE_ID = "returns_risk"
|
|
22
|
+
MODULE_VERSION = "1.0.0"
|
|
23
|
+
OUTPUT_NAME = "risk_metrics"
|
|
24
|
+
|
|
25
|
+
PERIODS_PER_YEAR_DEFAULT = 252
|
|
26
|
+
CONFIDENCE_DEFAULT = 0.95
|
|
27
|
+
MIN_RETURNS_FOR_STABLE = 30
|
|
28
|
+
|
|
29
|
+
ASSUMPTIONS = [
|
|
30
|
+
"价格口径沿用 Dataset 的取数参数(qfq / hfq / none),本模块不检测也不做复权调整",
|
|
31
|
+
"年化用参数 periods_per_year(默认 252)与样本内几何收益;日历天数不参与年化",
|
|
32
|
+
"波动率是日收益样本标准差(ddof=1)× sqrt(periods_per_year)",
|
|
33
|
+
"夏普 / 索提诺 =(年化收益 − risk_free_rate)/ 对应年化风险;risk_free_rate 为年化小数,省略时按 0 披露",
|
|
34
|
+
"VaR / CVaR 为历史法单期损失(正数 = 亏损幅度),置信度取参数",
|
|
35
|
+
"停牌或平盘日的价格重复会形成 0 收益,按原序列计入,不剔除",
|
|
36
|
+
"beta / 相关按重叠交易日的日收益计算;基准与标的不同复权口径时 beta 有偏",
|
|
37
|
+
]
|
|
38
|
+
|
|
39
|
+
LIMITATIONS = [
|
|
40
|
+
"历史风险不预测未来:样本期之外的波动、回撤与尾部损失可能显著更大",
|
|
41
|
+
"样本越短年化指标越不稳定;少于 30 个收益观测时只能当作方向性参考",
|
|
42
|
+
"不处理分红再投资、交易成本、停牌期间的机会成本与流动性折价",
|
|
43
|
+
"数值时间轴按参数 timezone 标注日历日(省略按 UTC);跨市场比较前先对齐时区",
|
|
44
|
+
"不构成投资建议,也不产生评级、目标价或收益承诺",
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
PRICE_COLUMNS = ("close", "adj_close", "close_price", "price", "nav")
|
|
48
|
+
TIME_COLUMNS = ("trade_date_ms", "date_ms", "period_end_ms", "datetime", "date", "trade_date", "time")
|
|
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
|
+
rounded = round(float(value), 6)
|
|
60
|
+
return 0.0 if rounded == 0 else rounded
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _number(row, name):
|
|
64
|
+
if row is None:
|
|
65
|
+
return None
|
|
66
|
+
value = row.get(name)
|
|
67
|
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
68
|
+
return None
|
|
69
|
+
number = float(value)
|
|
70
|
+
if number != number or number in (float("inf"), float("-inf")):
|
|
71
|
+
return None
|
|
72
|
+
return number
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _columns_of(view):
|
|
76
|
+
columns = view.get("columns") or []
|
|
77
|
+
names = {item.get("name") for item in columns if isinstance(item, dict)}
|
|
78
|
+
for row in (view.get("rows") or [])[:1]:
|
|
79
|
+
if isinstance(row, dict):
|
|
80
|
+
names |= set(row)
|
|
81
|
+
return names
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _text(value):
|
|
85
|
+
return value if isinstance(value, str) and value.strip() else None
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _timezone(name):
|
|
89
|
+
"""IANA zone when the caller names one; UTC otherwise (the dataset tz is not authoritative)."""
|
|
90
|
+
if name is None:
|
|
91
|
+
return timezone.utc
|
|
92
|
+
try:
|
|
93
|
+
from zoneinfo import ZoneInfo
|
|
94
|
+
|
|
95
|
+
return ZoneInfo(name)
|
|
96
|
+
except Exception as error: # noqa: BLE001 - any load failure is a caller error
|
|
97
|
+
raise AnalysisInputError(f"timezone={name!r} 无法加载(需要 IANA 时区名,如 Asia/Shanghai)") from error
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _time_column(view, override):
|
|
101
|
+
names = _columns_of(view)
|
|
102
|
+
if override is not None:
|
|
103
|
+
if override not in names:
|
|
104
|
+
raise AnalysisInputError(f"time_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
|
|
105
|
+
return override
|
|
106
|
+
axis = (view.get("time_axis") or {}).get("column")
|
|
107
|
+
if isinstance(axis, str) and axis in names:
|
|
108
|
+
return axis
|
|
109
|
+
for name in TIME_COLUMNS:
|
|
110
|
+
if name in names:
|
|
111
|
+
return name
|
|
112
|
+
raise AnalysisInputError(
|
|
113
|
+
"找不到时间列:需要 time_coverage 列,或 trade_date_ms / date_ms / period_end_ms / datetime / date / trade_date 之一"
|
|
114
|
+
)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _price_column(view, override):
|
|
118
|
+
names = _columns_of(view)
|
|
119
|
+
if override is not None:
|
|
120
|
+
if override not in names:
|
|
121
|
+
raise AnalysisInputError(f"price_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
|
|
122
|
+
return override
|
|
123
|
+
for name in PRICE_COLUMNS:
|
|
124
|
+
if name in names:
|
|
125
|
+
return name
|
|
126
|
+
raise AnalysisInputError(
|
|
127
|
+
"找不到价格列:需要 close / adj_close / close_price / price / nav 之一(或用 price_column 指明)"
|
|
128
|
+
)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def _parse_time(value, tz):
|
|
132
|
+
"""Return `(sort_key, day_label)`; `None` when the value is not a usable time."""
|
|
133
|
+
if isinstance(value, bool):
|
|
134
|
+
return None
|
|
135
|
+
if isinstance(value, (int, float)):
|
|
136
|
+
number = float(value)
|
|
137
|
+
if number != number or number in (float("inf"), float("-inf")):
|
|
138
|
+
return None
|
|
139
|
+
stamp = datetime.fromtimestamp(number / 1000.0, tz=tz)
|
|
140
|
+
return number, stamp.strftime("%Y-%m-%d")
|
|
141
|
+
if isinstance(value, str):
|
|
142
|
+
match = ISO_DAY.match(value.strip())
|
|
143
|
+
if match is None:
|
|
144
|
+
return None
|
|
145
|
+
day = match.group(1)
|
|
146
|
+
try:
|
|
147
|
+
stamp = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
|
148
|
+
except ValueError:
|
|
149
|
+
return None
|
|
150
|
+
return stamp.timestamp() * 1000.0, day
|
|
151
|
+
return None
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def _series(view, dataset_id, price_column, time_column, tz):
|
|
155
|
+
rows = view.get("rows") or []
|
|
156
|
+
if not rows:
|
|
157
|
+
raise AnalysisInputError(f"Dataset {dataset_id} 没有数据行:无法计算收益与风险")
|
|
158
|
+
points, dropped, kind = [], [], None
|
|
159
|
+
for row in rows:
|
|
160
|
+
if not isinstance(row, dict):
|
|
161
|
+
raise AnalysisInputError(f"Dataset {dataset_id} 的数据行不是对象:无法计算")
|
|
162
|
+
raw_time = row.get(time_column)
|
|
163
|
+
row_kind = "ms" if isinstance(raw_time, (int, float)) and not isinstance(raw_time, bool) else "date"
|
|
164
|
+
if kind is None:
|
|
165
|
+
kind = row_kind
|
|
166
|
+
elif row_kind != kind:
|
|
167
|
+
raise AnalysisInputError(
|
|
168
|
+
f"Dataset {dataset_id} 的 {time_column} 列混用了数值时间戳与日期字符串:无法排序,请取数时统一"
|
|
169
|
+
)
|
|
170
|
+
parsed = _parse_time(raw_time, tz)
|
|
171
|
+
price = _number(row, price_column)
|
|
172
|
+
if parsed is None or price is None or price <= 0:
|
|
173
|
+
dropped.append(raw_time)
|
|
174
|
+
continue
|
|
175
|
+
key, day = parsed
|
|
176
|
+
points.append({"key": key, "day": day, "price": price})
|
|
177
|
+
points.sort(key=lambda item: item["key"])
|
|
178
|
+
seen = set()
|
|
179
|
+
for point in points:
|
|
180
|
+
if point["day"] in seen:
|
|
181
|
+
raise AnalysisInputError(
|
|
182
|
+
f"Dataset {dataset_id} 在 {point['day']} 出现多行:无法判断用哪一行(请先去重)"
|
|
183
|
+
)
|
|
184
|
+
seen.add(point["day"])
|
|
185
|
+
return points, dropped
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _quantile(values, q):
|
|
189
|
+
if not values:
|
|
190
|
+
return None
|
|
191
|
+
position = (len(values) - 1) * q
|
|
192
|
+
lower = int(math.floor(position))
|
|
193
|
+
upper = int(math.ceil(position))
|
|
194
|
+
if lower == upper:
|
|
195
|
+
return values[lower]
|
|
196
|
+
weight = position - lower
|
|
197
|
+
return values[lower] * (1.0 - weight) + values[upper] * weight
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _variance(values):
|
|
201
|
+
mean = sum(values) / len(values)
|
|
202
|
+
return sum((value - mean) ** 2 for value in values) / (len(values) - 1), mean
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _risk(points, periods_per_year, risk_free_rate, confidence):
|
|
206
|
+
closes = [point["price"] for point in points]
|
|
207
|
+
returns = [closes[index] / closes[index - 1] - 1.0 for index in range(1, len(closes))]
|
|
208
|
+
count = len(returns)
|
|
209
|
+
total_return = closes[-1] / closes[0] - 1.0
|
|
210
|
+
annualized_return = (1.0 + total_return) ** (periods_per_year / count) - 1.0
|
|
211
|
+
variance, mean_return = _variance(returns)
|
|
212
|
+
annualized_volatility = math.sqrt(variance) * math.sqrt(periods_per_year)
|
|
213
|
+
|
|
214
|
+
peak, max_drawdown = closes[0], 0.0
|
|
215
|
+
for close in closes:
|
|
216
|
+
peak = max(peak, close)
|
|
217
|
+
max_drawdown = min(max_drawdown, close / peak - 1.0)
|
|
218
|
+
|
|
219
|
+
sharpe = (annualized_return - risk_free_rate) / annualized_volatility if annualized_volatility > 0 else None
|
|
220
|
+
downside = math.sqrt(sum(min(value, 0.0) ** 2 for value in returns) / count) * math.sqrt(periods_per_year)
|
|
221
|
+
sortino = (annualized_return - risk_free_rate) / downside if downside > 0 else None
|
|
222
|
+
calmar = annualized_return / abs(max_drawdown) if max_drawdown < 0 else None
|
|
223
|
+
|
|
224
|
+
ordered = sorted(returns)
|
|
225
|
+
quantile = _quantile(ordered, 1.0 - confidence)
|
|
226
|
+
var = 0.0 if quantile is None or quantile >= 0 else -quantile
|
|
227
|
+
tail = [value for value in returns if quantile is not None and value <= quantile]
|
|
228
|
+
cvar = -sum(tail) / len(tail) if tail and quantile is not None and quantile < 0 else 0.0
|
|
229
|
+
|
|
230
|
+
metrics = {
|
|
231
|
+
"observations": len(points),
|
|
232
|
+
"returns_count": count,
|
|
233
|
+
"total_return": _round(total_return),
|
|
234
|
+
"annualized_return": _round(annualized_return),
|
|
235
|
+
"annualized_volatility": _round(annualized_volatility),
|
|
236
|
+
"max_drawdown": _round(max_drawdown),
|
|
237
|
+
"mean_daily_return": _round(mean_return),
|
|
238
|
+
"best_day": _round(max(returns)),
|
|
239
|
+
"worst_day": _round(min(returns)),
|
|
240
|
+
"positive_day_ratio": _round(sum(1 for value in returns if value > 0) / count),
|
|
241
|
+
"var": _round(var),
|
|
242
|
+
"cvar": _round(cvar),
|
|
243
|
+
"confidence": confidence,
|
|
244
|
+
"risk_free_rate": risk_free_rate,
|
|
245
|
+
"annualization": periods_per_year,
|
|
246
|
+
}
|
|
247
|
+
for name, value in (("sharpe_ratio", sharpe), ("sortino_ratio", sortino), ("calmar_ratio", calmar)):
|
|
248
|
+
if value is not None:
|
|
249
|
+
metrics[name] = _round(value)
|
|
250
|
+
return metrics, returns
|
|
251
|
+
|
|
252
|
+
|
|
253
|
+
def _benchmark(points, bench_day_prices):
|
|
254
|
+
common = [point for point in points if point["day"] in bench_day_prices]
|
|
255
|
+
overlap = len(common) - 1
|
|
256
|
+
if overlap < 2:
|
|
257
|
+
return None, f"基准与价格序列重叠少于 2 个日收益(实际 {max(overlap, 0)}):beta / 相关未计算"
|
|
258
|
+
asset_returns, bench_returns = [], []
|
|
259
|
+
for previous, current in zip(common, common[1:]):
|
|
260
|
+
asset_returns.append(current["price"] / previous["price"] - 1.0)
|
|
261
|
+
bench_returns.append(bench_day_prices[current["day"]] / bench_day_prices[previous["day"]] - 1.0)
|
|
262
|
+
bench_variance, bench_mean = _variance(bench_returns)
|
|
263
|
+
asset_variance, asset_mean = _variance(asset_returns)
|
|
264
|
+
if bench_variance <= 0 or asset_variance <= 0:
|
|
265
|
+
return None, "基准或标的在重叠窗口内零波动:beta / 相关无经济含义,未计算"
|
|
266
|
+
covariance = sum(
|
|
267
|
+
(asset - asset_mean) * (bench - bench_mean)
|
|
268
|
+
for asset, bench in zip(asset_returns, bench_returns)
|
|
269
|
+
) / (len(asset_returns) - 1)
|
|
270
|
+
beta = covariance / bench_variance
|
|
271
|
+
correlation = covariance / math.sqrt(asset_variance * bench_variance)
|
|
272
|
+
benchmark_return = bench_day_prices[common[-1]["day"]] / bench_day_prices[common[0]["day"]] - 1.0
|
|
273
|
+
return {
|
|
274
|
+
"beta": _round(beta),
|
|
275
|
+
"correlation": _round(correlation),
|
|
276
|
+
"benchmark_overlap": overlap,
|
|
277
|
+
"benchmark_total_return": _round(benchmark_return),
|
|
278
|
+
}, None
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _pct(value):
|
|
282
|
+
return f"{value * 100:.2f}%"
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def _ratio(value):
|
|
286
|
+
return f"{value:.4f}"
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
def _summary(metrics, start, end, gaps):
|
|
290
|
+
parts = [
|
|
291
|
+
f"{start}..{end},{metrics['observations']} 个观测 / {metrics['returns_count']} 个收益",
|
|
292
|
+
f"区间收益 {_pct(metrics['total_return'])}",
|
|
293
|
+
f"年化收益 {_pct(metrics['annualized_return'])}",
|
|
294
|
+
f"年化波动 {_pct(metrics['annualized_volatility'])}",
|
|
295
|
+
f"最大回撤 {_pct(metrics['max_drawdown'])}",
|
|
296
|
+
]
|
|
297
|
+
if "sharpe_ratio" in metrics:
|
|
298
|
+
parts.append(f"夏普 {_ratio(metrics['sharpe_ratio'])}(rf={_pct(metrics['risk_free_rate'])})")
|
|
299
|
+
if "sortino_ratio" in metrics:
|
|
300
|
+
parts.append(f"索提诺 {_ratio(metrics['sortino_ratio'])}")
|
|
301
|
+
if "calmar_ratio" in metrics:
|
|
302
|
+
parts.append(f"Calmar {_ratio(metrics['calmar_ratio'])}")
|
|
303
|
+
parts.append(f"VaR{int(round(metrics['confidence'] * 100))} {_pct(metrics['var'])}")
|
|
304
|
+
parts.append(f"CVaR {_pct(metrics['cvar'])}")
|
|
305
|
+
if "beta" in metrics:
|
|
306
|
+
parts.append(
|
|
307
|
+
f"基准 beta {_ratio(metrics['beta'])}、相关 {_ratio(metrics['correlation'])}"
|
|
308
|
+
f"(重叠 {metrics['benchmark_overlap']} 个日收益)"
|
|
309
|
+
)
|
|
310
|
+
head = ";".join(parts) + "。"
|
|
311
|
+
if gaps:
|
|
312
|
+
head += "(有缺口未计算,见 data_gaps)"
|
|
313
|
+
return head
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _result(status, summary, metrics, methodology, limitations, gaps, outputs):
|
|
317
|
+
return {
|
|
318
|
+
"status": status,
|
|
319
|
+
"summary": summary,
|
|
320
|
+
"metrics": metrics,
|
|
321
|
+
"claims": [],
|
|
322
|
+
"assumptions": list(ASSUMPTIONS),
|
|
323
|
+
"methodology_log": methodology,
|
|
324
|
+
"sensitivity": {},
|
|
325
|
+
"limitations": limitations,
|
|
326
|
+
"data_gaps": gaps,
|
|
327
|
+
"outputs": outputs,
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
|
|
331
|
+
def _sample(values):
|
|
332
|
+
"""First few raw time values in a gap message; enough to locate the bad rows, not a data dump."""
|
|
333
|
+
shown = "、".join(str(value) for value in values[:5])
|
|
334
|
+
return shown if len(values) <= 5 else f"{shown} 等 {len(values)} 行"
|
|
335
|
+
|
|
336
|
+
|
|
337
|
+
def _read_views(request, context):
|
|
338
|
+
items = (request.get("inputs") or {}).get("datasets") or []
|
|
339
|
+
if not items:
|
|
340
|
+
raise AnalysisInputError("快照里没有任何 Dataset:先取价格序列再建快照")
|
|
341
|
+
views = {}
|
|
342
|
+
for item in items:
|
|
343
|
+
dataset_id = (item or {}).get("dataset_id")
|
|
344
|
+
if not isinstance(dataset_id, str) or not dataset_id:
|
|
345
|
+
raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
|
|
346
|
+
views[dataset_id] = context.read_dataset(dataset_id)
|
|
347
|
+
for dataset_id, view in views.items():
|
|
348
|
+
if view.get("shape") != "rows":
|
|
349
|
+
raise AnalysisInputError(
|
|
350
|
+
f"Dataset {dataset_id} 是 {view.get('shape')} 型:returns_risk 只吃表格数据,"
|
|
351
|
+
"文档型输入请先走 profile 或证据"
|
|
352
|
+
)
|
|
353
|
+
return views
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _candidate(views, price_override, time_override):
|
|
357
|
+
"""Dataset ids that look like a price series (a time column plus a price column)."""
|
|
358
|
+
candidates = []
|
|
359
|
+
for dataset_id, view in sorted(views.items()):
|
|
360
|
+
try:
|
|
361
|
+
time_column = _time_column(view, time_override)
|
|
362
|
+
_price_column(view, price_override)
|
|
363
|
+
except AnalysisInputError:
|
|
364
|
+
continue
|
|
365
|
+
candidates.append((dataset_id, time_column))
|
|
366
|
+
return candidates
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def analyze(request: dict, context) -> dict:
|
|
370
|
+
params = request.get("params") or {}
|
|
371
|
+
views = _read_views(request, context)
|
|
372
|
+
price_override = _text(params.get("price_column"))
|
|
373
|
+
time_override = _text(params.get("time_column"))
|
|
374
|
+
|
|
375
|
+
price_dataset_id = _text(params.get("price_dataset_id"))
|
|
376
|
+
if price_dataset_id is not None:
|
|
377
|
+
if price_dataset_id not in views:
|
|
378
|
+
raise AnalysisInputError(f"price_dataset_id={price_dataset_id} 不在本次快照的 Dataset 里")
|
|
379
|
+
price_view = views[price_dataset_id]
|
|
380
|
+
else:
|
|
381
|
+
candidates = _candidate(views, price_override, time_override)
|
|
382
|
+
if len(candidates) > 1:
|
|
383
|
+
raise AnalysisInputError(
|
|
384
|
+
f"有 {len(candidates)} 份 Dataset 都像价格序列({'、'.join(item[0] for item in candidates)}):"
|
|
385
|
+
"用 price_dataset_id 指明用哪一份(基准用 benchmark_dataset_id)"
|
|
386
|
+
)
|
|
387
|
+
if not candidates:
|
|
388
|
+
detail = f"(time_column={time_override} 不在任何 Dataset 里)" if time_override else ""
|
|
389
|
+
raise AnalysisInputError(
|
|
390
|
+
f"没有可识别的价格序列 Dataset{detail}:需要时间列 + close/adj_close/close_price/price/nav 之一"
|
|
391
|
+
)
|
|
392
|
+
price_dataset_id = candidates[0][0]
|
|
393
|
+
price_view = views[price_dataset_id]
|
|
394
|
+
|
|
395
|
+
time_column = _time_column(price_view, time_override)
|
|
396
|
+
price_column = _price_column(price_view, price_override)
|
|
397
|
+
tz = _timezone(_text(params.get("timezone")))
|
|
398
|
+
points, dropped = _series(price_view, price_dataset_id, price_column, time_column, tz)
|
|
399
|
+
|
|
400
|
+
periods_per_year = params.get("periods_per_year", PERIODS_PER_YEAR_DEFAULT)
|
|
401
|
+
if isinstance(periods_per_year, bool) or not isinstance(periods_per_year, int) or not 1 <= periods_per_year <= 366:
|
|
402
|
+
raise AnalysisInputError(f"periods_per_year={periods_per_year!r} 不在 1..366")
|
|
403
|
+
risk_free_rate = params.get("risk_free_rate", 0.0)
|
|
404
|
+
if isinstance(risk_free_rate, bool) or not isinstance(risk_free_rate, (int, float)) or not -1 <= float(risk_free_rate) <= 1:
|
|
405
|
+
raise AnalysisInputError(f"risk_free_rate={risk_free_rate!r} 不在 -1..1")
|
|
406
|
+
risk_free_rate = float(risk_free_rate)
|
|
407
|
+
confidence = params.get("confidence", CONFIDENCE_DEFAULT)
|
|
408
|
+
if isinstance(confidence, bool) or not isinstance(confidence, (int, float)) or not 0.5 <= float(confidence) <= 0.999:
|
|
409
|
+
raise AnalysisInputError(f"confidence={confidence!r} 不在 0.5..0.999")
|
|
410
|
+
confidence = float(confidence)
|
|
411
|
+
|
|
412
|
+
methodology = [
|
|
413
|
+
f"价格 Dataset {price_dataset_id}:时间列 {time_column}、价格列 {price_column}",
|
|
414
|
+
f"按时间升序取 {len(points)} 个正价格观测;跳过 {len(dropped)} 行(时间无法解析或价格非正)",
|
|
415
|
+
]
|
|
416
|
+
limitations = list(LIMITATIONS)
|
|
417
|
+
gaps = []
|
|
418
|
+
|
|
419
|
+
if len(points) < 3:
|
|
420
|
+
gaps.append(f"有效观测不足 3 个(实际 {len(points)}):至少需要 2 个日收益才能计算风险指标")
|
|
421
|
+
if dropped:
|
|
422
|
+
gaps.append(f"跳过 {len(dropped)} 行(时间无法解析或价格非正):{_sample(dropped)}")
|
|
423
|
+
return _result(
|
|
424
|
+
"blocked",
|
|
425
|
+
"价格序列有效观测不足 3 个:无法计算收益与风险。",
|
|
426
|
+
{},
|
|
427
|
+
methodology + ["未计算任何指标:有效价格点不足"],
|
|
428
|
+
limitations,
|
|
429
|
+
gaps,
|
|
430
|
+
[],
|
|
431
|
+
)
|
|
432
|
+
|
|
433
|
+
if dropped:
|
|
434
|
+
gaps.append(
|
|
435
|
+
f"价格列 {price_column} 有 {len(dropped)} 行不是正数或时间无法解析(已跳过):{_sample(dropped)}"
|
|
436
|
+
)
|
|
437
|
+
|
|
438
|
+
metrics, returns = _risk(points, periods_per_year, risk_free_rate, confidence)
|
|
439
|
+
if metrics["returns_count"] < MIN_RETURNS_FOR_STABLE:
|
|
440
|
+
limitations.append(f"只有 {metrics['returns_count']} 个收益观测:年化指标不稳定,只能作方向性参考")
|
|
441
|
+
limitations.append(f"年化因子取 {periods_per_year};换因子会改变年化收益、波动与夏普")
|
|
442
|
+
|
|
443
|
+
benchmark_payload = None
|
|
444
|
+
benchmark_dataset_id = _text(params.get("benchmark_dataset_id"))
|
|
445
|
+
if benchmark_dataset_id is not None:
|
|
446
|
+
if benchmark_dataset_id not in views:
|
|
447
|
+
raise AnalysisInputError(f"benchmark_dataset_id={benchmark_dataset_id} 不在本次快照的 Dataset 里")
|
|
448
|
+
bench_view = views[benchmark_dataset_id]
|
|
449
|
+
bench_time = _time_column(bench_view, None)
|
|
450
|
+
bench_price = _price_column(bench_view, None)
|
|
451
|
+
bench_points, bench_dropped = _series(bench_view, benchmark_dataset_id, bench_price, bench_time, tz)
|
|
452
|
+
bench_day_prices = {point["day"]: point["price"] for point in bench_points}
|
|
453
|
+
benchmark, benchmark_gap = _benchmark(points, bench_day_prices)
|
|
454
|
+
if benchmark_gap is not None:
|
|
455
|
+
gaps.append(benchmark_gap)
|
|
456
|
+
else:
|
|
457
|
+
metrics.update(benchmark)
|
|
458
|
+
benchmark_payload = {
|
|
459
|
+
"dataset_id": benchmark_dataset_id,
|
|
460
|
+
"time_column": bench_time,
|
|
461
|
+
"price_column": bench_price,
|
|
462
|
+
"observations": len(bench_points),
|
|
463
|
+
"skipped_rows": len(bench_dropped),
|
|
464
|
+
**{key: benchmark[key] for key in ("beta", "correlation", "benchmark_overlap", "benchmark_total_return")},
|
|
465
|
+
}
|
|
466
|
+
methodology.append(
|
|
467
|
+
f"基准 {benchmark_dataset_id}:重叠 {benchmark['benchmark_overlap']} 个日收益,"
|
|
468
|
+
f"beta={_ratio(benchmark['beta'])}、corr={_ratio(benchmark['correlation'])}"
|
|
469
|
+
)
|
|
470
|
+
else:
|
|
471
|
+
limitations.append("未提供基准 Dataset:beta 与相关未计算")
|
|
472
|
+
|
|
473
|
+
status = "partial" if gaps else "completed"
|
|
474
|
+
methodology.append(
|
|
475
|
+
f"计算 {len([key for key in metrics if isinstance(metrics[key], (int, float))])} 项数值指标;{len(gaps)} 项缺口"
|
|
476
|
+
)
|
|
477
|
+
|
|
478
|
+
start_day, end_day = points[0]["day"], points[-1]["day"]
|
|
479
|
+
payload = {
|
|
480
|
+
"protocol": "capital.analysis/v1",
|
|
481
|
+
"module_id": MODULE_ID,
|
|
482
|
+
"module_version": MODULE_VERSION,
|
|
483
|
+
"analysis_id": request.get("analysis_id"),
|
|
484
|
+
"module_run_id": request.get("module_run_id"),
|
|
485
|
+
"price_dataset_id": price_dataset_id,
|
|
486
|
+
"time_column": time_column,
|
|
487
|
+
"price_column": price_column,
|
|
488
|
+
"parameters": {
|
|
489
|
+
"periods_per_year": periods_per_year,
|
|
490
|
+
"risk_free_rate": risk_free_rate,
|
|
491
|
+
"confidence": confidence,
|
|
492
|
+
},
|
|
493
|
+
"window": {"start": start_day, "end": end_day, "observations": len(points)},
|
|
494
|
+
"metrics": metrics,
|
|
495
|
+
"benchmark": benchmark_payload,
|
|
496
|
+
"series": [
|
|
497
|
+
{
|
|
498
|
+
"date": point["day"],
|
|
499
|
+
"close": point["price"],
|
|
500
|
+
**({"return": _round(returns[index - 1])} if index > 0 else {}),
|
|
501
|
+
}
|
|
502
|
+
for index, point in enumerate(points)
|
|
503
|
+
],
|
|
504
|
+
"data_gaps": gaps,
|
|
505
|
+
}
|
|
506
|
+
ref = context.write_output(OUTPUT_NAME, payload)
|
|
507
|
+
context.log(f"{MODULE_ID}: {status} observations={len(points)} metrics={len(metrics)} gaps={len(gaps)}")
|
|
508
|
+
|
|
509
|
+
return _result(
|
|
510
|
+
status,
|
|
511
|
+
_summary(metrics, start_day, end_day, gaps),
|
|
512
|
+
metrics,
|
|
513
|
+
methodology,
|
|
514
|
+
limitations,
|
|
515
|
+
gaps,
|
|
516
|
+
[{"name": OUTPUT_NAME, "ref": ref}],
|
|
517
|
+
)
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 v587d
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "scenario_sensitivity",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"entrypoint": "module.py",
|
|
5
|
+
"runtime": "python",
|
|
6
|
+
"description": "假设网格与情景对比:按调用方给出的显式恒等式(乘积 / 加权和)计算目标值在不同因子假设下的取值,含基准、情景表与格点表(纯算术,不预测、不评级)",
|
|
7
|
+
"roles": ["senior_analyst"],
|
|
8
|
+
"capabilities": [],
|
|
9
|
+
"required_fields": [],
|
|
10
|
+
"input_schema": {
|
|
11
|
+
"type": "object",
|
|
12
|
+
"properties": {
|
|
13
|
+
"target_name": { "type": "string", "maxLength": 64, "description": "目标名称,如 net_profit / roe / fcf" },
|
|
14
|
+
"target_unit": { "type": "string", "maxLength": 32, "description": "目标单位,如 CNY / ratio;省略不填" },
|
|
15
|
+
"model": { "type": "string", "enum": ["product", "sum"], "description": "product = Π factor^exponent;sum = Σ factor×exponent(默认 product)" },
|
|
16
|
+
"factors": {
|
|
17
|
+
"type": "array",
|
|
18
|
+
"maxItems": 4,
|
|
19
|
+
"items": {
|
|
20
|
+
"type": "object",
|
|
21
|
+
"properties": {
|
|
22
|
+
"name": { "type": "string", "maxLength": 64 },
|
|
23
|
+
"base": { "type": "number", "description": "因子基准值;必须是同一口径、同一期的数" },
|
|
24
|
+
"unit": { "type": "string", "maxLength": 32 },
|
|
25
|
+
"exponent": { "type": "number", "description": "product 模型为幂次(可为负,如 1/权益 用 -1);sum 模型为权重;默认 1" }
|
|
26
|
+
},
|
|
27
|
+
"required": ["name", "base"],
|
|
28
|
+
"additionalProperties": false
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"grid": {
|
|
32
|
+
"type": "array",
|
|
33
|
+
"maxItems": 4,
|
|
34
|
+
"items": {
|
|
35
|
+
"type": "object",
|
|
36
|
+
"properties": {
|
|
37
|
+
"factor": { "type": "string", "maxLength": 64 },
|
|
38
|
+
"values": { "type": "array", "maxItems": 32, "items": { "type": "number" } }
|
|
39
|
+
},
|
|
40
|
+
"required": ["factor", "values"],
|
|
41
|
+
"additionalProperties": false
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"grid_mode": { "type": "string", "enum": ["oat", "full"], "description": "oat = 单因子扫描(其余因子取基准);full = 网格因子的笛卡尔积;默认 oat" },
|
|
45
|
+
"scenarios": {
|
|
46
|
+
"type": "array",
|
|
47
|
+
"maxItems": 12,
|
|
48
|
+
"items": {
|
|
49
|
+
"type": "object",
|
|
50
|
+
"properties": {
|
|
51
|
+
"name": { "type": "string", "maxLength": 64 },
|
|
52
|
+
"values": {
|
|
53
|
+
"type": "object",
|
|
54
|
+
"description": "该情景下被改写的因子值;未给出的因子继承基准"
|
|
55
|
+
}
|
|
56
|
+
},
|
|
57
|
+
"required": ["name", "values"],
|
|
58
|
+
"additionalProperties": false
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
},
|
|
62
|
+
"required": ["target_name", "factors"],
|
|
63
|
+
"additionalProperties": false
|
|
64
|
+
},
|
|
65
|
+
"output_schema": {
|
|
66
|
+
"type": "object",
|
|
67
|
+
"properties": {
|
|
68
|
+
"status": { "type": "string", "enum": ["completed", "partial", "blocked", "failed"] },
|
|
69
|
+
"summary": { "type": "string" },
|
|
70
|
+
"metrics": { "type": "object" },
|
|
71
|
+
"claims": { "type": "array" },
|
|
72
|
+
"assumptions": { "type": "array" },
|
|
73
|
+
"methodology_log": { "type": "array" },
|
|
74
|
+
"sensitivity": { "type": "object" },
|
|
75
|
+
"limitations": { "type": "array" },
|
|
76
|
+
"data_gaps": { "type": "array" },
|
|
77
|
+
"outputs": { "type": "array" }
|
|
78
|
+
},
|
|
79
|
+
"required": [
|
|
80
|
+
"status", "summary", "metrics", "claims", "assumptions", "methodology_log",
|
|
81
|
+
"sensitivity", "limitations", "data_gaps", "outputs"
|
|
82
|
+
],
|
|
83
|
+
"additionalProperties": false
|
|
84
|
+
},
|
|
85
|
+
"assumptions": [
|
|
86
|
+
"目标是显式算术恒等式:product 模型 target = Π factor^exponent;sum 模型 target = Σ factor×exponent",
|
|
87
|
+
"因子基准值由调用方给出,本模块不判断其来源、口径或是否来自同一期",
|
|
88
|
+
"情景值由调用方给出;未在情景里出现的因子继承基准,并在 trace 里标 inherited",
|
|
89
|
+
"网格是单因子扫描(oat)或网格因子笛卡尔积(full),不做随机采样、不插值",
|
|
90
|
+
"输出只是同一恒等式在不同假设下的取值,不是预测、不是概率,也不构成收益承诺",
|
|
91
|
+
"product 模型下负基准值只允许整数指数;零基准值不允许负指数"
|
|
92
|
+
],
|
|
93
|
+
"applicability": [
|
|
94
|
+
"目标可由 1–4 个因子按 product / sum 恒等式表达(如净利润 = 营收 × 净利率、ROE = 净利润 × 权益^-1)",
|
|
95
|
+
"因子基准值应来自同一口径、同一期;跨期或跨币种混用不在本模块校验",
|
|
96
|
+
"需要概率分布、反馈回路或非线性模型时,本模块不适用"
|
|
97
|
+
],
|
|
98
|
+
"limits": {
|
|
99
|
+
"timeout_ms": 15000,
|
|
100
|
+
"max_input_rows": 200000,
|
|
101
|
+
"max_output_bytes": 1048576,
|
|
102
|
+
"max_log_bytes": 65536
|
|
103
|
+
},
|
|
104
|
+
"provenance": { "source_type": "original", "license": "MIT" }
|
|
105
|
+
}
|