@weaxs/openclaw-stock-analysis 0.2.5 → 0.2.7
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 +1 -1
- package/dist/index.js +322 -21
- package/index.ts +257 -16
- package/openclaw.plugin.json +11 -1
- package/package.json +1 -1
- package/schemas/market_review_schema.json +12 -5
- package/schemas/report_schema.json +68 -4
- package/scripts/cli-timeout.mjs +27 -0
- package/scripts/json-input.mjs +26 -0
- package/scripts/setup-python.mjs +6 -6
- package/skills/bull-trend/SKILL.md +34 -10
- package/skills/bull-trend/references/fat-tails.md +91 -0
- package/skills/bull-trend/scripts/tail_analysis.py +132 -0
- package/skills/event-driven/SKILL.md +6 -0
- package/skills/growth-quality/SKILL.md +6 -0
- package/skills/market-review/SKILL.md +2 -0
- package/skills/stock-analysis/SKILL.md +25 -5
- package/skills/stock-analysis/references/stateless-analysis.md +66 -0
- package/skills/stock-screener/SKILL.md +7 -1
- package/skills/strategy-backtest/SKILL.md +13 -0
- package/skills/wisburg-research/SKILL.md +2 -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 +6 -1
- package/templates/stock_analysis/full.md.j2 +8 -3
- package/tools/_subproc.py +66 -11
- package/tools/alert_rules.py +32 -4
- package/tools/backtest.py +95 -18
- package/tools/capabilities.py +11 -0
- package/tools/cli_budgets.json +26 -0
- package/tools/gather.py +24 -16
- package/tools/lixinger.py +100 -0
- package/tools/market_regime.py +7 -3
- package/tools/market_review.py +37 -15
- package/tools/position_context.py +20 -2
- package/tools/report_renderer.py +2 -0
- package/tools/risk_screening.py +45 -17
- package/tools/screener.py +74 -24
- package/tools/sec_edgar.py +346 -0
- package/tools/sec_holders.py +263 -0
- package/tools/signal_tracker.py +218 -24
- package/tools/stateless_analysis.py +630 -0
- package/tools/stock_data.py +170 -32
- package/tools/technical.py +16 -2
- package/tools/value_data.py +159 -0
- package/tools/watchlist.py +24 -1
- package/tools/watchlist_context.py +25 -10
|
@@ -7,11 +7,14 @@
|
|
|
7
7
|
{% if risk_screening and risk_screening.veto_buy %}
|
|
8
8
|
⚠️ **一票否决** — 风险筛查触发,建议谨慎。
|
|
9
9
|
{% endif %}
|
|
10
|
+
{% if risk_screening and (risk_screening.data_complete is sameas false or risk_screening.risk_level == 'unknown') %}
|
|
11
|
+
⚠️ **数据不完整** — 当前风险筛查不能判定为低风险。
|
|
12
|
+
{% endif %}
|
|
10
13
|
|
|
11
14
|
{% set dp = data_perspective or {} -%}
|
|
12
15
|
{% set pp = dp.price_position or {} -%}
|
|
13
16
|
{% set ts = dp.trend_status or {} -%}
|
|
14
|
-
- 📈 **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is
|
|
17
|
+
- 📈 **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is boolean %}({{ '看多' if ts.is_bullish else '看空' }}){% endif %}
|
|
15
18
|
- 💰 **价位:** 现价 {{ m.fmt_num(pp.current_price) }} | 支撑 {{ m.fmt_num(pp.support_level) }} | 压力 {{ m.fmt_num(pp.resistance_level) }}
|
|
16
19
|
|
|
17
20
|
{% set bp = battle_plan or {} -%}
|
|
@@ -26,3 +29,5 @@
|
|
|
26
29
|
{% if intel.risk_alerts -%}
|
|
27
30
|
⚠️ **风险:** {{ intel.risk_alerts | join(';') }}
|
|
28
31
|
{% endif %}
|
|
32
|
+
|
|
33
|
+
{% include "stock_analysis/_evidence.md.j2" %}
|
|
@@ -26,12 +26,15 @@
|
|
|
26
26
|
## 风险筛查
|
|
27
27
|
|
|
28
28
|
{% if risk_screening -%}
|
|
29
|
-
- **风险等级:** {{ m.risk_emoji(risk_screening.risk_level) }} {{ risk_screening.risk_level or '-' }} | **风险分:** {{ risk_screening.risk_score }}/100
|
|
29
|
+
- **风险等级:** {{ m.risk_emoji(risk_screening.risk_level) }} {{ risk_screening.risk_level or '-' }} | **风险分:** {{ m.fmt_num(risk_screening.risk_score, 0) }}/100
|
|
30
|
+
{% if risk_screening.data_complete is sameas false or risk_screening.risk_level == 'unknown' -%}
|
|
31
|
+
- **数据不完整:** {{ risk_screening.warnings | join(';') }},当前结果不能判定为低风险。
|
|
32
|
+
{% endif %}
|
|
30
33
|
{% if risk_screening.flags -%}
|
|
31
34
|
- **风险标记:**
|
|
32
35
|
{% for f in risk_screening.flags %} - [{{ f.severity }}] {{ f.category }}:{{ f.description }}
|
|
33
36
|
{% endfor %}
|
|
34
|
-
{%-
|
|
37
|
+
{%- elif risk_screening.data_complete is not sameas false and risk_screening.risk_level != 'unknown' -%}
|
|
35
38
|
- **风险标记:** 无显著风险标记
|
|
36
39
|
{%- endif %}
|
|
37
40
|
{%- else -%}
|
|
@@ -45,7 +48,7 @@
|
|
|
45
48
|
{% set pp = dp.price_position or {} -%}
|
|
46
49
|
{% set vol = dp.volume_analysis or {} -%}
|
|
47
50
|
{% set chip = dp.chip_structure or {} -%}
|
|
48
|
-
- **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is
|
|
51
|
+
- **趋势:** {{ ts.ma_alignment or '-' }}{% if ts.is_bullish is boolean %}({{ '看多' if ts.is_bullish else '看空' }}){% endif %}{% if ts.trend_score is not none %} 趋势分 {{ m.fmt_num(ts.trend_score) }}{% endif %}
|
|
49
52
|
- **价格结构:** 现价 {{ m.fmt_num(pp.current_price) }} | 偏离 MA5 {{ m.change_pct(pp.bias_ma5) }} | 支撑 {{ m.fmt_num(pp.support_level) }} | 压力 {{ m.fmt_num(pp.resistance_level) }}
|
|
50
53
|
- **量价:** 量比 {{ m.fmt_num(vol.volume_ratio) }}{% if vol.volume_status %}({{ vol.volume_status }}){% endif %}{% if vol.turnover_rate is not none %} | 换手率 {{ m.change_pct(vol.turnover_rate) }}{% endif %}
|
|
51
54
|
{% if chip and (chip.profit_ratio is not none or chip.avg_cost is not none) -%}
|
|
@@ -104,5 +107,7 @@
|
|
|
104
107
|
{% endfor %}
|
|
105
108
|
{%- endif %}
|
|
106
109
|
|
|
110
|
+
{% include "stock_analysis/_evidence.md.j2" %}
|
|
111
|
+
|
|
107
112
|
---
|
|
108
113
|
*本报告由 stock-analysis-plugin 渲染,仅供参考,不构成投资建议。*
|
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/alert_rules.py
CHANGED
|
@@ -6,6 +6,7 @@ Does NOT store history, does NOT push, does NOT schedule. Host agent decides whe
|
|
|
6
6
|
|
|
7
7
|
import argparse
|
|
8
8
|
import json
|
|
9
|
+
import math
|
|
9
10
|
import sys
|
|
10
11
|
from concurrent.futures import ThreadPoolExecutor
|
|
11
12
|
from datetime import datetime, timezone
|
|
@@ -31,8 +32,14 @@ RULE_TYPES = {
|
|
|
31
32
|
def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) -> dict | None:
|
|
32
33
|
rtype = rule.get("type")
|
|
33
34
|
value = rule.get("value")
|
|
34
|
-
if rtype not in RULE_TYPES:
|
|
35
|
+
if not isinstance(rtype, str) or rtype not in RULE_TYPES:
|
|
35
36
|
return {"rule": rtype, "triggered": False, "error": f"unknown rule type: {rtype}"}
|
|
37
|
+
if rtype in ("price_below", "price_above", "change_pct_above", "change_pct_below", "volume_ratio_above"):
|
|
38
|
+
try:
|
|
39
|
+
if isinstance(value, bool) or not math.isfinite(float(value)):
|
|
40
|
+
raise ValueError
|
|
41
|
+
except (ValueError, TypeError):
|
|
42
|
+
return {"rule": rtype, "triggered": False, "error": "Rule value must be a finite number"}
|
|
36
43
|
|
|
37
44
|
price = quote.get("price")
|
|
38
45
|
change_pct = quote.get("change_pct")
|
|
@@ -90,6 +97,8 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
90
97
|
"message": f"量比 {ratio} 超过 {value}",
|
|
91
98
|
}
|
|
92
99
|
elif rtype == "anomaly":
|
|
100
|
+
if not isinstance(value, str) or not value:
|
|
101
|
+
return {"rule": rtype, "triggered": False, "error": "Anomaly type must be a nonempty string"}
|
|
93
102
|
# value is an anomaly type string, e.g. "macd_golden_cross"
|
|
94
103
|
anomalies = (anom or {}).get("anomalies", [])
|
|
95
104
|
for a in anomalies:
|
|
@@ -106,6 +115,8 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
106
115
|
return {"rule": rtype, "triggered": True, "severity": "high", "message": "风险筛查触发一票否决"}
|
|
107
116
|
elif rtype == "risk_level_at_least":
|
|
108
117
|
order = {"low": 0, "medium": 1, "high": 2}
|
|
118
|
+
if not isinstance(value, str) or value not in order:
|
|
119
|
+
return {"rule": rtype, "triggered": False, "error": "Risk threshold must be low/medium/high"}
|
|
109
120
|
cur = order.get((risk or {}).get("risk_level"))
|
|
110
121
|
want = order.get(value)
|
|
111
122
|
if cur is not None and want is not None and cur >= want:
|
|
@@ -122,7 +133,7 @@ def _check_rule(rule: dict, quote: dict, tech: dict, anom: dict, risk: dict) ->
|
|
|
122
133
|
|
|
123
134
|
|
|
124
135
|
def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
125
|
-
if not rules:
|
|
136
|
+
if not isinstance(rules, list) or not rules or any(not isinstance(rule, dict) for rule in rules):
|
|
126
137
|
return {"symbol": symbol, "error": "no rules provided"}
|
|
127
138
|
|
|
128
139
|
needs_tech = any(r.get("type") == "volume_ratio_above" for r in rules)
|
|
@@ -141,6 +152,9 @@ def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
|
141
152
|
with ThreadPoolExecutor(max_workers=len(jobs)) as pool:
|
|
142
153
|
futures = {key: pool.submit(_run_json, script, args) for key, (script, args) in jobs.items()}
|
|
143
154
|
fetched = {key: future.result() for key, future in futures.items()}
|
|
155
|
+
fetched = {
|
|
156
|
+
key: value if isinstance(value, dict) and "error" not in value else None for key, value in fetched.items()
|
|
157
|
+
}
|
|
144
158
|
quote = fetched["quote"] or {}
|
|
145
159
|
tech = fetched.get("tech")
|
|
146
160
|
anom = fetched.get("anom")
|
|
@@ -153,13 +167,25 @@ def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
|
153
167
|
warnings.append("technical analysis fetch failed — volume_ratio rules cannot fire")
|
|
154
168
|
if needs_anom and not anom:
|
|
155
169
|
warnings.append("anomaly fetch failed — anomaly rules cannot fire")
|
|
156
|
-
if needs_risk and not risk:
|
|
170
|
+
if needs_risk and (not risk or risk.get("data_complete") is False or risk.get("risk_level") == "unknown"):
|
|
157
171
|
warnings.append("risk screening fetch failed — risk rules cannot fire")
|
|
158
172
|
|
|
159
173
|
hits = []
|
|
160
174
|
evaluated = []
|
|
161
175
|
for rule in rules:
|
|
162
|
-
|
|
176
|
+
rtype = rule.get("type")
|
|
177
|
+
missing = (
|
|
178
|
+
(rtype in ("price_below", "price_above") and quote.get("price") is None)
|
|
179
|
+
or (rtype in ("change_pct_below", "change_pct_above") and quote.get("change_pct") is None)
|
|
180
|
+
or (rtype == "volume_ratio_above" and (tech or {}).get("volume", {}).get("volume_ratio") is None)
|
|
181
|
+
or (rtype == "anomaly" and not isinstance((anom or {}).get("anomalies"), list))
|
|
182
|
+
or (rtype == "risk_veto" and (risk or {}).get("veto_buy") is None)
|
|
183
|
+
or (rtype == "risk_level_at_least" and (risk or {}).get("risk_level") not in ("low", "medium", "high"))
|
|
184
|
+
)
|
|
185
|
+
if missing:
|
|
186
|
+
result = {"rule": rtype, "triggered": False, "error": "Required source data unavailable"}
|
|
187
|
+
else:
|
|
188
|
+
result = _check_rule(rule, quote, tech, anom, risk)
|
|
163
189
|
if result is None:
|
|
164
190
|
evaluated.append({"rule": rule.get("type"), "triggered": False})
|
|
165
191
|
else:
|
|
@@ -214,6 +240,8 @@ def main():
|
|
|
214
240
|
result = check_rules(args.symbol, rules)
|
|
215
241
|
json.dump(result, sys.stdout, ensure_ascii=False, indent=2, default=str)
|
|
216
242
|
print()
|
|
243
|
+
if "error" in result:
|
|
244
|
+
sys.exit(1)
|
|
217
245
|
|
|
218
246
|
|
|
219
247
|
if __name__ == "__main__":
|
package/tools/backtest.py
CHANGED
|
@@ -16,6 +16,7 @@ import yaml
|
|
|
16
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
|
+
from stock_data import detect_market
|
|
19
20
|
from technical import bollinger_series, ema_series, ma_series, macd_series, rsi_series
|
|
20
21
|
|
|
21
22
|
# --------------- Strategy Loading ---------------
|
|
@@ -67,11 +68,11 @@ def fetch_kline(symbol: str, start: str | None, end: str | None) -> pd.DataFrame
|
|
|
67
68
|
if start and end:
|
|
68
69
|
d0 = datetime.strptime(start, "%Y-%m-%d")
|
|
69
70
|
d1 = datetime.strptime(end, "%Y-%m-%d")
|
|
70
|
-
count = max((d1 - d0).days + 60, 300)
|
|
71
|
+
count = max((datetime.now() - d0).days + 60, (d1 - d0).days + 60, 300)
|
|
71
72
|
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
73
|
+
data = run_tool(
|
|
74
|
+
"stock_data.py", ["kline", symbol, "--period", "daily", "--count", str(count)], preserve_errors=True
|
|
75
|
+
)
|
|
75
76
|
if data is None:
|
|
76
77
|
raise RuntimeError(f"Failed to fetch kline for {symbol}")
|
|
77
78
|
if isinstance(data, dict) and "error" in data:
|
|
@@ -190,7 +191,7 @@ def get_indicator(
|
|
|
190
191
|
|
|
191
192
|
|
|
192
193
|
def check_condition(series: pd.Series, operator: str, value: float, idx: int) -> bool:
|
|
193
|
-
if idx <
|
|
194
|
+
if idx < 0 or idx >= len(series):
|
|
194
195
|
return False
|
|
195
196
|
cur = float(series.iloc[idx])
|
|
196
197
|
ops = {
|
|
@@ -202,6 +203,8 @@ def check_condition(series: pd.Series, operator: str, value: float, idx: int) ->
|
|
|
202
203
|
}
|
|
203
204
|
if operator in ops:
|
|
204
205
|
return ops[operator]
|
|
206
|
+
if idx == 0:
|
|
207
|
+
return False
|
|
205
208
|
prev = float(series.iloc[idx - 1])
|
|
206
209
|
if operator == "cross_above":
|
|
207
210
|
return prev <= value and cur > value
|
|
@@ -251,9 +254,21 @@ def evaluate_conditions(df: pd.DataFrame, conditions: list, logic: str, idx: int
|
|
|
251
254
|
|
|
252
255
|
|
|
253
256
|
def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> dict:
|
|
254
|
-
|
|
257
|
+
if not math.isfinite(capital) or capital <= 0:
|
|
258
|
+
raise ValueError("capital must be finite and positive")
|
|
259
|
+
if not np.isfinite(df["close"]).all() or (df["close"] <= 0).any():
|
|
260
|
+
raise ValueError("backtest prices must be finite and positive")
|
|
261
|
+
dates = pd.to_datetime(df["date"], errors="coerce")
|
|
262
|
+
if dates.isna().any() or dates.duplicated().any() or not dates.is_monotonic_increasing:
|
|
263
|
+
raise ValueError("backtest dates must be valid, unique and increasing")
|
|
264
|
+
market = detect_market(symbol)
|
|
255
265
|
lot_size = 100 if market == "A" else 1
|
|
256
266
|
sim_cfg = strategy.get("simulation", {})
|
|
267
|
+
execution = sim_cfg.get("execution", "next_open")
|
|
268
|
+
if execution not in ("next_open", "same_close"):
|
|
269
|
+
raise ValueError("simulation.execution must be next_open or same_close")
|
|
270
|
+
if execution == "next_open" and ("open" not in df or not np.isfinite(df["open"]).all() or (df["open"] <= 0).any()):
|
|
271
|
+
raise ValueError("next_open requires finite positive open prices")
|
|
257
272
|
slippage = float(sim_cfg.get("slippage", 0.001))
|
|
258
273
|
commission = float(sim_cfg.get("commission", 0.0015))
|
|
259
274
|
tax_raw = sim_cfg.get("stamp_tax") # sell-side only (e.g. A股印花税); absent/empty = 0 (disabled)
|
|
@@ -268,6 +283,8 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
268
283
|
exit_ = strategy.get("exit", {})
|
|
269
284
|
position_cfg = strategy.get("position", {})
|
|
270
285
|
size_frac = float(position_cfg.get("size", 1.0))
|
|
286
|
+
if not 0 <= size_frac <= 1:
|
|
287
|
+
raise ValueError("position.size must be a fraction in [0, 1]")
|
|
271
288
|
stop_loss = float(exit_.get("stop_loss", -0.10))
|
|
272
289
|
take_profit = float(exit_.get("take_profit", 0.50))
|
|
273
290
|
ts_val = exit_.get("trailing_stop")
|
|
@@ -286,19 +303,43 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
286
303
|
trade_id = 0
|
|
287
304
|
commission_paid = 0.0
|
|
288
305
|
stamp_tax_paid = 0.0
|
|
306
|
+
pending = None
|
|
307
|
+
blocked_orders = 0
|
|
308
|
+
|
|
309
|
+
def tradable(row, side):
|
|
310
|
+
if "volume" in row and (not pd.notna(row["volume"]) or row["volume"] <= 0):
|
|
311
|
+
return False
|
|
312
|
+
limit = row.get("limit_up" if side == "buy" else "limit_down")
|
|
313
|
+
# shortcut: limits need supplied historical prices; add verified limit series before enforcing provider bars.
|
|
314
|
+
return not (
|
|
315
|
+
limit is not None
|
|
316
|
+
and pd.notna(limit)
|
|
317
|
+
and row.get("high") == row.get("low")
|
|
318
|
+
and abs(float(row["high"]) - float(limit)) < 0.005
|
|
319
|
+
)
|
|
289
320
|
|
|
290
321
|
for i in range(1, len(df)):
|
|
291
322
|
row = df.iloc[i]
|
|
292
323
|
date_str = str(row["date"].date()) if hasattr(row["date"], "date") else str(row["date"])
|
|
293
|
-
|
|
324
|
+
signal_idx = i if execution == "same_close" else i - 1
|
|
325
|
+
price = float(df["close"].iloc[signal_idx])
|
|
326
|
+
fill_price = float(row["close"] if execution == "same_close" else row["open"])
|
|
327
|
+
signal_date = str(pd.Timestamp(df["date"].iloc[signal_idx]).date())
|
|
294
328
|
|
|
295
329
|
if holding is None:
|
|
296
|
-
hit, reason = evaluate_conditions(df, entry_conditions, entry_logic,
|
|
297
|
-
if
|
|
298
|
-
|
|
330
|
+
hit, reason = evaluate_conditions(df, entry_conditions, entry_logic, signal_idx, cache)
|
|
331
|
+
if pending:
|
|
332
|
+
hit, reason, signal_date = True, pending[0], pending[1]
|
|
333
|
+
if hit and not tradable(row, "buy"):
|
|
334
|
+
pending = (reason, signal_date)
|
|
335
|
+
blocked_orders += 1
|
|
336
|
+
if hit and tradable(row, "buy"):
|
|
337
|
+
pending = None
|
|
338
|
+
buy_price = fill_price * (1 + slippage)
|
|
299
339
|
buy_amount = cash * size_frac
|
|
300
|
-
shares = int(buy_amount / buy_price / lot_size) * lot_size
|
|
340
|
+
shares = int(buy_amount / (buy_price * (1 + commission)) / lot_size) * lot_size
|
|
301
341
|
if shares <= 0:
|
|
342
|
+
equity_curve.append({"date": date_str, "equity": round(cash, 2)})
|
|
302
343
|
continue
|
|
303
344
|
cost = shares * buy_price * (1 + commission)
|
|
304
345
|
commission_paid += shares * buy_price * commission
|
|
@@ -310,13 +351,14 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
310
351
|
"buy_price": round(buy_price, 4),
|
|
311
352
|
"shares": shares,
|
|
312
353
|
"cost": cost,
|
|
313
|
-
"peak_close":
|
|
354
|
+
"peak_close": float(row["close"]),
|
|
314
355
|
}
|
|
315
356
|
trades.append(
|
|
316
357
|
{
|
|
317
358
|
"id": trade_id,
|
|
318
359
|
"type": "buy",
|
|
319
360
|
"date": date_str,
|
|
361
|
+
"signal_date": signal_date,
|
|
320
362
|
"price": round(buy_price, 2),
|
|
321
363
|
"shares": shares,
|
|
322
364
|
"amount": round(cost, 2),
|
|
@@ -341,10 +383,16 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
341
383
|
elif pnl_pct >= take_profit:
|
|
342
384
|
sell, reason = True, f"止盈触发 ({round(pnl_pct * 100, 1)}% >= {round(take_profit * 100, 1)}%)"
|
|
343
385
|
elif exit_conditions:
|
|
344
|
-
sell, reason = evaluate_conditions(df, exit_conditions, exit_logic,
|
|
345
|
-
|
|
346
|
-
if
|
|
347
|
-
|
|
386
|
+
sell, reason = evaluate_conditions(df, exit_conditions, exit_logic, signal_idx, cache)
|
|
387
|
+
|
|
388
|
+
if pending:
|
|
389
|
+
sell, reason, signal_date = True, pending[0], pending[1]
|
|
390
|
+
if sell and not tradable(row, "sell"):
|
|
391
|
+
pending = (reason, signal_date)
|
|
392
|
+
blocked_orders += 1
|
|
393
|
+
if sell and tradable(row, "sell"):
|
|
394
|
+
pending = None
|
|
395
|
+
sell_price = fill_price * (1 - slippage)
|
|
348
396
|
gross = holding["shares"] * sell_price
|
|
349
397
|
proceeds = gross * (1 - commission - stamp_tax)
|
|
350
398
|
commission_paid += gross * commission
|
|
@@ -364,6 +412,7 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
364
412
|
"id": trade_id_sell,
|
|
365
413
|
"type": "sell",
|
|
366
414
|
"date": date_str,
|
|
415
|
+
"signal_date": signal_date,
|
|
367
416
|
"price": round(sell_price, 2),
|
|
368
417
|
"shares": holding["shares"],
|
|
369
418
|
"amount": round(proceeds, 2),
|
|
@@ -377,7 +426,7 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
377
426
|
|
|
378
427
|
equity = cash
|
|
379
428
|
if holding:
|
|
380
|
-
equity += holding["shares"] *
|
|
429
|
+
equity += holding["shares"] * float(row["close"])
|
|
381
430
|
equity_curve.append({"date": date_str, "equity": round(equity, 2)})
|
|
382
431
|
|
|
383
432
|
if holding:
|
|
@@ -389,6 +438,22 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
389
438
|
"trades": trades,
|
|
390
439
|
"equity_curve": equity_curve,
|
|
391
440
|
"final_equity": equity_curve[-1]["equity"] if equity_curve else capital,
|
|
441
|
+
"execution": {
|
|
442
|
+
"model": execution,
|
|
443
|
+
"blocked_orders": blocked_orders,
|
|
444
|
+
"unfilled_order": pending is not None,
|
|
445
|
+
"limitations": [
|
|
446
|
+
"Stops are close signals, not intraday guaranteed stop prices",
|
|
447
|
+
"Historical price limits are enforced only when limit_up/limit_down are supplied",
|
|
448
|
+
"Queue priority, partial fills, market impact and settlement are not simulated",
|
|
449
|
+
"Adjusted OHLC are synthetic prices; corporate actions and cash dividends are not simulated separately",
|
|
450
|
+
]
|
|
451
|
+
+ (
|
|
452
|
+
["same_close uses the signal day's close and can overstate executable returns"]
|
|
453
|
+
if execution == "same_close"
|
|
454
|
+
else []
|
|
455
|
+
),
|
|
456
|
+
},
|
|
392
457
|
"costs": {
|
|
393
458
|
"slippage": slippage,
|
|
394
459
|
"commission": commission,
|
|
@@ -417,7 +482,7 @@ def compute_metrics(trades: list, equity_curve: list, initial: float, final: flo
|
|
|
417
482
|
years = 1
|
|
418
483
|
annual_return = (1 + total_return) ** (1 / max(years, 0.01)) - 1 if total_return > -1 else total_return
|
|
419
484
|
|
|
420
|
-
equities = pd.Series([e["equity"] for e in equity_curve], dtype=float)
|
|
485
|
+
equities = pd.Series([initial, *[e["equity"] for e in equity_curve]], dtype=float)
|
|
421
486
|
peak = equities.cummax()
|
|
422
487
|
dd = (equities - peak) / peak
|
|
423
488
|
max_drawdown = float(dd.min()) if len(dd) > 0 else 0
|
|
@@ -653,6 +718,13 @@ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str |
|
|
|
653
718
|
if len(df) < 30:
|
|
654
719
|
return {"error": f"Insufficient data: {len(df)} rows (need at least 30)"}
|
|
655
720
|
|
|
721
|
+
requested_period = f"{start} to {end}"
|
|
722
|
+
actual_start = df["date"].iloc[0].strftime("%Y-%m-%d")
|
|
723
|
+
actual_end = df["date"].iloc[-1].strftime("%Y-%m-%d")
|
|
724
|
+
warnings = []
|
|
725
|
+
if actual_start != start or actual_end != end:
|
|
726
|
+
warnings.append(f"Actual data covers {actual_start} to {actual_end}; requested {requested_period}")
|
|
727
|
+
start, end = actual_start, actual_end
|
|
656
728
|
sim = simulate(df, strategy, capital, symbol)
|
|
657
729
|
final = sim["final_equity"]
|
|
658
730
|
metrics = compute_metrics(sim["trades"], sim["equity_curve"], capital, final, start, end)
|
|
@@ -661,9 +733,12 @@ def run_backtest(strategy_path: str, symbol: str, start: str | None, end: str |
|
|
|
661
733
|
"strategy": strategy.get("name", "unnamed"),
|
|
662
734
|
"symbol": symbol,
|
|
663
735
|
"period": f"{start} to {end}",
|
|
736
|
+
"requested_period": requested_period,
|
|
737
|
+
"warnings": warnings,
|
|
664
738
|
"initial_capital": capital,
|
|
665
739
|
"final_capital": final,
|
|
666
740
|
"costs": sim["costs"],
|
|
741
|
+
"execution": sim["execution"],
|
|
667
742
|
"metrics": metrics,
|
|
668
743
|
"trades": sim["trades"],
|
|
669
744
|
"equity_curve": sample_curve(sim["equity_curve"]),
|
|
@@ -837,6 +912,8 @@ def main():
|
|
|
837
912
|
sys.exit(1)
|
|
838
913
|
|
|
839
914
|
print(json.dumps(json_safe(result), ensure_ascii=False, default=str))
|
|
915
|
+
if "error" in result:
|
|
916
|
+
sys.exit(1)
|
|
840
917
|
|
|
841
918
|
|
|
842
919
|
if __name__ == "__main__":
|
package/tools/capabilities.py
CHANGED
|
@@ -18,6 +18,17 @@ 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
|
+
# Explicit-input analytics; data acquisition retains each provider's market limits.
|
|
22
|
+
"compare_stocks": {"markets": ALL_MARKETS, "reason": None},
|
|
23
|
+
"analyze_disclosure_changes": {"markets": ALL_MARKETS, "reason": None},
|
|
24
|
+
"analyze_portfolio_risk": {"markets": ALL_MARKETS, "reason": None},
|
|
25
|
+
"calculate_position_size": {"markets": ALL_MARKETS, "reason": None},
|
|
26
|
+
"analyze_event_study": {"markets": ALL_MARKETS, "reason": None},
|
|
27
|
+
"validate_backtest": {"markets": ALL_MARKETS, "reason": None},
|
|
28
|
+
"compare_analysis_snapshots": {"markets": ALL_MARKETS, "reason": None},
|
|
29
|
+
"get_announcements": {"markets": ["A"], "reason": "cninfo A-share disclosures only"},
|
|
30
|
+
"get_us_holdings": {"markets": ["US"], "reason": "SEC manager holdings or verified issuer-CUSIP reverse lookup"},
|
|
31
|
+
"get_insider_trades": {"markets": ["US"], "reason": "SEC issuer Form 4 only"},
|
|
21
32
|
"get_valuation_history": {"markets": ["A", "HK"], "reason": "A/HK historical valuation providers only"},
|
|
22
33
|
"get_index_valuation": {"markets": ["A"], "reason": "Chinese index valuation only"},
|
|
23
34
|
"get_earnings_calendar": {
|
|
@@ -0,0 +1,26 @@
|
|
|
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
|
+
}
|
package/tools/gather.py
CHANGED
|
@@ -8,14 +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
|
+
from technical import analyze_records # noqa: E402
|
|
13
14
|
|
|
14
15
|
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
def _run(script, args, timeout=60):
|
|
18
|
-
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)
|
|
19
18
|
|
|
20
19
|
|
|
21
20
|
def _news_query(symbol: str) -> str:
|
|
@@ -32,57 +31,66 @@ def _parse_json(raw: str | None):
|
|
|
32
31
|
return raw
|
|
33
32
|
|
|
34
33
|
|
|
35
|
-
def _run_all(tasks: dict) -> dict:
|
|
34
|
+
def _run_all(tasks: dict, symbol: str) -> dict:
|
|
36
35
|
with ThreadPoolExecutor(max_workers=len(tasks)) as pool:
|
|
37
36
|
futures = {pool.submit(_run, script, args): key for key, (script, args) in tasks.items()}
|
|
38
|
-
|
|
37
|
+
result = {key: _parse_json(f.result()) for f, key in futures.items()}
|
|
38
|
+
result["technical"] = analyze_records(symbol, result["kline"]) if result["kline"] is not None else None
|
|
39
|
+
return result
|
|
39
40
|
|
|
40
41
|
|
|
41
42
|
def gather_analysis(symbol: str) -> dict:
|
|
43
|
+
market = detect_market(symbol)
|
|
42
44
|
tasks = {
|
|
43
45
|
"quote": ("stock_data.py", ["quote", symbol]),
|
|
44
46
|
"kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", "120"]),
|
|
45
|
-
"technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "120"]),
|
|
46
47
|
"financials": ("stock_data.py", ["financials", symbol]),
|
|
47
48
|
"capital_flow": ("stock_data.py", ["capital_flow", symbol]),
|
|
48
49
|
"chip_distribution": ("stock_data.py", ["chip_distribution", symbol]),
|
|
49
50
|
"news": ("search_intel.py", ["search", _news_query(symbol)]),
|
|
50
51
|
"social_sentiment": ("search_intel.py", ["sentiment", symbol]),
|
|
51
52
|
"risk": ("risk_screening.py", ["screen", symbol]),
|
|
52
|
-
"regime": ("market_regime.py", ["detect"]),
|
|
53
53
|
}
|
|
54
|
-
|
|
54
|
+
if market in ("A", "HK", "US"):
|
|
55
|
+
tasks["regime"] = ("market_regime.py", ["detect", market])
|
|
56
|
+
result = _run_all(tasks, symbol)
|
|
57
|
+
if market not in ("A", "HK", "US"):
|
|
58
|
+
result["regime"] = {"error": f"Market regime unavailable for {market}"}
|
|
59
|
+
return result
|
|
55
60
|
|
|
56
61
|
|
|
57
62
|
def gather_technical(symbol: str, kline_count: int = 120, with_quote: bool = False) -> dict:
|
|
58
63
|
tasks = {
|
|
59
64
|
"kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", str(kline_count)]),
|
|
60
|
-
"technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", str(kline_count)]),
|
|
61
65
|
}
|
|
62
66
|
if with_quote:
|
|
63
67
|
tasks["quote"] = ("stock_data.py", ["quote", symbol])
|
|
64
|
-
return _run_all(tasks)
|
|
68
|
+
return _run_all(tasks, symbol)
|
|
65
69
|
|
|
66
70
|
|
|
67
71
|
def gather_screen(market: str = "A", top: int = 20, config: str | None = None) -> dict:
|
|
68
72
|
args = ["screen", "--market", market, "--top", str(top)]
|
|
69
73
|
if config:
|
|
70
74
|
args += ["--config", config]
|
|
71
|
-
raw = _run("screener.py", args, timeout=
|
|
75
|
+
raw = _run("screener.py", args, timeout=command_timeout("screener.py", args))
|
|
72
76
|
return {"screen_results": _parse_json(raw)}
|
|
73
77
|
|
|
74
78
|
|
|
75
79
|
def gather_fundamental(symbol: str) -> dict:
|
|
80
|
+
market = detect_market(symbol)
|
|
76
81
|
tasks = {
|
|
77
82
|
"quote": ("stock_data.py", ["quote", symbol]),
|
|
78
83
|
"kline": ("stock_data.py", ["kline", symbol, "--period", "daily", "--count", "60"]),
|
|
79
|
-
"technical": ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"]),
|
|
80
84
|
"financials": ("stock_data.py", ["financials", symbol]),
|
|
81
85
|
"news": ("search_intel.py", ["search", _news_query(symbol)]),
|
|
82
86
|
"stock_info": ("stock_data.py", ["stock_info", symbol]),
|
|
83
|
-
"sector_rankings": ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"]),
|
|
84
87
|
}
|
|
85
|
-
|
|
88
|
+
if market == "A":
|
|
89
|
+
tasks["sector_rankings"] = ("stock_data.py", ["sector_rankings", "--top", "5", "--direction", "both"])
|
|
90
|
+
result = _run_all(tasks, symbol)
|
|
91
|
+
if market != "A":
|
|
92
|
+
result["sector_rankings"] = {"error": f"Sector rankings unavailable for {market}"}
|
|
93
|
+
return result
|
|
86
94
|
|
|
87
95
|
|
|
88
96
|
def main():
|