dsh-stock-analysis 0.2.8 → 0.2.10
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 +4 -2
- package/deepseek-search.patch.yml +8 -0
- package/dist/index.js +437 -27
- package/dist/research-role.js +54 -0
- package/package.json +10 -4
- package/research.patch.yml +90 -0
- package/scripts/profile-offline.py +127 -0
- package/scripts/profile-workflows.py +87 -0
- package/scripts/setup-python.mjs +11 -4
- package/scripts/venv-python.mjs +7 -0
- package/skills/event-driven/SKILL.md +2 -0
- package/skills/growth-quality/SKILL.md +2 -0
- package/skills/market-review/SKILL.md +1 -1
- package/skills/sector-rotation/SKILL.md +57 -0
- package/skills/sector-rotation/references/computation.md +83 -0
- package/skills/sector-rotation/references/strategy_rules.md +62 -0
- package/skills/sector-rotation/scripts/rotation_metrics.py +11 -0
- package/skills/stock-analysis/SKILL.md +15 -4
- package/skills/stock-analysis/references/host-workflows.md +45 -0
- package/skills/stock-analysis/references/stateless-analysis.md +16 -2
- package/skills/stock-screener/SKILL.md +6 -0
- package/skills/strategy-backtest/SKILL.md +10 -3
- package/tools/_cache.py +93 -21
- package/tools/_subproc.py +43 -8
- package/tools/anomaly_detect.py +11 -6
- package/tools/backtest.py +225 -70
- package/tools/capabilities.py +3 -0
- package/tools/cli_budgets.json +2 -1
- package/tools/gather.py +63 -8
- package/tools/market_regime.py +26 -15
- package/tools/market_review.py +2 -2
- package/tools/position_context.py +5 -2
- package/tools/report_renderer.py +4 -0
- package/tools/requirements.txt +2 -2
- package/tools/risk_screening.py +40 -15
- package/tools/screener.py +44 -18
- package/tools/search_intel.py +94 -32
- package/tools/sec_holders.py +27 -25
- package/tools/sector_rotation.py +466 -0
- package/tools/signal_tracker.py +100 -49
- package/tools/stateless_analysis.py +600 -33
- package/tools/stock_data.py +111 -26
- package/tools/technical.py +42 -40
- package/tools/trading_calendar.py +26 -21
- package/tools/value_data.py +6 -2
- package/tools/watchlist.py +24 -15
- package/tools/watchlist_context.py +63 -49
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// dsh/research-role.ts
|
|
2
|
+
var name = "stock-research-role";
|
|
3
|
+
var inject = ["tools"];
|
|
4
|
+
var common = ["get_market_capabilities", "resolve_stock_name", "get_stock_info", "check_trading_day", "get_trading_phase"];
|
|
5
|
+
var roles = {
|
|
6
|
+
fundamentals: [
|
|
7
|
+
...common,
|
|
8
|
+
"get_quote",
|
|
9
|
+
"get_financials",
|
|
10
|
+
"get_fundamental_context",
|
|
11
|
+
"get_valuation_history",
|
|
12
|
+
"get_index_valuation",
|
|
13
|
+
"get_shareholder_structure",
|
|
14
|
+
"get_us_holdings",
|
|
15
|
+
"get_insider_trades",
|
|
16
|
+
"get_dividends",
|
|
17
|
+
"compare_stocks"
|
|
18
|
+
],
|
|
19
|
+
technical: [
|
|
20
|
+
...common,
|
|
21
|
+
"get_quote",
|
|
22
|
+
"get_kline",
|
|
23
|
+
"get_technical_analysis",
|
|
24
|
+
"analyze_pattern",
|
|
25
|
+
"get_volume_analysis",
|
|
26
|
+
"detect_market_regime",
|
|
27
|
+
"run_backtest",
|
|
28
|
+
"validate_backtest",
|
|
29
|
+
"analyze_trend_strategy",
|
|
30
|
+
"backtest_rotation_allocation"
|
|
31
|
+
],
|
|
32
|
+
events: [
|
|
33
|
+
...common,
|
|
34
|
+
"get_news",
|
|
35
|
+
"get_announcements",
|
|
36
|
+
"get_earnings_calendar",
|
|
37
|
+
"get_dividends",
|
|
38
|
+
"search_stock_news",
|
|
39
|
+
"search_comprehensive_intel",
|
|
40
|
+
"extract_article",
|
|
41
|
+
"analyze_disclosure_changes",
|
|
42
|
+
"analyze_event_study"
|
|
43
|
+
]
|
|
44
|
+
};
|
|
45
|
+
function apply(ctx, config) {
|
|
46
|
+
if (!config || !Object.hasOwn(roles, config.role)) throw new TypeError("Unknown stock research role");
|
|
47
|
+
const allowed = /* @__PURE__ */ new Set([...roles[config.role], "web_search", "web_fetch", "skill"]);
|
|
48
|
+
ctx.tools.restrict({ allow: [...allowed] });
|
|
49
|
+
}
|
|
50
|
+
export {
|
|
51
|
+
apply,
|
|
52
|
+
inject,
|
|
53
|
+
name
|
|
54
|
+
};
|
package/package.json
CHANGED
|
@@ -1,12 +1,15 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "dsh-stock-analysis",
|
|
3
|
-
"version": "0.2.
|
|
3
|
+
"version": "0.2.10",
|
|
4
4
|
"description": "DeepSeek Harness (dsh) plugin for stock analysis, screening, and strategy backtesting across A/HK/US/JP/KR/TW markets",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
7
7
|
"exports": {
|
|
8
8
|
".": "./dist/index.js",
|
|
9
|
-
"./cordis.patch.yml": "./cordis.patch.yml"
|
|
9
|
+
"./cordis.patch.yml": "./cordis.patch.yml",
|
|
10
|
+
"./research-role": "./dist/research-role.js",
|
|
11
|
+
"./research.patch.yml": "./research.patch.yml",
|
|
12
|
+
"./deepseek-search.patch.yml": "./deepseek-search.patch.yml"
|
|
10
13
|
},
|
|
11
14
|
"dsh": {
|
|
12
15
|
"bundle": {
|
|
@@ -18,10 +21,13 @@
|
|
|
18
21
|
},
|
|
19
22
|
"files": [
|
|
20
23
|
"dist/",
|
|
24
|
+
"research.patch.yml",
|
|
25
|
+
"deepseek-search.patch.yml",
|
|
21
26
|
"cordis.patch.yml",
|
|
22
27
|
"README.md",
|
|
23
28
|
"tools/",
|
|
24
29
|
"skills/",
|
|
30
|
+
"!skills/**/__pycache__/**",
|
|
25
31
|
"schemas/",
|
|
26
32
|
"templates/",
|
|
27
33
|
"strategies/",
|
|
@@ -45,7 +51,7 @@
|
|
|
45
51
|
"license": "MIT",
|
|
46
52
|
"peerDependencies": {
|
|
47
53
|
"@deepseek-ai/cordis": "^4.0.1",
|
|
48
|
-
"@deepseek-ai/dsh-skill": "^0.0.1-rc.1 || ^0.1.7-rc.1 || ^0.2.0-rc.2",
|
|
49
|
-
"@deepseek-ai/dsh-tools": "^0.0.1-rc.1 || ^0.1.7-rc.1 || ^0.2.0-rc.2"
|
|
54
|
+
"@deepseek-ai/dsh-skill": "^0.0.1-rc.1 || ^0.1.7-rc.1 || ^0.2.0-rc.2 || ^0.2.1-rc.2",
|
|
55
|
+
"@deepseek-ai/dsh-tools": "^0.0.1-rc.1 || ^0.1.7-rc.1 || ^0.2.0-rc.2 || ^0.2.1-rc.2"
|
|
50
56
|
}
|
|
51
57
|
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
# Optional overlay for dsh 0.2.1-rc.2 base/headless profiles. Install stock-analysis first.
|
|
2
|
+
- id: tools
|
|
3
|
+
config:
|
|
4
|
+
mode: ptc
|
|
5
|
+
- id: ptc-runtime
|
|
6
|
+
config:
|
|
7
|
+
executionMode: persistent-in-memory
|
|
8
|
+
- insert:
|
|
9
|
+
- id: stock-agent-presets
|
|
10
|
+
name: '@deepseek-ai/dsh-agent-preset-registry'
|
|
11
|
+
config:
|
|
12
|
+
default: stock-research
|
|
13
|
+
- id: preset-stock-research
|
|
14
|
+
name: '@deepseek-ai/dsh-agent-preset'
|
|
15
|
+
config:
|
|
16
|
+
id: stock-research
|
|
17
|
+
name: 股票综合研究
|
|
18
|
+
plugins: []
|
|
19
|
+
- id: preset-stock-fundamentals
|
|
20
|
+
name: '@deepseek-ai/dsh-agent-preset'
|
|
21
|
+
config:
|
|
22
|
+
id: stock-fundamentals
|
|
23
|
+
name: 股票基本面研究
|
|
24
|
+
plugins:
|
|
25
|
+
- id: persona
|
|
26
|
+
name: '@deepseek-ai/dsh-persona'
|
|
27
|
+
config:
|
|
28
|
+
prefix: >-
|
|
29
|
+
研究基本面、估值与财务质量。先读取 stock-analysis skill,按当前任务指定股票与期间取数。
|
|
30
|
+
向父任务返回原始工具字段路径、数值、来源、数据日期、币种、口径和缺失限制,区分事实与推断。
|
|
31
|
+
不生成最终报告、不记录持仓、不外发信息;发现技术或事件问题交回父任务。
|
|
32
|
+
- id: stock-role
|
|
33
|
+
name: 'dsh-stock-analysis/research-role'
|
|
34
|
+
config:
|
|
35
|
+
role: fundamentals
|
|
36
|
+
- id: tool-web
|
|
37
|
+
name: '@deepseek-ai/dsh-tool-web'
|
|
38
|
+
- id: tool-skill
|
|
39
|
+
name: '@deepseek-ai/dsh-tool-skill'
|
|
40
|
+
- id: preset-stock-technical
|
|
41
|
+
name: '@deepseek-ai/dsh-agent-preset'
|
|
42
|
+
config:
|
|
43
|
+
id: stock-technical
|
|
44
|
+
name: 股票技术与回测研究
|
|
45
|
+
plugins:
|
|
46
|
+
- id: persona
|
|
47
|
+
name: '@deepseek-ai/dsh-persona'
|
|
48
|
+
config:
|
|
49
|
+
prefix: >-
|
|
50
|
+
研究技术结构与策略历史表现。先读取 strategy-backtest 或当前任务指定策略 skill。
|
|
51
|
+
检查实际数据覆盖、复权、币种、费用、样本外与未来函数,缺失数据不补造。
|
|
52
|
+
向父任务返回原始字段、来源、数据日期、参数、结果与限制;不将回测结果写成收益承诺。
|
|
53
|
+
不生成最终报告、不记录持仓、不外发信息。
|
|
54
|
+
- id: stock-role
|
|
55
|
+
name: 'dsh-stock-analysis/research-role'
|
|
56
|
+
config:
|
|
57
|
+
role: technical
|
|
58
|
+
- id: tool-web
|
|
59
|
+
name: '@deepseek-ai/dsh-tool-web'
|
|
60
|
+
- id: tool-skill
|
|
61
|
+
name: '@deepseek-ai/dsh-tool-skill'
|
|
62
|
+
- id: preset-stock-events
|
|
63
|
+
name: '@deepseek-ai/dsh-agent-preset'
|
|
64
|
+
config:
|
|
65
|
+
id: stock-events
|
|
66
|
+
name: 股票公告与事件研究
|
|
67
|
+
plugins:
|
|
68
|
+
- id: persona
|
|
69
|
+
name: '@deepseek-ai/dsh-persona'
|
|
70
|
+
config:
|
|
71
|
+
prefix: >-
|
|
72
|
+
研究公告、新闻与事件。先读取 event-driven skill,检索原文并核对事件时间与披露时间。
|
|
73
|
+
向父任务返回事实、引用 URL、原文日期、工具证据路径、互相矛盾的证据与未验证点。
|
|
74
|
+
搜索摘要不是已核实正文,不能替代结构化行情;不生成最终报告、不记录持仓、不外发信息。
|
|
75
|
+
- id: stock-role
|
|
76
|
+
name: 'dsh-stock-analysis/research-role'
|
|
77
|
+
config:
|
|
78
|
+
role: events
|
|
79
|
+
- id: tool-web
|
|
80
|
+
name: '@deepseek-ai/dsh-tool-web'
|
|
81
|
+
- id: tool-skill
|
|
82
|
+
name: '@deepseek-ai/dsh-tool-skill'
|
|
83
|
+
# headless creates its parent without mounting an Agent Preset.
|
|
84
|
+
- id: stock-research-subagent
|
|
85
|
+
name: '@deepseek-ai/dsh-tool-subagent'
|
|
86
|
+
config:
|
|
87
|
+
provider: spawn
|
|
88
|
+
toolName: stock_research_subagent
|
|
89
|
+
agentPreset: stock-fundamentals
|
|
90
|
+
allowedAgentPresets: [stock-fundamentals, stock-technical, stock-events]
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Offline baseline: python scripts/profile-offline.py > baseline.json.
|
|
3
|
+
|
|
4
|
+
CLI --help includes interpreter/import/argparse cost, never provider latency.
|
|
5
|
+
Synthetic compute timings exclude imports; this is not a production throughput test.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import cProfile
|
|
9
|
+
import json
|
|
10
|
+
import platform
|
|
11
|
+
import pstats
|
|
12
|
+
import statistics
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import tempfile
|
|
16
|
+
import time
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
|
|
19
|
+
ROOT = Path(__file__).resolve().parents[1]
|
|
20
|
+
sys.path.insert(0, str(ROOT / "tools"))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def measure(operation, repeats=5):
|
|
24
|
+
samples = []
|
|
25
|
+
for _ in range(repeats):
|
|
26
|
+
start = time.perf_counter()
|
|
27
|
+
operation()
|
|
28
|
+
samples.append(round((time.perf_counter() - start) * 1000, 3))
|
|
29
|
+
return {"median_ms": statistics.median(samples), "samples_ms": samples}
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def main():
|
|
33
|
+
cli = {}
|
|
34
|
+
for path in sorted((ROOT / "tools").glob("*.py")):
|
|
35
|
+
if '__name__ == "__main__"' not in path.read_text():
|
|
36
|
+
continue
|
|
37
|
+
|
|
38
|
+
def help_call(path=path):
|
|
39
|
+
subprocess.run(
|
|
40
|
+
[sys.executable, str(path), "--help"],
|
|
41
|
+
stdout=subprocess.DEVNULL,
|
|
42
|
+
stderr=subprocess.PIPE,
|
|
43
|
+
timeout=15,
|
|
44
|
+
check=True,
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
cli[path.name] = measure(help_call, 3)
|
|
48
|
+
|
|
49
|
+
import _cache
|
|
50
|
+
import numpy as np
|
|
51
|
+
import pandas as pd
|
|
52
|
+
from backtest import load_strategy, simulate
|
|
53
|
+
from stateless_analysis import portfolio
|
|
54
|
+
from technical import analyze_records
|
|
55
|
+
|
|
56
|
+
def bars(count):
|
|
57
|
+
rng = np.random.default_rng(68)
|
|
58
|
+
close = 100 * np.exp(np.cumsum(rng.normal(0.0002, 0.01, count)))
|
|
59
|
+
return pd.DataFrame(
|
|
60
|
+
{
|
|
61
|
+
"date": pd.bdate_range("2000-01-03", periods=count).strftime("%Y-%m-%d"),
|
|
62
|
+
"open": close,
|
|
63
|
+
"close": close,
|
|
64
|
+
"high": close * 1.01,
|
|
65
|
+
"low": close * 0.99,
|
|
66
|
+
"volume": rng.integers(100000, 1000000, count),
|
|
67
|
+
}
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
compute = {}
|
|
71
|
+
strategy = load_strategy(str(ROOT / "strategies/examples/ma_crossover.yaml"))
|
|
72
|
+
for count in (120, 2500):
|
|
73
|
+
frame = bars(count)
|
|
74
|
+
records = frame.to_dict("records")
|
|
75
|
+
assert "error" not in analyze_records("TEST", records)
|
|
76
|
+
compute[f"technical_{count}"] = measure(lambda records=records: analyze_records("TEST", records))
|
|
77
|
+
compute[f"backtest_{count}"] = measure(lambda frame=frame: simulate(frame, strategy, 100000, "TEST"))
|
|
78
|
+
for count in (10, 50, 100):
|
|
79
|
+
histories = []
|
|
80
|
+
for i in range(count):
|
|
81
|
+
records = bars(250).to_dict("records")
|
|
82
|
+
histories.append({"symbol": f"S{i}", "prices": [{"date": r["date"], "close": r["close"]} for r in records]})
|
|
83
|
+
payload = {
|
|
84
|
+
"base_currency": "USD",
|
|
85
|
+
"cash": 0,
|
|
86
|
+
"positions": [{"symbol": f"S{i}", "quantity": 1, "price": 100, "currency": "USD"} for i in range(count)],
|
|
87
|
+
"histories": histories,
|
|
88
|
+
}
|
|
89
|
+
result = portfolio(payload)
|
|
90
|
+
assert len(result["correlations"]) == count * (count - 1) // 2
|
|
91
|
+
compute[f"portfolio_{count}_assets_250_dates"] = measure(lambda payload=payload: portfolio(payload), 3)
|
|
92
|
+
profiler = cProfile.Profile()
|
|
93
|
+
profiler.runcall(simulate, frame, strategy, 100000, "TEST")
|
|
94
|
+
stats = pstats.Stats(profiler)
|
|
95
|
+
hotspots = [
|
|
96
|
+
{"function": f"{Path(file).name}:{line}:{name}", "calls": values[1], "cumulative_s": round(values[3], 4)}
|
|
97
|
+
for (file, line, name), values in sorted(stats.stats.items(), key=lambda item: item[1][3], reverse=True)[:12]
|
|
98
|
+
]
|
|
99
|
+
original_dir = _cache.CACHE_DIR
|
|
100
|
+
with tempfile.TemporaryDirectory() as directory:
|
|
101
|
+
try:
|
|
102
|
+
_cache.CACHE_DIR = Path(directory)
|
|
103
|
+
payload = [{"symbol": str(i), "value": i} for i in range(10000)]
|
|
104
|
+
_cache.cached("profile", 60, lambda: payload)
|
|
105
|
+
|
|
106
|
+
def unexpected_fetch():
|
|
107
|
+
raise AssertionError("warm cache missed")
|
|
108
|
+
|
|
109
|
+
compute["cache_read_10000_rows"] = measure(lambda: _cache.cached("profile", 60, unexpected_fetch))
|
|
110
|
+
finally:
|
|
111
|
+
_cache.CACHE_DIR = original_dir
|
|
112
|
+
print(
|
|
113
|
+
json.dumps(
|
|
114
|
+
{
|
|
115
|
+
"python": platform.python_version(),
|
|
116
|
+
"platform": platform.platform(),
|
|
117
|
+
"cli": cli,
|
|
118
|
+
"compute": compute,
|
|
119
|
+
"backtest_hotspots": hotspots,
|
|
120
|
+
},
|
|
121
|
+
indent=2,
|
|
122
|
+
)
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
if __name__ == "__main__":
|
|
127
|
+
main()
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Offline workflow baseline with counted, fixed-latency CLI substitutes.
|
|
3
|
+
|
|
4
|
+
Run with the repo venv (pytest/pandas/numpy installed):
|
|
5
|
+
python scripts/profile-workflows.py [checkout-root]
|
|
6
|
+
This measures orchestration only, not provider throughput. Reuses the test OHLCV fixture.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import importlib.util
|
|
10
|
+
import json
|
|
11
|
+
import sys
|
|
12
|
+
import threading
|
|
13
|
+
import time
|
|
14
|
+
from collections import Counter
|
|
15
|
+
from pathlib import Path
|
|
16
|
+
|
|
17
|
+
root = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parents[1]
|
|
18
|
+
sys.path.insert(0, str(root / "tools"))
|
|
19
|
+
import anomaly_detect # noqa: E402
|
|
20
|
+
import gather # noqa: E402
|
|
21
|
+
import risk_screening # noqa: E402
|
|
22
|
+
import technical # noqa: E402
|
|
23
|
+
import watchlist_context # noqa: E402
|
|
24
|
+
|
|
25
|
+
spec = importlib.util.spec_from_file_location("perf_fixtures", root / "tests/conftest.py")
|
|
26
|
+
fixtures = importlib.util.module_from_spec(spec)
|
|
27
|
+
spec.loader.exec_module(fixtures)
|
|
28
|
+
bars = fixtures.make_kline_data.__wrapped__()(120, "volatile")
|
|
29
|
+
for row in bars:
|
|
30
|
+
row["date"] = row["date"].strftime("%Y-%m-%d")
|
|
31
|
+
calls = Counter()
|
|
32
|
+
lock = threading.Lock()
|
|
33
|
+
active = peak = 0
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def invoke(script, args, **kwargs):
|
|
37
|
+
global active, peak
|
|
38
|
+
if script == "risk_screening.py" and args[0] == "screen":
|
|
39
|
+
return risk_screening.screen_risk(args[1])
|
|
40
|
+
if script == "technical.py":
|
|
41
|
+
rows = invoke("stock_data.py", ["kline", args[1], "--count", "120"])
|
|
42
|
+
return technical.analyze_records(args[1], rows)
|
|
43
|
+
if script == "anomaly_detect.py":
|
|
44
|
+
return anomaly_detect.detect_anomalies(args[1])
|
|
45
|
+
key = script + ":" + args[0]
|
|
46
|
+
with lock:
|
|
47
|
+
calls[key] += 1
|
|
48
|
+
active += 1
|
|
49
|
+
peak = max(peak, active)
|
|
50
|
+
time.sleep(0.01)
|
|
51
|
+
with lock:
|
|
52
|
+
active -= 1
|
|
53
|
+
if args[0] == "kline":
|
|
54
|
+
n = int(args[args.index("--count") + 1]) if "--count" in args else 120
|
|
55
|
+
return bars[-n:]
|
|
56
|
+
if args[0] == "quote":
|
|
57
|
+
return {"price": 10, "pe": 15, "pb": 2}
|
|
58
|
+
if args[0] == "lockup":
|
|
59
|
+
return {"upcoming_30d": [], "flags": [], "available": True}
|
|
60
|
+
if args[0] == "capital_flow":
|
|
61
|
+
return []
|
|
62
|
+
if script == "market_regime.py":
|
|
63
|
+
return {"market": args[1]}
|
|
64
|
+
return []
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
gather._run = lambda script, args, **kw: json.dumps(invoke(script, args, **kw))
|
|
68
|
+
risk_screening._run_tool = invoke
|
|
69
|
+
anomaly_detect._run_tool = invoke
|
|
70
|
+
anomaly_detect.fetch_kline = lambda symbol, period, count: invoke(
|
|
71
|
+
"stock_data.py", ["kline", symbol, "--count", str(count)]
|
|
72
|
+
)
|
|
73
|
+
watchlist_context._run_json = invoke
|
|
74
|
+
start = time.perf_counter()
|
|
75
|
+
result = watchlist_context.build_context(["600519", "000001", "000002"], workers=3)
|
|
76
|
+
assert result["summary"]["success"] == 3
|
|
77
|
+
print(
|
|
78
|
+
json.dumps(
|
|
79
|
+
{
|
|
80
|
+
"seconds": time.perf_counter() - start,
|
|
81
|
+
"calls": dict(calls),
|
|
82
|
+
"total_calls": sum(calls.values()),
|
|
83
|
+
"peak_leaf_calls": peak,
|
|
84
|
+
"summary": result["summary"],
|
|
85
|
+
}
|
|
86
|
+
)
|
|
87
|
+
)
|
package/scripts/setup-python.mjs
CHANGED
|
@@ -1,17 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { execFileSync } from "node:child_process";
|
|
3
|
-
import { existsSync } from "node:fs";
|
|
3
|
+
import { existsSync, mkdirSync, renameSync } from "node:fs";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { fileURLToPath } from "node:url";
|
|
6
|
-
import { venvPythonPath } from "./venv-python.mjs";
|
|
6
|
+
import { pythonEnvironmentRoot, venvPythonPath } from "./venv-python.mjs";
|
|
7
7
|
|
|
8
8
|
// fileURLToPath (not URL.pathname) — the latter yields a bogus "/C:/..." path
|
|
9
9
|
// on Windows, which would put the venv in the wrong place or fail outright.
|
|
10
10
|
const pkgDir = fileURLToPath(new URL("..", import.meta.url));
|
|
11
|
-
const
|
|
11
|
+
const envRoot = pythonEnvironmentRoot(pkgDir);
|
|
12
|
+
const venvDir = join(envRoot, ".venv");
|
|
12
13
|
// Drive pip through the venv's own python (`-m pip`) instead of a pip/pip.exe
|
|
13
14
|
// shim — resolves correctly on both POSIX (bin/python3) and Windows (Scripts/python.exe).
|
|
14
|
-
const venvPython = venvPythonPath(
|
|
15
|
+
const venvPython = venvPythonPath(envRoot);
|
|
15
16
|
const requirements = join(pkgDir, "tools", "requirements.txt");
|
|
16
17
|
|
|
17
18
|
function run(bin, args) {
|
|
@@ -41,6 +42,12 @@ try {
|
|
|
41
42
|
process.exit(1);
|
|
42
43
|
}
|
|
43
44
|
|
|
45
|
+
if (envRoot !== pkgDir && existsSync(join(pkgDir, ".venv"))) {
|
|
46
|
+
// Preserve installed dependencies; never leave an old environment in captured source.
|
|
47
|
+
if (existsSync(venvDir)) throw new Error("Both legacy and current Python environments exist; move the legacy .venv outside the plugin package");
|
|
48
|
+
mkdirSync(envRoot, { recursive: true });
|
|
49
|
+
renameSync(join(pkgDir, ".venv"), venvDir);
|
|
50
|
+
}
|
|
44
51
|
if (!existsSync(venvDir)) {
|
|
45
52
|
run(python, ["-m", "venv", venvDir]);
|
|
46
53
|
}
|
package/scripts/venv-python.mjs
CHANGED
|
@@ -6,6 +6,13 @@ import { join } from "node:path";
|
|
|
6
6
|
|
|
7
7
|
const isWin = process.platform === "win32";
|
|
8
8
|
|
|
9
|
+
// OpenClaw captures package source, including .venv symlinks; node_modules is excluded.
|
|
10
|
+
export function pythonEnvironmentRoot(rootDir) {
|
|
11
|
+
return existsSync(join(rootDir, "openclaw.plugin.json"))
|
|
12
|
+
? join(rootDir, "node_modules", ".stock-analysis-python")
|
|
13
|
+
: rootDir;
|
|
14
|
+
}
|
|
15
|
+
|
|
9
16
|
// Windows venvs ship Scripts/python.exe (there is no python3); POSIX venvs ship bin/python3.
|
|
10
17
|
export function venvPythonPath(rootDir) {
|
|
11
18
|
return join(rootDir, ".venv", isWin ? "Scripts" : "bin", isWin ? "python.exe" : "python3");
|
|
@@ -5,6 +5,8 @@ description: 事件驱动分析:评估公告、业绩、政策、订单或资
|
|
|
5
5
|
|
|
6
6
|
# 事件驱动分析
|
|
7
7
|
|
|
8
|
+
批量研究、子任务分工或报告文件交付时,必须读取[宿主研究与报告交付](../stock-analysis/references/host-workflows.md),使用当前宿主实际提供的能力。
|
|
9
|
+
|
|
8
10
|
## 无状态分析扩展
|
|
9
11
|
|
|
10
12
|
历史事件窗口验证或公告原文变化分析时,MUST 读取[无状态研究工具](../stock-analysis/references/stateless-analysis.md),使用 analyze_event_study/analyze_disclosure_changes。事件日期、盘前盘后、价格窗口和正文覆盖必须核实。
|
|
@@ -28,6 +28,8 @@ gather 工具返回:
|
|
|
28
28
|
|
|
29
29
|
需要财务趋势时调用 `get_financials(symbol, annual=true, periods=10)`。港股配置 `LIXINGER_TOKEN` 后优先理杏仁非金融公司财报,按真实 `report_type` 判断年报,保留实际财年末、披露日期、币种;历史 ROE/毛利率/净利率为百分数,顶层 `roe/profit_margin` 延续小数比例。读取 `available_periods/warnings`,缺期不补造。有效 Yahoo 顶层快照与历史行分开读:`currency` 为快照财报币种、`market_cap_currency` 为市值币种,历史币种在 `periods` 每行,`snapshot_source` 标记快照来源;null 不用历史值补成跨期或跨币种数字;顶层 `report_date` 未知时读取 `periods` 的历史日期,不当作当前快照报告期。
|
|
30
30
|
|
|
31
|
+
Yahoo 顶层快照单位以 `snapshot_units` 为准:`roe/profit_margin/dividend_yield=ratio`,`debt_to_equity=percent`,例如 150 表示 150%,不是 150 倍;`pe=trailing`,不与 dynamic PE 直接比较。
|
|
32
|
+
|
|
31
33
|
`financials` 通常只是单期摘要。多期趋势、经营现金流、应收账款或同业估值未返回时,把对应维度标为“数据不足”,不推断趋势、不计分。
|
|
32
34
|
|
|
33
35
|
## 分析框架(4 步法)
|
|
@@ -63,7 +63,7 @@ gather 工具返回以下字段:
|
|
|
63
63
|
|
|
64
64
|
## 输出
|
|
65
65
|
|
|
66
|
-
按 [市场复盘 schema](../../schemas/market_review_schema.json) 构建报告对象,再调用 `render_market_report`。缺失的市场数据保持为空并在 `risks`
|
|
66
|
+
按 [市场复盘 schema](../../schemas/market_review_schema.json) 构建报告对象,再调用 `render_market_report`。缺失的市场数据保持为空并在 `risks` 中说明,不用定性文字补齐。报告文件/连接器交付或分工研究时,必须读取[宿主研究与报告交付](../stock-analysis/references/host-workflows.md);本轮仅剩回复时才传 `final=true`,否则保持默认 false。
|
|
67
67
|
|
|
68
68
|
## 多市场支持
|
|
69
69
|
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: sector-rotation
|
|
3
|
+
description: 行业ETF轮动研究:核对SSRN 4280640论文规则,复核预测分布集中度与历史配权,评估轮动对现有策略的增益。提供确定性计算与配权分项回测,不生成深度模型预测或实盘买卖计划。
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# 行业 ETF 轮动研究
|
|
7
|
+
|
|
8
|
+
用于研究一组行业 ETF 的周度轮动,以及它是否值得补充现有趋势、题材或组合策略。市场由用户指定,允许跨市场;论文的美国样本不构成插件市场限制。
|
|
9
|
+
|
|
10
|
+
实现状态:**共享Python数值计算与配权分项回测已实现,论文完整训练与信号模型未实现**。MUST 将“原文已披露规则”“尚未披露的实现细节”“插件的跨市场扩展”分别说明。MUST NOT 声称已经严格复现论文或重现其收益。
|
|
11
|
+
|
|
12
|
+
## 1. 明确要改善什么
|
|
13
|
+
|
|
14
|
+
- 行业配置:比较不同 ETF 的取舍、空仓和资金分配。这是与现有能力最直接的补充。
|
|
15
|
+
- 热点题材:`hot-theme` 判断板块强度与催化,不能用本论文证明其预测能力得到改善。
|
|
16
|
+
- 个股趋势:`bull-trend` 的月度持有与本论文的周内清仓时钟不同。MUST NOT 自动把轮动筛选叠加为个股买入过滤器。
|
|
17
|
+
- 单股回测:`strategy-backtest` 的单标的 YAML 不能代表跨 ETF 共享资金组合。
|
|
18
|
+
|
|
19
|
+
仅问是否有用时,结合上述区别回答;无独立对照证据时,结论为“有能力补充价值,收益增益未证实”。
|
|
20
|
+
|
|
21
|
+
## 2. 核对论文与数据
|
|
22
|
+
|
|
23
|
+
研究具体规则、复现、模型预测或交易时,MUST 先读取 [论文规则、缺项与输入格式](references/strategy_rules.md)。严格复现所需的损失函数或参数缺失时,列出缺项,停止生成模型信号;MUST NOT 自选参数并冠以原策略名称。
|
|
24
|
+
|
|
25
|
+
用户提供代码即可通过现有 `get_kline` 获取整个池的 daily OHLCV,按研究区间加预热历史;行业归属、ETF身份、币种或复权未知时明确标记。没有代码时才需要确定标的池。MUST 保留整池成员、来源、实际区间及缺失项,不能静默删掉失败成员改变横截面。
|
|
26
|
+
|
|
27
|
+
跨市场时,分别记录交易所、时区、币种、当地交易日和周末决策截止时间;只使用截止时已发布的数据。共同资金研究还需要历史汇率、换汇成本及结算约束,数据缺失时停止组合收益计算。MUST NOT 将不同币种净值相加、把后收盘市场的数据用于早开盘市场的历史订单,或把本地周线按日期直接拼接后宣称无前视。
|
|
28
|
+
|
|
29
|
+
## 3. 复核已披露计算
|
|
30
|
+
|
|
31
|
+
已有模型生成的 MC-dropout 样本或历史成交计数时,调用 `calculate_rotation_metrics(prediction_samples?, trade_counts?)`。Agent负责提供有来源的输入和解释结果,MUST 使用工具计算,不临场手算或重写算子。交易计数可直接复用分项回测返回的 `trade_counts`;缺原模型预测时,MUST NOT 用动量、随机数或语言模型猜测代替。
|
|
32
|
+
|
|
33
|
+
- `confidence`:复核预测值在“中位数 ± 总体标准差”内的经验占比。
|
|
34
|
+
- `allocation`:复核 `1 + wins/buys + streak/(wins+1)` 原始配权分数。
|
|
35
|
+
|
|
36
|
+
输入格式、样本来源与零历史边界见参考。所有算子以共享 `tools/sector_rotation.py` 为唯一实现,四宿主转发同一JSON。skill里的 `scripts/rotation_metrics.py` 仅保留旧调用兼容入口;没有另一套公式。没有模型训练、账户存储或下单功能。
|
|
37
|
+
|
|
38
|
+
MUST 同时报 `paper_reproduction=partial_calculations_only`。集中度不是盈利概率;原始配权分数不是目标权重、股数或已确认可用资金。两项计算都不能独立决定买入。
|
|
39
|
+
|
|
40
|
+
## 4. 运行配权分项回测
|
|
41
|
+
|
|
42
|
+
MUST 先读取 [计算与回测接口](references/computation.md),再调用 `backtest_rotation_allocation`。用户给代码时使用 `symbols` 自动获取行情与报价币种;已有核实的行情才传 `datasets`。两种模式互斥,不能要求正常用户手工准备行情文件。
|
|
43
|
+
|
|
44
|
+
该工具在相同全池周内买卖下比较等权与历史配权,自动计数、费用扣除、净值和回撤;MUST NOT 让Agent自行计算回测收益。按交易所与报价币种分组,每组独立初始资金;报告每组实际区间、跳过周、费用、两组表现及差值。混合代码池不等于跨币种共享资金组合。任一取数失败、复权/价格检查失败或评估期完整交易周缺bar/零成交量则停止,不缩小股票池,不按事后数据完整性选择交易周。预热不足不能用评估期收益补齐初始化。
|
|
45
|
+
|
|
46
|
+
该分项入口不需要缺失的神经网络,也不能替代它。MUST 同时报 `paper_reproduction=allocation_ablation_only`,并把历史分数归一化和预热约定与原文已披露公式分开。
|
|
47
|
+
|
|
48
|
+
## 5. 评估相对现有策略的增益
|
|
49
|
+
|
|
50
|
+
取得完整可执行模型后,按预先固定的区间、标的池、初始资金、成交时点和成本比较:
|
|
51
|
+
|
|
52
|
+
1. 基准持有、行业 ETF 等权、简单动量轮动、论文模型;现有月度策略仅在标的池和资金口径可比时加入。
|
|
53
|
+
2. 保持年度训练与周度更新的时间边界,归一化和阈值选择均只看当时已知数据;额外报告论文发表后的独立区间。
|
|
54
|
+
3. 分别比较净收益、最大回撤、换手、交易次数和资金占用;逐项关闭置信筛选、亏损过滤或动态配权,检验各部件实际贡献。
|
|
55
|
+
4. 如需改善某个现有策略,另做“原策略 vs 加入该部件”的同条件对照,不能凭独立策略收益推定组合效果。
|
|
56
|
+
|
|
57
|
+
完成时报告:已实现内容、缺项、对照条件和增益结论。没有完整模型或合格组合回测时,MUST 报“尚未验证”,不能用论文表3、单股回测相加或技术测试通过代替实际增益证据。
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# 确定性计算与配权分项回测
|
|
2
|
+
|
|
3
|
+
共享核心为 `tools/sector_rotation.py`。Pi、Hermes、OpenClaw、dsh 暴露相同的两个工具;Agent负责输入来源与结论,计算和资金递推均由Python完成。它们不包含尚未披露的神经网络训练或预测。
|
|
4
|
+
|
|
5
|
+
## calculate_rotation_metrics
|
|
6
|
+
|
|
7
|
+
`prediction_samples` 与 `trade_counts` 至少提供一项。每组样本2..100000个有限数,全请求最多100000个;最多100组唯一标识。同一组必须属于同一模型、标的和决策时间,来源由调用方核实。
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"prediction_samples": [{"symbol":"XLK","samples":[0.1,0.2,0.1,0.15]}],
|
|
12
|
+
"trade_counts": [{"symbol":"XLK","buys":4,"wins":3,"streak":2}]
|
|
13
|
+
}
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
返回逐标的 `confidence` 和/或 `allocation`,其中原始配权分数为2.25;`model_status=not_implemented_missing_specification`、`is_buy_signal=false`、`paper_reproduction=partial_calculations_only`。零历史和零方差边界见 [规则参考](strategy_rules.md)。不验证预测来源的真实性,不把集中度当作盈利概率。
|
|
17
|
+
|
|
18
|
+
## backtest_rotation_allocation
|
|
19
|
+
|
|
20
|
+
正常调用直接传股票/ETF代码,无须用户提供行情文件:
|
|
21
|
+
|
|
22
|
+
```json
|
|
23
|
+
{
|
|
24
|
+
"symbols":["XLK","XLE","512000","512010","1306.T"],
|
|
25
|
+
"start_date":"2021-01-01",
|
|
26
|
+
"end_date":"2026-10-16",
|
|
27
|
+
"history_start_date":"2020-01-01",
|
|
28
|
+
"warmup_weeks":26,
|
|
29
|
+
"capital":1000000,
|
|
30
|
+
"cost_per_side":0.001
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
| 字段 | 约束 |
|
|
35
|
+
|---|---|
|
|
36
|
+
| `symbols` | 1..20个插件格式代码;与datasets互斥,重复别名拒绝;任一成员取数失败整池停止 |
|
|
37
|
+
| `start_date/end_date` | 必填、有序的YYYY-MM-DD评估区间;截止日不得晚于当前UTC日期,不能使用未收盘bar;完整交易周才成交 |
|
|
38
|
+
| `history_start_date` | 仅代码模式,默认评估前一年;早于start_date,取数长度包括这段预热 |
|
|
39
|
+
| `warmup_weeks` | 评估前完整全池交易周,整数1..104,默认26;不足则停止,不延后起点冒充完整评估 |
|
|
40
|
+
| `capital` | 每个市场/报价币种分组的独立初始资金,默认1000000,0.01..1e12;不是混合池总资金 |
|
|
41
|
+
| `cost_per_side` | 假设的每边比例成本0..0.1,默认0.001;包含预算内买入成本及卖出成本,非交易所费率声明 |
|
|
42
|
+
|
|
43
|
+
A/HK/US/JP/KR/TW均按真实交易所日历取周内首末交易日。币种采用已核实的报价币种,不能依据市场猜测港股ETF一定报价HKD。跨市场或同市场多币种分成独立资金组,MUST NOT 把各组净值相加或称为完成了外汇/结算模拟。
|
|
44
|
+
|
|
45
|
+
复核已有行情时,用 `datasets` 代替symbols,省略history_start_date。每项包含:
|
|
46
|
+
|
|
47
|
+
```json
|
|
48
|
+
{
|
|
49
|
+
"symbol":"XLK",
|
|
50
|
+
"currency":"USD",
|
|
51
|
+
"price_basis":"total_return",
|
|
52
|
+
"bars":[
|
|
53
|
+
{"date":"2020-01-02","open":100,"high":102,"low":99,"close":101,"volume":1000}
|
|
54
|
+
]
|
|
55
|
+
}
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
上例只展示单条格式,不能单独运行:每个数据集需2..20000行,并覆盖完整预热及评估交易周;最多20组、总行数不超过100000,JSON输入最大8 MiB。日期递增唯一,OHLC为有限正数且范围一致、volume非负;currency为调用方核实的三字母币种。price_basis限 `qfq/total_return/split_adjusted`,不能把unknown或原始价改标签冒充已复权。额外逐bar `adjusted` 若存在,须与数据集口径一致。
|
|
59
|
+
|
|
60
|
+
### 固定分项实验
|
|
61
|
+
|
|
62
|
+
1. 每周全池均买入,没有预测挑选;相同周内首个交易日开盘买入、最后交易日收盘卖出。
|
|
63
|
+
2. 首次评估前必须有足够完整观察周。历史计数仅使用决策前已结束的周内交易,毛收益>0算赢,持平重置连胜;计数累计,不做未经披露的年度重置。
|
|
64
|
+
3. 等权组均分预算;历史组对 `1+wins/buys+streak/(wins+1)` 分数归一化。预热、全池买入、归一化是此独立实验的约定,不宣称为作者的完整策略。
|
|
65
|
+
4. 每笔预算含买入比例成本,按合成复权价格计算小数名义份额;逐日收盘盯市、末日扣卖出成本。费用、最终净值和收盘净值最大回撤由核心计算。
|
|
66
|
+
5. 评估期完整交易周中任一成员缺bar或零成交量,整组回测停止;不能用周末才知道的数据完整性决定周初是否买入。预热期的不完整周不计观察次数、不删除成员。周跨越评估边界时跳过;首周缺前几天不算完整预热周。
|
|
67
|
+
|
|
68
|
+
返回 `groups`:market/currency/symbols、实际period、price_basis/data_coverage、evaluated_weeks/skipped_weeks、决策日期和weights、最终trade_counts、equal_weight/historical_weight的净值与成本和指标、年化收益差。指标沿用共享回测函数的四位小数精度。历史计数包括预热,closed_trades仅包含评估期。
|
|
69
|
+
|
|
70
|
+
`paper_reproduction=allocation_ablation_only`。这不是ROC/MC/神经网络挑选后的组合,更不是现有月度策略的直接前后对照。无外汇、结算、整手、价格限制、盘口、税务或成交量容量模型;比例成本与成交时点只是该模拟假设。
|
|
71
|
+
|
|
72
|
+
### 数据验收
|
|
73
|
+
|
|
74
|
+
价格序列跳变大于1.5倍(或低于其倒数)、单日high/low大于1.5时,需要独立核查公司行动后再研究;这是一道保守审查阈值,不是认定真实市场不可能发生该涨跌。复权未知、日期/交易时段不符、未收盘或可疑价格会返回安全JSON错误,`market_data_requires_review` 表示整池未生成回测。检查通过也不证明来源无误。
|
|
75
|
+
|
|
76
|
+
## CLI 与兼容入口
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
python3 tools/sector_rotation.py analyze --input request.json
|
|
80
|
+
python3 tools/sector_rotation.py backtest --input request.json
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
skill中的 `scripts/rotation_metrics.py confidence predictions.json` 与 `allocation counts.json` 保留兼容,转调同一核心。所有入口stdout为JSON,错误非零退出,不保存账户或提交订单。
|