@v587d/capital-generation 2.31.1 → 2.31.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. package/CHANGELOG.md +125 -0
  2. package/README.md +45 -7
  3. package/automation/package.json +1 -1
  4. package/chart-ui/package.json +1 -1
  5. package/config/package.json +1 -1
  6. package/lib/analysis/registry.js +6 -1
  7. package/lib/analysis/validation.js +13 -3
  8. package/lib/web-retriever/local-fetch.d.ts +1 -1
  9. package/lib/web-retriever/local-fetch.js +1 -1
  10. package/lib/web-retriever/wind-client.d.ts +1 -1
  11. package/lib/web-retriever/wind-client.js +1 -1
  12. package/package.json +1 -1
  13. package/plugin-page/README.en.md +7 -0
  14. package/plugin-page/README.zh.md +7 -0
  15. package/preset/capital-generation/agent.patch.yml +11 -9
  16. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +47 -16
  17. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +2 -2
  18. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +5 -0
  19. package/python/analysis/modules/comps_valuation/LICENSE +21 -0
  20. package/python/analysis/modules/comps_valuation/module.json +61 -0
  21. package/python/analysis/modules/comps_valuation/module.py +360 -0
  22. package/python/analysis/modules/earnings_bridge/LICENSE +21 -0
  23. package/python/analysis/modules/earnings_bridge/module.json +58 -0
  24. package/python/analysis/modules/earnings_bridge/module.py +452 -0
  25. package/python/analysis/modules/kline_quality/LICENSE +21 -0
  26. package/python/analysis/modules/kline_quality/module.json +61 -0
  27. package/python/analysis/modules/kline_quality/module.py +538 -0
  28. package/python/analysis/modules/portfolio_stress/LICENSE +21 -0
  29. package/python/analysis/modules/portfolio_stress/module.json +89 -0
  30. package/python/analysis/modules/portfolio_stress/module.py +537 -0
  31. package/python/analysis/modules/returns_risk/LICENSE +21 -0
  32. package/python/analysis/modules/returns_risk/module.json +66 -0
  33. package/python/analysis/modules/returns_risk/module.py +517 -0
  34. package/python/analysis/modules/scenario_sensitivity/LICENSE +21 -0
  35. package/python/analysis/modules/scenario_sensitivity/module.json +105 -0
  36. package/python/analysis/modules/scenario_sensitivity/module.py +379 -0
  37. package/python/analysis/modules/simple_backtest/LICENSE +21 -0
  38. package/python/analysis/modules/simple_backtest/module.json +66 -0
  39. package/python/analysis/modules/simple_backtest/module.py +648 -0
  40. package/python/analysis/modules/statement_integrity/LICENSE +21 -0
  41. package/python/analysis/modules/statement_integrity/module.json +62 -0
  42. package/python/analysis/modules/statement_integrity/module.py +621 -0
  43. package/python/analysis/modules/technical_indicators/LICENSE +21 -0
  44. package/python/analysis/modules/technical_indicators/module.json +170 -0
  45. package/python/analysis/modules/technical_indicators/module.py +854 -0
  46. package/python/analysis/modules/valuation_sensitivity/LICENSE +21 -0
  47. package/python/analysis/modules/valuation_sensitivity/module.json +73 -0
  48. package/python/analysis/modules/valuation_sensitivity/module.py +589 -0
  49. package/watchlist/package.json +1 -1
@@ -0,0 +1,854 @@
1
+ """Technical indicators 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 optional high/low columns
4
+ that only ATR uses. An indicator group is computed only when the caller supplies its parameters, and
5
+ only when the window is complete: an incomplete window becomes a reported gap, never a shorter window
6
+ or a default value. The values and cross states are review conditions for the senior analyst; the
7
+ module does not forecast direction, rate or recommend anything.
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.
13
+ """
14
+ from __future__ import annotations
15
+
16
+ import math
17
+ import re
18
+ from datetime import datetime, timezone
19
+
20
+ MODULE_ID = "technical_indicators"
21
+ MODULE_VERSION = "1.0.0"
22
+ OUTPUT_NAME = "technical_indicators"
23
+
24
+ MAX_WINDOWS = 4
25
+ MAX_SERIES_BARS = 2000
26
+ MACD_DEFAULTS = (12, 26, 9)
27
+ BOLL_PERIOD_DEFAULT = 20
28
+ BOLL_MULTIPLIER_DEFAULT = 2.0
29
+
30
+ ASSUMPTIONS = [
31
+ "价格口径沿用 Dataset 的取数参数(qfq / hfq / none),本模块不检测也不做复权调整",
32
+ "所有指标只用收盘价序列按标准公式计算:SMA 算术平均、EMA 平滑系数 2/(n+1)、RSI 用 Wilder 平滑、MACD 为 EMA 差与信号线 EMA、布林带为 SMA ± 倍数×总体标准差、ATR 用真实波幅的 Wilder 平滑",
33
+ "指标值只在窗口完整时给出;样本不足的窗口写进 data_gaps,不用更短窗口或默认值凑数",
34
+ "交叉状态是「最新一根与前一根的相对位置」,是复盘条件,不是买卖信号或方向预测",
35
+ "指标对复权口径与停牌处理敏感;不同数据源的复权价不可混算",
36
+ ]
37
+
38
+ LIMITATIONS = [
39
+ "指标窗口不完整时只报缺口:样本不足的指标不会被更短窗口或默认值代替",
40
+ "SMA / EMA / RSI / MACD / 布林带只用收盘价;ATR 额外用 high / low;不同复权口径或停牌处理的价格不可混算",
41
+ "交叉与相对状态只描述最新一根 bar 的位置,不代表信号有效或方向",
42
+ "指标是复盘条件,不是买卖信号、评级或方向预测",
43
+ "不构成投资建议,也不产生评级、目标价或收益承诺",
44
+ ]
45
+
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
+ 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
+
66
+
67
+ def _publish(metrics, computed, gaps, key, label, value):
68
+ """Publish one latest indicator value; a non-finite one is a gap, not a NaN."""
69
+ rounded = _round(value)
70
+ if rounded is None:
71
+ gaps.append(f"{label} 最新值不是有限数字(价格量级导致数值溢出):未输出")
72
+ return
73
+ metrics[key] = rounded
74
+ computed.append(key)
75
+
76
+
77
+ def _fmt4(value):
78
+ return f"{value:.4f}"
79
+
80
+
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
+ def _series(view, dataset_id, price_column, time_column, tz):
173
+ """Positive prices on a time axis; bad rows are skipped and returned for `data_gaps`."""
174
+ rows = view.get("rows") or []
175
+ if not rows:
176
+ raise AnalysisInputError(f"Dataset {dataset_id} 没有数据行:无法计算技术指标")
177
+ points, dropped, kind = [], [], None
178
+ for index, row in enumerate(rows):
179
+ if not isinstance(row, dict):
180
+ raise AnalysisInputError(f"Dataset {dataset_id} 的数据行不是对象:无法计算技术指标")
181
+ raw_time = row.get(time_column)
182
+ row_kind = "ms" if isinstance(raw_time, (int, float)) and not isinstance(raw_time, bool) else "date"
183
+ if kind is None:
184
+ kind = row_kind
185
+ elif row_kind != kind:
186
+ raise AnalysisInputError(
187
+ f"Dataset {dataset_id} 的 {time_column} 列混用了数值时间戳与日期字符串:无法排序,请取数时统一"
188
+ )
189
+ parsed = _parse_time(raw_time, tz)
190
+ price = _number(row, price_column)
191
+ if parsed is None:
192
+ dropped.append({"index": index + 1, "time": raw_time, "reason": "时间无法解析"})
193
+ continue
194
+ if price is None:
195
+ dropped.append({"index": index + 1, "time": raw_time, "reason": "价格缺失"})
196
+ continue
197
+ if price <= 0:
198
+ dropped.append({"index": index + 1, "time": raw_time, "reason": f"价格非正 close={price:g}"})
199
+ continue
200
+ key, day = parsed
201
+ points.append({
202
+ "key": key,
203
+ "day": day,
204
+ "price": price,
205
+ "high": _number(row, "high"),
206
+ "low": _number(row, "low"),
207
+ })
208
+ points.sort(key=lambda item: item["key"])
209
+ seen = set()
210
+ for point in points:
211
+ if point["day"] in seen:
212
+ raise AnalysisInputError(
213
+ f"Dataset {dataset_id} 在 {point['day']} 出现多行:无法判断用哪一行(请先去重)"
214
+ )
215
+ seen.add(point["day"])
216
+ return points, dropped
217
+
218
+
219
+ def _sma_series(closes, window):
220
+ values = [None] * len(closes)
221
+ for index in range(window - 1, len(closes)):
222
+ values[index] = math.fsum(closes[index - window + 1:index + 1]) / window
223
+ return values
224
+
225
+
226
+ def _ema_series(closes, window):
227
+ """EMA seeded with the SMA of the first `window` closes, then 2/(n+1) smoothing."""
228
+ values = [None] * len(closes)
229
+ if len(closes) < window:
230
+ return values
231
+ factor = 2.0 / (window + 1)
232
+ values[window - 1] = math.fsum(closes[:window]) / window
233
+ for index in range(window, len(closes)):
234
+ values[index] = values[index - 1] + factor * (closes[index] - values[index - 1])
235
+ return values
236
+
237
+
238
+ def _rsi_value(average_gain, average_loss):
239
+ if average_loss == 0:
240
+ return 100.0 if average_gain > 0 else 50.0
241
+ relative = average_gain / average_loss
242
+ return 100.0 - 100.0 / (1.0 + relative)
243
+
244
+
245
+ def _rsi_series(closes, period):
246
+ """Wilder RSI: first average of the first `period` changes, then Wilder smoothing."""
247
+ values = [None] * len(closes)
248
+ if len(closes) < period + 1:
249
+ return values
250
+ gains, losses = [], []
251
+ for index in range(1, period + 1):
252
+ change = closes[index] - closes[index - 1]
253
+ gains.append(max(change, 0.0))
254
+ losses.append(max(-change, 0.0))
255
+ average_gain = math.fsum(gains) / period
256
+ average_loss = math.fsum(losses) / period
257
+ values[period] = _rsi_value(average_gain, average_loss)
258
+ for index in range(period + 1, len(closes)):
259
+ change = closes[index] - closes[index - 1]
260
+ average_gain = (average_gain * (period - 1) + max(change, 0.0)) / period
261
+ average_loss = (average_loss * (period - 1) + max(-change, 0.0)) / period
262
+ values[index] = _rsi_value(average_gain, average_loss)
263
+ return values
264
+
265
+
266
+ def _macd_series(closes, fast, slow, signal):
267
+ fast_series = _ema_series(closes, fast)
268
+ slow_series = _ema_series(closes, slow)
269
+ macd = [None] * len(closes)
270
+ for index in range(slow - 1, len(closes)):
271
+ macd[index] = fast_series[index] - slow_series[index]
272
+ compact = macd[slow - 1:]
273
+ signal_compact = _ema_series(compact, signal)
274
+ signal_series = [None] * len(closes)
275
+ for offset, value in enumerate(signal_compact):
276
+ signal_series[slow - 1 + offset] = value
277
+ hist = [None] * len(closes)
278
+ for index, value in enumerate(macd):
279
+ if value is not None and signal_series[index] is not None:
280
+ hist[index] = value - signal_series[index]
281
+ return macd, signal_series, hist
282
+
283
+
284
+ def _boll_series(closes, period, multiplier):
285
+ middle = _sma_series(closes, period)
286
+ upper, lower = [None] * len(closes), [None] * len(closes)
287
+ for index in range(period - 1, len(closes)):
288
+ mean = middle[index]
289
+ window = closes[index - period + 1:index + 1]
290
+ variance = math.fsum((value - mean) ** 2 for value in window) / period
291
+ deviation = math.sqrt(variance)
292
+ upper[index] = mean + multiplier * deviation
293
+ lower[index] = mean - multiplier * deviation
294
+ return upper, middle, lower
295
+
296
+
297
+ def _atr_series(points, period):
298
+ """Wilder ATR over true range; TR starts at bar 1, so the first ATR lands on bar `period`."""
299
+ closes = [point["price"] for point in points]
300
+ true_ranges = [None] * len(points)
301
+ for index in range(1, len(points)):
302
+ high, low, previous = points[index]["high"], points[index]["low"], closes[index - 1]
303
+ true_ranges[index] = max(high - low, abs(high - previous), abs(low - previous))
304
+ values = [None] * len(points)
305
+ if len(points) < period + 1:
306
+ return values
307
+ values[period] = math.fsum(true_ranges[1:period + 1]) / period
308
+ for index in range(period + 1, len(points)):
309
+ values[index] = (values[index - 1] * (period - 1) + true_ranges[index]) / period
310
+ return values
311
+
312
+
313
+ def _windows(params, key):
314
+ raw = params.get(key)
315
+ if raw is None:
316
+ return None
317
+ if not isinstance(raw, list) or not raw:
318
+ raise AnalysisInputError(f"{key} 必须是非空数组(或省略)")
319
+ if len(raw) > MAX_WINDOWS:
320
+ raise AnalysisInputError(f"{key} 最多 {MAX_WINDOWS} 个窗口,实际 {len(raw)} 个")
321
+ windows = []
322
+ for index, value in enumerate(raw):
323
+ if isinstance(value, bool) or not isinstance(value, int) or value < 2:
324
+ raise AnalysisInputError(f"{key}[{index}]={value!r} 必须是 ≥2 的整数")
325
+ if value in windows:
326
+ raise AnalysisInputError(f"{key} 有重复窗口 {value}:同一窗口只能出现一次")
327
+ windows.append(value)
328
+ return sorted(windows)
329
+
330
+
331
+ def _period(params, key, default):
332
+ raw = params.get(key, default)
333
+ if isinstance(raw, bool) or not isinstance(raw, int) or raw < 2:
334
+ raise AnalysisInputError(f"{key}={raw!r} 必须是 ≥2 的整数")
335
+ return raw
336
+
337
+
338
+ def _optional_period(params, key):
339
+ if key not in params:
340
+ return None
341
+ return _period(params, key, None)
342
+
343
+
344
+ def _multiplier(params):
345
+ raw = params.get("boll_multiplier", BOLL_MULTIPLIER_DEFAULT)
346
+ if isinstance(raw, bool) or not isinstance(raw, (int, float)):
347
+ raise AnalysisInputError(f"boll_multiplier={raw!r} 必须是数字")
348
+ value = float(raw)
349
+ if value != value or value in (float("inf"), float("-inf")):
350
+ raise AnalysisInputError(f"boll_multiplier={raw!r} 必须是有限数字")
351
+ if value < 0:
352
+ raise AnalysisInputError(f"boll_multiplier={value!r} 不能为负数")
353
+ return value
354
+
355
+
356
+ def _groups(params):
357
+ """Indicator groups requested by the caller: a group exists only when its parameters were given."""
358
+ sma_windows = _windows(params, "sma_windows")
359
+ ema_windows = _windows(params, "ema_windows")
360
+ rsi_period = _optional_period(params, "rsi_period")
361
+ macd = None
362
+ if any(key in params for key in ("macd_fast", "macd_slow", "macd_signal")):
363
+ fast = _period(params, "macd_fast", MACD_DEFAULTS[0])
364
+ slow = _period(params, "macd_slow", MACD_DEFAULTS[1])
365
+ signal = _period(params, "macd_signal", MACD_DEFAULTS[2])
366
+ if fast >= slow:
367
+ raise AnalysisInputError(f"macd_fast={fast} 必须小于 macd_slow={slow}:MACD 是快线 EMA 减慢线 EMA")
368
+ macd = (fast, slow, signal)
369
+ boll = None
370
+ if "boll_period" in params or "boll_multiplier" in params:
371
+ boll = (_period(params, "boll_period", BOLL_PERIOD_DEFAULT), _multiplier(params))
372
+ atr_period = _optional_period(params, "atr_period")
373
+ groups = {
374
+ "sma": sma_windows,
375
+ "ema": ema_windows,
376
+ "rsi": rsi_period,
377
+ "macd": macd,
378
+ "boll": boll,
379
+ "atr": atr_period,
380
+ }
381
+ if all(value is None for value in groups.values()):
382
+ raise AnalysisInputError(
383
+ "一个指标参数都没给:至少给出 sma_windows / ema_windows / rsi_period / macd_* / boll_* / atr_period 之一"
384
+ )
385
+ return groups
386
+
387
+
388
+ def _window_gap(label, need_text, actual):
389
+ return f"{label} 未计算:需要 {need_text},实际 {actual} 根(窗口不完整,不用更短窗口或默认值代替)"
390
+
391
+
392
+ def _indicators(points, groups, names):
393
+ """Compute every requested indicator; incomplete windows stay `None` and become gaps."""
394
+ closes = [point["price"] for point in points]
395
+ count = len(points)
396
+ metrics = {"close": _round(closes[-1]), "observations": count}
397
+ series_values, metadata, gaps, computed = {}, [], [], []
398
+
399
+ if groups["sma"] is not None:
400
+ for window in groups["sma"]:
401
+ key = f"sma_{window}"
402
+ values = _sma_series(closes, window)
403
+ series_values[key] = values
404
+ metadata.append({
405
+ "id": key,
406
+ "group": "sma",
407
+ "window": window,
408
+ "required_observations": window,
409
+ "formula": f"SMA({window}) = 最近 {window} 个收盘价的算术平均",
410
+ })
411
+ if count < window:
412
+ gaps.append(_window_gap(f"SMA({window})", f"{window} 根收盘价", count))
413
+ continue
414
+ _publish(metrics, computed, gaps, key, f"SMA({window})", values[-1])
415
+
416
+ if groups["ema"] is not None:
417
+ for window in groups["ema"]:
418
+ key = f"ema_{window}"
419
+ values = _ema_series(closes, window)
420
+ series_values[key] = values
421
+ metadata.append({
422
+ "id": key,
423
+ "group": "ema",
424
+ "window": window,
425
+ "required_observations": window,
426
+ "formula": f"EMA({window}) = 前值 + 2/({window}+1)×(收盘 − 前值),首值取前 {window} 个收盘价均值",
427
+ })
428
+ if count < window:
429
+ gaps.append(_window_gap(f"EMA({window})", f"{window} 根收盘价", count))
430
+ continue
431
+ _publish(metrics, computed, gaps, key, f"EMA({window})", values[-1])
432
+
433
+ if groups["rsi"] is not None:
434
+ period = groups["rsi"]
435
+ key = f"rsi_{period}"
436
+ values = _rsi_series(closes, period)
437
+ series_values[key] = values
438
+ metadata.append({
439
+ "id": key,
440
+ "group": "rsi",
441
+ "window": period,
442
+ "required_observations": period + 1,
443
+ "formula": (
444
+ f"RSI({period}) = 100 − 100/(1 + 平均涨幅/平均跌幅),Wilder 平滑;"
445
+ f"首值用前 {period} 个变动的平均涨/跌"
446
+ ),
447
+ })
448
+ if count < period + 1:
449
+ gaps.append(_window_gap(f"RSI({period})", f"{period + 1} 根(周期 + 1)", count))
450
+ else:
451
+ _publish(metrics, computed, gaps, key, f"RSI({period})", values[-1])
452
+
453
+ if groups["macd"] is not None:
454
+ fast, slow, signal = groups["macd"]
455
+ macd_values, signal_values, hist_values = _macd_series(closes, fast, slow, signal)
456
+ series_values["macd"] = macd_values
457
+ series_values["macd_signal"] = signal_values
458
+ series_values["macd_hist"] = hist_values
459
+ metadata.extend([
460
+ {
461
+ "id": "macd",
462
+ "group": "macd",
463
+ "window": slow,
464
+ "required_observations": slow + signal,
465
+ "formula": f"MACD = EMA({fast}) − EMA({slow})",
466
+ },
467
+ {
468
+ "id": "macd_signal",
469
+ "group": "macd",
470
+ "window": signal,
471
+ "required_observations": slow + signal,
472
+ "formula": f"signal = EMA({signal}) 于 MACD 序列,首值取前 {signal} 个 MACD 均值",
473
+ },
474
+ {
475
+ "id": "macd_hist",
476
+ "group": "macd",
477
+ "window": signal,
478
+ "required_observations": slow + signal,
479
+ "formula": "hist = MACD − signal",
480
+ },
481
+ ])
482
+ if count < slow + signal:
483
+ gaps.append(_window_gap(f"MACD({fast}/{slow}/{signal})", f"{slow + signal} 根(slow + signal)", count))
484
+ else:
485
+ _publish(metrics, computed, gaps, "macd", "MACD", macd_values[-1])
486
+ _publish(metrics, computed, gaps, "macd_signal", "MACD signal", signal_values[-1])
487
+ _publish(metrics, computed, gaps, "macd_hist", "MACD hist", hist_values[-1])
488
+
489
+ if groups["boll"] is not None:
490
+ period, multiplier = groups["boll"]
491
+ upper, middle, lower = _boll_series(closes, period, multiplier)
492
+ series_values["boll_upper"] = upper
493
+ series_values["boll_middle"] = middle
494
+ series_values["boll_lower"] = lower
495
+ factor = f"{multiplier:g}"
496
+ metadata.extend([
497
+ {
498
+ "id": "boll_upper",
499
+ "group": "boll",
500
+ "window": period,
501
+ "required_observations": period,
502
+ "formula": f"upper = SMA({period}) + {factor}×总体标准差({period})",
503
+ },
504
+ {
505
+ "id": "boll_middle",
506
+ "group": "boll",
507
+ "window": period,
508
+ "required_observations": period,
509
+ "formula": f"middle = SMA({period})",
510
+ },
511
+ {
512
+ "id": "boll_lower",
513
+ "group": "boll",
514
+ "window": period,
515
+ "required_observations": period,
516
+ "formula": f"lower = SMA({period}) − {factor}×总体标准差({period})",
517
+ },
518
+ ])
519
+ if count < period:
520
+ gaps.append(_window_gap(f"BOLL({period})", f"{period} 根收盘价", count))
521
+ else:
522
+ _publish(metrics, computed, gaps, "boll_upper", "BOLL 上轨", upper[-1])
523
+ _publish(metrics, computed, gaps, "boll_middle", "BOLL 中轨", middle[-1])
524
+ _publish(metrics, computed, gaps, "boll_lower", "BOLL 下轨", lower[-1])
525
+
526
+ if groups["atr"] is not None:
527
+ period = groups["atr"]
528
+ key = f"atr_{period}"
529
+ metadata.append({
530
+ "id": key,
531
+ "group": "atr",
532
+ "window": period,
533
+ "required_observations": period + 1,
534
+ "formula": (
535
+ f"ATR({period}) = 真实波幅的 Wilder 平滑;"
536
+ "TR = max(high − low, |high − 前收|, |low − 前收|),首值取前 "
537
+ f"{period} 个 TR 均值"
538
+ ),
539
+ })
540
+ missing = [name for name in OHLC_COLUMNS if name not in names]
541
+ invalid = sum(1 for point in points if point["high"] is None or point["low"] is None)
542
+ if missing:
543
+ series_values[key] = [None] * count
544
+ gaps.append(
545
+ f"ATR({period}) 未计算:需要 high / low / close 三列,Dataset 缺 {'、'.join(missing)}(ATR 要用真实波幅)"
546
+ )
547
+ elif invalid:
548
+ series_values[key] = [None] * count
549
+ gaps.append(f"ATR({period}) 未计算:有 {invalid} 行 high/low 不是有限数字(按缺口处理,不填默认值)")
550
+ elif count < period + 1:
551
+ series_values[key] = [None] * count
552
+ gaps.append(_window_gap(f"ATR({period})", f"{period + 1} 根(周期 + 1)", count))
553
+ else:
554
+ values = _atr_series(points, period)
555
+ series_values[key] = values
556
+ _publish(metrics, computed, gaps, key, f"ATR({period})", values[-1])
557
+
558
+ return metrics, series_values, metadata, gaps, computed
559
+
560
+
561
+ def _states(points, metrics, groups, series_values):
562
+ """Latest-bar relative positions and cross events; absent when either side has no value."""
563
+ close = points[-1]["price"]
564
+
565
+ available_smas = [window for window in (groups["sma"] or []) if f"sma_{window}" in metrics]
566
+ for window in available_smas:
567
+ metrics[f"close_above_sma_{window}"] = close > series_values[f"sma_{window}"][-1]
568
+ for first, second in zip(available_smas, available_smas[1:]):
569
+ left, right = series_values[f"sma_{first}"], series_values[f"sma_{second}"]
570
+ current = left[-1] > right[-1]
571
+ metrics[f"sma_{first}_above_sma_{second}"] = current
572
+ if len(left) >= 2 and left[-2] is not None and right[-2] is not None:
573
+ previous = left[-2] > right[-2]
574
+ metrics[f"sma_{first}_crossed_above_sma_{second}"] = current and not previous
575
+ metrics[f"sma_{first}_crossed_below_sma_{second}"] = previous and not current
576
+
577
+ for window in (groups["ema"] or []):
578
+ if f"ema_{window}" in metrics:
579
+ metrics[f"close_above_ema_{window}"] = close > series_values[f"ema_{window}"][-1]
580
+
581
+ if "macd" in metrics and "macd_signal" in metrics:
582
+ macd_values, signal_values = series_values["macd"], series_values["macd_signal"]
583
+ current = macd_values[-1] > signal_values[-1]
584
+ metrics["macd_above_signal"] = current
585
+ if len(macd_values) >= 2 and macd_values[-2] is not None and signal_values[-2] is not None:
586
+ previous = macd_values[-2] > signal_values[-2]
587
+ metrics["macd_crossed_above_signal"] = current and not previous
588
+ metrics["macd_crossed_below_signal"] = previous and not current
589
+
590
+ if all(key in metrics for key in ("boll_upper", "boll_middle", "boll_lower")):
591
+ metrics["close_above_boll_middle"] = close > series_values["boll_middle"][-1]
592
+ metrics["close_above_boll_upper"] = close > series_values["boll_upper"][-1]
593
+ metrics["close_below_boll_lower"] = close < series_values["boll_lower"][-1]
594
+
595
+
596
+ def _requested_text(groups):
597
+ parts = []
598
+ if groups["sma"] is not None:
599
+ parts.append("SMA [" + ", ".join(str(window) for window in groups["sma"]) + "]")
600
+ if groups["ema"] is not None:
601
+ parts.append("EMA [" + ", ".join(str(window) for window in groups["ema"]) + "]")
602
+ if groups["rsi"] is not None:
603
+ parts.append(f"RSI({groups['rsi']})")
604
+ if groups["macd"] is not None:
605
+ fast, slow, signal = groups["macd"]
606
+ parts.append(f"MACD({fast}/{slow}/{signal})")
607
+ if groups["boll"] is not None:
608
+ period, multiplier = groups["boll"]
609
+ parts.append(f"BOLL({period}, {multiplier:g})")
610
+ if groups["atr"] is not None:
611
+ parts.append(f"ATR({groups['atr']})")
612
+ return "、".join(parts)
613
+
614
+
615
+ def _summary(points, metrics, groups, gaps, dropped):
616
+ parts = [
617
+ f"{points[0]['day']}..{points[-1]['day']},{len(points)} 个观测",
618
+ f"最新收盘 {_fmt4(metrics['close'])}",
619
+ ]
620
+ if dropped:
621
+ parts.append(f"跳过 {len(dropped)} 条坏行")
622
+ for window in (groups["sma"] or []):
623
+ key = f"sma_{window}"
624
+ if key in metrics:
625
+ parts.append(f"SMA{window} {_fmt4(metrics[key])}")
626
+ for window in (groups["ema"] or []):
627
+ key = f"ema_{window}"
628
+ if key in metrics:
629
+ parts.append(f"EMA{window} {_fmt4(metrics[key])}")
630
+ rsi_period = groups["rsi"]
631
+ if rsi_period is not None and f"rsi_{rsi_period}" in metrics:
632
+ parts.append(f"RSI{rsi_period} {_fmt4(metrics[f'rsi_{rsi_period}'])}")
633
+ if all(key in metrics for key in ("macd", "macd_signal", "macd_hist")):
634
+ parts.append(
635
+ f"MACD {_fmt4(metrics['macd'])}(signal {_fmt4(metrics['macd_signal'])}、"
636
+ f"hist {_fmt4(metrics['macd_hist'])})"
637
+ )
638
+ if all(key in metrics for key in ("boll_upper", "boll_middle", "boll_lower")):
639
+ parts.append(
640
+ f"BOLL 上 {_fmt4(metrics['boll_upper'])} / 中 {_fmt4(metrics['boll_middle'])} / "
641
+ f"下 {_fmt4(metrics['boll_lower'])}"
642
+ )
643
+ atr_period = groups["atr"]
644
+ if atr_period is not None and f"atr_{atr_period}" in metrics:
645
+ parts.append(f"ATR{atr_period} {_fmt4(metrics[f'atr_{atr_period}'])}")
646
+ text = ";".join(parts) + "。"
647
+ if gaps:
648
+ text += "(有缺口未计算,见 data_gaps)。"
649
+ return text + "指标是复盘条件,不是买卖信号或方向预测。"
650
+
651
+
652
+ def _blocked_summary(points, dropped):
653
+ text = (
654
+ f"{points[0]['day']}..{points[-1]['day']},{len(points)} 个观测;"
655
+ "请求的指标都未能计算(见 data_gaps)。"
656
+ )
657
+ if dropped:
658
+ text += f"另有 {len(dropped)} 条坏行被跳过。"
659
+ return text + "指标是复盘条件,不是买卖信号或方向预测。"
660
+
661
+
662
+ def _skipped_gap(price_column, dropped):
663
+ labels = []
664
+ for item in dropped[:5]:
665
+ labels.append(f"第 {item['index']} 行 {item['time']}({item['reason']})")
666
+ shown = "、".join(labels)
667
+ suffix = "" if len(dropped) <= 5 else f" 等 {len(dropped)} 行"
668
+ return f"价格列 {price_column} 有 {len(dropped)} 行不是正数或时间无法解析(已跳过):{shown}{suffix}"
669
+
670
+
671
+ def _result(status, summary, metrics, methodology, limitations, gaps, outputs):
672
+ return {
673
+ "status": status,
674
+ "summary": summary,
675
+ "metrics": metrics,
676
+ "claims": [],
677
+ "assumptions": list(ASSUMPTIONS),
678
+ "methodology_log": methodology,
679
+ "sensitivity": {},
680
+ "limitations": limitations,
681
+ "data_gaps": gaps,
682
+ "outputs": outputs,
683
+ }
684
+
685
+
686
+ def _read_views(request, context):
687
+ items = (request.get("inputs") or {}).get("datasets") or []
688
+ if not items:
689
+ raise AnalysisInputError("快照里没有任何 Dataset:先取价格序列再建快照")
690
+ views = {}
691
+ for item in items:
692
+ dataset_id = (item or {}).get("dataset_id")
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
716
+
717
+
718
+ def analyze(request: dict, context) -> dict:
719
+ params = request.get("params") or {}
720
+ groups = _groups(params)
721
+ views = _read_views(request, context)
722
+ price_override = _text(params.get("price_column"))
723
+ time_override = _text(params.get("time_column"))
724
+
725
+ price_dataset_id = _text(params.get("price_dataset_id"))
726
+ if price_dataset_id is not None:
727
+ if price_dataset_id not in views:
728
+ raise AnalysisInputError(f"price_dataset_id={price_dataset_id} 不在本次快照的 Dataset 里")
729
+ price_view = views[price_dataset_id]
730
+ else:
731
+ candidates = _candidate(views, price_override, time_override)
732
+ if len(candidates) > 1:
733
+ raise AnalysisInputError(
734
+ f"有 {len(candidates)} 份 Dataset 都像价格序列({'、'.join(item[0] for item in candidates)}):"
735
+ "用 price_dataset_id 指明用哪一份"
736
+ )
737
+ if not candidates:
738
+ detail = f"(time_column={time_override} 不在任何 Dataset 里)" if time_override else ""
739
+ raise AnalysisInputError(
740
+ f"没有可识别的价格序列 Dataset{detail}:需要时间列 + close/adj_close/close_price/price/nav 之一"
741
+ )
742
+ price_dataset_id = candidates[0][0]
743
+ price_view = views[price_dataset_id]
744
+
745
+ time_column = _time_column(price_view, time_override)
746
+ price_column = _price_column(price_view, price_override)
747
+ tz = _timezone(_text(params.get("timezone")))
748
+ points, dropped = _series(price_view, price_dataset_id, price_column, time_column, tz)
749
+ if len(points) < 2:
750
+ raise AnalysisInputError(
751
+ f"Dataset {price_dataset_id} 只有 {len(points)} 个有效观测(跳过 {len(dropped)} 行):"
752
+ "技术指标至少需要 2 个正价格观测"
753
+ )
754
+
755
+ names = _columns_of(price_view)
756
+ metrics, series_values, metadata, gaps, computed = _indicators(points, groups, names)
757
+ if dropped:
758
+ gaps.insert(0, _skipped_gap(price_column, dropped))
759
+ _states(points, metrics, groups, series_values)
760
+
761
+ methodology = [
762
+ f"价格 Dataset {price_dataset_id}:时间列 {time_column}、价格列 {price_column}",
763
+ f"按时间升序取 {len(points)} 个正价格观测;跳过 {len(dropped)} 行(时间无法解析或价格非正)",
764
+ f"请求指标:{_requested_text(groups)}",
765
+ f"计算 {len(computed)} 项指标值、{len(gaps)} 项缺口;窗口不完整不缩短、不填默认值",
766
+ "指标公式、窗口与所需根数见 outputs 的 indicators 元数据",
767
+ ]
768
+ if groups["rsi"] is not None and f"rsi_{groups['rsi']}" in metrics:
769
+ methodology.append("RSI 平均跌幅为 0 时记 100;涨跌都为 0(完全平盘)时记 50(0/0 无定义,取中性值)")
770
+ limitations = list(LIMITATIONS)
771
+ if len(points) < 30:
772
+ limitations.append(f"只有 {len(points)} 个观测:短样本上的指标不稳定,只作复盘条件")
773
+ if price_view.get("truncated"):
774
+ limitations.append(
775
+ f"Dataset {price_dataset_id} 超过 max_input_rows,只用了前 {len(points)} 行:指标基于截断样本"
776
+ )
777
+ series_truncated = len(points) > MAX_SERIES_BARS
778
+ if series_truncated:
779
+ limitations.append(
780
+ f"审计文件只保留最近 {MAX_SERIES_BARS} 根 bar(共 {len(points)} 根):更早的 bar 未写入 outputs,指标仍用完整序列计算"
781
+ )
782
+
783
+ if not computed:
784
+ context.log(f"{MODULE_ID}: blocked observations={len(points)} gaps={len(gaps)}")
785
+ return _result(
786
+ "blocked",
787
+ _blocked_summary(points, dropped),
788
+ metrics,
789
+ methodology + ["未计算任何指标:请求的指标都没有完整窗口或必需列"],
790
+ limitations,
791
+ gaps,
792
+ [],
793
+ )
794
+
795
+ status = "partial" if gaps else "completed"
796
+ parameters = {}
797
+ if groups["sma"] is not None:
798
+ parameters["sma_windows"] = groups["sma"]
799
+ if groups["ema"] is not None:
800
+ parameters["ema_windows"] = groups["ema"]
801
+ if groups["rsi"] is not None:
802
+ parameters["rsi_period"] = groups["rsi"]
803
+ if groups["macd"] is not None:
804
+ fast, slow, signal = groups["macd"]
805
+ parameters.update({"macd_fast": fast, "macd_slow": slow, "macd_signal": signal})
806
+ if groups["boll"] is not None:
807
+ period, multiplier = groups["boll"]
808
+ parameters.update({"boll_period": period, "boll_multiplier": multiplier})
809
+ if groups["atr"] is not None:
810
+ parameters["atr_period"] = groups["atr"]
811
+
812
+ series_ids = [item["id"] for item in metadata]
813
+ series_rows = []
814
+ for index, point in enumerate(points):
815
+ row = {"date": point["day"], "close": _round(point["price"])}
816
+ for indicator_id in series_ids:
817
+ value = series_values[indicator_id][index]
818
+ row[indicator_id] = None if value is None else _round(value)
819
+ series_rows.append(row)
820
+ if series_truncated:
821
+ series_rows = series_rows[-MAX_SERIES_BARS:]
822
+
823
+ payload = {
824
+ "protocol": "capital.analysis/v1",
825
+ "module_id": MODULE_ID,
826
+ "module_version": MODULE_VERSION,
827
+ "analysis_id": request.get("analysis_id"),
828
+ "module_run_id": request.get("module_run_id"),
829
+ "price_dataset_id": price_dataset_id,
830
+ "time_column": time_column,
831
+ "price_column": price_column,
832
+ "parameters": parameters,
833
+ "window": {"start": points[0]["day"], "end": points[-1]["day"], "observations": len(points)},
834
+ "indicators": metadata,
835
+ "series": series_rows,
836
+ "series_total": len(points),
837
+ "series_truncated": series_truncated,
838
+ "skipped_rows": len(dropped),
839
+ "data_gaps": gaps,
840
+ }
841
+ ref = context.write_output(OUTPUT_NAME, payload)
842
+ context.log(
843
+ f"{MODULE_ID}: {status} observations={len(points)} indicators={len(computed)} gaps={len(gaps)}"
844
+ )
845
+
846
+ return _result(
847
+ status,
848
+ _summary(points, metrics, groups, gaps, dropped),
849
+ metrics,
850
+ methodology,
851
+ limitations,
852
+ gaps,
853
+ [{"name": OUTPUT_NAME, "ref": ref}],
854
+ )