stock-analysis-plugin 0.2.6 → 0.2.8
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/README.md +88 -15
- package/package.json +2 -1
- package/pi/index.ts +867 -72
- package/schemas/market_review_schema.json +12 -5
- package/schemas/report_schema.json +65 -1
- package/scripts/cli-timeout.mjs +27 -0
- package/scripts/json-input.mjs +26 -0
- package/skills/bull-trend/SKILL.md +11 -1
- package/skills/bull-trend/references/monthly-trend-strategy.md +47 -0
- package/skills/bull-trend/references/trend-horizons.md +43 -0
- package/skills/bull-trend/references/trend-temperature.md +57 -0
- package/skills/bull-trend/scripts/market_trend.py +78 -0
- package/skills/event-driven/SKILL.md +4 -0
- package/skills/growth-quality/SKILL.md +4 -0
- package/skills/market-review/SKILL.md +2 -0
- package/skills/stock-analysis/SKILL.md +17 -3
- package/skills/stock-analysis/references/stateless-analysis.md +66 -0
- package/skills/stock-screener/SKILL.md +5 -1
- package/skills/strategy-backtest/SKILL.md +19 -0
- package/templates/market_review/full.md.j2 +7 -0
- package/templates/stock_analysis/_evidence.md.j2 +11 -0
- package/templates/stock_analysis/brief.md.j2 +2 -0
- package/templates/stock_analysis/full.md.j2 +2 -0
- package/tools/_subproc.py +66 -11
- package/tools/backtest.py +143 -19
- package/tools/capabilities.py +12 -0
- package/tools/cli_budgets.json +27 -0
- package/tools/gather.py +4 -6
- package/tools/market_review.py +30 -9
- package/tools/screener.py +57 -15
- package/tools/signal_tracker.py +77 -6
- package/tools/stateless_analysis.py +630 -0
- package/tools/stock_data.py +90 -15
- package/tools/technical.py +186 -0
- package/tools/trend_strategy.py +365 -0
- package/tools/watchlist_context.py +18 -7
|
@@ -5,10 +5,16 @@ description: 策略回测:定义或读取 AlphaEvo YAML 策略,回测收益
|
|
|
5
5
|
|
|
6
6
|
# 策略回测与优化
|
|
7
7
|
|
|
8
|
+
生成股票池月度右侧趋势计划时,先读 [月度右侧趋势策略](../bull-trend/references/monthly-trend-strategy.md),直接以股票代码调用 `analyze_trend_strategy(symbols, ...)` 自动取行情,无需用户准备文件。这是整池信号/预算分析;共享资金历史绩效仍依据冻结研究,MUST NOT 用单股YAML或信号计划冒充组合回测。报告尚未通过跨样本效果验证的边界。
|
|
9
|
+
|
|
8
10
|
开始前读取[短线交易决策框架](../stock-analysis/references/short-term-trading.md)的风险单位和回测约束。回测用于反证策略,不把样本内收益包装成预测。
|
|
9
11
|
|
|
10
12
|
解读回测时,`period` 是实际取得的数据期间,`requested_period` 保留用户请求,`warnings` 提示两者差异。年化收益按实际期间计算;覆盖不完整时明确说明,不能声称完成了完整请求期间的验证。买入预算包含佣金,`position.size` 为 0..1 的资金比例。
|
|
11
13
|
|
|
14
|
+
## 无状态分析扩展
|
|
15
|
+
|
|
16
|
+
滚动样本外、参数敏感性或跨标的验证时,MUST 读取[无状态研究工具](../stock-analysis/references/stateless-analysis.md)的 validate_backtest 分支。复用 get_kline,传完整OHLCV和事先确定的DSL候选;样本内sensitivity不等于样本外验证。
|
|
17
|
+
|
|
12
18
|
## 工作流程
|
|
13
19
|
|
|
14
20
|
### 第一步:策略定义
|
|
@@ -42,6 +48,7 @@ exit:
|
|
|
42
48
|
take_profit: 0.15 # 止盈比例
|
|
43
49
|
|
|
44
50
|
simulation:
|
|
51
|
+
execution: next_open # 默认:前日收盘信号,次日开盘成交
|
|
45
52
|
slippage: 0.001 # 滑点(买卖双边),默认 0.001
|
|
46
53
|
commission: 0.00025 # 佣金(买卖双边,券商自定;A股常见万2.5),默认 0.0015
|
|
47
54
|
stamp_tax: 0.0005 # 印花税(仅卖出收;A股 0.05%,其他市场按当下实际费率,无则省略),默认 0
|
|
@@ -53,6 +60,12 @@ position:
|
|
|
53
60
|
|
|
54
61
|
**可用指标**:rsi, ma, ema, macd_dif, macd_dea, macd, volume_ratio, price_change, bollinger_position, close, volume
|
|
55
62
|
|
|
63
|
+
`monthly_momentum` 是共享核心的月度观察对数收益:`period` 默认63,支持21/63/252等正整数;月初首根正成交量日K收盘计算并保持到下次月度观察,次日开盘才可能成交。零成交量记录不计回溯根数。MUST 读取 [多期限月度趋势](../bull-trend/references/trend-horizons.md),不能把单期限YAML等同三子策略组合。需要在观察日已有period+1根有效日K;默认回测起点会截断输入历史,不能据此声称提前完成预热。三期限同资金起点的完整研究复现使用参考里的研究脚本。
|
|
64
|
+
|
|
65
|
+
独立趋势强度可用 `trend_score`,默认 `(EMA20-EMA60)/ATR14`,ATR 为真实波幅简单平均。`fast_period/slow_period/period` 分别控制快 EMA、慢 EMA、ATR,要求正整数且快线小于慢线;默认 60 根预热,预热或零 ATR 不触发条件。解释七档显示、初始化与样本外验证前 MUST 读取 [独立趋势温度](../bull-trend/references/trend-temperature.md)。它不是星球温度或肥尾信号,原固定止损/止盈默认值仍生效。
|
|
66
|
+
|
|
67
|
+
该字段的 `validation_status=not_validated`。已有真实股票试验未支持默认温度入场规则;MUST NOT 自行补出“温转热买、降温卖”或零轴规则作为推荐策略。用户指定规则时可运行研究回测,但 MUST 同时报基准、成本、回撤及验证局限。
|
|
68
|
+
|
|
56
69
|
**可用运算符**:`>`, `<`, `>=`, `<=`, `==`, `cross_above`, `cross_below`
|
|
57
70
|
|
|
58
71
|
### 第二步:运行回测
|
|
@@ -70,6 +83,10 @@ python3 tools/backtest.py run <path.yaml> <symbol> --start <date> --end <date>
|
|
|
70
83
|
- `--start` / `--end`:回测时间范围(可选,默认近一年)
|
|
71
84
|
- 初始资金默认 100 万,可用 `--capital` 调整
|
|
72
85
|
|
|
86
|
+
默认 `simulation.execution=next_open`:信号在前一交易日收盘确定,下一有效交易日按开盘价加滑点成交;交易同时保留 `signal_date` 与实际 `date`。最后一天新信号没有后续开盘时不能成交。需要复现旧结果时显式使用 `same_close`,并说明它按信号日收盘成交,可能高估可执行收益。零/缺失成交量(已有 volume 字段时)阻止成交;一字涨跌停仅在输入提供同口径历史 `limit_up/limit_down` 时保守阻止,不猜 ST、IPO 或 ETF 限价。
|
|
87
|
+
|
|
88
|
+
读取 `execution.model/blocked_orders/unfilled_order/limitations` 并说明未成交情况。止损、止盈和移动止损均是收盘信号,不承诺盘中按阈值成交;次日跳空按实际开盘价计算。没有历史限价数据时,不能声称已验证涨跌停可成交性。
|
|
89
|
+
|
|
73
90
|
### 第三步:分析结果
|
|
74
91
|
|
|
75
92
|
回测完成后,按共享框架的风险单位和回测约束解释原始结果。针对本工具:
|
|
@@ -141,3 +158,5 @@ python3 tools/backtest.py run <path.yaml> <symbol> --start <date> --end <date>
|
|
|
141
158
|
参考 `{baseDir}/strategies/examples/` 目录中的示例:
|
|
142
159
|
- `rsi_oversold.yaml` — RSI 超卖反弹
|
|
143
160
|
- `ma_crossover.yaml` — 均线金叉
|
|
161
|
+
|
|
162
|
+
市场环境只限制新开仓的三期限月度实验,使用 [bull-trend参考](../bull-trend/references/trend-horizons.md#市场环境入场实验) 与 `../bull-trend/scripts/market_trend.py`,输入两份带预热的daily OHLCV JSON。普通单期限YAML不会自动提供该组合或市场数据;未知市场历史禁止新入,市场转弱不冒充个股退出。初始投资时不能把预热虚拟信号当实际持仓。
|
|
@@ -4,6 +4,13 @@
|
|
|
4
4
|
{% set t = temperature or {} -%}
|
|
5
5
|
**温度:** {{ m.signal_emoji(t.signal) }} {{ m.fmt_num(t.score, 1) }}/100 | **信号灯:** {{ m.signal_label(t.signal) }} | **策略姿态:** {{ m.stance_label(strategy_stance) }}
|
|
6
6
|
|
|
7
|
+
{% if data_quality and data_quality.limitations -%}
|
|
8
|
+
**数据限制:**
|
|
9
|
+
{% for limitation in data_quality.limitations %}
|
|
10
|
+
- {{ limitation }}
|
|
11
|
+
{% endfor %}
|
|
12
|
+
{%- endif %}
|
|
13
|
+
|
|
7
14
|
{% if regime and (regime.regime_cn or regime.regime) -%}
|
|
8
15
|
> **市场阶段:** {{ regime.regime_cn or regime.regime }}{% if regime.confidence is not none %}(置信度 {{ m.fmt_num(regime.confidence) }}){% endif %}{% if regime.recommended_skills %} | **推荐策略:** {{ regime.recommended_skills | join('、') }}{% endif %}
|
|
9
16
|
{%- endif %}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
{% if data_quality or evidence %}
|
|
2
|
+
|
|
3
|
+
### 本次数据与限制
|
|
4
|
+
|
|
5
|
+
{% for item in evidence or [] %}
|
|
6
|
+
- **{{ item.label or '数据依据' }}:** {{ item.value if item.value is not none else '未知' }}(来源:{{ item.source or '未标明' }};数据时间:{{ item.as_of or '未知' }})
|
|
7
|
+
{% endfor %}
|
|
8
|
+
{% for limitation in (data_quality or {}).limitations or [] %}
|
|
9
|
+
- {{ limitation }}
|
|
10
|
+
{% endfor %}
|
|
11
|
+
{% endif %}
|
package/tools/_subproc.py
CHANGED
|
@@ -14,10 +14,44 @@ import re
|
|
|
14
14
|
import socket
|
|
15
15
|
import subprocess
|
|
16
16
|
import sys
|
|
17
|
+
from pathlib import Path
|
|
17
18
|
|
|
18
19
|
TOOLS_DIR = os.path.dirname(os.path.abspath(__file__))
|
|
19
20
|
|
|
20
21
|
|
|
22
|
+
COMMAND_BUDGETS = json.loads((Path(TOOLS_DIR) / "cli_budgets.json").read_text(encoding="utf-8"))
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def command_timeout(script: str, args: list) -> int:
|
|
26
|
+
key = f"{Path(script).name}:{args[0] if args else ''}"
|
|
27
|
+
budget = COMMAND_BUDGETS.get(key, COMMAND_BUDGETS["default"])
|
|
28
|
+
|
|
29
|
+
def option(name, default):
|
|
30
|
+
return args[args.index(name) + 1] if name in args and args.index(name) + 1 < len(args) else default
|
|
31
|
+
|
|
32
|
+
def positive_int(value, default):
|
|
33
|
+
return int(value) if str(value).isdigit() and int(value) > 0 else default
|
|
34
|
+
|
|
35
|
+
if key == "screener.py:screen":
|
|
36
|
+
top = positive_int(option("--top", 20), 20)
|
|
37
|
+
workers = COMMAND_BUDGETS["l2_workers"]
|
|
38
|
+
budget += math.ceil(top / workers) * COMMAND_BUDGETS["l2_batch"]
|
|
39
|
+
elif key in ("watchlist.py:analyze", "watchlist_context.py:build"):
|
|
40
|
+
count = len([s for s in str(args[1] if len(args) > 1 else "").split(",") if s.strip()])
|
|
41
|
+
workers = positive_int(option("--workers", 3), 3)
|
|
42
|
+
budget += math.ceil(count / workers) * COMMAND_BUDGETS["watchlist_item"]
|
|
43
|
+
if key == "watchlist_context.py:build":
|
|
44
|
+
budget += math.ceil(count / min(workers * 2, 6)) * COMMAND_BUDGETS["anomaly_detect.py:detect"]
|
|
45
|
+
if "--include-market-review" in args:
|
|
46
|
+
budget += 3 * COMMAND_BUDGETS["market_review.py:review"] + 30
|
|
47
|
+
elif key == "market_review.py:review" and option("--market", "A") == "all":
|
|
48
|
+
budget = 3 * budget + 30
|
|
49
|
+
elif key == "technical.py:analyze" and "--periods" in args:
|
|
50
|
+
periods = {p.strip() for p in str(option("--periods", "daily")).split(",") if p.strip()}
|
|
51
|
+
budget *= len(periods | {option("--period", "daily")})
|
|
52
|
+
return budget
|
|
53
|
+
|
|
54
|
+
|
|
21
55
|
def find_python() -> str:
|
|
22
56
|
"""Prefer the repo .venv interpreter; fall back to the current one.
|
|
23
57
|
|
|
@@ -29,12 +63,20 @@ def find_python() -> str:
|
|
|
29
63
|
return venv if os.path.exists(venv) else sys.executable
|
|
30
64
|
|
|
31
65
|
|
|
32
|
-
def run_tool(
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
66
|
+
def run_tool(
|
|
67
|
+
script: str, args: list, timeout: int | None = None, parse_json: bool = True, preserve_errors: bool = False
|
|
68
|
+
):
|
|
69
|
+
"""Run a sibling CLI; opt in to safe error data, otherwise keep the None sentinel."""
|
|
70
|
+
|
|
71
|
+
if timeout is None:
|
|
72
|
+
timeout = command_timeout(script, args)
|
|
73
|
+
|
|
74
|
+
def failure(message, code):
|
|
75
|
+
if not preserve_errors:
|
|
76
|
+
return None
|
|
77
|
+
payload = {"error": scrub_secrets(message), "error_code": code}
|
|
78
|
+
return payload if parse_json else json.dumps(payload, ensure_ascii=False)
|
|
79
|
+
|
|
38
80
|
try:
|
|
39
81
|
r = subprocess.run(
|
|
40
82
|
[find_python(), os.path.join(TOOLS_DIR, script), *args],
|
|
@@ -43,11 +85,24 @@ def run_tool(script: str, args: list, timeout: int = 30, parse_json: bool = True
|
|
|
43
85
|
encoding="utf-8",
|
|
44
86
|
timeout=timeout,
|
|
45
87
|
)
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
88
|
+
raw = r.stdout.strip()
|
|
89
|
+
if not raw:
|
|
90
|
+
return failure("Python command returned no JSON", "empty_output")
|
|
91
|
+
if not preserve_errors:
|
|
92
|
+
return (json.loads(raw) if parse_json else raw) if r.returncode == 0 else None
|
|
93
|
+
try:
|
|
94
|
+
payload = json.loads(raw)
|
|
95
|
+
except ValueError:
|
|
96
|
+
return failure("Python command returned invalid JSON", "invalid_json")
|
|
97
|
+
if isinstance(payload, dict) and isinstance(payload.get("error"), str):
|
|
98
|
+
return failure(payload["error"], payload.get("error_code", "tool_error"))
|
|
99
|
+
if r.returncode != 0:
|
|
100
|
+
return failure(f"Python command failed (exit {r.returncode})", "process_failed")
|
|
101
|
+
return payload if parse_json else raw
|
|
102
|
+
except subprocess.TimeoutExpired:
|
|
103
|
+
return failure(f"Command timed out after {timeout}s", "timeout")
|
|
104
|
+
except Exception as exc:
|
|
105
|
+
return failure(f"Python command failed ({type(exc).__name__})", "process_failed")
|
|
51
106
|
|
|
52
107
|
|
|
53
108
|
def utf8_stdio() -> None:
|
package/tools/backtest.py
CHANGED
|
@@ -17,7 +17,16 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
|
|
17
17
|
|
|
18
18
|
from _subproc import json_safe, run_tool, utf8_stdio
|
|
19
19
|
from stock_data import detect_market
|
|
20
|
-
from technical import
|
|
20
|
+
from technical import (
|
|
21
|
+
bollinger_series,
|
|
22
|
+
ema_series,
|
|
23
|
+
ma_series,
|
|
24
|
+
macd_series,
|
|
25
|
+
monthly_market_entry_series,
|
|
26
|
+
monthly_momentum_series,
|
|
27
|
+
rsi_series,
|
|
28
|
+
trend_score_series,
|
|
29
|
+
)
|
|
21
30
|
|
|
22
31
|
# --------------- Strategy Loading ---------------
|
|
23
32
|
|
|
@@ -70,9 +79,9 @@ def fetch_kline(symbol: str, start: str | None, end: str | None) -> pd.DataFrame
|
|
|
70
79
|
d1 = datetime.strptime(end, "%Y-%m-%d")
|
|
71
80
|
count = max((datetime.now() - d0).days + 60, (d1 - d0).days + 60, 300)
|
|
72
81
|
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
82
|
+
data = run_tool(
|
|
83
|
+
"stock_data.py", ["kline", symbol, "--period", "daily", "--count", str(count)], preserve_errors=True
|
|
84
|
+
)
|
|
76
85
|
if data is None:
|
|
77
86
|
raise RuntimeError(f"Failed to fetch kline for {symbol}")
|
|
78
87
|
if isinstance(data, dict) and "error" in data:
|
|
@@ -175,6 +184,10 @@ def get_indicator(
|
|
|
175
184
|
"macd": lambda: compute_macd_hist(close),
|
|
176
185
|
"ma_diff": lambda: compute_ma_diff(close, period, fast, slow),
|
|
177
186
|
"ema_diff": lambda: compute_ema_diff(close, period, fast, slow),
|
|
187
|
+
"trend_score": lambda: trend_score_series(
|
|
188
|
+
df, fast if fast is not None else 20, slow if slow is not None else 60, period if period is not None else 14
|
|
189
|
+
),
|
|
190
|
+
"monthly_momentum": lambda: monthly_momentum_series(df, period if period is not None else 63),
|
|
178
191
|
"volume_ratio": lambda: compute_volume_ratio(df["volume"], period or 5),
|
|
179
192
|
"price_change": lambda: compute_price_change(close),
|
|
180
193
|
"bollinger_position": lambda: compute_bollinger_position(close, period or 20),
|
|
@@ -191,7 +204,7 @@ def get_indicator(
|
|
|
191
204
|
|
|
192
205
|
|
|
193
206
|
def check_condition(series: pd.Series, operator: str, value: float, idx: int) -> bool:
|
|
194
|
-
if idx <
|
|
207
|
+
if idx < 0 or idx >= len(series):
|
|
195
208
|
return False
|
|
196
209
|
cur = float(series.iloc[idx])
|
|
197
210
|
ops = {
|
|
@@ -203,6 +216,8 @@ def check_condition(series: pd.Series, operator: str, value: float, idx: int) ->
|
|
|
203
216
|
}
|
|
204
217
|
if operator in ops:
|
|
205
218
|
return ops[operator]
|
|
219
|
+
if idx == 0:
|
|
220
|
+
return False
|
|
206
221
|
prev = float(series.iloc[idx - 1])
|
|
207
222
|
if operator == "cross_above":
|
|
208
223
|
return prev <= value and cur > value
|
|
@@ -225,9 +240,11 @@ def evaluate_conditions(df: pd.DataFrame, conditions: list, logic: str, idx: int
|
|
|
225
240
|
reasons = []
|
|
226
241
|
for cond in conditions:
|
|
227
242
|
ind_name = cond["indicator"]
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
243
|
+
parameters = (cond.get("period"), cond.get("fast_period"), cond.get("slow_period"))
|
|
244
|
+
if ind_name.lower() in ("trend_score", "monthly_momentum"):
|
|
245
|
+
period, fast, slow = (int(v) if isinstance(v, str) else v for v in parameters)
|
|
246
|
+
else:
|
|
247
|
+
period, fast, slow = map(_coerce_int, parameters)
|
|
231
248
|
|
|
232
249
|
cache_key = f"{ind_name}_{period}_{fast}_{slow}"
|
|
233
250
|
if cache_key not in cache:
|
|
@@ -251,14 +268,28 @@ def evaluate_conditions(df: pd.DataFrame, conditions: list, logic: str, idx: int
|
|
|
251
268
|
# --------------- Simulation ---------------
|
|
252
269
|
|
|
253
270
|
|
|
254
|
-
def simulate(
|
|
271
|
+
def simulate(
|
|
272
|
+
df: pd.DataFrame, strategy: dict, capital: float, symbol: str, *, entry_gate: pd.Series | None = None
|
|
273
|
+
) -> dict:
|
|
255
274
|
if not math.isfinite(capital) or capital <= 0:
|
|
256
275
|
raise ValueError("capital must be finite and positive")
|
|
257
276
|
if not np.isfinite(df["close"]).all() or (df["close"] <= 0).any():
|
|
258
277
|
raise ValueError("backtest prices must be finite and positive")
|
|
278
|
+
dates = pd.to_datetime(df["date"], errors="coerce")
|
|
279
|
+
if dates.isna().any() or dates.duplicated().any() or not dates.is_monotonic_increasing:
|
|
280
|
+
raise ValueError("backtest dates must be valid, unique and increasing")
|
|
281
|
+
if entry_gate is not None:
|
|
282
|
+
if not entry_gate.index.equals(df.index) or not (entry_gate.isna() | entry_gate.isin([True, False])).all():
|
|
283
|
+
raise ValueError("entry_gate must contain aligned booleans or unavailable values")
|
|
284
|
+
entry_gate = entry_gate.fillna(False).astype(bool)
|
|
259
285
|
market = detect_market(symbol)
|
|
260
286
|
lot_size = 100 if market == "A" else 1
|
|
261
287
|
sim_cfg = strategy.get("simulation", {})
|
|
288
|
+
execution = sim_cfg.get("execution", "next_open")
|
|
289
|
+
if execution not in ("next_open", "same_close"):
|
|
290
|
+
raise ValueError("simulation.execution must be next_open or same_close")
|
|
291
|
+
if execution == "next_open" and ("open" not in df or not np.isfinite(df["open"]).all() or (df["open"] <= 0).any()):
|
|
292
|
+
raise ValueError("next_open requires finite positive open prices")
|
|
262
293
|
slippage = float(sim_cfg.get("slippage", 0.001))
|
|
263
294
|
commission = float(sim_cfg.get("commission", 0.0015))
|
|
264
295
|
tax_raw = sim_cfg.get("stamp_tax") # sell-side only (e.g. A股印花税); absent/empty = 0 (disabled)
|
|
@@ -293,19 +324,45 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
293
324
|
trade_id = 0
|
|
294
325
|
commission_paid = 0.0
|
|
295
326
|
stamp_tax_paid = 0.0
|
|
327
|
+
pending = None
|
|
328
|
+
blocked_orders = 0
|
|
329
|
+
|
|
330
|
+
def tradable(row, side):
|
|
331
|
+
if "volume" in row and (not pd.notna(row["volume"]) or row["volume"] <= 0):
|
|
332
|
+
return False
|
|
333
|
+
limit = row.get("limit_up" if side == "buy" else "limit_down")
|
|
334
|
+
# shortcut: limits need supplied historical prices; add verified limit series before enforcing provider bars.
|
|
335
|
+
return not (
|
|
336
|
+
limit is not None
|
|
337
|
+
and pd.notna(limit)
|
|
338
|
+
and row.get("high") == row.get("low")
|
|
339
|
+
and abs(float(row["high"]) - float(limit)) < 0.005
|
|
340
|
+
)
|
|
296
341
|
|
|
297
342
|
for i in range(1, len(df)):
|
|
298
343
|
row = df.iloc[i]
|
|
299
344
|
date_str = str(row["date"].date()) if hasattr(row["date"], "date") else str(row["date"])
|
|
300
|
-
|
|
345
|
+
signal_idx = i if execution == "same_close" else i - 1
|
|
346
|
+
price = float(df["close"].iloc[signal_idx])
|
|
347
|
+
fill_price = float(row["close"] if execution == "same_close" else row["open"])
|
|
348
|
+
signal_date = str(pd.Timestamp(df["date"].iloc[signal_idx]).date())
|
|
301
349
|
|
|
302
350
|
if holding is None:
|
|
303
|
-
hit, reason = evaluate_conditions(df, entry_conditions, entry_logic,
|
|
304
|
-
if
|
|
305
|
-
|
|
351
|
+
hit, reason = evaluate_conditions(df, entry_conditions, entry_logic, signal_idx, cache)
|
|
352
|
+
if pending:
|
|
353
|
+
hit, reason, signal_date = True, pending[0], pending[1]
|
|
354
|
+
if entry_gate is not None and not entry_gate.iloc[signal_idx]:
|
|
355
|
+
hit, pending = False, None
|
|
356
|
+
if hit and not tradable(row, "buy"):
|
|
357
|
+
pending = (reason, signal_date)
|
|
358
|
+
blocked_orders += 1
|
|
359
|
+
if hit and tradable(row, "buy"):
|
|
360
|
+
pending = None
|
|
361
|
+
buy_price = fill_price * (1 + slippage)
|
|
306
362
|
buy_amount = cash * size_frac
|
|
307
363
|
shares = int(buy_amount / (buy_price * (1 + commission)) / lot_size) * lot_size
|
|
308
364
|
if shares <= 0:
|
|
365
|
+
equity_curve.append({"date": date_str, "equity": round(cash, 2)})
|
|
309
366
|
continue
|
|
310
367
|
cost = shares * buy_price * (1 + commission)
|
|
311
368
|
commission_paid += shares * buy_price * commission
|
|
@@ -317,13 +374,14 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
317
374
|
"buy_price": round(buy_price, 4),
|
|
318
375
|
"shares": shares,
|
|
319
376
|
"cost": cost,
|
|
320
|
-
"peak_close":
|
|
377
|
+
"peak_close": float(row["close"]),
|
|
321
378
|
}
|
|
322
379
|
trades.append(
|
|
323
380
|
{
|
|
324
381
|
"id": trade_id,
|
|
325
382
|
"type": "buy",
|
|
326
383
|
"date": date_str,
|
|
384
|
+
"signal_date": signal_date,
|
|
327
385
|
"price": round(buy_price, 2),
|
|
328
386
|
"shares": shares,
|
|
329
387
|
"amount": round(cost, 2),
|
|
@@ -348,10 +406,16 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
348
406
|
elif pnl_pct >= take_profit:
|
|
349
407
|
sell, reason = True, f"止盈触发 ({round(pnl_pct * 100, 1)}% >= {round(take_profit * 100, 1)}%)"
|
|
350
408
|
elif exit_conditions:
|
|
351
|
-
sell, reason = evaluate_conditions(df, exit_conditions, exit_logic,
|
|
352
|
-
|
|
353
|
-
if
|
|
354
|
-
|
|
409
|
+
sell, reason = evaluate_conditions(df, exit_conditions, exit_logic, signal_idx, cache)
|
|
410
|
+
|
|
411
|
+
if pending:
|
|
412
|
+
sell, reason, signal_date = True, pending[0], pending[1]
|
|
413
|
+
if sell and not tradable(row, "sell"):
|
|
414
|
+
pending = (reason, signal_date)
|
|
415
|
+
blocked_orders += 1
|
|
416
|
+
if sell and tradable(row, "sell"):
|
|
417
|
+
pending = None
|
|
418
|
+
sell_price = fill_price * (1 - slippage)
|
|
355
419
|
gross = holding["shares"] * sell_price
|
|
356
420
|
proceeds = gross * (1 - commission - stamp_tax)
|
|
357
421
|
commission_paid += gross * commission
|
|
@@ -371,6 +435,7 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
371
435
|
"id": trade_id_sell,
|
|
372
436
|
"type": "sell",
|
|
373
437
|
"date": date_str,
|
|
438
|
+
"signal_date": signal_date,
|
|
374
439
|
"price": round(sell_price, 2),
|
|
375
440
|
"shares": holding["shares"],
|
|
376
441
|
"amount": round(proceeds, 2),
|
|
@@ -384,7 +449,7 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
384
449
|
|
|
385
450
|
equity = cash
|
|
386
451
|
if holding:
|
|
387
|
-
equity += holding["shares"] *
|
|
452
|
+
equity += holding["shares"] * float(row["close"])
|
|
388
453
|
equity_curve.append({"date": date_str, "equity": round(equity, 2)})
|
|
389
454
|
|
|
390
455
|
if holding:
|
|
@@ -396,6 +461,22 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
396
461
|
"trades": trades,
|
|
397
462
|
"equity_curve": equity_curve,
|
|
398
463
|
"final_equity": equity_curve[-1]["equity"] if equity_curve else capital,
|
|
464
|
+
"execution": {
|
|
465
|
+
"model": execution,
|
|
466
|
+
"blocked_orders": blocked_orders,
|
|
467
|
+
"unfilled_order": pending is not None,
|
|
468
|
+
"limitations": [
|
|
469
|
+
"Stops are close signals, not intraday guaranteed stop prices",
|
|
470
|
+
"Historical price limits are enforced only when limit_up/limit_down are supplied",
|
|
471
|
+
"Queue priority, partial fills, market impact and settlement are not simulated",
|
|
472
|
+
"Adjusted OHLC are synthetic prices; corporate actions and cash dividends are not simulated separately",
|
|
473
|
+
]
|
|
474
|
+
+ (
|
|
475
|
+
["same_close uses the signal day's close and can overstate executable returns"]
|
|
476
|
+
if execution == "same_close"
|
|
477
|
+
else []
|
|
478
|
+
),
|
|
479
|
+
},
|
|
399
480
|
"costs": {
|
|
400
481
|
"slippage": slippage,
|
|
401
482
|
"commission": commission,
|
|
@@ -406,6 +487,48 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
406
487
|
}
|
|
407
488
|
|
|
408
489
|
|
|
490
|
+
def simulate_monthly_market(
|
|
491
|
+
df: pd.DataFrame, market: pd.DataFrame, capital: float, symbol: str, start: str, allocation: float = 1.0
|
|
492
|
+
) -> dict:
|
|
493
|
+
"""Fixed research protocol: three drifting sleeves, market-gated entries and explicit warmup."""
|
|
494
|
+
if isinstance(allocation, bool) or not math.isfinite(allocation) or not 0 < allocation <= 1:
|
|
495
|
+
raise ValueError("allocation must be finite and in (0, 1]")
|
|
496
|
+
if not math.isfinite(capital) or capital <= 0:
|
|
497
|
+
raise ValueError("capital must be finite and positive")
|
|
498
|
+
start_date = pd.Timestamp(start)
|
|
499
|
+
dates = pd.to_datetime(df["date"], errors="coerce")
|
|
500
|
+
before = dates[(dates < start_date) & (df["volume"] > 0)] if "volume" in df else dates[dates < start_date]
|
|
501
|
+
if pd.isna(start_date) or before.empty or not (dates >= start_date).any():
|
|
502
|
+
raise ValueError("start requires both prehistory and evaluation bars")
|
|
503
|
+
sleeve_capital = math.floor(capital * allocation / 3 * 100) / 100
|
|
504
|
+
curves, trades, paid = [], [], 0.0
|
|
505
|
+
for horizon in (21, 63, 252):
|
|
506
|
+
gate = monthly_market_entry_series(df, market, horizon, activation=before.iloc[-1])
|
|
507
|
+
condition = {"indicator": "monthly_momentum", "period": horizon, "value": 0}
|
|
508
|
+
strategy = {
|
|
509
|
+
"entry": {"conditions": [{**condition, "operator": ">"}]},
|
|
510
|
+
"exit": {"conditions": [{**condition, "operator": "<"}], "stop_loss": -1, "take_profit": 1e9},
|
|
511
|
+
"simulation": {"execution": "next_open", "commission": 0.001, "slippage": 0.001, "stamp_tax": 0},
|
|
512
|
+
}
|
|
513
|
+
result = simulate(df, strategy, sleeve_capital, symbol, entry_gate=gate)
|
|
514
|
+
curves.append(pd.Series({row["date"]: row["equity"] for row in result["equity_curve"]}))
|
|
515
|
+
trades.extend({**trade, "horizon": horizon} for trade in result["trades"])
|
|
516
|
+
paid += result["costs"]["commission_paid"]
|
|
517
|
+
total = pd.concat(curves, axis=1).sum(axis=1) + capital - sleeve_capital * 3
|
|
518
|
+
return {
|
|
519
|
+
"model": "monthly_momentum_market_entry",
|
|
520
|
+
"validation_status": "not_validated",
|
|
521
|
+
"experimental": True,
|
|
522
|
+
"allocation": allocation,
|
|
523
|
+
"start": str(start_date.date()),
|
|
524
|
+
"warmup_start": str(dates.iloc[0].date()),
|
|
525
|
+
"trades": sorted(trades, key=lambda trade: (trade["date"], trade["horizon"])),
|
|
526
|
+
"equity_curve": [{"date": date, "equity": round(float(value), 2)} for date, value in total.items()],
|
|
527
|
+
"final_equity": round(float(total.iloc[-1]), 2),
|
|
528
|
+
"costs": {"commission": 0.001, "slippage": 0.001, "stamp_tax": 0, "commission_paid": round(paid, 2)},
|
|
529
|
+
}
|
|
530
|
+
|
|
531
|
+
|
|
409
532
|
# --------------- Metrics ---------------
|
|
410
533
|
|
|
411
534
|
|
|
@@ -680,6 +803,7 @@ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str |
|
|
|
680
803
|
"initial_capital": capital,
|
|
681
804
|
"final_capital": final,
|
|
682
805
|
"costs": sim["costs"],
|
|
806
|
+
"execution": sim["execution"],
|
|
683
807
|
"metrics": metrics,
|
|
684
808
|
"trades": sim["trades"],
|
|
685
809
|
"equity_curve": sample_curve(sim["equity_curve"]),
|
package/tools/capabilities.py
CHANGED
|
@@ -18,6 +18,18 @@ ALL_MARKETS = ["A", "HK", "US", "JP", "KR", "TW"]
|
|
|
18
18
|
|
|
19
19
|
# tool_name -> {markets: [supported markets], reason: str for unsupported}
|
|
20
20
|
TOOL_MATRIX = {
|
|
21
|
+
"analyze_trend_strategy": {
|
|
22
|
+
"markets": ["A", "HK", "US"],
|
|
23
|
+
"reason": "Monthly trend strategy supports A/HK/US pools only",
|
|
24
|
+
},
|
|
25
|
+
# Explicit-input analytics; data acquisition retains each provider's market limits.
|
|
26
|
+
"compare_stocks": {"markets": ALL_MARKETS, "reason": None},
|
|
27
|
+
"analyze_disclosure_changes": {"markets": ALL_MARKETS, "reason": None},
|
|
28
|
+
"analyze_portfolio_risk": {"markets": ALL_MARKETS, "reason": None},
|
|
29
|
+
"calculate_position_size": {"markets": ALL_MARKETS, "reason": None},
|
|
30
|
+
"analyze_event_study": {"markets": ALL_MARKETS, "reason": None},
|
|
31
|
+
"validate_backtest": {"markets": ALL_MARKETS, "reason": None},
|
|
32
|
+
"compare_analysis_snapshots": {"markets": ALL_MARKETS, "reason": None},
|
|
21
33
|
"get_announcements": {"markets": ["A"], "reason": "cninfo A-share disclosures only"},
|
|
22
34
|
"get_us_holdings": {"markets": ["US"], "reason": "SEC manager holdings or verified issuer-CUSIP reverse lookup"},
|
|
23
35
|
"get_insider_trades": {"markets": ["US"], "reason": "SEC issuer Form 4 only"},
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
{
|
|
2
|
+
"default": 120,
|
|
3
|
+
"stock_data.py:market_snapshot": 240,
|
|
4
|
+
"screener.py:screen": 390,
|
|
5
|
+
"sec_edgar.py:holdings": 300,
|
|
6
|
+
"technical.py:analyze": 150,
|
|
7
|
+
"market_regime.py:detect": 270,
|
|
8
|
+
"backtest.py:run": 270,
|
|
9
|
+
"risk_screening.py:screen": 450,
|
|
10
|
+
"signal_tracker.py:evaluate": 300,
|
|
11
|
+
"stock_data.py:market_stats": 240,
|
|
12
|
+
"market_review.py:review": 300,
|
|
13
|
+
"anomaly_detect.py:detect": 390,
|
|
14
|
+
"position_context.py:analyze": 300,
|
|
15
|
+
"alert_rules.py:check": 480,
|
|
16
|
+
"technical.py:calculate_ma": 150,
|
|
17
|
+
"value_data.py:dividends": 300,
|
|
18
|
+
"value_data.py:etf_details": 450,
|
|
19
|
+
"watchlist.py:analyze": 30,
|
|
20
|
+
"watchlist_context.py:build": 30,
|
|
21
|
+
"l2_batch": 360,
|
|
22
|
+
"l2_workers": 6,
|
|
23
|
+
"watchlist_item": 480,
|
|
24
|
+
"stateless_analysis.py:event_study": 300,
|
|
25
|
+
"stateless_analysis.py:robustness": 660,
|
|
26
|
+
"trend_strategy.py:fetch": 660
|
|
27
|
+
}
|
package/tools/gather.py
CHANGED
|
@@ -8,15 +8,13 @@ from concurrent.futures import ThreadPoolExecutor
|
|
|
8
8
|
from pathlib import Path
|
|
9
9
|
|
|
10
10
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
11
|
-
from _subproc import json_safe, run_tool, utf8_stdio # noqa: E402
|
|
11
|
+
from _subproc import command_timeout, json_safe, run_tool, utf8_stdio # noqa: E402
|
|
12
12
|
from stock_data import detect_market # noqa: E402
|
|
13
13
|
from technical import analyze_records # noqa: E402
|
|
14
14
|
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
def _run(script, args, timeout=60):
|
|
19
|
-
return run_tool(script, args, timeout=timeout, parse_json=False)
|
|
16
|
+
def _run(script, args, timeout=None):
|
|
17
|
+
return run_tool(script, args, timeout=timeout, parse_json=False, preserve_errors=True)
|
|
20
18
|
|
|
21
19
|
|
|
22
20
|
def _news_query(symbol: str) -> str:
|
|
@@ -74,7 +72,7 @@ def gather_screen(market: str = "A", top: int = 20, config: str | None = None) -
|
|
|
74
72
|
args = ["screen", "--market", market, "--top", str(top)]
|
|
75
73
|
if config:
|
|
76
74
|
args += ["--config", config]
|
|
77
|
-
raw = _run("screener.py", args, timeout=
|
|
75
|
+
raw = _run("screener.py", args, timeout=command_timeout("screener.py", args))
|
|
78
76
|
return {"screen_results": _parse_json(raw)}
|
|
79
77
|
|
|
80
78
|
|