@v587d/capital-generation 2.31.8 → 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.
- package/CHANGELOG.md +44 -0
- package/README.md +14 -5
- package/automation/package.json +1 -1
- package/chart-ui/package.json +1 -1
- package/config/package.json +1 -1
- package/lib/analysis/artifact.d.ts +35 -0
- package/lib/analysis/artifact.js +250 -0
- package/lib/analysis/registry.d.ts +16 -2
- package/lib/analysis/registry.js +133 -23
- package/lib/analysis/runtime.d.ts +46 -19
- package/lib/analysis/runtime.js +485 -116
- package/lib/analysis/schemas.d.ts +46 -0
- package/lib/analysis/schemas.js +260 -7
- package/lib/analysis/snapshot.d.ts +10 -3
- package/lib/analysis/snapshot.js +298 -46
- package/lib/analysis/storage.d.ts +29 -1
- package/lib/analysis/storage.js +39 -6
- package/lib/analysis/tools.js +270 -29
- package/lib/analysis/types.d.ts +257 -3
- package/lib/analysis/types.js +31 -1
- package/lib/analysis/validation.d.ts +37 -1
- package/lib/analysis/validation.js +315 -1
- package/lib/chart/tool.js +1 -0
- package/lib/data-collector/store.d.ts +7 -1
- package/lib/data-collector/store.js +14 -0
- package/lib/python-runtime/child-env.d.ts +4 -2
- package/lib/python-runtime/child-env.js +21 -14
- package/lib/python-runtime/manager.d.ts +8 -0
- package/lib/python-runtime/manager.js +30 -14
- package/lib/web-retriever/local-fetch.d.ts +1 -1
- package/lib/web-retriever/local-fetch.js +1 -1
- package/lib/web-retriever/wind-client.d.ts +1 -1
- package/lib/web-retriever/wind-client.js +1 -1
- package/package.json +2 -1
- package/plugin-page/README.en.md +1 -1
- package/plugin-page/README.zh.md +1 -1
- package/preset/capital-generation/agent.patch.yml +1 -1
- package/preset/capital-generation/skills/capital-analysis-evidence/SKILL.md +15 -2
- package/preset/capital-generation/skills/capital-analysis-synthesis/SKILL.md +54 -9
- package/preset/capital-generation/skills/capital-analysis-validation/SKILL.md +41 -7
- package/preset/capital-generation/skills/capital-equity-research/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-event-impact/SKILL.md +20 -1
- package/preset/capital-generation/skills/capital-orchestration/SKILL.md +1 -1
- package/preset/capital-generation/skills/capital-senior-analysis/SKILL.md +38 -8
- package/python/analysis/lib/__init__.py +9 -0
- package/python/analysis/lib/errors.py +12 -0
- package/python/analysis/lib/eventstudy.py +164 -0
- package/python/analysis/lib/frames.py +95 -0
- package/python/analysis/lib/gaps.py +54 -0
- package/python/analysis/lib/jsonio.py +61 -0
- package/python/analysis/lib/metrics.py +147 -0
- package/python/analysis/lib/pit.py +84 -0
- package/python/analysis/lib/prices.py +140 -0
- package/python/analysis/lib/timeaxis.py +142 -0
- package/python/analysis/lib/version.py +3 -0
- package/python/analysis/modules/comps_valuation/module.py +26 -59
- package/python/analysis/modules/earnings_bridge/module.py +20 -77
- package/python/analysis/modules/event_study/LICENSE +21 -0
- package/python/analysis/modules/event_study/module.json +217 -0
- package/python/analysis/modules/event_study/module.py +979 -0
- package/python/analysis/modules/financial_quality/module.py +25 -88
- package/python/analysis/modules/hello/module.py +4 -0
- package/python/analysis/modules/kline_quality/module.py +26 -132
- package/python/analysis/modules/portfolio_stress/module.py +27 -112
- package/python/analysis/modules/returns_risk/module.json +108 -25
- package/python/analysis/modules/returns_risk/module.py +68 -227
- package/python/analysis/modules/scenario_sensitivity/module.py +11 -44
- package/python/analysis/modules/simple_backtest/module.json +244 -36
- package/python/analysis/modules/simple_backtest/module.py +1146 -459
- package/python/analysis/modules/statement_integrity/module.py +35 -87
- package/python/analysis/modules/technical_indicators/module.py +33 -152
- package/python/analysis/modules/valuation_sensitivity/module.py +30 -61
- package/python/worker.py +5 -0
- package/watchlist/package.json +1 -1
|
@@ -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
|
+
)]
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
"""Price series: column discovery, ordered points, bad-row handling and period-in-time gate.
|
|
2
|
+
|
|
3
|
+
A bad row is skipped and reported; the return that would have bridged the hole is **not** computed,
|
|
4
|
+
because counting a multi-day jump as one daily return would silently inflate volatility and Sharpe.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from . import gaps
|
|
9
|
+
from .errors import AnalysisInputError
|
|
10
|
+
from .frames import columns_of, number
|
|
11
|
+
from .pit import require_bar_available
|
|
12
|
+
from .timeaxis import parse_time, temporal_of, time_column
|
|
13
|
+
PRICE_COLUMNS = ("close", "adj_close", "close_price", "price", "nav")
|
|
14
|
+
ADJUST_COLUMNS = ("adjust", "adjust_type", "adjustment", "price_adjust", "adjust_flag")
|
|
15
|
+
ADJUST_LABELS = {
|
|
16
|
+
"qfq": "qfq", "前复权": "qfq", "forward": "qfq",
|
|
17
|
+
"hfq": "hfq", "后复权": "hfq", "backward": "hfq",
|
|
18
|
+
"none": "none", "不复权": "none", "raw": "none", "": "none",
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def price_column(view, override):
|
|
23
|
+
names = columns_of(view)
|
|
24
|
+
if override is not None:
|
|
25
|
+
if override not in names:
|
|
26
|
+
raise AnalysisInputError(f"price_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
|
|
27
|
+
return override
|
|
28
|
+
for name in PRICE_COLUMNS:
|
|
29
|
+
if name in names:
|
|
30
|
+
return name
|
|
31
|
+
raise AnalysisInputError(
|
|
32
|
+
"找不到价格列:需要 close / adj_close / close_price / price / nav 之一(或用 price_column 指明);"
|
|
33
|
+
f"现有列:{sorted(names)}"
|
|
34
|
+
)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def candidate(views, price_override, time_override):
|
|
38
|
+
"""Dataset ids that look like a price series (a time column plus a price column)."""
|
|
39
|
+
candidates = []
|
|
40
|
+
for dataset_id, view in sorted(views.items()):
|
|
41
|
+
try:
|
|
42
|
+
time_column(view, time_override)
|
|
43
|
+
price_column(view, price_override)
|
|
44
|
+
except AnalysisInputError:
|
|
45
|
+
continue
|
|
46
|
+
candidates.append((dataset_id, time_column(view, time_override)))
|
|
47
|
+
return candidates
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def adjustment_conflict(view):
|
|
51
|
+
"""Mixed adjustment regimes in one series make every return ambiguous; refuse instead of guessing."""
|
|
52
|
+
names = columns_of(view)
|
|
53
|
+
column = next((name for name in ADJUST_COLUMNS if name in names), None)
|
|
54
|
+
if column is None:
|
|
55
|
+
return None
|
|
56
|
+
seen = set()
|
|
57
|
+
for row in view.get("rows") or []:
|
|
58
|
+
if not isinstance(row, dict):
|
|
59
|
+
continue
|
|
60
|
+
value = row.get(column)
|
|
61
|
+
if value is None:
|
|
62
|
+
continue
|
|
63
|
+
label = ADJUST_LABELS.get(str(value).strip().lower(), str(value).strip().lower())
|
|
64
|
+
seen.add(label)
|
|
65
|
+
if len(seen) <= 1:
|
|
66
|
+
return None
|
|
67
|
+
return f"Dataset 的 {column} 列混用了 {sorted(seen)}:同一序列不能混用复权口径({gaps.adjustment_unknown('请在取数时统一复权口径')})"
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def series(view, dataset_id, price_column_name, time_column_name, tz, *, request=None, temporal=None):
|
|
71
|
+
"""Ordered price points plus the raw values of the rows that were skipped.
|
|
72
|
+
|
|
73
|
+
Under `as_known_then` a bar whose day is after `as_of` is a hard input error: the snapshot
|
|
74
|
+
claims to be known-as-of that date, so using a later bar would leak the future into the result.
|
|
75
|
+
"""
|
|
76
|
+
rows = view.get("rows") or []
|
|
77
|
+
if not rows:
|
|
78
|
+
raise AnalysisInputError(f"Dataset {dataset_id} 没有数据行:无法计算收益与风险")
|
|
79
|
+
conflict = adjustment_conflict(view)
|
|
80
|
+
if conflict is not None:
|
|
81
|
+
raise AnalysisInputError(conflict, code="analysis_adjustment_unknown")
|
|
82
|
+
resolved_temporal = temporal if temporal is not None else temporal_of(request or {})
|
|
83
|
+
points, dropped, kind = [], [], None
|
|
84
|
+
for index, row in enumerate(rows):
|
|
85
|
+
if not isinstance(row, dict):
|
|
86
|
+
raise AnalysisInputError(f"Dataset {dataset_id} 的数据行不是对象:无法计算")
|
|
87
|
+
raw_time = row.get(time_column_name)
|
|
88
|
+
row_kind = "ms" if isinstance(raw_time, (int, float)) and not isinstance(raw_time, bool) else "date"
|
|
89
|
+
if kind is None:
|
|
90
|
+
kind = row_kind
|
|
91
|
+
elif row_kind != kind:
|
|
92
|
+
raise AnalysisInputError(
|
|
93
|
+
f"Dataset {dataset_id} 的 {time_column_name} 列混用了数值时间戳与日期字符串:无法排序,请取数时统一"
|
|
94
|
+
)
|
|
95
|
+
parsed = parse_time(raw_time, tz)
|
|
96
|
+
price = number(row, price_column_name)
|
|
97
|
+
if parsed is None or price is None or price <= 0:
|
|
98
|
+
dropped.append(raw_time)
|
|
99
|
+
continue
|
|
100
|
+
key, day = parsed
|
|
101
|
+
require_bar_available(day, resolved_temporal, dataset_id)
|
|
102
|
+
points.append({"key": key, "day": day, "price": price, "row_index": index})
|
|
103
|
+
points.sort(key=lambda item: item["key"])
|
|
104
|
+
seen = set()
|
|
105
|
+
for point in points:
|
|
106
|
+
if point["day"] in seen:
|
|
107
|
+
raise AnalysisInputError(
|
|
108
|
+
f"Dataset {dataset_id} 在 {point['day']} 出现多行:无法判断用哪一行(请先去重)"
|
|
109
|
+
)
|
|
110
|
+
seen.add(point["day"])
|
|
111
|
+
return points, dropped
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def pair_returns(points, trading_days=None):
|
|
115
|
+
"""Adjacent-bar returns; a pair separated by a skipped row (or a missing calendar day) is a gap.
|
|
116
|
+
|
|
117
|
+
Returns `(pairs, holes)`: `pairs` are `(previous_point, current_point, value)`, `holes` are gap
|
|
118
|
+
strings for the returns that were deliberately not computed.
|
|
119
|
+
"""
|
|
120
|
+
pairs, holes = [], []
|
|
121
|
+
for previous, current in zip(points, points[1:]):
|
|
122
|
+
if current["row_index"] != previous["row_index"] + 1:
|
|
123
|
+
holes.append(gaps.time_unavailable(
|
|
124
|
+
f"{previous['day']} 与 {current['day']} 之间有被跳过的行:这段收益未计入"
|
|
125
|
+
))
|
|
126
|
+
continue
|
|
127
|
+
if trading_days is not None:
|
|
128
|
+
missing = sorted(
|
|
129
|
+
day for day in trading_days
|
|
130
|
+
if previous["day"] < day < current["day"]
|
|
131
|
+
)
|
|
132
|
+
if missing:
|
|
133
|
+
shown = "、".join(missing[:5])
|
|
134
|
+
more = f" 等 {len(missing)} 个交易日" if len(missing) > 5 else ""
|
|
135
|
+
holes.append(gaps.time_unavailable(
|
|
136
|
+
f"{previous['day']} 与 {current['day']} 之间缺少交易日 {shown}{more}:这段收益未计入"
|
|
137
|
+
))
|
|
138
|
+
continue
|
|
139
|
+
pairs.append((previous, current, current["price"] / previous["price"] - 1.0))
|
|
140
|
+
return pairs, holes
|