@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.
- package/CHANGELOG.md +60 -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/sources/tencent-http.js +9 -3
- 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
|
@@ -1,260 +1,395 @@
|
|
|
1
|
-
"""
|
|
1
|
+
"""Historical simulation of one moving-average rule (the "price series" input shape of the protocol).
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
per round trip, and the standard interval statistics. The signal is computed from bar t's close and
|
|
7
|
-
executed at bar t+1's close, so no close is used before it is knowable; nothing is optimised,
|
|
8
|
-
forecast, rated or recommended.
|
|
3
|
+
This is a *simulation*, not a live-trading claim: the caller supplies explicit parameters, the signal
|
|
4
|
+
is computed from bar t's close and executed at bar t+1's close, and the module reports what the rule
|
|
5
|
+
would have done on that sample under the constraints it could actually verify.
|
|
9
6
|
|
|
10
|
-
|
|
11
|
-
the module runs on the minimal analysis runtime.
|
|
7
|
+
Two simulation grades exist, and the result always says which one ran:
|
|
12
8
|
|
|
13
|
-
|
|
14
|
-
|
|
9
|
+
- `constrained_simulation`: the caller supplied a volume column and a trading-calendar Dataset, so the
|
|
10
|
+
module can refuse fills at limit-up/limit-down, on suspended/zero-volume sessions, under A-share T+1
|
|
11
|
+
and lot-size rules, and charge commission/stamp duty/transfer fee/slippage from effective-dated
|
|
12
|
+
rules. Every order and rejection lands in the ledger.
|
|
13
|
+
- `signal_replay`: only a close series was available. The module replays the signal close-to-close and
|
|
14
|
+
charges a flat percentage cost; fills are not simulated, and the audit lists what was not covered.
|
|
15
|
+
This grade is deliberately weaker and must be read as such.
|
|
16
|
+
|
|
17
|
+
`simulation_mode="constrained"` refuses to fall back: missing volume/calendar marks the run
|
|
18
|
+
`insufficient_data` instead of pretending a constrained simulation happened.
|
|
19
|
+
|
|
20
|
+
Pure standard library on purpose: no numpy/pandas, so the ledger arithmetic is auditable line by line.
|
|
21
|
+
The result carries a `simulation` block (grade, constraints, fee rules, audit) that the host copies
|
|
22
|
+
into the artifact; `outputs/ledger.json` holds the immutable day/order/trade history so every summary
|
|
23
|
+
number can be recomputed from it.
|
|
24
|
+
|
|
25
|
+
Protocol: `docs/dev/senior-analysis.md` §1.9. `module.json` `assumptions` / `limitations` are repeated
|
|
26
|
+
verbatim in ASSUMPTIONS / LIMITATIONS so describe_analysis_module and run_analysis cannot contradict
|
|
27
|
+
each other.
|
|
15
28
|
"""
|
|
16
29
|
from __future__ import annotations
|
|
17
30
|
|
|
18
|
-
import
|
|
19
|
-
|
|
31
|
+
import json
|
|
32
|
+
import math
|
|
33
|
+
|
|
34
|
+
from lib import frames as _frames
|
|
35
|
+
from lib import gaps as gapvocab
|
|
36
|
+
from lib.errors import AnalysisInputError
|
|
37
|
+
from lib.frames import columns_of as _columns_of
|
|
38
|
+
from lib.frames import number as _number
|
|
39
|
+
from lib.frames import text as _text
|
|
40
|
+
from lib.jsonio import fmt6 as _fmt6
|
|
41
|
+
from lib.jsonio import pct as _pct
|
|
42
|
+
from lib.jsonio import round_metric as _round
|
|
43
|
+
from lib.jsonio import round_or_none as _round_or_none
|
|
44
|
+
from lib.jsonio import sample_values as _sample
|
|
45
|
+
from lib.metrics import (
|
|
46
|
+
annualized_return,
|
|
47
|
+
annualized_volatility,
|
|
48
|
+
calmar,
|
|
49
|
+
drawdown_duration,
|
|
50
|
+
information_ratio,
|
|
51
|
+
max_drawdown,
|
|
52
|
+
payoff_ratio,
|
|
53
|
+
profit_factor,
|
|
54
|
+
quantile,
|
|
55
|
+
sharpe,
|
|
56
|
+
sortino,
|
|
57
|
+
tracking_error,
|
|
58
|
+
)
|
|
59
|
+
from lib.pit import require_bar_available
|
|
60
|
+
from lib.prices import adjustment_conflict, series as price_series
|
|
61
|
+
from lib.timeaxis import parse_time as _parse_time
|
|
62
|
+
from lib.timeaxis import temporal_of as _temporal_of
|
|
63
|
+
from lib.timeaxis import time_column as _time_column
|
|
64
|
+
from lib.timeaxis import timezone_of as _timezone
|
|
65
|
+
from lib.timeaxis import trading_days_from as _trading_days_from
|
|
20
66
|
|
|
21
67
|
MODULE_ID = "simple_backtest"
|
|
22
|
-
MODULE_VERSION = "
|
|
23
|
-
OUTPUT_NAME = "
|
|
68
|
+
MODULE_VERSION = "2.0.0"
|
|
69
|
+
OUTPUT_NAME = "ledger"
|
|
70
|
+
LEDGER_SCHEMA = "capital-simulation-ledger/v1"
|
|
24
71
|
|
|
25
72
|
RULES = ("sma_cross", "price_above_sma")
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
ISO_DAY = re.compile(r"^(\d{4}-\d{2}-\d{2})")
|
|
73
|
+
SIMULATION_MODES = ("auto", "constrained", "signal_replay")
|
|
74
|
+
BASIS_CHOICES = ("auto", "adjusted", "unadjusted")
|
|
29
75
|
MIN_OBSERVATIONS_FOR_STABLE = 20
|
|
76
|
+
ROBUSTNESS_MAX_BARS = 5000
|
|
77
|
+
LEDGER_INLINE_MAX_BYTES = 700_000
|
|
78
|
+
LEDGER_CHUNK_MAX_BYTES = 700_000
|
|
79
|
+
LEDGER_COLUMNS = ["date", "close", "position", "shares", "sellable", "cash", "equity", "fees", "benchmark"]
|
|
80
|
+
|
|
81
|
+
# Effective-dated A-share rules. The stamp duty is sell-side only; the transfer fee is charged on both
|
|
82
|
+
# sides (SH/SZ unified since 2015-08-01, halved 2022-04-29). Commission and its minimum are broker
|
|
83
|
+
# practice, not regulation, so they are caller parameters and are disclosed as assumptions.
|
|
84
|
+
STAMP_DUTY_RULES = (("2023-08-28", 0.0005), ("2008-09-19", 0.001))
|
|
85
|
+
TRANSFER_FEE_RULES = (("2022-04-29", 0.00001), ("2015-08-01", 0.00002))
|
|
86
|
+
A_SHARE_FEE_EFFECTIVE = "A 股费用规则按生效日分段(印花税 2023-08-28 起 0.05%,此前 0.1%;过户费 2022-04-29 起 0.001%,此前 0.002%)"
|
|
30
87
|
|
|
31
88
|
ASSUMPTIONS = [
|
|
32
|
-
"信号在第 t 根收盘算出、按第 t+1
|
|
33
|
-
"
|
|
34
|
-
"
|
|
35
|
-
"
|
|
36
|
-
"
|
|
89
|
+
"信号在第 t 根收盘算出、按第 t+1 根收盘成交;不使用未来数据,也不假设盘中成交或收盘集合竞价成交",
|
|
90
|
+
"只做多、空仓二态:持有期按收盘价标记,空仓日收益为 0;不做空、杠杆、组合或仓位管理",
|
|
91
|
+
"constrained_simulation 按 A 股规则约束成交:T+1 可卖、整手、涨跌停不成交、停牌/零成交量不成交;" + A_SHARE_FEE_EFFECTIVE,
|
|
92
|
+
"signal_replay 只按收盘价重放信号并扣固定比例成本:不模拟涨跌停、停牌、T+1、整手与最低佣金,等级会如实标注",
|
|
93
|
+
"佣金费率与最低佣金是券商惯例而不是法规:由调用方给出并在结果里披露,未给出时按默认值并标注为假设",
|
|
94
|
+
"复权价沿用 Dataset 的取数口径;未复权价格里的除权跳变会计入收益,公司行为不单独建模",
|
|
95
|
+
"回测使用样本内价格:参数由调用方给定,模块不做参数寻优、不选择最佳窗口,也不做样本外检验",
|
|
96
|
+
"结果只描述这段历史上该规则在给定假设下发生了什么;不构成策略推荐、收益预测或评级",
|
|
37
97
|
]
|
|
38
98
|
|
|
39
99
|
LIMITATIONS = [
|
|
40
|
-
"
|
|
41
|
-
"
|
|
42
|
-
"
|
|
43
|
-
"
|
|
44
|
-
"
|
|
45
|
-
"
|
|
100
|
+
"历史模拟不是实盘验证:没有真实订单队列、盘口优先权、券源、融券或券商特殊规则,成交是收盘价上的规则化判断",
|
|
101
|
+
"涨跌停价优先取 Dataset 的涨跌停列;没有该列时按前收盘 × (1 ± limit_pct) 推导并标注 rule_derived,不保证与交易所精确到分一致",
|
|
102
|
+
"停牌与零成交量只在有成交量列或交易日历时可识别;两者都没有时降级为 signal_replay 并列入审计未覆盖风险",
|
|
103
|
+
"公司行为(分红、送转、拆股)不单独建模:复权价视为已处理;未复权价格里的除权跳变会原样进入净值",
|
|
104
|
+
"容量与冲击成本未建模:没有按分钟成交量或盘口深度约束成交数量,只按整手与现金约束",
|
|
105
|
+
"只支持单标的日频序列;多标的组合、分钟级、做空与杠杆不适用;历史结果不预测未来",
|
|
46
106
|
]
|
|
47
107
|
|
|
108
|
+
DISCLAIMER = "样本内历史模拟、参数由调用方给定、未做参数寻优;不预测、不构成策略推荐或收益承诺。"
|
|
48
109
|
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
analysis_code = "analysis_input_invalid"
|
|
110
|
+
TRADE_ACTIONS = ("buy", "sell")
|
|
111
|
+
REJECT_REASONS = ("limit_up", "limit_down", "suspended", "insufficient_cash", "t_plus_one", "no_position")
|
|
53
112
|
|
|
54
113
|
|
|
55
|
-
|
|
56
|
-
rounded = round(float(value), 6)
|
|
57
|
-
return 0.0 if rounded == 0 else rounded
|
|
114
|
+
# ── parameter handling ─────────────────────────────────────────────────────────────────────────
|
|
58
115
|
|
|
59
116
|
|
|
60
|
-
def
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
117
|
+
def _window(params, name, required):
|
|
118
|
+
value = params.get(name)
|
|
119
|
+
if value is None:
|
|
120
|
+
if required:
|
|
121
|
+
raise AnalysisInputError(f"sma_cross 需要 {name}(且必须大于 fast_window)")
|
|
122
|
+
return None
|
|
123
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
124
|
+
raise AnalysisInputError(f"{name}={value!r} 必须是整数")
|
|
125
|
+
if value < 2:
|
|
126
|
+
raise AnalysisInputError(f"{name}={value} 至少为 2(均线窗口不能是 1)")
|
|
127
|
+
return value
|
|
68
128
|
|
|
69
129
|
|
|
70
|
-
def
|
|
71
|
-
|
|
72
|
-
return None
|
|
73
|
-
value = row.get(name)
|
|
130
|
+
def _number_param(params, name, default, *, minimum=None, maximum=None):
|
|
131
|
+
value = params.get(name, default)
|
|
74
132
|
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
|
75
|
-
|
|
133
|
+
raise AnalysisInputError(f"{name}={value!r} 必须是数字")
|
|
76
134
|
number = float(value)
|
|
77
135
|
if number != number or number in (float("inf"), float("-inf")):
|
|
78
|
-
|
|
136
|
+
raise AnalysisInputError(f"{name}={value!r} 必须是有限数字")
|
|
137
|
+
if minimum is not None and number < minimum:
|
|
138
|
+
raise AnalysisInputError(f"{name}={value!r} 不能小于 {minimum}")
|
|
139
|
+
if maximum is not None and number >= maximum:
|
|
140
|
+
raise AnalysisInputError(f"{name}={value!r} 必须小于 {maximum}")
|
|
79
141
|
return number
|
|
80
142
|
|
|
81
143
|
|
|
82
|
-
def
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
for row in view.get("rows") or []:
|
|
90
|
-
if isinstance(row, dict):
|
|
91
|
-
names |= set(row)
|
|
92
|
-
return names
|
|
144
|
+
def _integer_param(params, name, default, *, minimum=1):
|
|
145
|
+
value = params.get(name, default)
|
|
146
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
147
|
+
raise AnalysisInputError(f"{name}={value!r} 必须是整数")
|
|
148
|
+
if value < minimum:
|
|
149
|
+
raise AnalysisInputError(f"{name}={value!r} 不能小于 {minimum}")
|
|
150
|
+
return value
|
|
93
151
|
|
|
94
152
|
|
|
95
|
-
def
|
|
96
|
-
|
|
153
|
+
def _choice(params, name, choices, default):
|
|
154
|
+
value = params.get(name, default)
|
|
155
|
+
if value not in choices:
|
|
156
|
+
raise AnalysisInputError(f"{name}={value!r} 只能是 {' / '.join(choices)}")
|
|
157
|
+
return value
|
|
97
158
|
|
|
98
159
|
|
|
99
|
-
def
|
|
100
|
-
|
|
101
|
-
if
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
160
|
+
def _parameters(params):
|
|
161
|
+
rule = params.get("rule")
|
|
162
|
+
if rule not in RULES:
|
|
163
|
+
raise AnalysisInputError(f"rule={rule!r} 只能是 sma_cross 或 price_above_sma")
|
|
164
|
+
fast = _window(params, "fast_window", required=True)
|
|
165
|
+
slow = _window(params, "slow_window", required=rule == "sma_cross")
|
|
166
|
+
if rule == "sma_cross" and slow <= fast:
|
|
167
|
+
raise AnalysisInputError(f"slow_window={slow} 必须大于 fast_window={fast}:快慢线不能相等或反置")
|
|
168
|
+
return {
|
|
169
|
+
"rule": rule,
|
|
170
|
+
"fast_window": fast,
|
|
171
|
+
"slow_window": slow if rule == "sma_cross" else None,
|
|
172
|
+
"initial_capital": _number_param(params, "initial_capital", 100_000.0, minimum=1e-9),
|
|
173
|
+
"simulation_mode": _choice(params, "simulation_mode", SIMULATION_MODES, "auto"),
|
|
174
|
+
"price_basis": _choice(params, "price_basis", BASIS_CHOICES, "auto"),
|
|
175
|
+
"limit_pct": _number_param(params, "limit_pct", 0.10, minimum=0.001, maximum=1.0),
|
|
176
|
+
"lot_size": _integer_param(params, "lot_size", 100),
|
|
177
|
+
"commission_rate": _number_param(params, "commission_rate", 0.0003, minimum=0.0, maximum=1.0),
|
|
178
|
+
"min_commission": _number_param(params, "min_commission", 5.0, minimum=0.0),
|
|
179
|
+
"slippage_bps": _number_param(params, "slippage_bps", 0.0, minimum=0.0, maximum=500.0),
|
|
180
|
+
"stamp_duty_rate": _number_param(params, "stamp_duty_rate", None, minimum=0.0, maximum=1.0)
|
|
181
|
+
if params.get("stamp_duty_rate") is not None else None,
|
|
182
|
+
"transfer_fee_rate": _number_param(params, "transfer_fee_rate", None, minimum=0.0, maximum=1.0)
|
|
183
|
+
if params.get("transfer_fee_rate") is not None else None,
|
|
184
|
+
"risk_free_rate": _number_param(params, "risk_free_rate", 0.0),
|
|
185
|
+
"periods_per_year": _integer_param(params, "periods_per_year", 252),
|
|
186
|
+
"robustness_enabled": _boolean_param(params, "robustness_enabled", True),
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
|
|
190
|
+
def _boolean_param(params, name, default):
|
|
191
|
+
value = params.get(name, default)
|
|
192
|
+
if not isinstance(value, bool):
|
|
193
|
+
raise AnalysisInputError(f"{name}={value!r} 必须是布尔值")
|
|
194
|
+
return value
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
# ── dataset reading ───────────────────────────────────────────────────────────────────────────
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def _read_views(request, context):
|
|
201
|
+
return _frames.read_views(
|
|
202
|
+
request, context,
|
|
203
|
+
module_id=MODULE_ID,
|
|
204
|
+
empty_message="快照里没有任何 Dataset:先取价格序列再建快照",
|
|
205
|
+
)
|
|
105
206
|
|
|
106
|
-
return ZoneInfo(name)
|
|
107
|
-
except Exception as error: # noqa: BLE001 - any load failure is a caller error
|
|
108
|
-
raise AnalysisInputError(f"timezone={name!r} 无法加载(需要 IANA 时区名,如 Asia/Shanghai)") from error
|
|
109
207
|
|
|
208
|
+
VALUE_COLUMNS = {
|
|
209
|
+
"volume": ("volume", "vol", "turnover_volume", "share_volume", "quantity", "成交量"),
|
|
210
|
+
"high": ("high", "high_price", "最高价"),
|
|
211
|
+
"low": ("low", "low_price", "最低价"),
|
|
212
|
+
"limit_up": ("limit_up", "limit_up_price", "up_limit", "涨停价"),
|
|
213
|
+
"limit_down": ("limit_down", "limit_down_price", "down_limit", "跌停价"),
|
|
214
|
+
}
|
|
110
215
|
|
|
111
|
-
|
|
216
|
+
|
|
217
|
+
def _optional_column(params, view, name, key):
|
|
218
|
+
override = _text(params.get(name))
|
|
112
219
|
names = _columns_of(view)
|
|
113
220
|
if override is not None:
|
|
114
221
|
if override not in names:
|
|
115
|
-
raise AnalysisInputError(f"
|
|
222
|
+
raise AnalysisInputError(f"{name}={override} 不在 Dataset 的列里:可选 {sorted(names)}")
|
|
116
223
|
return override
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
if name in names:
|
|
122
|
-
return name
|
|
123
|
-
raise AnalysisInputError(
|
|
124
|
-
"找不到时间列:需要 time_coverage 列,或 trade_date_ms / date_ms / period_end_ms / datetime / date / trade_date / time 之一"
|
|
125
|
-
)
|
|
224
|
+
for candidate in VALUE_COLUMNS[key]:
|
|
225
|
+
if candidate in names:
|
|
226
|
+
return candidate
|
|
227
|
+
return None
|
|
126
228
|
|
|
127
229
|
|
|
128
|
-
def
|
|
230
|
+
def _pick_price_column(view, params):
|
|
129
231
|
names = _columns_of(view)
|
|
232
|
+
override = _text(params.get("price_column"))
|
|
130
233
|
if override is not None:
|
|
131
234
|
if override not in names:
|
|
132
235
|
raise AnalysisInputError(f"price_column={override} 不在 Dataset 的列里:可选 {sorted(names)}")
|
|
133
|
-
return override
|
|
134
|
-
for
|
|
135
|
-
if
|
|
136
|
-
return
|
|
236
|
+
return override, "adjusted" if "adj" in override.lower() else "unadjusted"
|
|
237
|
+
for candidate in ("adj_close", "close", "close_price", "price", "nav"):
|
|
238
|
+
if candidate in names:
|
|
239
|
+
return candidate, "adjusted" if "adj" in candidate.lower() else "unadjusted"
|
|
137
240
|
raise AnalysisInputError(
|
|
138
241
|
"找不到价格列:需要 close / adj_close / close_price / price / nav 之一(或用 price_column 指明);"
|
|
139
242
|
f"现有列:{sorted(names)}"
|
|
140
243
|
)
|
|
141
244
|
|
|
142
245
|
|
|
143
|
-
def
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
if
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
except (OverflowError, OSError, ValueError):
|
|
154
|
-
return None
|
|
155
|
-
return number, stamp.strftime("%Y-%m-%d")
|
|
156
|
-
if isinstance(value, str):
|
|
157
|
-
match = ISO_DAY.match(value.strip())
|
|
158
|
-
if match is None:
|
|
159
|
-
return None
|
|
160
|
-
day = match.group(1)
|
|
246
|
+
def _pick_price_view(views, params):
|
|
247
|
+
price_override = _text(params.get("price_column"))
|
|
248
|
+
time_override = _text(params.get("time_column"))
|
|
249
|
+
price_dataset_id = _text(params.get("price_dataset_id"))
|
|
250
|
+
if price_dataset_id is not None:
|
|
251
|
+
if price_dataset_id not in views:
|
|
252
|
+
raise AnalysisInputError(f"price_dataset_id={price_dataset_id} 不在本次快照的 Dataset 里")
|
|
253
|
+
return price_dataset_id, views[price_dataset_id]
|
|
254
|
+
candidates = []
|
|
255
|
+
for dataset_id, view in sorted(views.items()):
|
|
161
256
|
try:
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
257
|
+
_time_column(view, time_override)
|
|
258
|
+
_pick_price_column(view, params)
|
|
259
|
+
except AnalysisInputError:
|
|
260
|
+
continue
|
|
261
|
+
candidates.append(dataset_id)
|
|
262
|
+
if len(candidates) > 1:
|
|
263
|
+
raise AnalysisInputError(
|
|
264
|
+
f"有 {len(candidates)} 份 Dataset 都像价格序列({'、'.join(candidates)}):用 price_dataset_id 指明用哪一份"
|
|
265
|
+
)
|
|
266
|
+
if not candidates:
|
|
267
|
+
detail = f"(time_column={time_override} 不在任何 Dataset 里)" if time_override else ""
|
|
268
|
+
columns = ";".join(f"{dataset_id} 现有列 {sorted(_columns_of(view))}" for dataset_id, view in sorted(views.items()))
|
|
269
|
+
raise AnalysisInputError(
|
|
270
|
+
f"没有可识别的价格序列 Dataset{detail}:需要时间列 + close/adj_close/close_price/price/nav 之一;{columns}"
|
|
271
|
+
)
|
|
272
|
+
return candidates[0], views[candidates[0]]
|
|
167
273
|
|
|
168
274
|
|
|
169
|
-
def
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
def _series(view, dataset_id, price_column, time_column, tz):
|
|
175
|
-
rows = view.get("rows") or []
|
|
176
|
-
if not rows:
|
|
177
|
-
raise AnalysisInputError(f"Dataset {dataset_id} 没有数据行:无法回测")
|
|
178
|
-
points, dropped, kind = [], [], None
|
|
179
|
-
for row in rows:
|
|
180
|
-
if not isinstance(row, dict):
|
|
181
|
-
raise AnalysisInputError(f"Dataset {dataset_id} 的数据行不是对象:无法回测")
|
|
182
|
-
raw_time = row.get(time_column)
|
|
183
|
-
row_kind = "ms" if isinstance(raw_time, (int, float)) and not isinstance(raw_time, bool) else "date"
|
|
184
|
-
if kind is None:
|
|
185
|
-
kind = row_kind
|
|
186
|
-
elif row_kind != kind:
|
|
187
|
-
raise AnalysisInputError(
|
|
188
|
-
f"Dataset {dataset_id} 的 {time_column} 列混用了数值时间戳与日期字符串:无法排序,请取数时统一"
|
|
189
|
-
)
|
|
190
|
-
parsed = _parse_time(raw_time, tz)
|
|
191
|
-
price = _number(row, price_column)
|
|
192
|
-
if parsed is None or price is None or price <= 0:
|
|
193
|
-
dropped.append(raw_time)
|
|
194
|
-
continue
|
|
195
|
-
key, day = parsed
|
|
196
|
-
points.append({"key": key, "day": day, "price": price})
|
|
197
|
-
points.sort(key=lambda item: item["key"])
|
|
198
|
-
seen = set()
|
|
275
|
+
def _bars(points, rows, columns):
|
|
276
|
+
"""Attach the execution-relevant cells to each price point (same rows, same order)."""
|
|
277
|
+
bars = []
|
|
199
278
|
for point in points:
|
|
200
|
-
if point["
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
)
|
|
204
|
-
|
|
205
|
-
return
|
|
279
|
+
row = rows[point["row_index"]] if point["row_index"] < len(rows) else None
|
|
280
|
+
bar = {"day": point["day"], "close": point["price"], "row_index": point["row_index"]}
|
|
281
|
+
for key, column in columns.items():
|
|
282
|
+
bar[key] = None if column is None else _number(row, column)
|
|
283
|
+
bars.append(bar)
|
|
284
|
+
return bars
|
|
206
285
|
|
|
207
286
|
|
|
208
|
-
|
|
209
|
-
value = params.get(name)
|
|
210
|
-
if value is None:
|
|
211
|
-
if required:
|
|
212
|
-
raise AnalysisInputError(f"sma_cross 需要 {name}(且必须大于 fast_window)")
|
|
213
|
-
return None
|
|
214
|
-
if isinstance(value, bool) or not isinstance(value, int):
|
|
215
|
-
raise AnalysisInputError(f"{name}={value!r} 必须是整数")
|
|
216
|
-
if value < 2:
|
|
217
|
-
raise AnalysisInputError(f"{name}={value} 至少为 2(均线窗口不能是 1)")
|
|
218
|
-
return value
|
|
287
|
+
# ── fees and constraints ─────────────────────────────────────────────────────────────────────
|
|
219
288
|
|
|
220
289
|
|
|
221
|
-
def
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
if number != number or number in (float("inf"), float("-inf")) or number <= 0:
|
|
227
|
-
raise AnalysisInputError(f"initial_capital={value!r} 必须是正的有限数字")
|
|
228
|
-
return number
|
|
290
|
+
def _rate_on(day, rules, fallback):
|
|
291
|
+
for effective, rate in rules:
|
|
292
|
+
if day >= effective:
|
|
293
|
+
return rate, effective
|
|
294
|
+
return fallback, None
|
|
229
295
|
|
|
230
296
|
|
|
231
|
-
def
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
297
|
+
def _fee_plan(params):
|
|
298
|
+
return {
|
|
299
|
+
"commission_rate": params["commission_rate"],
|
|
300
|
+
"min_commission": params["min_commission"],
|
|
301
|
+
"slippage_bps": params["slippage_bps"],
|
|
302
|
+
"stamp_duty_override": params["stamp_duty_rate"],
|
|
303
|
+
"transfer_fee_override": params["transfer_fee_rate"],
|
|
304
|
+
}
|
|
239
305
|
|
|
240
306
|
|
|
241
|
-
def
|
|
242
|
-
|
|
243
|
-
if
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
307
|
+
def _costs(day, amount, side, params):
|
|
308
|
+
plan = _fee_plan(params)
|
|
309
|
+
commission = max(amount * plan["commission_rate"], plan["min_commission"]) if amount > 0 else 0.0
|
|
310
|
+
if plan["transfer_fee_override"] is not None:
|
|
311
|
+
transfer_rate, transfer_effective = plan["transfer_fee_override"], "caller_override"
|
|
312
|
+
else:
|
|
313
|
+
transfer_rate, transfer_effective = _rate_on(day, TRANSFER_FEE_RULES, 0.00001)
|
|
314
|
+
transfer = amount * transfer_rate
|
|
315
|
+
if side == "sell":
|
|
316
|
+
if plan["stamp_duty_override"] is not None:
|
|
317
|
+
stamp_rate, stamp_effective = plan["stamp_duty_override"], "caller_override"
|
|
318
|
+
else:
|
|
319
|
+
stamp_rate, stamp_effective = _rate_on(day, STAMP_DUTY_RULES, 0.001)
|
|
320
|
+
else:
|
|
321
|
+
stamp_rate, stamp_effective = 0.0, "sell_side_only"
|
|
322
|
+
stamp = amount * stamp_rate
|
|
249
323
|
return {
|
|
250
|
-
"
|
|
251
|
-
"
|
|
252
|
-
"
|
|
253
|
-
"
|
|
254
|
-
"
|
|
324
|
+
"commission": _round(commission),
|
|
325
|
+
"transfer_fee": _round(transfer),
|
|
326
|
+
"stamp_duty": _round(stamp),
|
|
327
|
+
"total": _round(commission + transfer + stamp),
|
|
328
|
+
"stamp_duty_rate": stamp_rate,
|
|
329
|
+
"stamp_duty_effective": stamp_effective,
|
|
330
|
+
"transfer_fee_rate": transfer_rate,
|
|
331
|
+
"transfer_fee_effective": transfer_effective,
|
|
255
332
|
}
|
|
256
333
|
|
|
257
334
|
|
|
335
|
+
def _flat_cost_rate(day, side, params):
|
|
336
|
+
"""Signal-replay cost: one percentage applied multiplicatively, no minimums/lot sizing."""
|
|
337
|
+
commission = params["commission_rate"]
|
|
338
|
+
transfer = params["transfer_fee_rate"] if params["transfer_fee_rate"] is not None else _rate_on(day, TRANSFER_FEE_RULES, 0.00001)[0]
|
|
339
|
+
stamp = 0.0
|
|
340
|
+
if side == "sell":
|
|
341
|
+
stamp = params["stamp_duty_rate"] if params["stamp_duty_rate"] is not None else _rate_on(day, STAMP_DUTY_RULES, 0.001)[0]
|
|
342
|
+
slippage = params["slippage_bps"] / 10_000.0
|
|
343
|
+
return commission + transfer + stamp + slippage
|
|
344
|
+
|
|
345
|
+
|
|
346
|
+
def _limit_prices(bar, previous_close, columns, params):
|
|
347
|
+
if columns.get("limit_up") is not None and bar.get("limit_up") is not None:
|
|
348
|
+
down = bar.get("limit_down") if columns.get("limit_down") is not None else None
|
|
349
|
+
return bar["limit_up"], down, "dataset"
|
|
350
|
+
if previous_close is None or previous_close <= 0:
|
|
351
|
+
return None, None, "unavailable"
|
|
352
|
+
pct = params["limit_pct"]
|
|
353
|
+
return (round(previous_close * (1.0 + pct), 2), round(previous_close * (1.0 - pct), 2), "rule_derived")
|
|
354
|
+
|
|
355
|
+
|
|
356
|
+
def _at_limit_up(bar, limit_up):
|
|
357
|
+
if limit_up is None:
|
|
358
|
+
return False
|
|
359
|
+
high = bar.get("high") if bar.get("high") is not None else bar["close"]
|
|
360
|
+
return high >= limit_up - 0.005 and bar["close"] >= limit_up - 0.005
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
def _at_limit_down(bar, limit_down):
|
|
364
|
+
if limit_down is None:
|
|
365
|
+
return False
|
|
366
|
+
low = bar.get("low") if bar.get("low") is not None else bar["close"]
|
|
367
|
+
return low <= limit_down + 0.005 and bar["close"] <= limit_down + 0.005
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def _suspended(bar):
|
|
371
|
+
volume = bar.get("volume")
|
|
372
|
+
return volume is not None and volume <= 0
|
|
373
|
+
|
|
374
|
+
|
|
375
|
+
def _affordable(cash, price, params):
|
|
376
|
+
lot = params["lot_size"]
|
|
377
|
+
if price <= 0:
|
|
378
|
+
return 0
|
|
379
|
+
lots = int(cash // (price * lot))
|
|
380
|
+
while lots > 0:
|
|
381
|
+
quantity = lots * lot
|
|
382
|
+
amount = quantity * price
|
|
383
|
+
fees = _costs("1970-01-01", amount, "buy", params)["total"]
|
|
384
|
+
if amount + fees <= cash + 1e-9:
|
|
385
|
+
return quantity
|
|
386
|
+
lots -= 1
|
|
387
|
+
return 0
|
|
388
|
+
|
|
389
|
+
|
|
390
|
+
# ── signal & engines ────────────────────────────────────────────────────────────────────────
|
|
391
|
+
|
|
392
|
+
|
|
258
393
|
def _sma(closes, window):
|
|
259
394
|
n = len(closes)
|
|
260
395
|
prefix, total = [], 0.0
|
|
@@ -269,7 +404,6 @@ def _sma(closes, window):
|
|
|
269
404
|
|
|
270
405
|
|
|
271
406
|
def _targets(closes, rule, fast, slow):
|
|
272
|
-
"""Desired state at each bar's close; `None` while a window is not yet full."""
|
|
273
407
|
n = len(closes)
|
|
274
408
|
fast_sma = _sma(closes, fast)
|
|
275
409
|
slow_sma = _sma(closes, slow) if slow is not None else None
|
|
@@ -288,113 +422,496 @@ def _targets(closes, rule, fast, slow):
|
|
|
288
422
|
return targets, fast_sma, slow_sma
|
|
289
423
|
|
|
290
424
|
|
|
291
|
-
def
|
|
292
|
-
"""
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
425
|
+
def _benchmark_equity(axis_days, benchmark_points):
|
|
426
|
+
"""Carry the last known benchmark close onto the strategy axis; missing days are flat."""
|
|
427
|
+
by_day = {point["day"]: point["price"] for point in benchmark_points}
|
|
428
|
+
values, last = [], None
|
|
429
|
+
for day in axis_days:
|
|
430
|
+
if day in by_day:
|
|
431
|
+
last = by_day[day]
|
|
432
|
+
values.append(last)
|
|
433
|
+
first = next((value for value in values if value is not None), None)
|
|
434
|
+
if first is None or first <= 0:
|
|
435
|
+
return [None] * len(axis_days), 0
|
|
436
|
+
return [None if value is None else value / first * 1000.0 for value in values], sum(1 for value in values if value is None)
|
|
437
|
+
|
|
438
|
+
|
|
439
|
+
def _run_constrained(bars, targets, axis_days, columns, params, initial_capital):
|
|
440
|
+
"""Walk the calendar once with integer shares, T+1, lot size, limit and suspension rules."""
|
|
441
|
+
by_day = {bar["day"]: bar for bar in bars}
|
|
442
|
+
index_by_day = {bar["day"]: index for index, bar in enumerate(bars)}
|
|
443
|
+
cash, shares, position, sellable = initial_capital, 0, 0, 0
|
|
444
|
+
last_close, buy_day = None, None
|
|
445
|
+
rows, orders, trades = [], [], []
|
|
446
|
+
fees_total, slippage_total, traded_amount = 0.0, 0.0, 0.0
|
|
447
|
+
entry = None
|
|
448
|
+
for day in axis_days:
|
|
449
|
+
if day not in by_day:
|
|
450
|
+
if buy_day is not None and day > buy_day:
|
|
451
|
+
sellable = shares
|
|
452
|
+
equity = cash + shares * (last_close if last_close is not None else 0.0)
|
|
453
|
+
rows.append([day, _round(last_close) if last_close is not None else None, position, shares, sellable,
|
|
454
|
+
_round(cash), _round(equity), 0.0, None])
|
|
455
|
+
continue
|
|
456
|
+
bar = by_day[day]
|
|
457
|
+
index = index_by_day[day]
|
|
458
|
+
close = bar["close"]
|
|
459
|
+
if buy_day is not None and day > buy_day:
|
|
460
|
+
sellable = shares
|
|
461
|
+
day_fees, day_slippage = 0.0, 0.0
|
|
462
|
+
if index >= 1:
|
|
463
|
+
target = targets[index - 1]
|
|
464
|
+
previous_close = bars[index - 1]["close"]
|
|
465
|
+
limit_up, limit_down, _source = _limit_prices(bar, previous_close, columns, params)
|
|
466
|
+
suspended = _suspended(bar)
|
|
467
|
+
if target == 1 and position == 0:
|
|
468
|
+
reason = None
|
|
469
|
+
if suspended:
|
|
470
|
+
reason = "suspended"
|
|
471
|
+
elif _at_limit_up(bar, limit_up):
|
|
472
|
+
reason = "limit_up"
|
|
473
|
+
price = close * (1.0 + params["slippage_bps"] / 10_000.0)
|
|
474
|
+
if limit_up is not None and price > limit_up - 0.005:
|
|
475
|
+
price = limit_up
|
|
476
|
+
if reason is None and limit_up is not None and close >= limit_up - 0.005:
|
|
477
|
+
reason = "limit_up"
|
|
478
|
+
quantity = 0 if reason else _affordable(cash, price, params)
|
|
479
|
+
if reason is None and quantity == 0:
|
|
480
|
+
reason = "insufficient_cash"
|
|
481
|
+
if reason is not None:
|
|
482
|
+
orders.append({"signal_date": bars[index - 1]["day"], "date": day, "side": "buy",
|
|
483
|
+
"status": "rejected", "reason": reason, "price": _round(close), "quantity": 0})
|
|
484
|
+
else:
|
|
485
|
+
amount = quantity * price
|
|
486
|
+
costs = _costs(day, amount, "buy", params)
|
|
487
|
+
cash -= amount + costs["total"]
|
|
488
|
+
shares, position, buy_day, sellable = quantity, 1, day, 0
|
|
489
|
+
day_fees += costs["total"]
|
|
490
|
+
day_slippage += quantity * (price - close)
|
|
491
|
+
fees_total += costs["total"]
|
|
492
|
+
slippage_total += quantity * (price - close)
|
|
493
|
+
traded_amount += amount
|
|
494
|
+
entry = {"date": day, "index": index, "close": close, "price": price,
|
|
495
|
+
"shares": quantity, "equity_before": cash + amount + costs["total"], "fees": costs["total"]}
|
|
496
|
+
orders.append({"signal_date": bars[index - 1]["day"], "date": day, "side": "buy",
|
|
497
|
+
"status": "filled", "reason": None, "price": _round(price), "close": _round(close),
|
|
498
|
+
"quantity": quantity, "amount": _round(amount), "fees": costs})
|
|
499
|
+
elif target == 0 and position == 1:
|
|
500
|
+
reason = None
|
|
501
|
+
if suspended:
|
|
502
|
+
reason = "suspended"
|
|
503
|
+
elif _at_limit_down(bar, limit_down):
|
|
504
|
+
reason = "limit_down"
|
|
505
|
+
elif sellable <= 0:
|
|
506
|
+
reason = "t_plus_one"
|
|
507
|
+
if reason is not None:
|
|
508
|
+
orders.append({"signal_date": bars[index - 1]["day"], "date": day, "side": "sell",
|
|
509
|
+
"status": "rejected", "reason": reason, "price": _round(close),
|
|
510
|
+
"quantity": shares})
|
|
511
|
+
else:
|
|
512
|
+
price = close * (1.0 - params["slippage_bps"] / 10_000.0)
|
|
513
|
+
if limit_down is not None and price < limit_down + 0.005:
|
|
514
|
+
price = limit_down
|
|
515
|
+
amount = shares * price
|
|
516
|
+
costs = _costs(day, amount, "sell", params)
|
|
517
|
+
proceeds = amount - costs["total"]
|
|
518
|
+
cash += proceeds
|
|
519
|
+
day_fees += costs["total"]
|
|
520
|
+
day_slippage += shares * (close - price)
|
|
521
|
+
fees_total += costs["total"]
|
|
522
|
+
slippage_total += shares * (close - price)
|
|
523
|
+
traded_amount += amount
|
|
524
|
+
net_return = cash / entry["equity_before"] - 1.0 if entry is not None else None
|
|
525
|
+
trades.append({
|
|
526
|
+
"open": False,
|
|
527
|
+
"entry_date": entry["date"] if entry is not None else None,
|
|
528
|
+
"entry_close": _round(entry["close"]) if entry is not None else None,
|
|
529
|
+
"entry_price": _round(entry["price"]) if entry is not None else None,
|
|
530
|
+
"exit_date": day,
|
|
531
|
+
"exit_close": _round(close),
|
|
532
|
+
"exit_price": _round(price),
|
|
533
|
+
"shares": shares,
|
|
534
|
+
"bars": index - entry["index"] if entry is not None else None,
|
|
535
|
+
"price_return": _round(close / entry["close"] - 1.0) if entry is not None else None,
|
|
536
|
+
"net_return": _round(net_return) if net_return is not None else None,
|
|
537
|
+
"fees": _round(entry["fees"] + costs["total"]) if entry is not None else None,
|
|
538
|
+
"win": bool(net_return is not None and net_return > 0),
|
|
539
|
+
})
|
|
540
|
+
shares, position, sellable, entry = 0, 0, 0, None
|
|
541
|
+
orders.append({"signal_date": bars[index - 1]["day"], "date": day, "side": "sell",
|
|
542
|
+
"status": "filled", "reason": None, "price": _round(price), "close": _round(close),
|
|
543
|
+
"quantity": trades[-1]["shares"], "amount": _round(amount), "fees": costs})
|
|
544
|
+
last_close = close
|
|
545
|
+
equity = cash + shares * close
|
|
546
|
+
rows.append([day, _round(close), position, shares, sellable, _round(cash), _round(equity), _round(day_fees), None])
|
|
547
|
+
if entry is not None:
|
|
548
|
+
trades.append({
|
|
549
|
+
"open": True,
|
|
550
|
+
"entry_date": entry["date"],
|
|
551
|
+
"entry_close": _round(entry["close"]),
|
|
552
|
+
"entry_price": _round(entry["price"]),
|
|
553
|
+
"last_date": bars[-1]["day"],
|
|
554
|
+
"last_close": _round(bars[-1]["close"]),
|
|
555
|
+
"shares": shares,
|
|
556
|
+
"bars": len(bars) - entry["index"],
|
|
557
|
+
"price_return": _round(bars[-1]["close"] / entry["close"] - 1.0),
|
|
558
|
+
"fees": _round(entry["fees"]),
|
|
559
|
+
})
|
|
560
|
+
return {
|
|
561
|
+
"rows": rows,
|
|
562
|
+
"orders": orders,
|
|
563
|
+
"trades": trades,
|
|
564
|
+
"equity": [row[6] for row in rows],
|
|
565
|
+
"positions": [row[2] for row in rows],
|
|
566
|
+
"fees_total": fees_total,
|
|
567
|
+
"slippage_total": slippage_total,
|
|
568
|
+
"traded_amount": traded_amount,
|
|
569
|
+
"shares_final": shares,
|
|
570
|
+
}
|
|
571
|
+
|
|
572
|
+
|
|
573
|
+
def _run_signal_replay(bars, targets, axis_days, params, initial_capital):
|
|
574
|
+
"""Close-to-close replay with a flat percentage cost; no fill constraints are simulated."""
|
|
575
|
+
by_day = {bar["day"]: bar for bar in bars}
|
|
576
|
+
index_by_day = {bar["day"]: index for index, bar in enumerate(bars)}
|
|
577
|
+
equity, position = initial_capital, 0
|
|
578
|
+
rows, orders, trades = [], [], []
|
|
579
|
+
fees_total, traded_amount = 0.0, 0.0
|
|
580
|
+
entry, last_close = None, None
|
|
581
|
+
for day in axis_days:
|
|
582
|
+
if day not in by_day:
|
|
583
|
+
rows.append([day, _round(last_close) if last_close is not None else None, position, None, None,
|
|
584
|
+
None, _round(equity), 0.0, None])
|
|
585
|
+
continue
|
|
586
|
+
bar = by_day[day]
|
|
587
|
+
index = index_by_day[day]
|
|
588
|
+
close = bar["close"]
|
|
589
|
+
day_fees = 0.0
|
|
590
|
+
if index >= 1:
|
|
591
|
+
if position == 1:
|
|
592
|
+
equity *= close / bars[index - 1]["close"]
|
|
593
|
+
target = targets[index - 1]
|
|
594
|
+
side = "buy" if target == 1 and position == 0 else ("sell" if target == 0 and position == 1 else None)
|
|
595
|
+
if side is not None:
|
|
596
|
+
rate = _flat_cost_rate(day, side, params)
|
|
597
|
+
cost = equity * rate
|
|
598
|
+
equity -= cost
|
|
599
|
+
day_fees += cost
|
|
600
|
+
fees_total += cost
|
|
601
|
+
if side == "buy":
|
|
602
|
+
traded_amount += equity + cost
|
|
603
|
+
position = 1
|
|
604
|
+
entry = {"date": day, "index": index, "close": close, "equity_before": equity + cost}
|
|
605
|
+
orders.append({"signal_date": bars[index - 1]["day"], "date": day, "side": "buy",
|
|
606
|
+
"status": "filled", "reason": None, "model": "signal_replay",
|
|
607
|
+
"price": _round(close), "cost": _round(cost)})
|
|
608
|
+
else:
|
|
609
|
+
traded_amount += equity + cost
|
|
610
|
+
net_return = equity / entry["equity_before"] - 1.0 if entry is not None else None
|
|
611
|
+
trades.append({
|
|
612
|
+
"open": False,
|
|
613
|
+
"entry_date": entry["date"] if entry is not None else None,
|
|
614
|
+
"entry_close": _round(entry["close"]) if entry is not None else None,
|
|
615
|
+
"entry_price": _round(entry["close"]) if entry is not None else None,
|
|
616
|
+
"exit_date": day,
|
|
617
|
+
"exit_close": _round(close),
|
|
618
|
+
"exit_price": _round(close),
|
|
619
|
+
"bars": index - entry["index"] if entry is not None else None,
|
|
620
|
+
"price_return": _round(close / entry["close"] - 1.0) if entry is not None else None,
|
|
621
|
+
"net_return": _round(net_return) if net_return is not None else None,
|
|
622
|
+
"fees": None,
|
|
623
|
+
"win": bool(net_return is not None and net_return > 0),
|
|
624
|
+
})
|
|
625
|
+
orders.append({"signal_date": bars[index - 1]["day"], "date": day, "side": "sell",
|
|
626
|
+
"status": "filled", "reason": None, "model": "signal_replay",
|
|
627
|
+
"price": _round(close), "cost": _round(cost)})
|
|
628
|
+
position, entry = 0, None
|
|
629
|
+
last_close = close
|
|
630
|
+
rows.append([day, _round(close), position, None, None, None, _round(equity), _round(day_fees), None])
|
|
631
|
+
if entry is not None:
|
|
325
632
|
trades.append({
|
|
326
633
|
"open": True,
|
|
327
|
-
"
|
|
328
|
-
"
|
|
329
|
-
"
|
|
330
|
-
"
|
|
331
|
-
"
|
|
332
|
-
"
|
|
634
|
+
"entry_date": entry["date"],
|
|
635
|
+
"entry_close": _round(entry["close"]),
|
|
636
|
+
"entry_price": _round(entry["close"]),
|
|
637
|
+
"last_date": bars[-1]["day"],
|
|
638
|
+
"last_close": _round(bars[-1]["close"]),
|
|
639
|
+
"bars": len(bars) - entry["index"],
|
|
640
|
+
"price_return": _round(bars[-1]["close"] / entry["close"] - 1.0),
|
|
333
641
|
})
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
642
|
+
return {
|
|
643
|
+
"rows": rows,
|
|
644
|
+
"orders": orders,
|
|
645
|
+
"trades": trades,
|
|
646
|
+
"equity": [row[6] for row in rows],
|
|
647
|
+
"positions": [row[2] for row in rows],
|
|
648
|
+
"fees_total": fees_total,
|
|
649
|
+
"slippage_total": 0.0,
|
|
650
|
+
"traded_amount": traded_amount,
|
|
651
|
+
"shares_final": 0,
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
|
|
655
|
+
# ── metrics ──────────────────────────────────────────────────────────────────────────────────
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def _performance(equity, benchmark_equity, trades, axis_days, params, fees_total, slippage_total, traded_amount):
|
|
659
|
+
initial = equity[0]
|
|
660
|
+
total = equity[-1] / initial - 1.0
|
|
661
|
+
returns = [equity[index] / equity[index - 1] - 1.0 for index in range(1, len(equity)) if equity[index - 1] > 0]
|
|
662
|
+
ppy = params["periods_per_year"]
|
|
663
|
+
annualized = annualized_return(len(returns), total, ppy) if returns else None
|
|
664
|
+
volatility = annualized_volatility(returns, ppy) if len(returns) >= 2 else None
|
|
665
|
+
drawdown = max_drawdown(equity)
|
|
666
|
+
bench_values = [value for value in benchmark_equity if value is not None]
|
|
667
|
+
benchmark_return = bench_values[-1] / bench_values[0] - 1.0 if len(bench_values) >= 2 else None
|
|
668
|
+
excess = total - benchmark_return if benchmark_return is not None else None
|
|
669
|
+
closed = [trade for trade in trades if not trade.get("open")]
|
|
670
|
+
wins = [trade["net_return"] for trade in closed if isinstance(trade.get("net_return"), (int, float))]
|
|
671
|
+
active = []
|
|
672
|
+
if benchmark_return is not None:
|
|
673
|
+
for index in range(1, len(equity)):
|
|
674
|
+
left, right = benchmark_equity[index - 1], benchmark_equity[index]
|
|
675
|
+
if left and right and equity[index - 1] > 0:
|
|
676
|
+
active.append((equity[index] / equity[index - 1] - 1.0) - (right / left - 1.0))
|
|
677
|
+
benchmark_returns = []
|
|
678
|
+
for index in range(1, len(benchmark_equity)):
|
|
679
|
+
left, right = benchmark_equity[index - 1], benchmark_equity[index]
|
|
680
|
+
if left and right:
|
|
681
|
+
benchmark_returns.append(right / left - 1.0)
|
|
682
|
+
te = tracking_error(active, ppy) if len(active) >= 2 else None
|
|
683
|
+
excess_annualized = annualized_return(len(returns), excess, ppy) if (excess is not None and returns) else None
|
|
346
684
|
metrics = {
|
|
347
|
-
"observations": len(
|
|
348
|
-
"
|
|
349
|
-
"
|
|
350
|
-
"
|
|
685
|
+
"observations": len(equity),
|
|
686
|
+
"trading_days": len(axis_days),
|
|
687
|
+
"total_return": _round(total),
|
|
688
|
+
"annualized_return": _round_or_none(annualized),
|
|
689
|
+
"benchmark_return": _round_or_none(benchmark_return),
|
|
690
|
+
"excess_return": _round_or_none(excess),
|
|
691
|
+
"annualized_volatility": _round_or_none(volatility),
|
|
692
|
+
"max_drawdown": _round(drawdown),
|
|
693
|
+
"max_drawdown_duration": drawdown_duration(equity),
|
|
694
|
+
"sharpe_ratio": _round_or_none(sharpe(annualized, params["risk_free_rate"], volatility) if annualized is not None and volatility else None),
|
|
695
|
+
"sortino_ratio": _round_or_none(sortino(returns, annualized, params["risk_free_rate"], ppy) if annualized is not None and returns else None),
|
|
696
|
+
"calmar_ratio": _round_or_none(calmar(annualized, drawdown) if annualized is not None else None),
|
|
697
|
+
"tracking_error": _round_or_none(te),
|
|
698
|
+
"information_ratio": _round_or_none(information_ratio(excess_annualized, te) if excess_annualized is not None and te else None),
|
|
699
|
+
"exposure_ratio": None,
|
|
700
|
+
"turnover": _round(traded_amount / (sum(equity) / len(equity))) if traded_amount > 0 else 0.0,
|
|
701
|
+
"trade_count": len(closed),
|
|
702
|
+
"win_rate": _round(sum(1 for value in wins if value > 0) / len(wins)) if wins else None,
|
|
703
|
+
"profit_factor": _round_or_none(profit_factor(wins)),
|
|
704
|
+
"payoff_ratio": _round_or_none(payoff_ratio(wins)),
|
|
705
|
+
"total_fees": _round(fees_total),
|
|
706
|
+
"slippage_cost": _round(slippage_total),
|
|
707
|
+
"cost_drag": _round((fees_total + slippage_total) / initial) if initial > 0 else None,
|
|
351
708
|
"final_equity": _round(equity[-1]),
|
|
709
|
+
}
|
|
710
|
+
return metrics, returns, benchmark_returns, closed, wins
|
|
711
|
+
|
|
712
|
+
|
|
713
|
+
# ── simulation block ────────────────────────────────────────────────────────────────────────
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
def _blocked_simulation(reason, evidence, columns=None, has_calendar=False):
|
|
717
|
+
return {
|
|
718
|
+
"grade": "insufficient_data",
|
|
719
|
+
"cost_basis": "gross",
|
|
720
|
+
"out_of_sample": False,
|
|
721
|
+
"restated_history": False,
|
|
722
|
+
"constraints": {
|
|
723
|
+
"calendar": "dataset" if has_calendar else "unavailable",
|
|
724
|
+
"limit_prices": "unavailable",
|
|
725
|
+
"suspension": "unavailable",
|
|
726
|
+
"zero_volume": bool(columns and columns.get("volume")),
|
|
727
|
+
"t_plus_one": False,
|
|
728
|
+
"lot_size": None,
|
|
729
|
+
"commission": False,
|
|
730
|
+
"min_commission": False,
|
|
731
|
+
"stamp_duty": False,
|
|
732
|
+
"transfer_fee": False,
|
|
733
|
+
"slippage": False,
|
|
734
|
+
"capacity": False,
|
|
735
|
+
"corporate_actions": "unknown",
|
|
736
|
+
"execution_price": "none",
|
|
737
|
+
},
|
|
738
|
+
"audit": {"status": "FAIL", "reasons": [reason], "evidence": evidence,
|
|
739
|
+
"uncovered_risks": ["样本或输入不足:不能做任何模拟结论"]},
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
|
|
743
|
+
def _constraints_block(grade, columns, calendar_days, adjusted, params, fees):
|
|
744
|
+
return {
|
|
745
|
+
"calendar": "dataset" if calendar_days is not None else "unavailable",
|
|
746
|
+
"limit_prices": "dataset" if columns.get("limit_up") is not None else "rule_derived",
|
|
747
|
+
"suspension": "volume" if columns.get("volume") is not None else ("calendar" if calendar_days is not None else "unavailable"),
|
|
748
|
+
"zero_volume": columns.get("volume") is not None,
|
|
749
|
+
"t_plus_one": grade == "constrained_simulation",
|
|
750
|
+
"lot_size": params["lot_size"] if grade == "constrained_simulation" else None,
|
|
751
|
+
"commission": fees["commission_rate"] > 0,
|
|
752
|
+
"min_commission": fees["min_commission"] > 0,
|
|
753
|
+
"stamp_duty": True,
|
|
754
|
+
"transfer_fee": True,
|
|
755
|
+
"slippage": params["slippage_bps"] > 0,
|
|
756
|
+
"capacity": False,
|
|
757
|
+
"corporate_actions": "adjusted_price_series" if adjusted else "unadjusted_price_series",
|
|
758
|
+
"execution_price": "close" if grade == "constrained_simulation" else "close_to_close_replay",
|
|
759
|
+
}
|
|
760
|
+
|
|
761
|
+
|
|
762
|
+
def _audit(grade, adjusted, dropped, calendar_mismatch, benchmark_source, robustness_skipped, closed_trades, params):
|
|
763
|
+
reasons, evidence, risks = [], [], []
|
|
764
|
+
if grade == "signal_replay":
|
|
765
|
+
reasons.append("缺少成交量列或交易日历:未模拟涨跌停之外的成交约束")
|
|
766
|
+
evidence.append("grade=signal_replay:只按收盘价重放信号,成本按固定比例扣除")
|
|
767
|
+
risks.append("未模拟涨跌停、停牌、零成交量、T+1 与整手约束;成交假设比 constrained_simulation 弱")
|
|
768
|
+
if not adjusted:
|
|
769
|
+
reasons.append("价格未声明为复权价:除权跳变会进入收益")
|
|
770
|
+
evidence.append("constraints.corporate_actions=unadjusted_price_series")
|
|
771
|
+
risks.append("分红/送转/拆股未单独建模,除权日可能出现非经济性跳变")
|
|
772
|
+
else:
|
|
773
|
+
risks.append("涨跌停判断基于复权价,与交易所原始价按分取整可能有差异")
|
|
774
|
+
if benchmark_source == "same_instrument_buy_and_hold":
|
|
775
|
+
risks.append("基准是同标的买入持有,不含指数或行业基准,超额收益的解释力有限")
|
|
776
|
+
if calendar_mismatch:
|
|
777
|
+
reasons.append("价格序列包含不在交易日历里的日期")
|
|
778
|
+
evidence.append(f"calendar_mismatch={calendar_mismatch}")
|
|
779
|
+
if dropped:
|
|
780
|
+
evidence.append(f"跳过 {len(dropped)} 行无法解析的时间/价格")
|
|
781
|
+
if robustness_skipped is not None:
|
|
782
|
+
reasons.append(f"稳健性检查跳过:{robustness_skipped}")
|
|
783
|
+
risks.append("未模拟容量与冲击成本、盘口深度、券商拒单与真实撮合顺序")
|
|
784
|
+
risks.append("参数由调用方给定且为样本内结果:不构成样本外有效性证据")
|
|
785
|
+
status = "WARN" if (grade != "constrained_simulation" or not adjusted or calendar_mismatch or dropped) else "PASS"
|
|
786
|
+
return {"status": status, "reasons": reasons, "evidence": evidence, "uncovered_risks": risks}
|
|
787
|
+
|
|
788
|
+
|
|
789
|
+
def _fee_rules(rows):
|
|
790
|
+
last = rows[-1][0] if rows else None
|
|
791
|
+
first = rows[0][0] if rows else None
|
|
792
|
+
if last is None:
|
|
793
|
+
return []
|
|
794
|
+
stamp = _rate_on(last, STAMP_DUTY_RULES, 0.001)
|
|
795
|
+
transfer = _rate_on(last, TRANSFER_FEE_RULES, 0.00001)
|
|
796
|
+
return [
|
|
797
|
+
{"name": "stamp_duty", "side": "sell", "rate": stamp[0], "effective_from": stamp[1], "checked_date": last},
|
|
798
|
+
{"name": "transfer_fee", "side": "both", "rate": transfer[0], "effective_from": transfer[1], "checked_date": last},
|
|
799
|
+
{"name": "stamp_duty_history", "side": "sell", "rule": [[day, rate] for day, rate in STAMP_DUTY_RULES], "period": [first, last]},
|
|
800
|
+
{"name": "transfer_fee_history", "side": "both", "rule": [[day, rate] for day, rate in TRANSFER_FEE_RULES], "period": [first, last]},
|
|
801
|
+
]
|
|
802
|
+
|
|
803
|
+
|
|
804
|
+
# ── robustness ──────────────────────────────────────────────────────────────────────────────
|
|
805
|
+
|
|
806
|
+
|
|
807
|
+
def _variant_metrics(bars, axis_days, targets, columns, params, initial_capital, grade):
|
|
808
|
+
if grade == "constrained_simulation":
|
|
809
|
+
run = _run_constrained(bars, targets, axis_days, columns, params, initial_capital)
|
|
810
|
+
else:
|
|
811
|
+
run = _run_signal_replay(bars, targets, axis_days, params, initial_capital)
|
|
812
|
+
closed = [trade for trade in run["trades"] if not trade.get("open")]
|
|
813
|
+
return {
|
|
814
|
+
"total_return": _round(run["equity"][-1] / run["equity"][0] - 1.0),
|
|
815
|
+
"max_drawdown": _round(max_drawdown(run["equity"])),
|
|
352
816
|
"trade_count": len(closed),
|
|
353
|
-
"exposure_bars": bars,
|
|
354
|
-
"exposure_ratio": _round(bars / len(closes)),
|
|
355
817
|
}
|
|
356
|
-
if closed:
|
|
357
|
-
metrics["win_rate"] = _round(sum(1 for trade in closed if trade["win"]) / len(closed))
|
|
358
|
-
return metrics
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
def _trade_rows(trades, points):
|
|
362
|
-
rows = []
|
|
363
|
-
for number, trade in enumerate(trades, start=1):
|
|
364
|
-
entry = points[trade["entry_index"]]
|
|
365
|
-
if trade["open"]:
|
|
366
|
-
rows.append({
|
|
367
|
-
"trade": number,
|
|
368
|
-
"open": True,
|
|
369
|
-
"entry_date": entry["day"],
|
|
370
|
-
"entry_price": _round(trade["entry_price"]),
|
|
371
|
-
"entry_index": trade["entry_index"],
|
|
372
|
-
"last_date": points[trade["last_index"]]["day"],
|
|
373
|
-
"last_price": _round(trade["last_price"]),
|
|
374
|
-
"bars": trade["bars"],
|
|
375
|
-
"price_return": _round(trade["price_return"]),
|
|
376
|
-
})
|
|
377
|
-
continue
|
|
378
|
-
exit_ = points[trade["exit_index"]]
|
|
379
|
-
rows.append({
|
|
380
|
-
"trade": number,
|
|
381
|
-
"open": False,
|
|
382
|
-
"entry_date": entry["day"],
|
|
383
|
-
"entry_price": _round(trade["entry_price"]),
|
|
384
|
-
"entry_index": trade["entry_index"],
|
|
385
|
-
"exit_date": exit_["day"],
|
|
386
|
-
"exit_price": _round(trade["exit_price"]),
|
|
387
|
-
"exit_index": trade["exit_index"],
|
|
388
|
-
"bars": trade["bars"],
|
|
389
|
-
"price_return": _round(trade["price_return"]),
|
|
390
|
-
"net_return": _round(trade["net_return"]),
|
|
391
|
-
"win": trade["win"],
|
|
392
|
-
})
|
|
393
|
-
return rows
|
|
394
818
|
|
|
395
819
|
|
|
396
|
-
def
|
|
820
|
+
def _robustness(bars, closes, targets, columns, params, initial_capital, grade):
|
|
821
|
+
n = len(bars)
|
|
822
|
+
if not params["robustness_enabled"]:
|
|
823
|
+
return {"enabled": False, "skipped": "robustness_enabled=false"}, "调用方关闭了稳健性检查"
|
|
824
|
+
if n > ROBUSTNESS_MAX_BARS:
|
|
825
|
+
return ({"enabled": True, "skipped": "sample_too_large",
|
|
826
|
+
"limit_bars": ROBUSTNESS_MAX_BARS, "observations": n},
|
|
827
|
+
f"样本 {n} 根超过 {ROBUSTNESS_MAX_BARS} 根,未做参数邻域/起始日期/成本压力复算")
|
|
828
|
+
start_indices = sorted({0, int(n * 0.1), int(n * 0.25), int(n * 0.5), int(n * 0.75)})
|
|
829
|
+
parameter, starts, costs = [], [], []
|
|
830
|
+
rule, fast, slow = params["rule"], params["fast_window"], params["slow_window"]
|
|
831
|
+
variants = []
|
|
832
|
+
if rule == "price_above_sma":
|
|
833
|
+
for candidate in (fast - 1, fast + 1):
|
|
834
|
+
if candidate >= 2:
|
|
835
|
+
variants.append({"fast_window": candidate})
|
|
836
|
+
else:
|
|
837
|
+
for candidate in (fast - 1, fast + 1):
|
|
838
|
+
if candidate >= 2 and candidate < slow:
|
|
839
|
+
variants.append({"fast_window": candidate})
|
|
840
|
+
for candidate in (slow - 1, slow + 1):
|
|
841
|
+
if candidate > fast:
|
|
842
|
+
variants.append({"slow_window": candidate})
|
|
843
|
+
for index, override in enumerate(variants[:4]):
|
|
844
|
+
variant_fast = override.get("fast_window", fast)
|
|
845
|
+
variant_slow = override.get("slow_window", slow)
|
|
846
|
+
variant_targets, _f, _s = _targets(closes, rule, variant_fast, variant_slow)
|
|
847
|
+
variant_params = dict(params, **override)
|
|
848
|
+
try:
|
|
849
|
+
result = _variant_metrics(bars, [bar["day"] for bar in bars], variant_targets, columns, variant_params, initial_capital, grade)
|
|
850
|
+
except (AnalysisInputError, ZeroDivisionError):
|
|
851
|
+
continue
|
|
852
|
+
parameter.append({"variant": index + 1, "params": override, **result})
|
|
853
|
+
for index in start_indices:
|
|
854
|
+
if index >= n - 2:
|
|
855
|
+
continue
|
|
856
|
+
sliced_bars = bars[index:]
|
|
857
|
+
sliced_targets = targets[index:]
|
|
858
|
+
sliced_axis = [bar["day"] for bar in sliced_bars]
|
|
859
|
+
if len(sliced_bars) < 3:
|
|
860
|
+
continue
|
|
861
|
+
try:
|
|
862
|
+
result = _variant_metrics(sliced_bars, sliced_axis, sliced_targets, columns, params, initial_capital, grade)
|
|
863
|
+
except (AnalysisInputError, ZeroDivisionError):
|
|
864
|
+
continue
|
|
865
|
+
starts.append({"start": bars[index]["day"], "bars": len(sliced_bars), **result})
|
|
866
|
+
if params["commission_rate"] > 0 or params["slippage_bps"] > 0:
|
|
867
|
+
for factor in (2.0, 3.0):
|
|
868
|
+
stressed = dict(params, commission_rate=params["commission_rate"] * factor,
|
|
869
|
+
slippage_bps=params["slippage_bps"] * factor,
|
|
870
|
+
stamp_duty_rate=None if params["stamp_duty_rate"] is None else params["stamp_duty_rate"] * factor,
|
|
871
|
+
transfer_fee_rate=None if params["transfer_fee_rate"] is None else params["transfer_fee_rate"] * factor)
|
|
872
|
+
try:
|
|
873
|
+
result = _variant_metrics(bars, [bar["day"] for bar in bars], targets, columns, stressed, initial_capital, grade)
|
|
874
|
+
except (AnalysisInputError, ZeroDivisionError):
|
|
875
|
+
continue
|
|
876
|
+
costs.append({"cost_multiplier": factor, **result})
|
|
877
|
+
rolling = None
|
|
878
|
+
equity = None
|
|
879
|
+
if grade == "constrained_simulation":
|
|
880
|
+
equity = _run_constrained(bars, targets, [bar["day"] for bar in bars], columns, params, initial_capital)["equity"]
|
|
881
|
+
else:
|
|
882
|
+
equity = _run_signal_replay(bars, targets, [bar["day"] for bar in bars], params, initial_capital)["equity"]
|
|
883
|
+
window = min(120, max(20, n // 3))
|
|
884
|
+
if n >= window * 2:
|
|
885
|
+
window_returns = []
|
|
886
|
+
for index in range(window, len(equity), window):
|
|
887
|
+
start_value = equity[index - window]
|
|
888
|
+
if start_value > 0:
|
|
889
|
+
window_returns.append(equity[index] / start_value - 1.0)
|
|
890
|
+
if window_returns:
|
|
891
|
+
ordered = sorted(window_returns)
|
|
892
|
+
rolling = {
|
|
893
|
+
"window_bars": window,
|
|
894
|
+
"count": len(window_returns),
|
|
895
|
+
"min_return": _round(ordered[0]),
|
|
896
|
+
"median_return": _round(quantile(ordered, 0.5)),
|
|
897
|
+
"max_return": _round(ordered[-1]),
|
|
898
|
+
}
|
|
397
899
|
return {
|
|
900
|
+
"enabled": True,
|
|
901
|
+
"skipped": None,
|
|
902
|
+
"parameter_neighborhood": parameter,
|
|
903
|
+
"start_date": starts,
|
|
904
|
+
"cost_stress": costs,
|
|
905
|
+
"rolling_windows": rolling,
|
|
906
|
+
"note": "展示全部变体,不选择最佳参数或最佳区间",
|
|
907
|
+
}, None
|
|
908
|
+
|
|
909
|
+
|
|
910
|
+
# ── result assembly ────────────────────────────────────────────────────────────────────────
|
|
911
|
+
|
|
912
|
+
|
|
913
|
+
def _result(status, summary, metrics, methodology, limitations, gaps, outputs, simulation=None):
|
|
914
|
+
result = {
|
|
398
915
|
"status": status,
|
|
399
916
|
"summary": summary,
|
|
400
917
|
"metrics": metrics,
|
|
@@ -406,6 +923,9 @@ def _result(status, summary, metrics, methodology, limitations, gaps, outputs):
|
|
|
406
923
|
"data_gaps": gaps,
|
|
407
924
|
"outputs": outputs,
|
|
408
925
|
}
|
|
926
|
+
if simulation is not None:
|
|
927
|
+
result["simulation"] = simulation
|
|
928
|
+
return result
|
|
409
929
|
|
|
410
930
|
|
|
411
931
|
def _rule_text(rule, fast, slow):
|
|
@@ -414,199 +934,295 @@ def _rule_text(rule, fast, slow):
|
|
|
414
934
|
return f"price_above_sma(close 对 SMA{fast})"
|
|
415
935
|
|
|
416
936
|
|
|
417
|
-
def
|
|
418
|
-
if
|
|
419
|
-
return "
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
DISCLAIMER = "样本内回测、参数由调用方给定、未做参数寻优;不预测、不构成策略推荐。"
|
|
937
|
+
def _benchmark_label(source):
|
|
938
|
+
if source == "same_instrument_buy_and_hold":
|
|
939
|
+
return "同标的买入持有"
|
|
940
|
+
if isinstance(source, str) and source.startswith("dataset:"):
|
|
941
|
+
return f"外部基准 {source.split(':', 1)[1]}"
|
|
942
|
+
return str(source)
|
|
424
943
|
|
|
425
944
|
|
|
426
|
-
def
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
rule_text = _rule_text(rule, fast, slow)
|
|
431
|
-
parts = [
|
|
432
|
-
f"区间收益 {_pct(metrics['total_return'])}",
|
|
433
|
-
f"买入持有 {_pct(metrics['buy_and_hold_return'])}",
|
|
434
|
-
f"最大回撤 {_pct(metrics['max_drawdown'])}",
|
|
435
|
-
f"期末净值 {_fmt6(metrics['final_equity'])}",
|
|
436
|
-
]
|
|
437
|
-
trade_text = f"完整往返 {metrics['trade_count']} 笔"
|
|
438
|
-
if "win_rate" in metrics:
|
|
439
|
-
trade_text += f"、胜率 {_pct(metrics['win_rate'])}"
|
|
440
|
-
else:
|
|
441
|
-
trade_text += "(没有平仓交易,胜率无定义)"
|
|
442
|
-
if open_trades:
|
|
443
|
-
trade_text += f"、未平仓 {open_trades} 笔"
|
|
444
|
-
parts.append(trade_text)
|
|
445
|
-
parts.append(f"持有占比 {_pct(metrics['exposure_ratio'])}({metrics['exposure_bars']}/{len(points)} 根)")
|
|
446
|
-
parts.append(_fee_text(fee_rate))
|
|
447
|
-
body = f"{head},{rule_text}:" + ";".join(parts) + "。"
|
|
448
|
-
if gaps:
|
|
449
|
-
body += f"有 {len(gaps)} 项缺口,见 data_gaps。"
|
|
450
|
-
return body + DISCLAIMER
|
|
945
|
+
def _mode_text(mode):
|
|
946
|
+
return {"auto": "auto(有成交量与日历时约束模拟,否则降级)",
|
|
947
|
+
"constrained": "constrained(缺关键数据即拒绝)",
|
|
948
|
+
"signal_replay": "signal_replay(只重放信号)"}[mode]
|
|
451
949
|
|
|
452
950
|
|
|
453
951
|
def _blocked_summary(rule, fast, slow, points, required):
|
|
454
952
|
start, end = points[0]["day"], points[-1]["day"]
|
|
455
|
-
head = f"{start}..{end}(有效观测 {len(points)} 个)"
|
|
456
953
|
return (
|
|
457
|
-
f"{
|
|
458
|
-
f"(需要 max 窗口 + 2 = {required}
|
|
954
|
+
f"{start}..{end}(有效观测 {len(points)} 个):{_rule_text(rule, fast, slow)} 样本不足,未回测"
|
|
955
|
+
f"(需要 max 窗口 + 2 = {required} 个有效观测)。"
|
|
956
|
+
f"模拟等级 insufficient_data。" + DISCLAIMER
|
|
459
957
|
)
|
|
460
958
|
|
|
461
959
|
|
|
462
|
-
def
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
960
|
+
def _ledger_outputs(context, ledger_header, days):
|
|
961
|
+
"""Write the ledger inline when it fits one output, otherwise split it into numbered parts."""
|
|
962
|
+
inline = dict(ledger_header, columns=LEDGER_COLUMNS, days=days)
|
|
963
|
+
text = json.dumps(inline, ensure_ascii=False, separators=(",", ":"))
|
|
964
|
+
if len(text.encode("utf-8")) <= LEDGER_INLINE_MAX_BYTES:
|
|
965
|
+
ref = context.write_output(OUTPUT_NAME, inline)
|
|
966
|
+
return [{"name": OUTPUT_NAME, "ref": ref}], None
|
|
967
|
+
parts, chunk, size = [], [], 0
|
|
968
|
+
for row in days:
|
|
969
|
+
row_text = json.dumps(row, ensure_ascii=False, separators=(",", ":"))
|
|
970
|
+
if chunk and size + len(row_text) > LEDGER_CHUNK_MAX_BYTES:
|
|
971
|
+
parts.append(list(chunk))
|
|
972
|
+
chunk, size = [], 0
|
|
973
|
+
chunk.append(row)
|
|
974
|
+
size += len(row_text) + 1
|
|
975
|
+
if chunk:
|
|
976
|
+
parts.append(list(chunk))
|
|
977
|
+
outputs = []
|
|
978
|
+
part_meta = []
|
|
979
|
+
for number, rows in enumerate(parts, start=1):
|
|
980
|
+
name = f"ledger_part_{number:04d}"
|
|
981
|
+
ref = context.write_output(name, {"schema": LEDGER_SCHEMA, "part": number, "columns": LEDGER_COLUMNS, "days": rows})
|
|
982
|
+
outputs.append({"name": name, "ref": ref})
|
|
983
|
+
part_meta.append({"name": name, "rows": len(rows), "from": rows[0][0], "to": rows[-1][0]})
|
|
984
|
+
index = dict(ledger_header, columns=LEDGER_COLUMNS, row_count=len(days), parts=part_meta)
|
|
985
|
+
ref = context.write_output(OUTPUT_NAME, index)
|
|
986
|
+
outputs.insert(0, {"name": OUTPUT_NAME, "ref": ref})
|
|
987
|
+
return outputs, {
|
|
988
|
+
"reason": "账本超过单文件预算,按段输出(ledger.json 为索引)",
|
|
989
|
+
"parts": part_meta,
|
|
990
|
+
}
|
|
492
991
|
|
|
493
992
|
|
|
494
993
|
def analyze(request: dict, context) -> dict:
|
|
495
994
|
params = request.get("params") or {}
|
|
496
995
|
settings = _parameters(params)
|
|
497
996
|
rule, fast, slow = settings["rule"], settings["fast_window"], settings["slow_window"]
|
|
498
|
-
|
|
997
|
+
initial_capital = settings["initial_capital"]
|
|
499
998
|
|
|
500
999
|
views = _read_views(request, context)
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
if
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
price_view = views[price_dataset_id]
|
|
508
|
-
else:
|
|
509
|
-
candidates = _candidate(views, price_override, time_override)
|
|
510
|
-
if len(candidates) > 1:
|
|
511
|
-
raise AnalysisInputError(
|
|
512
|
-
f"有 {len(candidates)} 份 Dataset 都像价格序列({'、'.join(item[0] for item in candidates)}):"
|
|
513
|
-
"用 price_dataset_id 指明用哪一份"
|
|
514
|
-
)
|
|
515
|
-
if not candidates:
|
|
516
|
-
detail = f"(time_column={time_override} 不在任何 Dataset 里)" if time_override else ""
|
|
517
|
-
raise AnalysisInputError(
|
|
518
|
-
f"没有可识别的价格序列 Dataset{detail}:需要时间列 + close/adj_close/close_price/price/nav 之一"
|
|
519
|
-
)
|
|
520
|
-
price_dataset_id = candidates[0][0]
|
|
521
|
-
price_view = views[price_dataset_id]
|
|
522
|
-
|
|
523
|
-
time_column = _time_column(price_view, time_override)
|
|
524
|
-
price_column = _price_column(price_view, price_override)
|
|
1000
|
+
price_dataset_id, price_view = _pick_price_view(views, params)
|
|
1001
|
+
time_column = _time_column(price_view, _text(params.get("time_column")))
|
|
1002
|
+
price_column, inferred_basis = _pick_price_column(price_view, params)
|
|
1003
|
+
if settings["price_basis"] != "auto":
|
|
1004
|
+
inferred_basis = settings["price_basis"]
|
|
1005
|
+
adjusted = inferred_basis == "adjusted"
|
|
525
1006
|
tz_name = _text(params.get("timezone")) or "UTC"
|
|
526
1007
|
tz = _timezone(_text(params.get("timezone")))
|
|
527
|
-
points, dropped =
|
|
1008
|
+
points, dropped = price_series(price_view, price_dataset_id, price_column, time_column, tz, request=request)
|
|
528
1009
|
if not points:
|
|
529
1010
|
raise AnalysisInputError(f"Dataset {price_dataset_id} 没有有效价格观测:无法回测")
|
|
530
|
-
|
|
531
|
-
|
|
1011
|
+
rows = price_view.get("rows") or []
|
|
1012
|
+
columns = {
|
|
1013
|
+
"volume": _optional_column(params, price_view, "volume_column", "volume"),
|
|
1014
|
+
"high": _optional_column(params, price_view, "high_column", "high"),
|
|
1015
|
+
"low": _optional_column(params, price_view, "low_column", "low"),
|
|
1016
|
+
"limit_up": _optional_column(params, price_view, "limit_up_column", "limit_up"),
|
|
1017
|
+
"limit_down": _optional_column(params, price_view, "limit_down_column", "limit_down"),
|
|
1018
|
+
}
|
|
1019
|
+
bars = _bars(points, rows, columns)
|
|
1020
|
+
closes = [bar["close"] for bar in bars]
|
|
1021
|
+
n = len(bars)
|
|
532
1022
|
max_window = max(fast, slow if slow is not None else 0)
|
|
533
1023
|
required = max_window + 2
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
1024
|
+
|
|
1025
|
+
calendar_dataset_id = _text(params.get("calendar_dataset_id"))
|
|
1026
|
+
calendar_days = None
|
|
1027
|
+
if calendar_dataset_id is not None:
|
|
1028
|
+
if calendar_dataset_id not in views:
|
|
1029
|
+
raise AnalysisInputError(f"calendar_dataset_id={calendar_dataset_id} 不在本次快照的 Dataset 里")
|
|
1030
|
+
calendar_days = _trading_days_from(views[calendar_dataset_id])
|
|
1031
|
+
|
|
1032
|
+
has_volume = columns["volume"] is not None
|
|
1033
|
+
requested = settings["simulation_mode"]
|
|
1034
|
+
if requested == "constrained" and not (has_volume and calendar_days is not None):
|
|
1035
|
+
missing = []
|
|
1036
|
+
if not has_volume:
|
|
1037
|
+
missing.append("成交量列")
|
|
1038
|
+
if calendar_days is None:
|
|
1039
|
+
missing.append("交易日历 Dataset")
|
|
1040
|
+
gaps = [gapvocab.field_missing(f"constrained_simulation 需要{'与'.join(missing)}:缺这些输入时无法判断停牌与零成交量,未模拟成交")]
|
|
1041
|
+
simulation = _blocked_simulation(
|
|
1042
|
+
"调用方要求 constrained_simulation,但缺少 " + "、".join(missing),
|
|
1043
|
+
["simulation_mode=constrained"], columns, calendar_days is not None,
|
|
1044
|
+
)
|
|
1045
|
+
return _result(
|
|
1046
|
+
"blocked",
|
|
1047
|
+
f"{points[0]['day']}..{points[-1]['day']}:constrained_simulation 需要{'与'.join(missing)},未回测。"
|
|
1048
|
+
f"模拟等级 insufficient_data。" + DISCLAIMER,
|
|
1049
|
+
{}, ["读取价格序列", f"simulation_mode=constrained 但缺少 {'、'.join(missing)}:拒绝降级"],
|
|
1050
|
+
list(LIMITATIONS), gaps, [],
|
|
1051
|
+
simulation,
|
|
548
1052
|
)
|
|
549
|
-
limitations.append(f"跳过 {len(dropped)} 行后按剩余观测重排 bar 序号,均线窗口因此跨过被跳过的日期")
|
|
550
1053
|
|
|
551
1054
|
if n < required:
|
|
552
|
-
gaps.
|
|
1055
|
+
gaps = [gapvocab.sample_insufficient(
|
|
553
1056
|
f"有效观测不足 {required} 个(实际 {n} 个):{rule} 用 fast_window={fast}"
|
|
554
1057
|
+ (f" / slow_window={slow}" if slow is not None else "")
|
|
555
1058
|
+ f",需要 max 窗口 + 2 = {required} 个有效观测(填满窗口才出信号、下一根才成交)"
|
|
556
|
-
)
|
|
557
|
-
|
|
1059
|
+
)]
|
|
1060
|
+
simulation = _blocked_simulation(
|
|
1061
|
+
"有效观测不足", [f"observations={n} < required={required}"], columns, calendar_days is not None,
|
|
1062
|
+
)
|
|
1063
|
+
return _result(
|
|
1064
|
+
"blocked", _blocked_summary(rule, fast, slow, points, required), {},
|
|
1065
|
+
[f"价格 Dataset {price_dataset_id}:时间列 {time_column}、价格列 {price_column}",
|
|
1066
|
+
f"有效观测 {n} < {required}:未计算净值曲线、交易与统计"],
|
|
1067
|
+
list(LIMITATIONS), gaps, [], simulation,
|
|
1068
|
+
)
|
|
1069
|
+
|
|
1070
|
+
if dropped:
|
|
1071
|
+
gaps = [
|
|
1072
|
+
gapvocab.field_missing(
|
|
1073
|
+
f"价格列 {price_column} 有 {len(dropped)} 行不是正数或时间无法解析(已跳过):{_sample(dropped)}"
|
|
1074
|
+
),
|
|
1075
|
+
gapvocab.time_unavailable(
|
|
1076
|
+
f"价格序列有 {len(dropped)} 行被跳过:bar 序号会跨过缺口,回测要求连续 bar,未回测"
|
|
1077
|
+
),
|
|
1078
|
+
]
|
|
1079
|
+
simulation = _blocked_simulation(
|
|
1080
|
+
"价格序列有被跳过的坏行", [f"skipped_rows={len(dropped)}"], columns, calendar_days is not None,
|
|
1081
|
+
)
|
|
558
1082
|
return _result(
|
|
559
1083
|
"blocked",
|
|
560
|
-
|
|
1084
|
+
f"{points[0]['day']}..{points[-1]['day']}:价格序列有 {len(dropped)} 行坏行,缺口处不拼接收益,未回测。"
|
|
1085
|
+
f"模拟等级 insufficient_data。" + DISCLAIMER,
|
|
561
1086
|
{},
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
gaps,
|
|
565
|
-
[],
|
|
1087
|
+
[f"价格 Dataset {price_dataset_id}:时间列 {time_column}、价格列 {price_column}",
|
|
1088
|
+
f"跳过 {len(dropped)} 行:bar 必须连续,未计算净值与统计"],
|
|
1089
|
+
list(LIMITATIONS), gaps, [], simulation,
|
|
566
1090
|
)
|
|
567
1091
|
|
|
568
|
-
|
|
1092
|
+
axis_days = [bar["day"] for bar in bars]
|
|
1093
|
+
calendar_mismatch = []
|
|
1094
|
+
if calendar_days is not None:
|
|
1095
|
+
start, end = axis_days[0], axis_days[-1]
|
|
1096
|
+
in_range = sorted(day for day in calendar_days if start <= day <= end)
|
|
1097
|
+
not_in_calendar = [day for day in axis_days if day not in calendar_days]
|
|
1098
|
+
if not_in_calendar:
|
|
1099
|
+
calendar_mismatch = not_in_calendar[:5]
|
|
1100
|
+
axis_days = sorted(set(in_range) | set(axis_days))
|
|
1101
|
+
|
|
1102
|
+
grade = "signal_replay"
|
|
1103
|
+
if has_volume and calendar_days is not None:
|
|
1104
|
+
grade = "constrained_simulation"
|
|
1105
|
+
if requested == "signal_replay":
|
|
1106
|
+
grade = "signal_replay"
|
|
569
1107
|
targets, fast_sma, slow_sma = _targets(closes, rule, fast, slow)
|
|
570
|
-
closes, equity, position, trades = _backtest(points, targets, fee_rate, settings["initial_capital"])
|
|
571
|
-
metrics = _metrics(equity, closes, position, trades, settings["initial_capital"])
|
|
572
|
-
closed = [trade for trade in trades if not trade["open"]]
|
|
573
|
-
open_trades = len(trades) - len(closed)
|
|
574
|
-
if not closed:
|
|
575
|
-
gaps.append("没有已平仓交易:win_rate 无定义(不写 0)")
|
|
576
|
-
limitations.append("没有已平仓交易:win_rate 缺省,交易层面的统计给不出来,不是 0%")
|
|
577
|
-
if open_trades:
|
|
578
|
-
limitations.append(f"期末仍有 {open_trades} 笔未平仓交易:total_return 含未实现浮动盈亏,net_return 只对已平仓交易给")
|
|
579
|
-
if fee_rate == 0:
|
|
580
|
-
limitations.append("本次 fee_rate=0(未扣手续费):净值不含任何交易成本,不是策略本身没有成本")
|
|
581
|
-
if n < MIN_OBSERVATIONS_FOR_STABLE:
|
|
582
|
-
limitations.append(f"只有 {n} 个有效观测:样本很短,胜率与净值对个别交易日敏感,只能作方向性参考")
|
|
583
|
-
status = "partial" if gaps else "completed"
|
|
584
|
-
methodology.append(
|
|
585
|
-
f"完整往返 {len(closed)} 笔、未平仓 {open_trades} 笔;"
|
|
586
|
-
f"持有占比 {metrics['exposure_bars']}/{n} = {_fmt6(metrics['exposure_ratio'])}"
|
|
587
|
-
)
|
|
588
|
-
methodology.append(f"{len(gaps)} 项缺口")
|
|
589
|
-
|
|
590
|
-
series = []
|
|
591
|
-
for index, point in enumerate(points):
|
|
592
|
-
row = {
|
|
593
|
-
"date": point["day"],
|
|
594
|
-
"close": _round(closes[index]),
|
|
595
|
-
"sma_fast": None if fast_sma[index] is None else _round(fast_sma[index]),
|
|
596
|
-
}
|
|
597
|
-
if slow_sma is not None:
|
|
598
|
-
row["sma_slow"] = None if slow_sma[index] is None else _round(slow_sma[index])
|
|
599
|
-
row.update({
|
|
600
|
-
"signal": targets[index],
|
|
601
|
-
"position": position[index],
|
|
602
|
-
"equity": _round(equity[index]),
|
|
603
|
-
})
|
|
604
|
-
series.append(row)
|
|
605
1108
|
|
|
606
|
-
|
|
607
|
-
|
|
1109
|
+
benchmark_dataset_id = _text(params.get("benchmark_dataset_id"))
|
|
1110
|
+
benchmark_source = "same_instrument_buy_and_hold"
|
|
1111
|
+
benchmark_equity = None
|
|
1112
|
+
benchmark_missing_days = 0
|
|
1113
|
+
if benchmark_dataset_id is not None:
|
|
1114
|
+
if benchmark_dataset_id not in views:
|
|
1115
|
+
raise AnalysisInputError(f"benchmark_dataset_id={benchmark_dataset_id} 不在本次快照的 Dataset 里")
|
|
1116
|
+
benchmark_view = views[benchmark_dataset_id]
|
|
1117
|
+
benchmark_time = _time_column(benchmark_view, _text(params.get("benchmark_time_column")))
|
|
1118
|
+
benchmark_price_column, _basis = _pick_price_column(benchmark_view, {})
|
|
1119
|
+
benchmark_points, benchmark_dropped = price_series(
|
|
1120
|
+
benchmark_view, benchmark_dataset_id, benchmark_price_column, benchmark_time, tz, request=request
|
|
1121
|
+
)
|
|
1122
|
+
if len(benchmark_points) < 2:
|
|
1123
|
+
raise AnalysisInputError(f"基准 Dataset {benchmark_dataset_id} 有效观测不足 2 个:无法对齐")
|
|
1124
|
+
benchmark_equity, benchmark_missing_days = _benchmark_equity(axis_days, benchmark_points)
|
|
1125
|
+
benchmark_source = f"dataset:{benchmark_dataset_id}"
|
|
1126
|
+
if benchmark_equity is None:
|
|
1127
|
+
by_day = {bar["day"]: bar["close"] for bar in bars}
|
|
1128
|
+
last = None
|
|
1129
|
+
benchmark_equity = []
|
|
1130
|
+
for day in axis_days:
|
|
1131
|
+
last = by_day.get(day, last)
|
|
1132
|
+
benchmark_equity.append(last)
|
|
1133
|
+
benchmark_equity, benchmark_missing_days = _benchmark_equity(
|
|
1134
|
+
axis_days, [{"day": day, "price": value} for day, value in zip(axis_days, benchmark_equity) if value is not None]
|
|
1135
|
+
)
|
|
1136
|
+
|
|
1137
|
+
sim_params = dict(settings)
|
|
1138
|
+
if grade == "constrained_simulation":
|
|
1139
|
+
run = _run_constrained(bars, targets, axis_days, columns, sim_params, initial_capital)
|
|
1140
|
+
else:
|
|
1141
|
+
run = _run_signal_replay(bars, targets, axis_days, sim_params, initial_capital)
|
|
1142
|
+
|
|
1143
|
+
positions = run["positions"]
|
|
1144
|
+
exposure_bars = sum(1 for position in positions if position == 1)
|
|
1145
|
+
equity = run["equity"]
|
|
1146
|
+
metrics, returns, _benchmark_returns, closed, wins = _performance(
|
|
1147
|
+
equity, benchmark_equity, run["trades"], axis_days, settings, run["fees_total"], run["slippage_total"],
|
|
1148
|
+
run["traded_amount"],
|
|
1149
|
+
)
|
|
1150
|
+
metrics["exposure_ratio"] = _round(exposure_bars / len(equity)) if equity else None
|
|
1151
|
+
removed_keys = []
|
|
1152
|
+
gaps = []
|
|
1153
|
+
if dropped:
|
|
1154
|
+
gaps.append(gapvocab.field_missing(
|
|
1155
|
+
f"价格列 {price_column} 有 {len(dropped)} 行不是正数或时间无法解析(已跳过):{_sample(dropped)}"
|
|
1156
|
+
))
|
|
1157
|
+
if calendar_mismatch:
|
|
1158
|
+
gaps.append(gapvocab.calendar_mismatch(
|
|
1159
|
+
f"价格序列有 {len(calendar_mismatch)} 个日期不在交易日历里(按交易日处理):{'、'.join(calendar_mismatch)}"
|
|
1160
|
+
))
|
|
1161
|
+
if benchmark_missing_days:
|
|
1162
|
+
gaps.append(gapvocab.time_unavailable(
|
|
1163
|
+
f"基准序列有 {benchmark_missing_days} 天没有有效收盘(按前值标记)"
|
|
1164
|
+
))
|
|
1165
|
+
for name in ("win_rate", "profit_factor", "payoff_ratio"):
|
|
1166
|
+
if metrics.get(name) is None:
|
|
1167
|
+
gaps.append(gapvocab.sample_insufficient(f"没有可用于该统计的已平仓交易:{name} 无定义(不写 0)"))
|
|
1168
|
+
removed_keys.append(name)
|
|
1169
|
+
if metrics.get("sharpe_ratio") is None:
|
|
1170
|
+
gaps.append(gapvocab.sample_insufficient("波动率为 0 或样本不足:sharpe_ratio 无定义"))
|
|
1171
|
+
removed_keys.append("sharpe_ratio")
|
|
1172
|
+
if metrics.get("sortino_ratio") is None:
|
|
1173
|
+
gaps.append(gapvocab.sample_insufficient("下行波动为 0 或样本不足:sortino_ratio 无定义"))
|
|
1174
|
+
removed_keys.append("sortino_ratio")
|
|
1175
|
+
if metrics.get("calmar_ratio") is None:
|
|
1176
|
+
gaps.append(gapvocab.sample_insufficient("没有回撤:calmar_ratio 无定义"))
|
|
1177
|
+
removed_keys.append("calmar_ratio")
|
|
1178
|
+
if metrics.get("tracking_error") is None:
|
|
1179
|
+
gaps.append(gapvocab.sample_insufficient("主动收益样本不足:tracking_error 无定义"))
|
|
1180
|
+
removed_keys.append("tracking_error")
|
|
1181
|
+
if metrics.get("information_ratio") is None:
|
|
1182
|
+
gaps.append(gapvocab.sample_insufficient("tracking_error 无定义或无超额:information_ratio 无定义"))
|
|
1183
|
+
removed_keys.append("information_ratio")
|
|
1184
|
+
for name in removed_keys:
|
|
1185
|
+
if name in metrics:
|
|
1186
|
+
metrics[name] = None
|
|
1187
|
+
robustness, robustness_skipped = _robustness(bars, closes, targets, columns, settings, initial_capital, grade)
|
|
1188
|
+
audit = _audit(grade, adjusted, dropped, calendar_mismatch, benchmark_source, robustness_skipped, len(closed), settings)
|
|
1189
|
+
fees_block = _fee_plan(settings)
|
|
1190
|
+
simulation = {
|
|
1191
|
+
"grade": grade,
|
|
1192
|
+
"cost_basis": "net" if (settings["commission_rate"] > 0 or settings["slippage_bps"] > 0) else "gross",
|
|
1193
|
+
"out_of_sample": False,
|
|
1194
|
+
"restated_history": False,
|
|
1195
|
+
"constraints": _constraints_block(grade, columns, calendar_days, adjusted, settings, fees_block),
|
|
1196
|
+
"fee_rules": _fee_rules(run["rows"]),
|
|
1197
|
+
"audit": audit,
|
|
1198
|
+
}
|
|
1199
|
+
if requested == "auto" and grade == "signal_replay":
|
|
1200
|
+
gaps.insert(0, gapvocab.assumption_missing(
|
|
1201
|
+
"缺少成交量列或交易日历:自动降级为 signal_replay(模拟等级与未覆盖风险见 simulation.audit)"
|
|
1202
|
+
))
|
|
1203
|
+
if has_volume is False and requested != "signal_replay":
|
|
1204
|
+
simulation["audit"]["uncovered_risks"].append("没有成交量列:零成交量与停牌无法从数据识别")
|
|
1205
|
+
if calendar_days is None and requested != "signal_replay":
|
|
1206
|
+
simulation["audit"]["uncovered_risks"].append("没有交易日历:节假日与停牌日无法区分")
|
|
1207
|
+
if robustness.get("skipped") == "sample_too_large":
|
|
1208
|
+
gaps.append(gapvocab.sample_insufficient(
|
|
1209
|
+
f"样本 {n} 根超过稳健性复算上限 {ROBUSTNESS_MAX_BARS} 根:参数邻域/起始日期/成本压力未计算"
|
|
1210
|
+
))
|
|
1211
|
+
status = "completed"
|
|
1212
|
+
if grade == "signal_replay" and requested == "auto":
|
|
1213
|
+
status = "partial"
|
|
1214
|
+
if gaps:
|
|
1215
|
+
status = "partial"
|
|
1216
|
+
if audit["status"] == "FAIL":
|
|
1217
|
+
status = "blocked"
|
|
1218
|
+
if status == "blocked":
|
|
1219
|
+
simulation["audit"]["status"] = "FAIL"
|
|
1220
|
+
|
|
1221
|
+
ledger_header = {
|
|
1222
|
+
"schema": LEDGER_SCHEMA,
|
|
608
1223
|
"module_id": MODULE_ID,
|
|
609
1224
|
"module_version": MODULE_VERSION,
|
|
1225
|
+
"protocol": request.get("protocol"),
|
|
610
1226
|
"analysis_id": request.get("analysis_id"),
|
|
611
1227
|
"module_run_id": request.get("module_run_id"),
|
|
612
1228
|
"price_dataset_id": price_dataset_id,
|
|
@@ -617,32 +1233,103 @@ def analyze(request: dict, context) -> dict:
|
|
|
617
1233
|
"rule": rule,
|
|
618
1234
|
"fast_window": fast,
|
|
619
1235
|
"slow_window": slow,
|
|
620
|
-
"initial_capital":
|
|
621
|
-
"fee_rate": fee_rate,
|
|
1236
|
+
"initial_capital": initial_capital,
|
|
622
1237
|
"timezone": tz_name,
|
|
1238
|
+
"simulation_mode": requested,
|
|
1239
|
+
"price_basis": inferred_basis,
|
|
1240
|
+
"limit_pct": settings["limit_pct"],
|
|
1241
|
+
"lot_size": settings["lot_size"],
|
|
1242
|
+
"commission_rate": settings["commission_rate"],
|
|
1243
|
+
"min_commission": settings["min_commission"],
|
|
1244
|
+
"slippage_bps": settings["slippage_bps"],
|
|
1245
|
+
"stamp_duty_rate": settings["stamp_duty_rate"],
|
|
1246
|
+
"transfer_fee_rate": settings["transfer_fee_rate"],
|
|
1247
|
+
"risk_free_rate": settings["risk_free_rate"],
|
|
1248
|
+
"periods_per_year": settings["periods_per_year"],
|
|
1249
|
+
"benchmark_dataset_id": benchmark_dataset_id,
|
|
1250
|
+
"calendar_dataset_id": calendar_dataset_id,
|
|
623
1251
|
},
|
|
624
1252
|
"window": {
|
|
625
|
-
"start":
|
|
626
|
-
"end":
|
|
1253
|
+
"start": axis_days[0],
|
|
1254
|
+
"end": axis_days[-1],
|
|
627
1255
|
"observations": n,
|
|
1256
|
+
"axis_days": len(axis_days),
|
|
628
1257
|
"skipped_rows": len(dropped),
|
|
629
1258
|
},
|
|
630
|
-
"
|
|
631
|
-
"
|
|
632
|
-
"
|
|
633
|
-
|
|
1259
|
+
"simulation": simulation,
|
|
1260
|
+
"benchmark_source": benchmark_source,
|
|
1261
|
+
"research_design": {
|
|
1262
|
+
"in_sample": True,
|
|
1263
|
+
"out_of_sample": False,
|
|
1264
|
+
"parameter_selection": "caller_supplied",
|
|
1265
|
+
"data_snooping_disclosed": True,
|
|
1266
|
+
"survivorship_bias_note": "单标的/显式集合;不宣称无幸存者偏差,也不把当前存活标的当作历史全市场",
|
|
1267
|
+
},
|
|
1268
|
+
"summary": metrics,
|
|
1269
|
+
"robustness": robustness,
|
|
1270
|
+
"orders": run["orders"],
|
|
1271
|
+
"trades": run["trades"],
|
|
634
1272
|
}
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
1273
|
+
outputs, ledger_split = _ledger_outputs(context, ledger_header, run["rows"])
|
|
1274
|
+
if ledger_split is not None:
|
|
1275
|
+
gaps.append(gapvocab.assumption_missing(ledger_split["reason"] + ":ledger.json 为索引,逐日记录在 parts 里"))
|
|
1276
|
+
limitations = list(LIMITATIONS) + [ledger_split["reason"]]
|
|
1277
|
+
status = "partial" if status == "completed" else status
|
|
1278
|
+
else:
|
|
1279
|
+
limitations = list(LIMITATIONS)
|
|
1280
|
+
if dropped:
|
|
1281
|
+
limitations.append(f"跳过 {len(dropped)} 行:时间无法解析或价格非正")
|
|
1282
|
+
if calendar_mismatch:
|
|
1283
|
+
limitations.append(f"{len(calendar_mismatch)} 个价格日期不在交易日历里:按交易日处理并记缺口")
|
|
1284
|
+
if not adjusted:
|
|
1285
|
+
limitations.append("未复权价格:除权跳变会原样进入净值,公司行为未单独建模")
|
|
1286
|
+
if settings["commission_rate"] == 0 and settings["slippage_bps"] == 0:
|
|
1287
|
+
limitations.append("本次 commission_rate=0、slippage_bps=0:净值不含交易成本,不是策略本身没有成本")
|
|
1288
|
+
if grade == "signal_replay":
|
|
1289
|
+
limitations.append("signal_replay:未模拟涨跌停/停牌/T+1/整手,成交假设弱于 constrained_simulation")
|
|
1290
|
+
if benchmark_dataset_id is None:
|
|
1291
|
+
limitations.append("没有外部基准:基准为同标的买入持有,不含指数或行业基准")
|
|
1292
|
+
if n < MIN_OBSERVATIONS_FOR_STABLE:
|
|
1293
|
+
limitations.append(f"只有 {n} 个有效观测:样本很短,胜率与净值对个别交易日敏感,只能作方向性参考")
|
|
1294
|
+
|
|
1295
|
+
trade_text = f"完整往返 {len(closed)} 笔"
|
|
1296
|
+
if metrics.get("win_rate") is None:
|
|
1297
|
+
trade_text += "(没有平仓交易,胜率无定义)"
|
|
1298
|
+
else:
|
|
1299
|
+
trade_text += f"、胜率 {_pct(metrics['win_rate'])}"
|
|
1300
|
+
open_trades = len(run["trades"]) - len(closed)
|
|
1301
|
+
if open_trades:
|
|
1302
|
+
trade_text += f"、未平仓 {open_trades} 笔"
|
|
1303
|
+
summary = (
|
|
1304
|
+
f"{axis_days[0]}..{axis_days[-1]}(有效观测 {n} 个"
|
|
1305
|
+
+ (f",跳过 {len(dropped)} 行" if dropped else "")
|
|
1306
|
+
+ f"):{_rule_text(rule, fast, slow)},模拟等级 {grade}、费用口径 {simulation['cost_basis']}。"
|
|
1307
|
+
f"区间收益 {_pct(metrics['total_return'])};"
|
|
1308
|
+
f"基准({_benchmark_label(benchmark_source)}){_pct(metrics['benchmark_return'])}"
|
|
1309
|
+
+ (f",超额 {_pct(metrics['excess_return'])}" if metrics.get('excess_return') is not None else "")
|
|
1310
|
+
+ f";最大回撤 {_pct(metrics['max_drawdown'])}(持续 {metrics['max_drawdown_duration']} 根);"
|
|
1311
|
+
f"{trade_text};持有占比 {_pct(metrics['exposure_ratio'])};"
|
|
1312
|
+
f"费用 {_fmt6(metrics['total_fees'])}、滑点 {_fmt6(metrics['slippage_cost'])};"
|
|
1313
|
+
f"审计 {audit['status']}(未覆盖风险 {len(audit['uncovered_risks'])} 项,见 simulation.audit)。"
|
|
1314
|
+
+ (f"有 {len(gaps)} 项缺口,见 data_gaps。" if gaps else "")
|
|
1315
|
+
+ DISCLAIMER
|
|
639
1316
|
)
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
1317
|
+
methodology = [
|
|
1318
|
+
f"价格 Dataset {price_dataset_id}:时间列 {time_column}、价格列 {price_column}({inferred_basis});"
|
|
1319
|
+
f"数值时间轴按 {tz_name} 标注日历日",
|
|
1320
|
+
f"模拟模式 {_mode_text(requested)};simulation_mode={requested}、limit_pct={settings['limit_pct']:g}、"
|
|
1321
|
+
f"lot_size={settings['lot_size']}、commission_rate={settings['commission_rate']:g}、"
|
|
1322
|
+
f"min_commission={settings['min_commission']:g}、slippage_bps={settings['slippage_bps']:g}",
|
|
1323
|
+
f"规则 {_rule_text(rule, fast, slow)};initial_capital={_fmt6(initial_capital)};"
|
|
1324
|
+
f"信号在第 t 根收盘算出、第 t+1 根收盘执行",
|
|
1325
|
+
f"账本 {len(run['orders'])} 条订单({len(closed)} 笔平仓、{open_trades} 笔未平仓)、{len(axis_days)} 个交易日;"
|
|
1326
|
+
f"涨跌停来源 {simulation['constraints']['limit_prices']}、交易日历 "
|
|
1327
|
+
f"{'dataset' if calendar_days is not None else 'none'}、基准 {benchmark_source}",
|
|
1328
|
+
]
|
|
1329
|
+
context.log(
|
|
1330
|
+
f"{MODULE_ID}: {status} grade={grade} audit={audit['status']} bars={len(axis_days)} "
|
|
1331
|
+
f"trades={len(closed)} open={open_trades} gaps={len(gaps)}"
|
|
648
1332
|
)
|
|
1333
|
+
result = _result(status, summary, metrics, methodology, limitations, gaps, outputs, simulation)
|
|
1334
|
+
result["sensitivity"] = {"robustness": robustness}
|
|
1335
|
+
return result
|