@v587d/capital-generation 2.31.3 → 2.31.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +74 -0
- package/README.md +46 -8
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/package.json +1 -1
- package/lib/analysis/registry.js +6 -1
- package/lib/collector-runtime.js +8 -0
- package/lib/data-collector/catalog-taxonomy.js +11 -0
- package/lib/sources/eastmoney-http.js +274 -0
- package/lib/sources/sec-http.d.ts +9 -0
- package/lib/sources/sec-http.js +643 -0
- package/lib/sources/us-official-http.d.ts +4 -0
- package/lib/sources/us-official-http.js +654 -0
- package/lib/time/tools.js +6 -0
- 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/plugin-page/README.en.md +7 -0
- package/plugin-page/README.zh.md +7 -0
- package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +47 -37
- package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +4 -2
- package/python/analysis/modules/comps_valuation/LICENSE +21 -0
- package/python/analysis/modules/comps_valuation/module.json +61 -0
- package/python/analysis/modules/comps_valuation/module.py +360 -0
- package/python/analysis/modules/earnings_bridge/LICENSE +21 -0
- package/python/analysis/modules/earnings_bridge/module.json +58 -0
- package/python/analysis/modules/earnings_bridge/module.py +452 -0
- package/python/analysis/modules/kline_quality/LICENSE +21 -0
- package/python/analysis/modules/kline_quality/module.json +61 -0
- package/python/analysis/modules/kline_quality/module.py +538 -0
- package/python/analysis/modules/portfolio_stress/LICENSE +21 -0
- package/python/analysis/modules/portfolio_stress/module.json +89 -0
- package/python/analysis/modules/portfolio_stress/module.py +537 -0
- package/python/analysis/modules/simple_backtest/LICENSE +21 -0
- package/python/analysis/modules/simple_backtest/module.json +66 -0
- package/python/analysis/modules/simple_backtest/module.py +648 -0
- package/python/analysis/modules/statement_integrity/LICENSE +21 -0
- package/python/analysis/modules/statement_integrity/module.json +62 -0
- package/python/analysis/modules/statement_integrity/module.py +621 -0
- package/python/analysis/modules/technical_indicators/LICENSE +21 -0
- package/python/analysis/modules/technical_indicators/module.json +170 -0
- package/python/analysis/modules/technical_indicators/module.py +854 -0
- package/python/analysis/modules/valuation_sensitivity/LICENSE +21 -0
- package/python/analysis/modules/valuation_sensitivity/module.json +73 -0
- package/python/analysis/modules/valuation_sensitivity/module.py +589 -0
- package/watchlist/package.json +1 -1
|
@@ -0,0 +1,537 @@
|
|
|
1
|
+
"""Portfolio stress: replay one weighted portfolio through explicit historical windows.
|
|
2
|
+
|
|
3
|
+
Each position is one price-series Dataset; each window is the caller's already-happened interval.
|
|
4
|
+
The module only measures what those windows already did to that static weighting — window return is
|
|
5
|
+
first/last usable close inside the window, portfolio return is the weighted sum, concentration is
|
|
6
|
+
weight-only HHI/max weight. Missing coverage is a stated gap, never a borrowed date and never a
|
|
7
|
+
weight renormalization; no forecasting, no stress scenarios, no rating.
|
|
8
|
+
|
|
9
|
+
Pure standard library on purpose (no numpy/pandas): the arithmetic stays auditable line by line on
|
|
10
|
+
the minimal analysis runtime. Protocol: `docs/dev/senior-analysis.md` §1.9; conclusions and claims
|
|
11
|
+
belong to the senior analyst.
|
|
12
|
+
"""
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
import math
|
|
16
|
+
import re
|
|
17
|
+
from datetime import datetime, timezone
|
|
18
|
+
|
|
19
|
+
MODULE_ID = "portfolio_stress"
|
|
20
|
+
MODULE_VERSION = "1.0.0"
|
|
21
|
+
OUTPUT_NAME = "portfolio_stress"
|
|
22
|
+
|
|
23
|
+
MAX_POSITIONS = 30
|
|
24
|
+
MAX_WINDOWS = 12
|
|
25
|
+
WEIGHT_TOLERANCE = 1e-6
|
|
26
|
+
|
|
27
|
+
ASSUMPTIONS = [
|
|
28
|
+
"权重是调用方给的静态组合权重:回放期间不再平衡,也不考虑现金流出入、分红与税费",
|
|
29
|
+
"组合窗口收益 = Σ 权重 × 该持仓窗口收益;持仓收益按窗口内首个与最后一个可用收盘价计算",
|
|
30
|
+
"窗口是已发生的历史区间:start 必须早于 end,且两端的交易日必须落在价格序列覆盖范围内;越界写缺口,不向前/向后找替代日期",
|
|
31
|
+
"集中度只用调用方权重计算(HHI = Σ w²、最大单持仓权重),与价格数据无关",
|
|
32
|
+
"历史情景回放只说明这些窗口里组合会怎样;不是压力测试的假设情景,不预测、不评级,也不给仓位建议",
|
|
33
|
+
]
|
|
34
|
+
|
|
35
|
+
LIMITATIONS = [
|
|
36
|
+
"历史窗口回放只说明这些窗口里组合会怎样:不预测未来,也不是假设情景压力测试",
|
|
37
|
+
"权重是调用方给的静态权重:回放期间不再平衡,不含现金流出入、分红再投资与交易成本",
|
|
38
|
+
"窗口越界或窗口内可用价格不足时写缺口,不向前/向后借日期;组合收益不按剩余权重重归一化",
|
|
39
|
+
"每个持仓的价格口径沿用该 Dataset 的取数参数(qfq / hfq / none),本模块不检测也不做复权调整",
|
|
40
|
+
"数值时间轴按参数 timezone 标注日历日(省略按 UTC);跨市场比较前先对齐时区",
|
|
41
|
+
"不构成投资建议,也不产生评级、目标价或收益承诺",
|
|
42
|
+
]
|
|
43
|
+
|
|
44
|
+
PRICE_COLUMNS = ("close", "adj_close", "close_price", "price", "nav")
|
|
45
|
+
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
|
+
DAY = re.compile(r"^\d{4}-\d{2}-\d{2}$")
|
|
48
|
+
|
|
49
|
+
|
|
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
|
+
def _day(value, label):
|
|
92
|
+
if not isinstance(value, str) or DAY.match(value.strip()) is None:
|
|
93
|
+
raise AnalysisInputError(f"{label} 必须是 YYYY-MM-DD 日期,实际是 {value!r}")
|
|
94
|
+
text = value.strip()
|
|
95
|
+
try:
|
|
96
|
+
datetime.strptime(text, "%Y-%m-%d")
|
|
97
|
+
except ValueError as error:
|
|
98
|
+
raise AnalysisInputError(f"{label} 不是合法日期:{value!r}") from error
|
|
99
|
+
return text
|
|
100
|
+
|
|
101
|
+
|
|
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
|
+
def _time_column(view, dataset_id, override):
|
|
136
|
+
names = _columns_of(view)
|
|
137
|
+
if override is not None:
|
|
138
|
+
if override not in names:
|
|
139
|
+
raise AnalysisInputError(
|
|
140
|
+
f"Dataset {dataset_id} 的 time_column={override} 不在列里:可选 {sorted(names)}"
|
|
141
|
+
)
|
|
142
|
+
return override
|
|
143
|
+
axis = (view.get("time_axis") or {}).get("column")
|
|
144
|
+
if isinstance(axis, str) and axis in names:
|
|
145
|
+
return axis
|
|
146
|
+
for name in TIME_COLUMNS:
|
|
147
|
+
if name in names:
|
|
148
|
+
return name
|
|
149
|
+
raise AnalysisInputError(
|
|
150
|
+
f"Dataset {dataset_id} 找不到时间列:需要 time_coverage 列,或 trade_date_ms / date_ms / "
|
|
151
|
+
"period_end_ms / datetime / date / trade_date 之一(或用 time_column 指明)"
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
def _price_column(view, dataset_id, override):
|
|
156
|
+
names = _columns_of(view)
|
|
157
|
+
if override is not None:
|
|
158
|
+
if override not in names:
|
|
159
|
+
raise AnalysisInputError(
|
|
160
|
+
f"Dataset {dataset_id} 的 price_column={override} 不在列里:可选 {sorted(names)}"
|
|
161
|
+
)
|
|
162
|
+
return override
|
|
163
|
+
for name in PRICE_COLUMNS:
|
|
164
|
+
if name in names:
|
|
165
|
+
return name
|
|
166
|
+
raise AnalysisInputError(
|
|
167
|
+
f"Dataset {dataset_id} 找不到价格列:需要 close / adj_close / close_price / price / nav 之一"
|
|
168
|
+
"(或用 price_column 指明)"
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
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
|
+
def _series(view, dataset_id, time_column, price_column, tz):
|
|
199
|
+
"""Time-ordered usable closes; bad rows are dropped and reported, ambiguity is an input error."""
|
|
200
|
+
rows = view.get("rows") or []
|
|
201
|
+
if not rows:
|
|
202
|
+
raise AnalysisInputError(f"Dataset {dataset_id} 没有数据行:无法回放任何窗口")
|
|
203
|
+
points, dropped, kind = [], [], None
|
|
204
|
+
for row in rows:
|
|
205
|
+
if not isinstance(row, dict):
|
|
206
|
+
raise AnalysisInputError(f"Dataset {dataset_id} 的数据行不是对象:无法回放")
|
|
207
|
+
raw_time = row.get(time_column)
|
|
208
|
+
if isinstance(raw_time, bool) or not isinstance(raw_time, (int, float, str)):
|
|
209
|
+
row_kind = None
|
|
210
|
+
else:
|
|
211
|
+
row_kind = "ms" if isinstance(raw_time, (int, float)) else "date"
|
|
212
|
+
if row_kind is not None:
|
|
213
|
+
if kind is None:
|
|
214
|
+
kind = row_kind
|
|
215
|
+
elif row_kind != kind:
|
|
216
|
+
raise AnalysisInputError(
|
|
217
|
+
f"Dataset {dataset_id} 的 {time_column} 列混用了数值时间戳与日期字符串:"
|
|
218
|
+
"无法排序,请取数时统一"
|
|
219
|
+
)
|
|
220
|
+
parsed = _parse_time(raw_time, tz)
|
|
221
|
+
price = _number(row, price_column)
|
|
222
|
+
if parsed is None or price is None or price <= 0:
|
|
223
|
+
dropped.append(raw_time)
|
|
224
|
+
continue
|
|
225
|
+
key, day = parsed
|
|
226
|
+
points.append({"key": key, "day": day, "price": price})
|
|
227
|
+
points.sort(key=lambda item: item["key"])
|
|
228
|
+
seen = set()
|
|
229
|
+
for point in points:
|
|
230
|
+
if point["day"] in seen:
|
|
231
|
+
raise AnalysisInputError(
|
|
232
|
+
f"Dataset {dataset_id} 在 {point['day']} 出现多行:无法判断用哪一行(请先去重)"
|
|
233
|
+
)
|
|
234
|
+
seen.add(point["day"])
|
|
235
|
+
return points, dropped
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def _positions(params):
|
|
239
|
+
raw = params.get("positions")
|
|
240
|
+
if not isinstance(raw, list) or not raw:
|
|
241
|
+
raise AnalysisInputError("positions 必须是非空数组:至少给出一个持仓(dataset_id + weight)")
|
|
242
|
+
if len(raw) > MAX_POSITIONS:
|
|
243
|
+
raise AnalysisInputError(f"positions 最多 {MAX_POSITIONS} 个,实际 {len(raw)} 个")
|
|
244
|
+
positions, seen = [], set()
|
|
245
|
+
for index, item in enumerate(raw):
|
|
246
|
+
if not isinstance(item, dict):
|
|
247
|
+
raise AnalysisInputError(f"positions[{index}] 必须是对象(dataset_id + weight)")
|
|
248
|
+
dataset_id = _text(item.get("dataset_id"), f"positions[{index}].dataset_id", required=True)
|
|
249
|
+
if dataset_id in seen:
|
|
250
|
+
raise AnalysisInputError(f"持仓数据集 {dataset_id} 出现了多次:同一数据集只能作为一个持仓")
|
|
251
|
+
seen.add(dataset_id)
|
|
252
|
+
weight = _finite_number(item.get("weight"), f"positions[{index}].weight")
|
|
253
|
+
if weight < 0:
|
|
254
|
+
raise AnalysisInputError(f"positions[{index}].weight 不能为负,实际是 {weight:g}")
|
|
255
|
+
positions.append({"dataset_id": dataset_id, "weight": weight})
|
|
256
|
+
total = math.fsum(position["weight"] for position in positions)
|
|
257
|
+
if abs(total - 1.0) > WEIGHT_TOLERANCE:
|
|
258
|
+
raise AnalysisInputError(f"持仓权重合计必须为 1(容差 1e-6),实际 {total:.6f}")
|
|
259
|
+
return positions
|
|
260
|
+
|
|
261
|
+
|
|
262
|
+
def _windows(params):
|
|
263
|
+
raw = params.get("windows")
|
|
264
|
+
if not isinstance(raw, list) or not raw:
|
|
265
|
+
raise AnalysisInputError("windows 必须是非空数组:至少给出一个历史窗口")
|
|
266
|
+
if len(raw) > MAX_WINDOWS:
|
|
267
|
+
raise AnalysisInputError(f"windows 最多 {MAX_WINDOWS} 个,实际 {len(raw)} 个")
|
|
268
|
+
windows = []
|
|
269
|
+
for index, item in enumerate(raw):
|
|
270
|
+
if not isinstance(item, dict):
|
|
271
|
+
raise AnalysisInputError(f"windows[{index}] 必须是对象(name + start + end)")
|
|
272
|
+
name = _text(item.get("name"), f"windows[{index}].name", required=True)
|
|
273
|
+
start = _day(item.get("start"), f"windows[{index}].start")
|
|
274
|
+
end = _day(item.get("end"), f"windows[{index}].end")
|
|
275
|
+
if start >= end:
|
|
276
|
+
raise AnalysisInputError(f"windows[{index}] 的 start({start})必须早于 end({end})")
|
|
277
|
+
windows.append({"name": name, "start": start, "end": end})
|
|
278
|
+
return windows
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def _views(request, context, positions):
|
|
282
|
+
items = (request.get("inputs") or {}).get("datasets") or []
|
|
283
|
+
declared = set()
|
|
284
|
+
for item in items:
|
|
285
|
+
dataset_id = (item or {}).get("dataset_id")
|
|
286
|
+
if isinstance(dataset_id, str) and dataset_id:
|
|
287
|
+
declared.add(dataset_id)
|
|
288
|
+
views = {}
|
|
289
|
+
for position in positions:
|
|
290
|
+
dataset_id = position["dataset_id"]
|
|
291
|
+
if dataset_id not in declared:
|
|
292
|
+
raise AnalysisInputError(
|
|
293
|
+
f"持仓数据集 {dataset_id} 不在本次快照的 Dataset 里:先用 dataset_refs 把它加进快照"
|
|
294
|
+
)
|
|
295
|
+
view = context.read_dataset(dataset_id)
|
|
296
|
+
if view.get("shape") != "rows":
|
|
297
|
+
raise AnalysisInputError(
|
|
298
|
+
f"Dataset {dataset_id} 是 {view.get('shape')} 型:portfolio_stress 只回放价格序列表格,"
|
|
299
|
+
"文档型输入请先走 profile 或证据"
|
|
300
|
+
)
|
|
301
|
+
views[dataset_id] = view
|
|
302
|
+
return views
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
def _evaluate_window(window, positions, series_by_id):
|
|
306
|
+
"""Per-position window rows; `None` portfolio return when any position's window is unmeasurable."""
|
|
307
|
+
rows, reasons, weighted = [], [], []
|
|
308
|
+
for position in positions:
|
|
309
|
+
dataset_id = position["dataset_id"]
|
|
310
|
+
points = series_by_id[dataset_id]["points"]
|
|
311
|
+
entry = {
|
|
312
|
+
"dataset_id": dataset_id,
|
|
313
|
+
"weight": position["weight"],
|
|
314
|
+
"status": "missing",
|
|
315
|
+
"first_date": None,
|
|
316
|
+
"first_price": None,
|
|
317
|
+
"last_date": None,
|
|
318
|
+
"last_price": None,
|
|
319
|
+
"return": None,
|
|
320
|
+
"contribution": None,
|
|
321
|
+
}
|
|
322
|
+
reason = None
|
|
323
|
+
if not points:
|
|
324
|
+
reason = f"{dataset_id} 没有可用价格"
|
|
325
|
+
elif window["start"] < points[0]["day"]:
|
|
326
|
+
reason = f"{dataset_id} 起点 {window['start']} 早于序列覆盖(首日 {points[0]['day']})"
|
|
327
|
+
elif window["end"] > points[-1]["day"]:
|
|
328
|
+
reason = f"{dataset_id} 终点 {window['end']} 晚于序列覆盖(末日 {points[-1]['day']})"
|
|
329
|
+
else:
|
|
330
|
+
inside = [point for point in points if window["start"] <= point["day"] <= window["end"]]
|
|
331
|
+
if len(inside) < 2:
|
|
332
|
+
reason = f"{dataset_id} 窗口内只有 {len(inside)} 个可用价格(至少 2 个才能算收益)"
|
|
333
|
+
else:
|
|
334
|
+
first, last = inside[0], inside[-1]
|
|
335
|
+
exact = last["price"] / first["price"] - 1.0
|
|
336
|
+
if not math.isfinite(exact):
|
|
337
|
+
reason = f"{dataset_id} 的区间收益不是有限数:检查价格量级"
|
|
338
|
+
else:
|
|
339
|
+
entry.update({
|
|
340
|
+
"status": "computed",
|
|
341
|
+
"first_date": first["day"],
|
|
342
|
+
"first_price": first["price"],
|
|
343
|
+
"last_date": last["day"],
|
|
344
|
+
"last_price": last["price"],
|
|
345
|
+
"return": _round(exact),
|
|
346
|
+
"contribution": _round(position["weight"] * exact),
|
|
347
|
+
})
|
|
348
|
+
weighted.append(position["weight"] * exact)
|
|
349
|
+
if reason is not None:
|
|
350
|
+
reasons.append(reason)
|
|
351
|
+
rows.append(entry)
|
|
352
|
+
if reasons:
|
|
353
|
+
return rows, reasons, None, None
|
|
354
|
+
portfolio_return = _round(math.fsum(weighted))
|
|
355
|
+
return rows, reasons, portfolio_return, portfolio_return
|
|
356
|
+
|
|
357
|
+
|
|
358
|
+
def _sample(values):
|
|
359
|
+
"""First few raw time values in a gap message; enough to locate the bad rows, not a data dump."""
|
|
360
|
+
shown = "、".join("<缺失>" if value is None else str(value) for value in values[:5])
|
|
361
|
+
return shown if len(values) <= 5 else f"{shown} 等 {len(values)} 行"
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
def _summary(positions, windows, metrics, gaps):
|
|
365
|
+
computed = [window for window in windows if window["portfolio_return"] is not None]
|
|
366
|
+
parts = [
|
|
367
|
+
"历史窗口回放(不是假设情景、不预测未来)",
|
|
368
|
+
f"{len(positions)} 个持仓 / {len(windows)} 个窗口",
|
|
369
|
+
f"权重最大 {_pct(metrics['max_weight'])}(HHI {_ratio(metrics['hhi'])})",
|
|
370
|
+
]
|
|
371
|
+
if computed:
|
|
372
|
+
parts.append("窗口收益:" + "、".join(
|
|
373
|
+
f"{window['name']} {_pct(window['portfolio_return'])}" for window in computed
|
|
374
|
+
))
|
|
375
|
+
parts.append(f"最差窗口 {_pct(metrics['worst_window_return'])}、最好窗口 {_pct(metrics['best_window_return'])}")
|
|
376
|
+
else:
|
|
377
|
+
parts.append("所有窗口都没有可回放的区间收益")
|
|
378
|
+
missing = len(windows) - len(computed)
|
|
379
|
+
if computed and missing:
|
|
380
|
+
parts.append(f"{missing} 个窗口没有可回放的区间收益")
|
|
381
|
+
if gaps:
|
|
382
|
+
parts.append(f"{len(gaps)} 项缺口(见 data_gaps)")
|
|
383
|
+
return ";".join(parts) + "。"
|
|
384
|
+
|
|
385
|
+
|
|
386
|
+
def _result(status, summary, metrics, methodology, limitations, gaps, outputs):
|
|
387
|
+
return {
|
|
388
|
+
"status": status,
|
|
389
|
+
"summary": summary,
|
|
390
|
+
"metrics": metrics,
|
|
391
|
+
"claims": [],
|
|
392
|
+
"assumptions": list(ASSUMPTIONS),
|
|
393
|
+
"methodology_log": methodology,
|
|
394
|
+
"sensitivity": {},
|
|
395
|
+
"limitations": limitations,
|
|
396
|
+
"data_gaps": gaps,
|
|
397
|
+
"outputs": outputs,
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
|
|
401
|
+
def analyze(request: dict, context) -> dict:
|
|
402
|
+
params = request.get("params") or {}
|
|
403
|
+
positions = _positions(params)
|
|
404
|
+
windows = _windows(params)
|
|
405
|
+
price_override = _text(params.get("price_column"), "price_column")
|
|
406
|
+
time_override = _text(params.get("time_column"), "time_column")
|
|
407
|
+
tz_name = _text(params.get("timezone"), "timezone")
|
|
408
|
+
tz = _timezone(tz_name)
|
|
409
|
+
|
|
410
|
+
views = _views(request, context, positions)
|
|
411
|
+
series_by_id, dataset_rows = {}, []
|
|
412
|
+
gaps = []
|
|
413
|
+
limitations = list(LIMITATIONS)
|
|
414
|
+
methodology = [
|
|
415
|
+
f"持仓 {len(positions)} 个、窗口 {len(windows)} 个;权重合计 {_fmt6(math.fsum(p['weight'] for p in positions))}"
|
|
416
|
+
"(容差 1e-6)",
|
|
417
|
+
]
|
|
418
|
+
for position in positions:
|
|
419
|
+
dataset_id = position["dataset_id"]
|
|
420
|
+
view = views[dataset_id]
|
|
421
|
+
if view.get("truncated"):
|
|
422
|
+
limitations.append(f"Dataset {dataset_id} 超过 max_input_rows:回放只用到前 {len(view.get('rows') or [])} 行")
|
|
423
|
+
time_column = _time_column(view, dataset_id, time_override)
|
|
424
|
+
price_column = _price_column(view, dataset_id, price_override)
|
|
425
|
+
points, dropped = _series(view, dataset_id, time_column, price_column, tz)
|
|
426
|
+
series_by_id[dataset_id] = {"points": points}
|
|
427
|
+
if dropped:
|
|
428
|
+
gaps.append(
|
|
429
|
+
f"Dataset {dataset_id}:跳过 {len(dropped)} 行(时间无法解析、价格缺失或非正):{_sample(dropped)}"
|
|
430
|
+
)
|
|
431
|
+
coverage = None
|
|
432
|
+
if points:
|
|
433
|
+
coverage = {
|
|
434
|
+
"first_date": points[0]["day"],
|
|
435
|
+
"first_price": points[0]["price"],
|
|
436
|
+
"last_date": points[-1]["day"],
|
|
437
|
+
"last_price": points[-1]["price"],
|
|
438
|
+
}
|
|
439
|
+
dataset_rows.append({
|
|
440
|
+
"dataset_id": dataset_id,
|
|
441
|
+
"weight": position["weight"],
|
|
442
|
+
"time_column": time_column,
|
|
443
|
+
"price_column": price_column,
|
|
444
|
+
"observations": len(points),
|
|
445
|
+
"skipped_rows": len(dropped),
|
|
446
|
+
"coverage": coverage,
|
|
447
|
+
})
|
|
448
|
+
span = "(没有可用价格)" if coverage is None else f"({coverage['first_date']}..{coverage['last_date']})"
|
|
449
|
+
methodology.append(
|
|
450
|
+
f"Dataset {dataset_id}:时间列 {time_column}、价格列 {price_column},"
|
|
451
|
+
f"有效价格 {len(points)} 个{span},跳过 {len(dropped)} 行"
|
|
452
|
+
)
|
|
453
|
+
|
|
454
|
+
window_rows = []
|
|
455
|
+
for window in windows:
|
|
456
|
+
rows, reasons, portfolio_return, contribution_sum = _evaluate_window(window, positions, series_by_id)
|
|
457
|
+
prefix = f"窗口 {window['name']}({window['start']}..{window['end']})"
|
|
458
|
+
for reason in reasons:
|
|
459
|
+
gaps.append(f"{prefix}:{reason}")
|
|
460
|
+
if reasons:
|
|
461
|
+
gaps.append(
|
|
462
|
+
f"{prefix}:{len(reasons)}/{len(positions)} 个持仓缺区间收益,"
|
|
463
|
+
"组合收益未计算(不按剩余权重重归一化)"
|
|
464
|
+
)
|
|
465
|
+
window_rows.append({
|
|
466
|
+
"name": window["name"],
|
|
467
|
+
"start": window["start"],
|
|
468
|
+
"end": window["end"],
|
|
469
|
+
"status": "computed" if portfolio_return is not None else "missing",
|
|
470
|
+
"portfolio_return": portfolio_return,
|
|
471
|
+
"contribution_sum": contribution_sum,
|
|
472
|
+
"positions": rows,
|
|
473
|
+
})
|
|
474
|
+
|
|
475
|
+
weights = [position["weight"] for position in positions]
|
|
476
|
+
metrics = {
|
|
477
|
+
"positions_count": len(positions),
|
|
478
|
+
"windows_count": len(windows),
|
|
479
|
+
"hhi": _round(math.fsum(weight * weight for weight in weights)),
|
|
480
|
+
"max_weight": _round(max(weights)),
|
|
481
|
+
}
|
|
482
|
+
computed_returns = [
|
|
483
|
+
window["portfolio_return"] for window in window_rows if window["portfolio_return"] is not None
|
|
484
|
+
]
|
|
485
|
+
for index, window in enumerate(window_rows):
|
|
486
|
+
if window["portfolio_return"] is not None:
|
|
487
|
+
metrics[f"window_{index + 1}_return"] = window["portfolio_return"]
|
|
488
|
+
if computed_returns:
|
|
489
|
+
metrics["worst_window_return"] = min(computed_returns)
|
|
490
|
+
metrics["best_window_return"] = max(computed_returns)
|
|
491
|
+
|
|
492
|
+
if not computed_returns:
|
|
493
|
+
status = "blocked"
|
|
494
|
+
elif gaps:
|
|
495
|
+
status = "partial"
|
|
496
|
+
else:
|
|
497
|
+
status = "completed"
|
|
498
|
+
|
|
499
|
+
methodology.extend([
|
|
500
|
+
"逐窗口取窗口内首个与最后一个可用收盘价:ret = last / first − 1;同一 bar 不能同时当起点和终点",
|
|
501
|
+
"组合收益 = Σ 权重 × 持仓窗口收益(逐窗口加权和);贡献 = 权重 × 持仓窗口收益;不做重归一化",
|
|
502
|
+
f"集中度只用权重:HHI = Σ w² = {_fmt6(metrics['hhi'])}、max_weight = {_pct(metrics['max_weight'])}",
|
|
503
|
+
f"{len(computed_returns)}/{len(window_rows)} 个窗口算出组合收益;{len(gaps)} 项缺口",
|
|
504
|
+
])
|
|
505
|
+
|
|
506
|
+
summary = _summary(positions, window_rows, metrics, gaps)
|
|
507
|
+
if status == "blocked":
|
|
508
|
+
context.log(f"{MODULE_ID}: blocked windows={len(windows)} gaps={len(gaps)}")
|
|
509
|
+
return _result(status, summary, metrics, methodology, limitations, gaps, [])
|
|
510
|
+
|
|
511
|
+
payload = {
|
|
512
|
+
"protocol": "capital.analysis/v1",
|
|
513
|
+
"module_id": MODULE_ID,
|
|
514
|
+
"module_version": MODULE_VERSION,
|
|
515
|
+
"analysis_id": request.get("analysis_id"),
|
|
516
|
+
"module_run_id": request.get("module_run_id"),
|
|
517
|
+
"parameters": {
|
|
518
|
+
"price_column": price_override,
|
|
519
|
+
"time_column": time_override,
|
|
520
|
+
"timezone": tz_name,
|
|
521
|
+
},
|
|
522
|
+
"method": {
|
|
523
|
+
"window_return": "last_price / first_price − 1(窗口内首个与最后一个可用收盘)",
|
|
524
|
+
"portfolio_return": "Σ weight × window_return(全部持仓都算出时才计算,不按剩余权重重归一化)",
|
|
525
|
+
"contribution": "weight × window_return",
|
|
526
|
+
"hhi": "Σ weight²",
|
|
527
|
+
"max_weight": "max(weight)",
|
|
528
|
+
},
|
|
529
|
+
"positions": dataset_rows,
|
|
530
|
+
"windows": window_rows,
|
|
531
|
+
"metrics": metrics,
|
|
532
|
+
"concentration": {"hhi": metrics["hhi"], "max_weight": metrics["max_weight"]},
|
|
533
|
+
"data_gaps": gaps,
|
|
534
|
+
}
|
|
535
|
+
ref = context.write_output(OUTPUT_NAME, payload)
|
|
536
|
+
context.log(f"{MODULE_ID}: {status} windows={len(windows)} computed={len(computed_returns)} gaps={len(gaps)}")
|
|
537
|
+
return _result(status, summary, metrics, methodology, limitations, gaps, [{"name": OUTPUT_NAME, "ref": ref}])
|
|
@@ -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,66 @@
|
|
|
1
|
+
{
|
|
2
|
+
"id": "simple_backtest",
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"entrypoint": "module.py",
|
|
5
|
+
"runtime": "python",
|
|
6
|
+
"description": "单标的均线规则的历史回测:按下一根收盘执行、默认含手续费,输出净值曲线、交易记录与区间统计;只说明历史上发生了什么,不预测、不评级",
|
|
7
|
+
"roles": ["senior_analyst"],
|
|
8
|
+
"capabilities": ["dataset.read"],
|
|
9
|
+
"required_fields": [],
|
|
10
|
+
"input_schema": {
|
|
11
|
+
"type": "object",
|
|
12
|
+
"properties": {
|
|
13
|
+
"price_dataset_id": { "type": "string", "maxLength": 128, "description": "价格序列 Dataset;只有一份像日线序列时可省略" },
|
|
14
|
+
"price_column": { "type": "string", "maxLength": 64, "description": "价格列名;省略按 close / adj_close / close_price / price 识别" },
|
|
15
|
+
"time_column": { "type": "string", "maxLength": 64, "description": "时间列名;省略优先用 time_coverage 列,再按 trade_date_ms / date 等识别" },
|
|
16
|
+
"timezone": { "type": "string", "maxLength": 64, "description": "数值时间轴(epoch 毫秒)标注日期用的 IANA 时区;省略按 UTC" },
|
|
17
|
+
"rule": { "type": "string", "enum": ["sma_cross", "price_above_sma"], "description": "sma_cross = 快线上穿慢线持有、下穿空仓;price_above_sma = 收盘价高于均线持有、否则空仓" },
|
|
18
|
+
"fast_window": { "type": "integer", "minimum": 2, "description": "快线 / 单均线窗口(如 5)" },
|
|
19
|
+
"slow_window": { "type": "integer", "minimum": 2, "description": "慢线窗口(仅 sma_cross 需要,如 20;必须大于 fast_window)" },
|
|
20
|
+
"initial_capital": { "type": "number", "minimum": 1, "description": "初始资金(原币),默认 1;只影响金额规模,不影响收益率" },
|
|
21
|
+
"fee_rate": { "type": "number", "minimum": 0, "description": "单边手续费率(小数,0.001 = 0.1%),默认 0 并在结果里披露" }
|
|
22
|
+
},
|
|
23
|
+
"required": ["rule", "fast_window"],
|
|
24
|
+
"additionalProperties": false
|
|
25
|
+
},
|
|
26
|
+
"output_schema": {
|
|
27
|
+
"type": "object",
|
|
28
|
+
"properties": {
|
|
29
|
+
"status": { "type": "string", "enum": ["completed", "partial", "blocked", "failed"] },
|
|
30
|
+
"summary": { "type": "string" },
|
|
31
|
+
"metrics": { "type": "object" },
|
|
32
|
+
"claims": { "type": "array" },
|
|
33
|
+
"assumptions": { "type": "array" },
|
|
34
|
+
"methodology_log": { "type": "array" },
|
|
35
|
+
"sensitivity": { "type": "object" },
|
|
36
|
+
"limitations": { "type": "array" },
|
|
37
|
+
"data_gaps": { "type": "array" },
|
|
38
|
+
"outputs": { "type": "array" }
|
|
39
|
+
},
|
|
40
|
+
"required": [
|
|
41
|
+
"status", "summary", "metrics", "claims", "assumptions", "methodology_log",
|
|
42
|
+
"sensitivity", "limitations", "data_gaps", "outputs"
|
|
43
|
+
],
|
|
44
|
+
"additionalProperties": false
|
|
45
|
+
},
|
|
46
|
+
"assumptions": [
|
|
47
|
+
"信号在第 t 根收盘算出、按第 t+1 根收盘执行:不使用未来数据,也不假设盘中成交",
|
|
48
|
+
"只做多、空仓二态:持有期收益按收盘价到收盘价,卖出后空仓收益为 0",
|
|
49
|
+
"手续费按单边 fee_rate 从每次买入与卖出金额中扣除;默认 0 时必须原样披露“未扣手续费”",
|
|
50
|
+
"回测使用样本内价格:参数是调用方给的,模块不做参数寻优、不选择最佳窗口,也不做样本外检验",
|
|
51
|
+
"结果只描述这段历史上该规则发生了什么;不构成策略推荐、收益预测或评级"
|
|
52
|
+
],
|
|
53
|
+
"applicability": [
|
|
54
|
+
"单只标的的日频或周频价格序列:一行一个时间点,价格为正数;有效观测至少为 max(窗口) + 2",
|
|
55
|
+
"只支持 sma_cross 与 price_above_sma 两条规则;需要其他规则时本模块不适用",
|
|
56
|
+
"A 股、港股、美股与指数均可;复权口径由调用方选定,跨口径比较不适用",
|
|
57
|
+
"不适用于高频、做空、杠杆、组合层回测或需要交易成本模型的场景"
|
|
58
|
+
],
|
|
59
|
+
"limits": {
|
|
60
|
+
"timeout_ms": 30000,
|
|
61
|
+
"max_input_rows": 200000,
|
|
62
|
+
"max_output_bytes": 1048576,
|
|
63
|
+
"max_log_bytes": 65536
|
|
64
|
+
},
|
|
65
|
+
"provenance": { "source_type": "original", "license": "MIT" }
|
|
66
|
+
}
|