@v587d/capital-generation 2.31.7 → 2.32.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/CHANGELOG.md +60 -0
  2. package/README.md +14 -5
  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/artifact.d.ts +35 -0
  7. package/lib/analysis/artifact.js +250 -0
  8. package/lib/analysis/registry.d.ts +16 -2
  9. package/lib/analysis/registry.js +133 -23
  10. package/lib/analysis/runtime.d.ts +46 -19
  11. package/lib/analysis/runtime.js +485 -116
  12. package/lib/analysis/schemas.d.ts +46 -0
  13. package/lib/analysis/schemas.js +260 -7
  14. package/lib/analysis/snapshot.d.ts +10 -3
  15. package/lib/analysis/snapshot.js +298 -46
  16. package/lib/analysis/storage.d.ts +29 -1
  17. package/lib/analysis/storage.js +39 -6
  18. package/lib/analysis/tools.js +270 -29
  19. package/lib/analysis/types.d.ts +257 -3
  20. package/lib/analysis/types.js +31 -1
  21. package/lib/analysis/validation.d.ts +37 -1
  22. package/lib/analysis/validation.js +315 -1
  23. package/lib/chart/tool.js +1 -0
  24. package/lib/data-collector/store.d.ts +7 -1
  25. package/lib/data-collector/store.js +14 -0
  26. package/lib/python-runtime/child-env.d.ts +4 -2
  27. package/lib/python-runtime/child-env.js +21 -14
  28. package/lib/python-runtime/manager.d.ts +8 -0
  29. package/lib/python-runtime/manager.js +30 -14
  30. package/lib/sources/tencent-http.js +9 -3
  31. package/lib/web-retriever/local-fetch.d.ts +1 -1
  32. package/lib/web-retriever/local-fetch.js +1 -1
  33. package/lib/web-retriever/wind-client.d.ts +1 -1
  34. package/lib/web-retriever/wind-client.js +1 -1
  35. package/package.json +2 -1
  36. package/plugin-page/README.en.md +1 -1
  37. package/plugin-page/README.zh.md +1 -1
  38. package/preset/capital-generation/agent.patch.yml +1 -1
  39. package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +15 -2
  40. package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +54 -9
  41. package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +41 -7
  42. package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
  43. package/preset/capital-generation/skills/capital-event-impact/SKILL.md +20 -1
  44. package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
  45. package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +38 -8
  46. package/python/analysis/lib/__init__.py +9 -0
  47. package/python/analysis/lib/errors.py +12 -0
  48. package/python/analysis/lib/eventstudy.py +164 -0
  49. package/python/analysis/lib/frames.py +95 -0
  50. package/python/analysis/lib/gaps.py +54 -0
  51. package/python/analysis/lib/jsonio.py +61 -0
  52. package/python/analysis/lib/metrics.py +147 -0
  53. package/python/analysis/lib/pit.py +84 -0
  54. package/python/analysis/lib/prices.py +140 -0
  55. package/python/analysis/lib/timeaxis.py +142 -0
  56. package/python/analysis/lib/version.py +3 -0
  57. package/python/analysis/modules/comps_valuation/module.py +26 -59
  58. package/python/analysis/modules/earnings_bridge/module.py +20 -77
  59. package/python/analysis/modules/event_study/LICENSE +21 -0
  60. package/python/analysis/modules/event_study/module.json +217 -0
  61. package/python/analysis/modules/event_study/module.py +979 -0
  62. package/python/analysis/modules/financial_quality/module.py +25 -88
  63. package/python/analysis/modules/hello/module.py +4 -0
  64. package/python/analysis/modules/kline_quality/module.py +26 -132
  65. package/python/analysis/modules/portfolio_stress/module.py +27 -112
  66. package/python/analysis/modules/returns_risk/module.json +108 -25
  67. package/python/analysis/modules/returns_risk/module.py +68 -227
  68. package/python/analysis/modules/scenario_sensitivity/module.py +11 -44
  69. package/python/analysis/modules/simple_backtest/module.json +244 -36
  70. package/python/analysis/modules/simple_backtest/module.py +1146 -459
  71. package/python/analysis/modules/statement_integrity/module.py +35 -87
  72. package/python/analysis/modules/technical_indicators/module.py +33 -152
  73. package/python/analysis/modules/valuation_sensitivity/module.py +30 -61
  74. package/python/worker.py +5 -0
  75. package/watchlist/package.json +1 -1
@@ -0,0 +1,164 @@
1
+ """Event-study primitives: event timestamp parsing, session alignment and the market model.
2
+
3
+ An event study asks what a price did around a dated event. Two things decide whether the answer
4
+ means anything, and both live here so the modules cannot disagree about them:
5
+
6
+ - **When the event became knowable.** An announcement stamped `18:30` on a Friday is not tradeable
7
+ until the next session, while `08:30` the same morning is tradeable that day. `align_event` maps
8
+ the timestamp to the day whose return can legitimately react to it, and says when it had to roll.
9
+ - **What "expected" means.** `market_adjusted` takes the benchmark's same-day return as expected;
10
+ `market_model` fits OLS `r = alpha + beta * rm` on an estimation window that must not overlap the
11
+ event window. `market_model` returns raw coefficients; rounding stays at the JSON boundary.
12
+
13
+ Pure standard library on purpose: the arithmetic must be auditable line by line.
14
+ """
15
+ from __future__ import annotations
16
+
17
+ import re
18
+ from bisect import bisect_left, bisect_right
19
+ from datetime import datetime, timedelta, timezone
20
+
21
+ MARKET_MODELS = ("market_adjusted", "market_model")
22
+ METHOD_VERSIONS = {
23
+ "market_adjusted": "event-study/market-adjust-v1",
24
+ "market_model": "event-study/market-model-v1",
25
+ }
26
+
27
+ DATE_ONLY = re.compile(r"^(\d{4})-(\d{2})-(\d{2})$")
28
+ SLASH_DATE_ONLY = re.compile(r"^(\d{4})/(\d{2})/(\d{2})$")
29
+ DATE_TIME = re.compile(
30
+ r"^(\d{4})-(\d{2})-(\d{2})[T ](\d{2}):(\d{2})(?::(\d{2}))?(Z|[+-]\d{2}:\d{2})?$"
31
+ )
32
+ SECOND = 1000.0
33
+
34
+
35
+ def _stamp_from(fields, tz, offset):
36
+ """Build an aware datetime; the offset form wins, naive input is read in the caller's zone."""
37
+ year, month, day, hour, minute, second = fields
38
+ if offset == "Z":
39
+ zone = timezone.utc
40
+ elif offset is not None:
41
+ hours, minutes = int(offset[1:3]), int(offset[4:6])
42
+ if hours > 23 or minutes > 59:
43
+ return None
44
+ sign = -1 if offset[0] == "-" else 1
45
+ zone = timezone(sign * timedelta(hours=hours, minutes=minutes))
46
+ else:
47
+ zone = tz
48
+ try:
49
+ return datetime(year, month, day, hour, minute, second, tzinfo=zone).astimezone(tz)
50
+ except ValueError:
51
+ return None
52
+
53
+
54
+ def parse_event_time(value, tz):
55
+ """Return `{"day", "has_time", "minute"}` for a usable event timestamp, else `None`.
56
+
57
+ Accepted shapes: `YYYY-MM-DD`, `YYYY/MM/DD`, `YYYY-MM-DDTHH:MM[:SS]` with an optional `Z` or
58
+ `±HH:MM` suffix, and epoch milliseconds. A timestamp with an offset is converted into `tz`
59
+ before the local day and minute are read; a naive timestamp is read in `tz`. A date-only value
60
+ keeps `has_time=False` and `minute=None` so the caller can align conservatively.
61
+ """
62
+ if isinstance(value, bool) or value is None:
63
+ return None
64
+ if isinstance(value, (int, float)):
65
+ number = float(value)
66
+ if number != number or number in (float("inf"), float("-inf")):
67
+ return None
68
+ try:
69
+ stamp = datetime.fromtimestamp(number / SECOND, tz=tz)
70
+ except (OverflowError, OSError, ValueError):
71
+ return None
72
+ return {"day": stamp.strftime("%Y-%m-%d"), "has_time": True, "minute": stamp.hour * 60 + stamp.minute}
73
+ if not isinstance(value, str):
74
+ return None
75
+ text = value.strip()
76
+ match = DATE_ONLY.match(text) or SLASH_DATE_ONLY.match(text)
77
+ if match is not None:
78
+ year, month, day = (int(part) for part in match.groups())
79
+ try:
80
+ datetime(year, month, day)
81
+ except ValueError:
82
+ return None
83
+ return {"day": f"{year:04d}-{month:02d}-{day:02d}", "has_time": False, "minute": None}
84
+ match = DATE_TIME.match(text)
85
+ if match is None:
86
+ return None
87
+ year, month, day, hour, minute = (int(part) for part in match.groups()[:5])
88
+ second = int(match.group(6) or 0)
89
+ stamp = _stamp_from((year, month, day, hour, minute, second), tz, match.group(7))
90
+ if stamp is None:
91
+ return None
92
+ return {"day": stamp.strftime("%Y-%m-%d"), "has_time": True, "minute": stamp.hour * 60 + stamp.minute}
93
+
94
+
95
+ def session_of(minute, open_minute, close_minute):
96
+ """Which part of the trading day a minute-of-day falls in (`pre_open` / `intraday` / `after_close`)."""
97
+ if minute < open_minute:
98
+ return "pre_open"
99
+ if minute < close_minute:
100
+ return "intraday"
101
+ return "after_close"
102
+
103
+
104
+ def _first_after(days, day):
105
+ index = bisect_right(days, day)
106
+ return days[index] if index < len(days) else None
107
+
108
+
109
+ def align_event(event, trading_days, bar_days, open_minute=570, close_minute=900):
110
+ """Map an event timestamp to the session expected to react to it.
111
+
112
+ Returns `{"session", "scheduled_day", "bar_day", "rolled"}`. Conservative by construction:
113
+
114
+ - a date-only event is placed on the first trading day **strictly after** its date, because a
115
+ day label alone cannot prove the event was knowable before that session's close;
116
+ - an event on a non-trading day rolls to the next trading day;
117
+ - `pre_open` / `intraday` events land on their own trading day, `after_close` rolls forward;
118
+ - `bar_day` additionally skips dates with no bar (suspension), and `rolled` records that skip.
119
+ """
120
+ days = sorted(set(trading_days))
121
+ bars = sorted(set(bar_days))
122
+ day = event["day"]
123
+ if not event["has_time"]:
124
+ session = "date_only"
125
+ earliest = _first_after(days, day)
126
+ elif day not in set(days):
127
+ session = "non_trading"
128
+ earliest = _first_after(days, day)
129
+ else:
130
+ session = session_of(event["minute"], open_minute, close_minute)
131
+ earliest = _first_after(days, day) if session == "after_close" else day
132
+ scheduled = None
133
+ if earliest is not None:
134
+ index = bisect_left(days, earliest)
135
+ scheduled = days[index] if index < len(days) else None
136
+ bar_day = None
137
+ if scheduled is not None:
138
+ index = bisect_left(bars, scheduled)
139
+ bar_day = bars[index] if index < len(bars) else None
140
+ return {
141
+ "session": session,
142
+ "scheduled_day": scheduled,
143
+ "bar_day": bar_day,
144
+ "rolled": bool(scheduled is not None and bar_day is not None and bar_day != scheduled),
145
+ }
146
+
147
+
148
+ def market_model(returns, market_returns):
149
+ """OLS `r = alpha + beta * rm`; `None` when there are fewer than two pairs or no market variance."""
150
+ if len(returns) != len(market_returns) or len(returns) < 2:
151
+ return None
152
+ count = len(returns)
153
+ mean_market = sum(market_returns) / count
154
+ mean_return = sum(returns) / count
155
+ covariance = 0.0
156
+ variance = 0.0
157
+ for value, market in zip(returns, market_returns):
158
+ deviation = market - mean_market
159
+ covariance += deviation * (value - mean_return)
160
+ variance += deviation * deviation
161
+ if variance == 0:
162
+ return None
163
+ beta = covariance / variance
164
+ return {"alpha": mean_return - beta * mean_market, "beta": beta, "observations": count}
@@ -0,0 +1,95 @@
1
+ """Dataset-view framing: columns, numeric cells, table reads and period-key indexing.
2
+
3
+ Views arrive from `context.read_dataset` as the shape the host staged (`shape == "rows"`). These
4
+ helpers are deliberately strict: a missing column is a named error, never an empty series.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from .errors import AnalysisInputError
9
+
10
+
11
+ def columns_of(view):
12
+ """Column names from the staged schema plus every row (heterogeneous rows still count)."""
13
+ names = set()
14
+ for item in view.get("columns") or []:
15
+ if isinstance(item, dict):
16
+ name = item.get("name")
17
+ if isinstance(name, str):
18
+ names.add(name)
19
+ for row in view.get("rows") or []:
20
+ if isinstance(row, dict):
21
+ names |= set(row)
22
+ return names
23
+
24
+
25
+ def number(row, name):
26
+ """A finite numeric cell, else `None`: a bad cell is a gap, not a zero."""
27
+ if row is None:
28
+ return None
29
+ value = row.get(name)
30
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
31
+ return None
32
+ number_ = float(value)
33
+ if number_ != number_ or number_ in (float("inf"), float("-inf")):
34
+ return None
35
+ return number_
36
+
37
+
38
+ def text(value):
39
+ return value if isinstance(value, str) and value.strip() else None
40
+
41
+
42
+ def require_text(value, label, *, required=False):
43
+ if value is None and not required:
44
+ return None
45
+ if not isinstance(value, str) or not value.strip():
46
+ raise AnalysisInputError(f"{label} 必须是非空字符串")
47
+ return value.strip()
48
+
49
+
50
+ def read_views(request, context, *, module_id, empty_message):
51
+ """Read every Dataset of the request as a staged view; a document view is refused."""
52
+ items = (request.get("inputs") or {}).get("datasets") or []
53
+ if not items:
54
+ raise AnalysisInputError(empty_message)
55
+ views = {}
56
+ for item in items:
57
+ dataset_id = (item or {}).get("dataset_id")
58
+ if not isinstance(dataset_id, str) or not dataset_id:
59
+ raise AnalysisInputError("request.inputs.datasets 里有缺失 dataset_id 的条目")
60
+ views[dataset_id] = context.read_dataset(dataset_id)
61
+ for dataset_id, view in views.items():
62
+ if view.get("shape") != "rows":
63
+ raise AnalysisInputError(
64
+ f"Dataset {dataset_id} 是 {view.get('shape')} 型:{module_id} 只吃表格数据,"
65
+ "文档型输入请先走 profile 或证据"
66
+ )
67
+ return views
68
+
69
+
70
+ def index_rows(view, column, label):
71
+ """Rows keyed by one period column; an empty or duplicated key is an input error."""
72
+ indexed = {}
73
+ for row in view.get("rows") or []:
74
+ if not isinstance(row, dict):
75
+ raise AnalysisInputError(f"{label}的数据行不是对象:无法计算")
76
+ key = row.get(column)
77
+ if isinstance(key, bool) or not isinstance(key, (int, float, str)) or key == "":
78
+ raise AnalysisInputError(f"{label}的 {column} 列有空值:无法对齐报告期")
79
+ if key in indexed:
80
+ raise AnalysisInputError(f"{label}在报告期 {key} 出现多行:无法判断用哪一行(请先去重)")
81
+ indexed[key] = row
82
+ return indexed
83
+
84
+
85
+ def row_at(rows_by_role, key, role):
86
+ row = rows_by_role.get(role, {}).get(key)
87
+ return row if isinstance(row, dict) else None
88
+
89
+
90
+ def join_key(views, roles, *, period_keys, hint):
91
+ """The first period column present in every role's view: the join axis for cross-statement rows."""
92
+ for column in period_keys:
93
+ if all(column in columns_of(views[dataset_id]) for dataset_id in roles.values()):
94
+ return column
95
+ raise AnalysisInputError(hint)
@@ -0,0 +1,54 @@
1
+ """Data-gap vocabulary: every gap starts with one of these prefixes.
2
+
3
+ The host rejects an unregistered prefix, because a free-text gap cannot be counted, aggregated or
4
+ turned into a rule. Prefixes are protocol, not prose.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ PREFIXES = (
9
+ "source_unavailable",
10
+ "field_missing",
11
+ "period_conflict",
12
+ "time_unavailable",
13
+ "adjustment_unknown",
14
+ "calendar_mismatch",
15
+ "sample_insufficient",
16
+ "assumption_missing",
17
+ )
18
+
19
+
20
+ def _gap(prefix, text):
21
+ return f"{prefix}: {text}"
22
+
23
+
24
+ def source_unavailable(text):
25
+ return _gap("source_unavailable", text)
26
+
27
+
28
+ def field_missing(text):
29
+ return _gap("field_missing", text)
30
+
31
+
32
+ def period_conflict(text):
33
+ return _gap("period_conflict", text)
34
+
35
+
36
+ def time_unavailable(text):
37
+ return _gap("time_unavailable", text)
38
+
39
+
40
+ def adjustment_unknown(text):
41
+ return _gap("adjustment_unknown", text)
42
+
43
+
44
+ def calendar_mismatch(text):
45
+ return _gap("calendar_mismatch", text)
46
+
47
+
48
+ def sample_insufficient(text):
49
+ return _gap("sample_insufficient", text)
50
+
51
+
52
+ def assumption_missing(text):
53
+ return _gap("assumption_missing", text)
54
+
@@ -0,0 +1,61 @@
1
+ """Numbers as they cross the JSON boundary: one rounding rule, one formatter set, no NaN escapes."""
2
+ from .errors import AnalysisInputError
3
+
4
+ ROUND_DIGITS = 6
5
+
6
+
7
+ def round_metric(value, digits=ROUND_DIGITS):
8
+ """Six decimals by default; `-0.0` becomes `0.0` so the artifact never shows a signed zero."""
9
+ rounded = round(float(value), digits)
10
+ return 0.0 if rounded == 0 else rounded
11
+
12
+
13
+ def round_or_none(value, digits=ROUND_DIGITS):
14
+ """Variant for modules that expose optional indicators: `None`/non-finite becomes `None`."""
15
+ if value is None:
16
+ return None
17
+ number = float(value)
18
+ if number != number or number in (float("inf"), float("-inf")):
19
+ return None
20
+ rounded = round(number, digits)
21
+ return 0.0 if rounded == 0 else rounded
22
+
23
+
24
+ def pct(value):
25
+ return f"{value * 100:.2f}%"
26
+
27
+
28
+ def ratio(value):
29
+ return f"{value:.4f}"
30
+
31
+
32
+ def fmt6(value):
33
+ """Six decimals with trailing zeros trimmed: the same shape the metrics are rounded to."""
34
+ text = f"{round_metric(value):.6f}".rstrip("0").rstrip(".")
35
+ return text if text not in ("", "-0") else "0"
36
+
37
+
38
+ def fmt6_fixed(value):
39
+ """Six decimals without trimming: some methodology/adjustment texts must keep the scale."""
40
+ return f"{value:.6f}"
41
+
42
+
43
+ def plain(value):
44
+ """Integral floats as ints: the audit file then shows 100000000000, not 100000000000.0."""
45
+ return int(value) if isinstance(value, float) and value.is_integer() else value
46
+
47
+
48
+ def require_number(value, label):
49
+ """A caller parameter that must be a finite number; anything else is an input error."""
50
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
51
+ raise AnalysisInputError(f"{label} 必须是数字,实际是 {value!r}")
52
+ number = float(value)
53
+ if number != number or number in (float("inf"), float("-inf")):
54
+ raise AnalysisInputError(f"{label} 必须是有限数字,实际是 {value!r}")
55
+ return number
56
+
57
+
58
+ def sample_values(values):
59
+ """First few raw values in a gap message; enough to locate the bad rows, not a data dump."""
60
+ shown = "、".join(str(value) for value in values[:5])
61
+ return shown if len(values) <= 5 else f"{shown} 等 {len(values)} 行"
@@ -0,0 +1,147 @@
1
+ """Return/risk metrics, one implementation. Modules import these instead of copying the formulas.
2
+
3
+ Every function is a pure function over floats; rounding stays in `jsonio.round_metric`.
4
+ """
5
+ from __future__ import annotations
6
+
7
+ import math
8
+
9
+ from .jsonio import round_metric
10
+
11
+
12
+ def returns_from_closes(closes):
13
+ """Simple close-to-close returns; the caller guarantees the closes are adjacent bars."""
14
+ return [closes[index] / closes[index - 1] - 1.0 for index in range(1, len(closes))]
15
+
16
+
17
+ def variance(values):
18
+ mean = sum(values) / len(values)
19
+ return sum((value - mean) ** 2 for value in values) / (len(values) - 1), mean
20
+
21
+
22
+ def quantile(values, q):
23
+ if not values:
24
+ return None
25
+ position = (len(values) - 1) * q
26
+ lower = int(math.floor(position))
27
+ upper = int(math.ceil(position))
28
+ if lower == upper:
29
+ return values[lower]
30
+ weight = position - lower
31
+ return values[lower] * (1.0 - weight) + values[upper] * weight
32
+
33
+
34
+ def max_drawdown(values):
35
+ """Deepest close/equity drawdown from a running peak, as a negative ratio (0.0 if none)."""
36
+ peak, worst = values[0], 0.0
37
+ for value in values:
38
+ peak = max(peak, value)
39
+ worst = min(worst, value / peak - 1.0)
40
+ return worst
41
+
42
+
43
+ def total_return(values):
44
+ return values[-1] / values[0] - 1.0
45
+
46
+
47
+ def drawdown_duration(values):
48
+ """Longest run of bars below a previous peak (0 when the series only rises)."""
49
+ peak, start, longest = values[0], 0, 0
50
+ for index, value in enumerate(values):
51
+ if value >= peak:
52
+ peak, start = value, index
53
+ continue
54
+ longest = max(longest, index - start)
55
+ return longest
56
+
57
+
58
+ def tracking_error(active_returns, periods_per_year):
59
+ if len(active_returns) < 2:
60
+ return None
61
+ spread, _mean = variance(active_returns)
62
+ return math.sqrt(spread) * math.sqrt(periods_per_year)
63
+
64
+
65
+ def information_ratio(annualized_excess, tracking_error_value):
66
+ return annualized_excess / tracking_error_value if tracking_error_value and tracking_error_value > 0 else None
67
+
68
+
69
+ def profit_factor(net_returns):
70
+ gains = sum(value for value in net_returns if value > 0)
71
+ losses = -sum(value for value in net_returns if value < 0)
72
+ return gains / losses if losses > 0 else None
73
+
74
+
75
+ def payoff_ratio(net_returns):
76
+ wins = [value for value in net_returns if value > 0]
77
+ losses = [value for value in net_returns if value < 0]
78
+ if not wins or not losses:
79
+ return None
80
+ return (sum(wins) / len(wins)) / abs(sum(losses) / len(losses))
81
+
82
+
83
+ def annualized_return(returns_count, total, periods_per_year):
84
+ return (1.0 + total) ** (periods_per_year / returns_count) - 1.0
85
+
86
+
87
+ def annualized_volatility(returns, periods_per_year):
88
+ variance_, _mean = variance(returns)
89
+ return math.sqrt(variance_) * math.sqrt(periods_per_year)
90
+
91
+
92
+ def sharpe(annualized, risk_free_rate, volatility):
93
+ return (annualized - risk_free_rate) / volatility if volatility > 0 else None
94
+
95
+
96
+ def sortino(returns, annualized, risk_free_rate, periods_per_year):
97
+ downside = math.sqrt(sum(min(value, 0.0) ** 2 for value in returns) / len(returns)) * math.sqrt(periods_per_year)
98
+ return (annualized - risk_free_rate) / downside if downside > 0 else None
99
+
100
+
101
+ def calmar(annualized, drawdown):
102
+ return annualized / abs(drawdown) if drawdown < 0 else None
103
+
104
+
105
+ def var_cvar(returns, confidence):
106
+ """Historical one-period loss: positive numbers are losses (VaR/CVaR conventions)."""
107
+ ordered = sorted(returns)
108
+ cut = quantile(ordered, 1.0 - confidence)
109
+ value_at_risk = 0.0 if cut is None or cut >= 0 else -cut
110
+ tail = [value for value in returns if cut is not None and value <= cut]
111
+ cvar = -sum(tail) / len(tail) if tail and cut is not None and cut < 0 else 0.0
112
+ return value_at_risk, cvar
113
+
114
+
115
+ def risk_metrics(returns, total, drawdown, periods_per_year, risk_free_rate, confidence):
116
+ """The interval risk block shared by the series modules (rounded like every other metric).
117
+
118
+ `returns` are adjacent-bar returns only: a hole in the series must never be counted as one bar,
119
+ so the caller drops the pair instead of bridging it, and `total`/`drawdown` come from the price
120
+ levels the caller kept.
121
+ """
122
+ count = len(returns)
123
+ annualized = annualized_return(count, total, periods_per_year)
124
+ volatility = annualized_volatility(returns, periods_per_year)
125
+ _variance, mean_return = variance(returns)
126
+ value_at_risk, cvar = var_cvar(returns, confidence)
127
+ metrics = {
128
+ "returns_count": count,
129
+ "total_return": round_metric(total),
130
+ "annualized_return": round_metric(annualized),
131
+ "annualized_volatility": round_metric(volatility),
132
+ "max_drawdown": round_metric(drawdown),
133
+ "mean_daily_return": round_metric(mean_return),
134
+ "best_day": round_metric(max(returns)),
135
+ "worst_day": round_metric(min(returns)),
136
+ "positive_day_ratio": round_metric(sum(1 for value in returns if value > 0) / count),
137
+ "var": round_metric(value_at_risk),
138
+ "cvar": round_metric(cvar),
139
+ }
140
+ for name, value in (
141
+ ("sharpe_ratio", sharpe(annualized, risk_free_rate, volatility)),
142
+ ("sortino_ratio", sortino(returns, annualized, risk_free_rate, periods_per_year)),
143
+ ("calmar_ratio", calmar(annualized, drawdown)),
144
+ ):
145
+ if value is not None:
146
+ metrics[name] = round_metric(value)
147
+ return metrics
@@ -0,0 +1,84 @@
1
+ """Point-in-time helpers: what was knowable at `as_of`, and the two ways data can violate it.
2
+
3
+ Metatada-level checks (`available_at <= as_of`) run in the host when the snapshot is created. These
4
+ are the row-level primitives a module uses on the rows it actually reads.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ from . import gaps
9
+ from .errors import AnalysisInputError
10
+ from .timeaxis import as_of_day, day_of, disclosure_column, period_column, temporal_of
11
+
12
+ __all__ = [
13
+ "as_of_day", "day_of", "disclosure_column", "period_column", "temporal_of",
14
+ "require_bar_available", "filter_known_rows", "disclosure_day",
15
+ ]
16
+
17
+
18
+ def require_bar_available(day, temporal, dataset_id):
19
+ """A bar later than `as_of` must not be used under `as_known_then`; `ex_post` allows it."""
20
+ if temporal.get("mode") != "as_known_then":
21
+ return
22
+ boundary = as_of_day(temporal)
23
+ if boundary is None:
24
+ raise AnalysisInputError(
25
+ f"as_known_then 快照缺少可解析的 as_of:无法判断 Dataset {dataset_id} 的 bar 是否可知",
26
+ code="analysis_point_in_time_conflict",
27
+ )
28
+ if day > boundary:
29
+ raise AnalysisInputError(
30
+ f"Dataset {dataset_id} 的 {day} 晚于 as_of {boundary}:as_known_then 不能使用未来 bar",
31
+ code="analysis_point_in_time_conflict",
32
+ )
33
+
34
+
35
+ def disclosure_day(row, column):
36
+ return day_of((row or {}).get(column))
37
+
38
+
39
+ def filter_known_rows(view, temporal, dataset_id):
40
+ """Keep only rows disclosed by `as_of`; a statement table without disclosure time is refused.
41
+
42
+ Filtering is the statement analogue of "don't use the future": a report whose disclosure date is
43
+ after `as_of` was simply not knowable then, so it drops out with a `period_conflict` gap.
44
+ """
45
+ rows = view.get("rows") or []
46
+ if temporal.get("mode") != "as_known_then":
47
+ return rows, []
48
+ columns = set()
49
+ for item in view.get("columns") or []:
50
+ if isinstance(item, dict) and isinstance(item.get("name"), str):
51
+ columns.add(item["name"])
52
+ for row in rows[:1]:
53
+ if isinstance(row, dict):
54
+ columns |= set(row)
55
+ column = disclosure_column(columns)
56
+ if column is None:
57
+ period = period_column(columns)
58
+ detail = f"(只有报告期列 {period},不能回填披露日)" if period is not None else ""
59
+ raise AnalysisInputError(
60
+ f"Dataset {dataset_id} 没有披露日列,as_known_then 下无法判断 {len(rows)} 行何时可知{detail}",
61
+ code="analysis_event_time_missing",
62
+ )
63
+ boundary = as_of_day(temporal)
64
+ if boundary is None:
65
+ raise AnalysisInputError(
66
+ f"as_known_then 快照缺少可解析的 as_of:无法过滤 Dataset {dataset_id} 的报告期",
67
+ code="analysis_point_in_time_conflict",
68
+ )
69
+ kept, dropped = [], []
70
+ for row in rows:
71
+ day = disclosure_day(row, column)
72
+ if day is None:
73
+ dropped.append("(披露日无法解析)")
74
+ elif day > boundary:
75
+ dropped.append(day)
76
+ else:
77
+ kept.append(row)
78
+ if not dropped:
79
+ return kept, []
80
+ shown = "、".join(str(item) for item in dropped[:5])
81
+ more = f" 等 {len(dropped)} 行" if len(dropped) > 5 else ""
82
+ return kept, [gaps.period_conflict(
83
+ f"Dataset {dataset_id} 有 {len(dropped)} 行在 as_of {boundary} 之后才披露({shown}{more}):已按 PIT 排除"
84
+ )]