@v587d/capital-generation 2.31.8 → 2.32.1
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 +68 -0
- package/README.md +11 -7
- 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/sources/ftshare-rest.js +1 -1
- package/lib/sources/tencent-http.js +210 -53
- 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,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
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
"""Time axis: IANA zones, epoch-ms/date-string parsing, day labels and trading-day sets.
|
|
2
|
+
|
|
3
|
+
Daily bars are labelled by their close day in the caller's zone (the dataset timezone is not
|
|
4
|
+
authoritative). `2024-01-01T16:00Z` under `Asia/Shanghai` is `2024-01-02` — the Shanghai-midnight
|
|
5
|
+
case that decides whether a bar is knowable before or after an `as_of` date.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import re
|
|
10
|
+
from datetime import datetime, timezone
|
|
11
|
+
|
|
12
|
+
from .errors import AnalysisInputError
|
|
13
|
+
from .frames import columns_of
|
|
14
|
+
|
|
15
|
+
ISO_DAY = re.compile(r"^(\d{4}-\d{2}-\d{2})")
|
|
16
|
+
TIME_COLUMNS = ("trade_date_ms", "date_ms", "period_end_ms", "datetime", "date", "trade_date", "time")
|
|
17
|
+
# Disclosure columns come before period columns: "when was this knowable" beats "what period".
|
|
18
|
+
DISCLOSURE_COLUMNS = (
|
|
19
|
+
"report_date_ms", "report_date", "announce_date_ms", "announce_date",
|
|
20
|
+
"disclosure_date", "notice_date", "publish_date", "pub_date",
|
|
21
|
+
)
|
|
22
|
+
PERIOD_COLUMNS = ("period_end_ms", "period_end", "period", "report_period", "fiscal_year")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def timezone_of(name):
|
|
26
|
+
"""IANA zone when the caller names one; UTC otherwise (the dataset tz is not authoritative)."""
|
|
27
|
+
if name is None:
|
|
28
|
+
return timezone.utc
|
|
29
|
+
try:
|
|
30
|
+
from zoneinfo import ZoneInfo
|
|
31
|
+
|
|
32
|
+
return ZoneInfo(name)
|
|
33
|
+
except Exception as error: # noqa: BLE001 - any load failure is a caller error
|
|
34
|
+
raise AnalysisInputError(f"timezone={name!r} 无法加载(需要 IANA 时区名,如 Asia/Shanghai)") from error
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def parse_time(value, tz):
|
|
38
|
+
"""Return `(sort_key, day_label)`; `None` when the value is not a usable time."""
|
|
39
|
+
if isinstance(value, bool):
|
|
40
|
+
return None
|
|
41
|
+
if isinstance(value, (int, float)):
|
|
42
|
+
number = float(value)
|
|
43
|
+
if number != number or number in (float("inf"), float("-inf")):
|
|
44
|
+
return None
|
|
45
|
+
try:
|
|
46
|
+
stamp = datetime.fromtimestamp(number / 1000.0, tz=tz)
|
|
47
|
+
except (OverflowError, OSError, ValueError):
|
|
48
|
+
return None
|
|
49
|
+
return number, stamp.strftime("%Y-%m-%d")
|
|
50
|
+
if isinstance(value, str):
|
|
51
|
+
match = ISO_DAY.match(value.strip())
|
|
52
|
+
if match is None:
|
|
53
|
+
return None
|
|
54
|
+
day = match.group(1)
|
|
55
|
+
try:
|
|
56
|
+
stamp = datetime.strptime(day, "%Y-%m-%d").replace(tzinfo=timezone.utc)
|
|
57
|
+
except ValueError:
|
|
58
|
+
return None
|
|
59
|
+
return stamp.timestamp() * 1000.0, day
|
|
60
|
+
return None
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def iso_date(ms):
|
|
64
|
+
return datetime.fromtimestamp(float(ms) / 1000, tz=timezone.utc).strftime("%Y-%m-%d")
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def day_of(value):
|
|
68
|
+
"""ISO day of a date/timestamp cell, or `None` (disclosure dates may be ms or `YYYY-MM-DD`)."""
|
|
69
|
+
parsed = parse_time(value, timezone.utc)
|
|
70
|
+
return None if parsed is None else parsed[1]
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def time_column(view, override):
|
|
74
|
+
names = columns_of(view)
|
|
75
|
+
if override is not None:
|
|
76
|
+
if override not in names:
|
|
77
|
+
raise AnalysisInputError(f"time_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
|
|
78
|
+
return override
|
|
79
|
+
axis = (view.get("time_axis") or {}).get("column")
|
|
80
|
+
if isinstance(axis, str) and axis in names:
|
|
81
|
+
return axis
|
|
82
|
+
for name in TIME_COLUMNS:
|
|
83
|
+
if name in names:
|
|
84
|
+
return name
|
|
85
|
+
raise AnalysisInputError(
|
|
86
|
+
"找不到时间列:需要 time_coverage 列,或 trade_date_ms / date_ms / period_end_ms / datetime / date / trade_date 之一"
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def disclosure_column(columns):
|
|
91
|
+
for name in DISCLOSURE_COLUMNS:
|
|
92
|
+
if name in columns:
|
|
93
|
+
return name
|
|
94
|
+
return None
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def period_column(columns):
|
|
98
|
+
for name in PERIOD_COLUMNS:
|
|
99
|
+
if name in columns:
|
|
100
|
+
return name
|
|
101
|
+
return None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def trading_days_from(view, column=None):
|
|
105
|
+
"""ISO days of a trading-calendar view: one row per day (or one row per day with a flag)."""
|
|
106
|
+
names = columns_of(view)
|
|
107
|
+
selected = column
|
|
108
|
+
if selected is None:
|
|
109
|
+
for candidate in ("trade_date_ms", "date", "trade_date", "datetime", "time"):
|
|
110
|
+
if candidate in names:
|
|
111
|
+
selected = candidate
|
|
112
|
+
break
|
|
113
|
+
if selected is None:
|
|
114
|
+
raise AnalysisInputError("交易日历 Dataset 找不到日期列:需要 trade_date_ms / date / trade_date 之一")
|
|
115
|
+
days = set()
|
|
116
|
+
for row in view.get("rows") or []:
|
|
117
|
+
if not isinstance(row, dict):
|
|
118
|
+
continue
|
|
119
|
+
parsed = parse_time(row.get(selected), timezone.utc)
|
|
120
|
+
if parsed is not None:
|
|
121
|
+
days.add(parsed[1])
|
|
122
|
+
return days
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def temporal_of(request):
|
|
126
|
+
"""The snapshot's temporal contract as the module sees it (v1 requests default to `ex_post`)."""
|
|
127
|
+
temporal = request.get("temporal")
|
|
128
|
+
if not isinstance(temporal, dict):
|
|
129
|
+
return {"mode": "ex_post", "as_of": request.get("as_of"), "data_cutoff": None}
|
|
130
|
+
return {
|
|
131
|
+
"mode": temporal.get("mode") or "ex_post",
|
|
132
|
+
"as_of": temporal.get("as_of") or request.get("as_of"),
|
|
133
|
+
"data_cutoff": temporal.get("data_cutoff"),
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def as_of_day(temporal):
|
|
138
|
+
raw = temporal.get("as_of") if isinstance(temporal, dict) else None
|
|
139
|
+
if not isinstance(raw, str):
|
|
140
|
+
return None
|
|
141
|
+
match = ISO_DAY.match(raw.strip())
|
|
142
|
+
return match.group(1) if match else None
|