openclaw-stock-analysis 0.2.1 → 0.2.5
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/LICENSE +21 -0
- package/README.md +2 -2
- package/dist/index.js +170 -23
- package/index.ts +184 -26
- package/openclaw.plugin.json +10 -1
- package/package.json +1 -1
- package/scripts/ci-resolve-llm-host.mjs +29 -0
- package/scripts/setup-python.mjs +7 -9
- package/skills/event-driven/SKILL.md +6 -0
- package/skills/growth-quality/SKILL.md +6 -0
- package/skills/hot-theme/SKILL.md +3 -2
- package/skills/stock-analysis/SKILL.md +22 -0
- package/skills/stock-screener/SKILL.md +19 -1
- package/skills/strategy-backtest/SKILL.md +11 -5
- package/strategies/examples/bottom_volume.yaml +5 -0
- package/strategies/examples/box_oscillation.yaml +5 -0
- package/strategies/examples/bull_trend.yaml +11 -3
- package/strategies/examples/dragon_head.yaml +4 -2
- package/strategies/examples/emotion_cycle.yaml +5 -0
- package/strategies/examples/ma_crossover.yaml +10 -3
- package/strategies/examples/rsi_oversold.yaml +5 -0
- package/strategies/examples/shrink_pullback.yaml +7 -1
- package/strategies/examples/volume_breakout.yaml +7 -1
- package/tools/_cache.py +61 -0
- package/tools/_subproc.py +49 -0
- package/tools/alert_rules.py +19 -9
- package/tools/anomaly_detect.py +24 -35
- package/tools/backtest.py +180 -100
- package/tools/capabilities.py +13 -5
- package/tools/diagnostics.py +12 -6
- package/tools/gather.py +13 -9
- package/tools/import_parser.py +2 -5
- package/tools/market_regime.py +27 -35
- package/tools/market_review.py +56 -9
- package/tools/name_resolver.py +2 -5
- package/tools/pattern.py +2 -5
- package/tools/position_context.py +2 -5
- package/tools/report_renderer.py +10 -6
- package/tools/requirements.txt +2 -1
- package/tools/risk_screening.py +29 -23
- package/tools/screener.py +80 -18
- package/tools/search_intel.py +5 -13
- package/tools/signal_tracker.py +2 -6
- package/tools/stock_data.py +612 -177
- package/tools/technical.py +136 -40
- package/tools/trading_calendar.py +78 -18
- package/tools/value_data.py +1368 -0
- package/tools/volume_analysis.py +2 -5
- package/tools/watchlist.py +2 -5
- package/tools/watchlist_context.py +2 -5
package/openclaw.plugin.json
CHANGED
|
@@ -21,6 +21,8 @@
|
|
|
21
21
|
"get_limit_up_pool",
|
|
22
22
|
"get_dragon_tiger",
|
|
23
23
|
"get_hot_stocks",
|
|
24
|
+
"get_margin_trading",
|
|
25
|
+
"get_northbound_flow",
|
|
24
26
|
"get_fundamental_context",
|
|
25
27
|
"screen_stocks",
|
|
26
28
|
"run_backtest",
|
|
@@ -51,7 +53,14 @@
|
|
|
51
53
|
"record_signal",
|
|
52
54
|
"evaluate_signals",
|
|
53
55
|
"get_signal_summary",
|
|
54
|
-
"
|
|
56
|
+
"get_review_history",
|
|
57
|
+
"parse_stock_list",
|
|
58
|
+
"get_valuation_history",
|
|
59
|
+
"get_index_valuation",
|
|
60
|
+
"get_earnings_calendar",
|
|
61
|
+
"get_shareholder_structure",
|
|
62
|
+
"get_etf_details",
|
|
63
|
+
"get_dividends"
|
|
55
64
|
]
|
|
56
65
|
},
|
|
57
66
|
"activation": {
|
package/package.json
CHANGED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
// Some model gateways resolve through Chinese DNS but not the runner's resolver.
|
|
2
|
+
// Keep the original hostname for HTTPS; only supply its missing A record.
|
|
3
|
+
import { execFileSync } from "node:child_process";
|
|
4
|
+
import { lookup } from "node:dns/promises";
|
|
5
|
+
import { isIP } from "node:net";
|
|
6
|
+
|
|
7
|
+
if (process.env.OPENAI_BASE_URL) {
|
|
8
|
+
const host = new URL(process.env.OPENAI_BASE_URL).hostname;
|
|
9
|
+
let resolved = false;
|
|
10
|
+
try {
|
|
11
|
+
await lookup(host, { family: 4 });
|
|
12
|
+
resolved = true;
|
|
13
|
+
} catch { /* ask a second resolver below */ }
|
|
14
|
+
|
|
15
|
+
if (!resolved) {
|
|
16
|
+
// Ask for the China-facing record; the runner's overseas view gets only a CNAME.
|
|
17
|
+
const url = `https://dns.alidns.com/resolve?name=${encodeURIComponent(host)}&type=A&edns_client_subnet=223.5.5.0%2F24`;
|
|
18
|
+
const response = await fetch(url, { signal: AbortSignal.timeout(10_000) });
|
|
19
|
+
if (!response.ok) throw new Error(`AliDNS lookup failed: HTTP ${response.status}`);
|
|
20
|
+
const answer = (await response.json()).Answer?.find((record) => record.type === 1);
|
|
21
|
+
if (isIP(answer?.data) !== 4) throw new Error(`No IPv4 address found for ${host}`);
|
|
22
|
+
execFileSync("sudo", ["tee", "-a", "/etc/hosts"], {
|
|
23
|
+
input: `${answer.data} ${host}\n`,
|
|
24
|
+
stdio: ["pipe", "ignore", "pipe"],
|
|
25
|
+
});
|
|
26
|
+
await fetch(`https://${host}/`, { signal: AbortSignal.timeout(10_000) });
|
|
27
|
+
console.log(`Resolved ${host} through AliDNS; HTTPS is reachable`);
|
|
28
|
+
}
|
|
29
|
+
}
|
package/scripts/setup-python.mjs
CHANGED
|
@@ -15,7 +15,7 @@ const venvPython = venvPythonPath(pkgDir);
|
|
|
15
15
|
const requirements = join(pkgDir, "tools", "requirements.txt");
|
|
16
16
|
|
|
17
17
|
function run(cmd) {
|
|
18
|
-
execSync(cmd, { stdio: "
|
|
18
|
+
execSync(cmd, { stdio: "inherit", timeout: 1_800_000 });
|
|
19
19
|
}
|
|
20
20
|
|
|
21
21
|
function findPython() {
|
|
@@ -23,7 +23,7 @@ function findPython() {
|
|
|
23
23
|
try {
|
|
24
24
|
const ver = execSync(`${name} --version`, { stdio: "pipe" }).toString().trim();
|
|
25
25
|
const match = ver.match(/(\d+)\.(\d+)/);
|
|
26
|
-
if (match && (parseInt(match[1]) > 3 || (parseInt(match[1]) === 3 && parseInt(match[2]) >=
|
|
26
|
+
if (match && (parseInt(match[1]) > 3 || (parseInt(match[1]) === 3 && parseInt(match[2]) >= 10))) {
|
|
27
27
|
return name;
|
|
28
28
|
}
|
|
29
29
|
} catch {}
|
|
@@ -35,23 +35,21 @@ try {
|
|
|
35
35
|
const python = findPython();
|
|
36
36
|
if (!python) {
|
|
37
37
|
console.warn(
|
|
38
|
-
"\n[
|
|
39
|
-
"Install Python 3.
|
|
38
|
+
"\n[stock-analysis-plugin] python3 >= 3.10 not found.\n" +
|
|
39
|
+
"Install Python 3.10+, then re-run: npm install\n"
|
|
40
40
|
);
|
|
41
|
-
process.exit(
|
|
41
|
+
process.exit(1);
|
|
42
42
|
}
|
|
43
43
|
|
|
44
44
|
if (!existsSync(venvDir)) {
|
|
45
45
|
run(`${python} -m venv "${venvDir}"`);
|
|
46
46
|
}
|
|
47
47
|
|
|
48
|
-
|
|
49
|
-
run(`"${venvPython}" -m pip install -q -r "${requirements}"`);
|
|
50
|
-
}
|
|
48
|
+
run(`"${venvPython}" -m pip install -q -r "${requirements}"`);
|
|
51
49
|
} catch (err) {
|
|
52
50
|
console.warn(
|
|
53
51
|
`\n[pi-stock-analysis] Python setup failed: ${err.message}\n` +
|
|
54
52
|
"You can manually create the venv and install tools/requirements.txt with your platform's python.\n"
|
|
55
53
|
);
|
|
56
|
-
process.exit(
|
|
54
|
+
process.exit(1);
|
|
57
55
|
}
|
|
@@ -87,3 +87,9 @@ gather 工具返回:
|
|
|
87
87
|
5. 触发、失效、时间止损、潜在收益/R 与风险提示
|
|
88
88
|
|
|
89
89
|
完成标准:区分“已确认事实”“推断的影响路径”和“待验证项”,并为交易计划给出可观察的失效条件。
|
|
90
|
+
|
|
91
|
+
财报季排期使用 `get_earnings_calendar(report_date="YYYY-MM-DD", symbol=...)`:最新预约/修订日期是计划,实际披露日期是实绩时间,业绩预告是已公告预估。除息事件用 `get_dividends(mode="calendar", symbol=...)`;不补造未公告日期或把分红预案计入已支付现金。
|
|
92
|
+
|
|
93
|
+
### 补充数据覆盖
|
|
94
|
+
|
|
95
|
+
get_earnings_calendar 查询 A 股仍需 report_date;HK 提供 symbol,可选财政期末 report_date;优先 HKEX 已公告业绩审批董事会排期 confirmation=official_board_meeting_notice、date_kind=scheduled_board_meeting,不能称实际披露日。供应商备选日期为 provider_only,未知期次在请求特定报告期时另列 unverified_schedules,不能强行匹配。
|
|
@@ -77,3 +77,9 @@ gather 工具返回:
|
|
|
77
77
|
5. 投资建议与关注风险点
|
|
78
78
|
|
|
79
79
|
只有收入、利润、现金流和 ROE 均有可比多期数据时,才可给出“优质”结论;否则完成标准是给出已验证项、缺失项和最小补证建议。
|
|
80
|
+
|
|
81
|
+
用户要求长期质量、五到十年财报或 ROE/利润率趋势时,补充 `get_financials(symbol, periods=10, annual=true)`;逐年比较同口径年报,实际可得年份不足时明确标注,不以最近十个季度代替十年。结合 `get_valuation_history` 检查估值分位,分位窗口以实际返回数据为准。
|
|
82
|
+
|
|
83
|
+
### 补充数据覆盖
|
|
84
|
+
|
|
85
|
+
指数估值可用 get_index_valuation;中证补充多年滚动 PE,配置 LIXINGER_TOKEN 可补理杏仁 mcw 历史 PB。每个指标按其来源/口径使用,不把缺失 PB 或近期 PE1 当长期数据。
|
|
@@ -10,7 +10,7 @@ description: 热点题材分析:评估板块强度、扩散度、个股关联
|
|
|
10
10
|
先运行:
|
|
11
11
|
|
|
12
12
|
```bash
|
|
13
|
-
python3
|
|
13
|
+
python3 tools/gather.py fundamental <symbol>
|
|
14
14
|
```
|
|
15
15
|
|
|
16
16
|
gather 工具返回:
|
|
@@ -21,7 +21,8 @@ gather 工具返回:
|
|
|
21
21
|
- `news` — 近期新闻(题材催化来源)
|
|
22
22
|
- `stock_info` — 公司基本信息(行业、业务)
|
|
23
23
|
- `sector_rankings` — 板块排名(核心数据源);`get_sector_rankings` 传 `board_type=concept` 时为概念板块排行,热点题材以概念口径为主
|
|
24
|
-
|
|
24
|
+
|
|
25
|
+
人气热搜榜不在 gather 返回中,需要时单独调用 `get_hot_stocks`(东方财富人气榜)辅助判断题材热度。
|
|
25
26
|
|
|
26
27
|
评估扩散度前,必须获取板块成分股及其当日表现;只有板块排名时,仅可判断当日相对强弱,不判断扩散度或持续性。
|
|
27
28
|
|
|
@@ -77,6 +77,7 @@ python3 scripts/gather.py <symbol>
|
|
|
77
77
|
- 信号持久化在本地 JSONL(`$STOCK_SIGNAL_STORE` 或 `~/.stock-analysis/signals.jsonl`);是否记录由宿主 Agent 决定,不阻塞报告输出。
|
|
78
78
|
|
|
79
79
|
## 注意事项
|
|
80
|
+
- `get_kline` 的 A 股股票/ETF 数据为前复权,每条记录 `adjusted="qfq"`;显式指数 `sh000xxx` / `sz399xxx` 为原始点位,`adjusted="none"`。复权数据源全部失败时说明数据缺失,不用未复权价格补算指标或信号。
|
|
80
81
|
- 始终提供风险提示
|
|
81
82
|
- 不做绝对化的涨跌预测
|
|
82
83
|
- 建议用户结合自身风险偏好做决策
|
|
@@ -84,3 +85,24 @@ python3 scripts/gather.py <symbol>
|
|
|
84
85
|
- 如果风险筛查返回 veto_buy=true,必须醒目标注并建议谨慎
|
|
85
86
|
|
|
86
87
|
完成标准:每个买卖建议都对应可观察的触发条件和失效条件,且所有缺失数据及其影响已说明。
|
|
88
|
+
|
|
89
|
+
## 低频价投数据
|
|
90
|
+
|
|
91
|
+
按用户问题选择数据,完整说明口径、采样覆盖和缺失项:
|
|
92
|
+
|
|
93
|
+
- 判断估值贵贱:`get_valuation_history(symbol, years=5)` 的 PE-TTM/PB 历史正值分位与 Band;亏损 PE 不计算分位,实际采样不足五年必须说明。
|
|
94
|
+
- 读多年财报:`get_financials(symbol, periods=10, annual=true)`;A 股按年报筛选,港股按源实际可得年度数返回。财报期不等于公告日,年报历史不能用于假定当时已知信息的回测。
|
|
95
|
+
- 财报季排期:`get_earnings_calendar(report_date="YYYY-MM-DD", symbol=...)`,区分最新预约日期、实际披露日期和已公告业绩预告,不把预告当业绩实绩。
|
|
96
|
+
- 股东变化:`get_shareholder_structure`。A 股北向值是财报十大流通股东中的 HKSCC 名义持股,缺席不等于零,不能当成日度北向买卖;港股南向值按港交所披露日期使用。
|
|
97
|
+
- 大盘估值:`get_index_valuation(symbol="000300", years=5)`;中证近期 PE1 不冒充 PE-TTM、PB 或多年分位。
|
|
98
|
+
- ETF:`get_etf_details(symbol="510300", benchmark="sh000300")`。折溢价须看净值/行情日期;披露持仓不是完整实时申赎篮子,指数成分与基金持仓分别呈现。跟踪误差必须给出用户认可的基准。
|
|
99
|
+
- 股息:`get_dividends` 区分历史、未来已公布除息日历和 A 股报告期排行;预案不计入已实现 TTM 股息。名义每股现金未重算送转股口径,遇送转股时不得据此精确比较持有收益。
|
|
100
|
+
- 两融:`get_margin_trading(include_ratio=true)` 的 `margin_buy_ratio_pct` 只使用同日成交额;null 表示不可计算。
|
|
101
|
+
|
|
102
|
+
慢变数据存于 `~/.stock-analysis/cache`:财报、基本信息及新历史数据按天,板块映射按周;行情仍实时查询。输出中的报告期/数据日期决定能否用于判断,缓存命中不代表数据已更新。
|
|
103
|
+
|
|
104
|
+
### 补充数据覆盖
|
|
105
|
+
|
|
106
|
+
get_shareholder_structure 的 northbound 优先使用沪深官方季度总量;northbound_nominee 只是十大股东推断,不能混同。get_etf_details 的 basket 是完整已发布 PCF,对价数量/现金替代规则不是基金实际持仓或NAV权重。HK 股息排行使用 get_dividends(mode=ranking, market=HK),年度口径不能称 TTM。
|
|
107
|
+
|
|
108
|
+
实际披露股票持仓可用 get_etf_details(include_full_holdings=true) 获取半年度/年度表;按 as_of 解释,数量为股、市值为人民币元。默认不取大量明细;不是实时全资产组合,不与 PCF 对价数量混同。
|
|
@@ -21,7 +21,7 @@ description: 全市场股票筛选:按市场、估值、成长、趋势或自
|
|
|
21
21
|
运行数据采集脚本进行 L1 量化筛选:
|
|
22
22
|
|
|
23
23
|
```bash
|
|
24
|
-
python3
|
|
24
|
+
python3 tools/screener.py screen --market A --top 20
|
|
25
25
|
```
|
|
26
26
|
|
|
27
27
|
可选参数:`--market`(A/HK/US)、`--top`(返回数量)、`--config`(自定义 YAML 配置路径)、`--l2`(L2 量化增强开关,默认关闭)。
|
|
@@ -73,3 +73,21 @@ python3 scripts/gather.py --market A --top 20
|
|
|
73
73
|
- **成长型**:中等PE + 高营收增长 + 高换手率
|
|
74
74
|
- **趋势型**:放量突破 + 均线多头 + 高量比
|
|
75
75
|
- **低估反转**:超跌 + 低PB + 资金净流入
|
|
76
|
+
|
|
77
|
+
## 股息因子(A股,可选)
|
|
78
|
+
|
|
79
|
+
配置 `filters.dividend_yield_min` / `dividend_yield_max` 或 `sort_by: dividend_score` / `dividend_yield` 时才拉取股息数据。`dividend_report_date` 可指定报告期,默认上一年年末。这里使用已实施方案的**报告期股息率**(百分数),不是滚动十二个月股息率;缺失为未知,使用股息阈值时排除。启用后 value 分项加入股息横截面评分,未启用时不增加股息请求。
|
|
80
|
+
|
|
81
|
+
```yaml
|
|
82
|
+
filters:
|
|
83
|
+
dividend_yield_min: 3
|
|
84
|
+
sort_by: dividend_score
|
|
85
|
+
sort_order: desc
|
|
86
|
+
dividend_report_date: "2025-12-31"
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
筛选结果仍需用 `get_dividends(mode="history", symbol=...)` 核查已实施现金分红、连续支付年数与除息时间,不能把高股息直接解释为低风险。
|
|
90
|
+
|
|
91
|
+
### 补充数据覆盖
|
|
92
|
+
|
|
93
|
+
股息筛选支持 A/HK:A 股为报告期已实施方案股息率,HK 为 HKEX/LSEG 年度股息率。两者都不是当前价 TTM;使用结果的 yield_basis 和 report_date,缺失不当零。
|
|
@@ -39,6 +39,11 @@ exit:
|
|
|
39
39
|
stop_loss: -0.05 # 止损比例
|
|
40
40
|
take_profit: 0.15 # 止盈比例
|
|
41
41
|
|
|
42
|
+
simulation:
|
|
43
|
+
slippage: 0.001 # 滑点(买卖双边),默认 0.001
|
|
44
|
+
commission: 0.00025 # 佣金(买卖双边,券商自定;A股常见万2.5),默认 0.0015
|
|
45
|
+
stamp_tax: 0.0005 # 印花税(仅卖出收;A股 0.05%,其他市场按当下实际费率,无则省略),默认 0
|
|
46
|
+
|
|
42
47
|
position:
|
|
43
48
|
size: 1.0 # 仓位比例
|
|
44
49
|
max_positions: 1 # 最大持仓数
|
|
@@ -50,17 +55,18 @@ position:
|
|
|
50
55
|
|
|
51
56
|
### 第二步:运行回测
|
|
52
57
|
|
|
58
|
+
A 股股票/ETF 回测统一使用前复权 K 线(每条记录 `adjusted="qfq"`),显式指数使用原始点位(`adjusted="none"`)。复权源不可用时停止本次回测并说明缺失,不混用未复权历史价格。
|
|
59
|
+
|
|
53
60
|
运行回测脚本:
|
|
54
61
|
|
|
55
62
|
```bash
|
|
56
|
-
python3
|
|
63
|
+
python3 tools/backtest.py run <path.yaml> <symbol> --start <date> --end <date>
|
|
57
64
|
```
|
|
58
65
|
|
|
59
66
|
参数说明:
|
|
60
|
-
-
|
|
61
|
-
- `--symbol`:股票代码
|
|
67
|
+
- 前两个为位置参数,依次为:策略 YAML 文件路径、股票代码
|
|
62
68
|
- `--start` / `--end`:回测时间范围(可选,默认近一年)
|
|
63
|
-
- 初始资金默认 100
|
|
69
|
+
- 初始资金默认 100 万,可用 `--capital` 调整
|
|
64
70
|
|
|
65
71
|
### 第三步:分析结果
|
|
66
72
|
|
|
@@ -69,7 +75,7 @@ python3 scripts/gather.py --strategy <path.yaml> --symbol <symbol> --start <date
|
|
|
69
75
|
- 从 `metrics` 和 `trades` 计算期望值并与盈亏比一起报告。
|
|
70
76
|
- 报告最大回撤、连续亏损、交易次数和平均持有期;结果未携带初始风险时,将 1R 分布标为不可计算。
|
|
71
77
|
- 使用用户指定的互斥日期区间分别运行样本内和样本外回测。
|
|
72
|
-
-
|
|
78
|
+
- 成本假设引用结果中的 `costs` 字段(实际生效的佣金/滑点/印花税费率与实付费用合计),未模拟的费用与成交约束列入限制。
|
|
73
79
|
|
|
74
80
|
未模拟的结算、涨跌停、复权或特定市场费用列入限制,结论限定为该模拟条件下的历史表现。
|
|
75
81
|
|
|
@@ -42,6 +42,11 @@ exit:
|
|
|
42
42
|
stop_loss: "{stop_loss}"
|
|
43
43
|
take_profit: "{take_profit}"
|
|
44
44
|
|
|
45
|
+
simulation:
|
|
46
|
+
slippage: 0.001 # 滑点(买卖双边)
|
|
47
|
+
commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
|
|
48
|
+
stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
|
|
49
|
+
|
|
45
50
|
position:
|
|
46
51
|
size: 0.6
|
|
47
52
|
max_positions: 1
|
|
@@ -36,6 +36,11 @@ exit:
|
|
|
36
36
|
stop_loss: "{stop_loss}"
|
|
37
37
|
take_profit: "{take_profit}"
|
|
38
38
|
|
|
39
|
+
simulation:
|
|
40
|
+
slippage: 0.001 # 滑点(买卖双边)
|
|
41
|
+
commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
|
|
42
|
+
stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
|
|
43
|
+
|
|
39
44
|
position:
|
|
40
45
|
size: 0.8
|
|
41
46
|
max_positions: 1
|
|
@@ -9,11 +9,13 @@ parameters:
|
|
|
9
9
|
entry:
|
|
10
10
|
conditions:
|
|
11
11
|
- indicator: "ma_diff"
|
|
12
|
-
|
|
12
|
+
fast_period: 5
|
|
13
|
+
slow_period: 10
|
|
13
14
|
operator: ">"
|
|
14
15
|
value: 0
|
|
15
16
|
- indicator: "ma_diff"
|
|
16
|
-
|
|
17
|
+
fast_period: 10
|
|
18
|
+
slow_period: 20
|
|
17
19
|
operator: ">"
|
|
18
20
|
value: 0
|
|
19
21
|
- indicator: "macd_dif"
|
|
@@ -27,7 +29,8 @@ entry:
|
|
|
27
29
|
exit:
|
|
28
30
|
conditions:
|
|
29
31
|
- indicator: "ma_diff"
|
|
30
|
-
|
|
32
|
+
fast_period: 5
|
|
33
|
+
slow_period: 10
|
|
31
34
|
operator: "cross_below"
|
|
32
35
|
value: 0
|
|
33
36
|
- indicator: "macd_dif"
|
|
@@ -37,6 +40,11 @@ exit:
|
|
|
37
40
|
stop_loss: "{stop_loss}"
|
|
38
41
|
take_profit: "{take_profit}"
|
|
39
42
|
|
|
43
|
+
simulation:
|
|
44
|
+
slippage: 0.001 # 滑点(买卖双边)
|
|
45
|
+
commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
|
|
46
|
+
stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
|
|
47
|
+
|
|
40
48
|
position:
|
|
41
49
|
size: 1.0
|
|
42
50
|
max_positions: 1
|
|
@@ -18,7 +18,8 @@ entry:
|
|
|
18
18
|
operator: ">"
|
|
19
19
|
value: "{volume_threshold}"
|
|
20
20
|
- indicator: "ma_diff"
|
|
21
|
-
|
|
21
|
+
fast_period: 5
|
|
22
|
+
slow_period: 10
|
|
22
23
|
operator: ">"
|
|
23
24
|
value: 0
|
|
24
25
|
logic: "all"
|
|
@@ -37,8 +38,9 @@ exit:
|
|
|
37
38
|
take_profit: "{take_profit}"
|
|
38
39
|
|
|
39
40
|
simulation:
|
|
40
|
-
slippage: 0.002
|
|
41
|
+
slippage: 0.002 # 打板策略用更保守的费率:滑点0.2%、佣金万15(其余示例为 0.001/万2.5)
|
|
41
42
|
commission: 0.0015
|
|
43
|
+
stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
|
|
42
44
|
|
|
43
45
|
position:
|
|
44
46
|
size: 0.5
|
|
@@ -38,6 +38,11 @@ exit:
|
|
|
38
38
|
stop_loss: "{stop_loss}"
|
|
39
39
|
take_profit: "{take_profit}"
|
|
40
40
|
|
|
41
|
+
simulation:
|
|
42
|
+
slippage: 0.001 # 滑点(买卖双边)
|
|
43
|
+
commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
|
|
44
|
+
stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
|
|
45
|
+
|
|
41
46
|
position:
|
|
42
47
|
size: 0.5
|
|
43
48
|
max_positions: 1
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
name: "MA Golden Cross"
|
|
2
2
|
version: "1.0"
|
|
3
|
-
description: "均线金叉策略 — MA5上穿MA20时买入,MA5下穿MA20时卖出。使用 ma_diff
|
|
3
|
+
description: "均线金叉策略 — MA5上穿MA20时买入,MA5下穿MA20时卖出。使用 ma_diff 指标(fast_period/slow_period 显式指定快慢均线)检测交叉"
|
|
4
4
|
|
|
5
5
|
parameters:
|
|
6
6
|
fast_period: 5
|
|
@@ -11,7 +11,8 @@ parameters:
|
|
|
11
11
|
entry:
|
|
12
12
|
conditions:
|
|
13
13
|
- indicator: "ma_diff"
|
|
14
|
-
|
|
14
|
+
fast_period: "{fast_period}"
|
|
15
|
+
slow_period: "{slow_period}"
|
|
15
16
|
operator: "cross_above"
|
|
16
17
|
value: 0
|
|
17
18
|
- indicator: "volume_ratio"
|
|
@@ -22,13 +23,19 @@ entry:
|
|
|
22
23
|
exit:
|
|
23
24
|
conditions:
|
|
24
25
|
- indicator: "ma_diff"
|
|
25
|
-
|
|
26
|
+
fast_period: "{fast_period}"
|
|
27
|
+
slow_period: "{slow_period}"
|
|
26
28
|
operator: "cross_below"
|
|
27
29
|
value: 0
|
|
28
30
|
logic: "any"
|
|
29
31
|
stop_loss: "{stop_loss}"
|
|
30
32
|
take_profit: "{take_profit}"
|
|
31
33
|
|
|
34
|
+
simulation:
|
|
35
|
+
slippage: 0.001 # 滑点(买卖双边)
|
|
36
|
+
commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
|
|
37
|
+
stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
|
|
38
|
+
|
|
32
39
|
position:
|
|
33
40
|
size: 1.0
|
|
34
41
|
max_positions: 1
|
|
@@ -30,6 +30,11 @@ exit:
|
|
|
30
30
|
stop_loss: "{stop_loss}"
|
|
31
31
|
take_profit: "{take_profit}"
|
|
32
32
|
|
|
33
|
+
simulation:
|
|
34
|
+
slippage: 0.001 # 滑点(买卖双边)
|
|
35
|
+
commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
|
|
36
|
+
stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
|
|
37
|
+
|
|
33
38
|
position:
|
|
34
39
|
size: 1.0
|
|
35
40
|
max_positions: 1
|
|
@@ -9,7 +9,8 @@ parameters:
|
|
|
9
9
|
entry:
|
|
10
10
|
conditions:
|
|
11
11
|
- indicator: "ma_diff"
|
|
12
|
-
|
|
12
|
+
fast_period: 10
|
|
13
|
+
slow_period: 20
|
|
13
14
|
operator: ">"
|
|
14
15
|
value: 0
|
|
15
16
|
- indicator: "bollinger_position"
|
|
@@ -40,6 +41,11 @@ exit:
|
|
|
40
41
|
stop_loss: "{stop_loss}"
|
|
41
42
|
take_profit: "{take_profit}"
|
|
42
43
|
|
|
44
|
+
simulation:
|
|
45
|
+
slippage: 0.001 # 滑点(买卖双边)
|
|
46
|
+
commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
|
|
47
|
+
stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
|
|
48
|
+
|
|
43
49
|
position:
|
|
44
50
|
size: 1.0
|
|
45
51
|
max_positions: 1
|
|
@@ -26,7 +26,8 @@ entry:
|
|
|
26
26
|
exit:
|
|
27
27
|
conditions:
|
|
28
28
|
- indicator: "ma_diff"
|
|
29
|
-
|
|
29
|
+
fast_period: 5
|
|
30
|
+
slow_period: 10
|
|
30
31
|
operator: "cross_below"
|
|
31
32
|
value: 0
|
|
32
33
|
- indicator: "rsi"
|
|
@@ -37,6 +38,11 @@ exit:
|
|
|
37
38
|
stop_loss: "{stop_loss}"
|
|
38
39
|
take_profit: "{take_profit}"
|
|
39
40
|
|
|
41
|
+
simulation:
|
|
42
|
+
slippage: 0.001 # 滑点(买卖双边)
|
|
43
|
+
commission: 0.00025 # 佣金(买卖双边,A股常见万2.5)
|
|
44
|
+
stamp_tax: 0.0005 # 印花税(A股卖出单边;其他市场按当下实际费率,无则删除本行)
|
|
45
|
+
|
|
40
46
|
position:
|
|
41
47
|
size: 0.8
|
|
42
48
|
max_positions: 1
|
package/tools/_cache.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
"""TTL cache for slow public datasets; live quotes and errors are never stored."""
|
|
2
|
+
|
|
3
|
+
import contextlib
|
|
4
|
+
import hashlib
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import tempfile
|
|
8
|
+
import time
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
CACHE_DIR = Path.home() / ".stock-analysis" / "cache"
|
|
12
|
+
DAY = 86400
|
|
13
|
+
WEEK = 7 * DAY
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _namespace_prefix(namespace):
|
|
17
|
+
return hashlib.sha256(namespace.encode()).hexdigest()[:12]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _read(path, ttl):
|
|
21
|
+
try:
|
|
22
|
+
entry = json.loads(path.read_text(encoding="utf-8"))
|
|
23
|
+
if 0 <= time.time() - entry["fetched_at"] < ttl:
|
|
24
|
+
return entry
|
|
25
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
26
|
+
pass
|
|
27
|
+
return None
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def cached_values(namespace, ttl):
|
|
31
|
+
for path in CACHE_DIR.glob(f"{_namespace_prefix(namespace)}-*.json"):
|
|
32
|
+
entry = _read(path, ttl)
|
|
33
|
+
if entry and str(entry.get("key", "")).startswith(namespace + ":"):
|
|
34
|
+
yield entry.get("data")
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def cached(key: str, ttl: int, fetch):
|
|
38
|
+
path = CACHE_DIR / f"{_namespace_prefix(key.partition(':')[0])}-{hashlib.sha256(key.encode()).hexdigest()}.json"
|
|
39
|
+
entry = _read(path, ttl)
|
|
40
|
+
if entry and "data" in entry:
|
|
41
|
+
return entry["data"]
|
|
42
|
+
result = fetch()
|
|
43
|
+
rows = result if isinstance(result, list) else [result]
|
|
44
|
+
if not result or any(isinstance(row, dict) and (row.get("error") or row.get("warnings")) for row in rows):
|
|
45
|
+
return result
|
|
46
|
+
tmp = None
|
|
47
|
+
try:
|
|
48
|
+
CACHE_DIR.mkdir(parents=True, exist_ok=True)
|
|
49
|
+
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", dir=CACHE_DIR, delete=False) as stream:
|
|
50
|
+
tmp = stream.name
|
|
51
|
+
json.dump(
|
|
52
|
+
{"key": key, "fetched_at": time.time(), "data": result}, stream, ensure_ascii=False, allow_nan=False
|
|
53
|
+
)
|
|
54
|
+
os.replace(tmp, path)
|
|
55
|
+
except (OSError, ValueError, TypeError):
|
|
56
|
+
pass
|
|
57
|
+
finally:
|
|
58
|
+
if tmp:
|
|
59
|
+
with contextlib.suppress(OSError):
|
|
60
|
+
Path(tmp).unlink(missing_ok=True)
|
|
61
|
+
return result
|
package/tools/_subproc.py
CHANGED
|
@@ -6,8 +6,12 @@ so this resolves both when a tool runs as a script (sys.path[0] = tools/) and wh
|
|
|
6
6
|
pytest imports it as tools.*.
|
|
7
7
|
"""
|
|
8
8
|
|
|
9
|
+
import contextlib
|
|
9
10
|
import json
|
|
11
|
+
import math
|
|
10
12
|
import os
|
|
13
|
+
import re
|
|
14
|
+
import socket
|
|
11
15
|
import subprocess
|
|
12
16
|
import sys
|
|
13
17
|
|
|
@@ -44,3 +48,48 @@ def run_tool(script: str, args: list, timeout: int = 30, parse_json: bool = True
|
|
|
44
48
|
except Exception:
|
|
45
49
|
pass
|
|
46
50
|
return None
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def utf8_stdio() -> None:
|
|
54
|
+
"""Force UTF-8 stdio. Windows defaults stdio to a legacy code page (cp1252)
|
|
55
|
+
that cannot encode the Chinese text these tools emit — call at CLI entry."""
|
|
56
|
+
for s in (sys.stdout, sys.stderr):
|
|
57
|
+
if hasattr(s, "reconfigure"):
|
|
58
|
+
s.reconfigure(encoding="utf-8")
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
@contextlib.contextmanager
|
|
62
|
+
def socket_timeout(seconds: float):
|
|
63
|
+
"""Bound every blocking socket op for the wrapped chain's duration: akshare/efinance
|
|
64
|
+
leave requests timeout-less, so on a blackholed network a leg hangs until the kernel
|
|
65
|
+
TCP timeout (~2min) and the chain would overrun the caller's subprocess budget before
|
|
66
|
+
ever reaching the plain-HTTPS legs. try/finally always restores the previous default
|
|
67
|
+
(no global-state leak); explicit per-request timeouts (tencent/sina legs) still win."""
|
|
68
|
+
old_timeout = socket.getdefaulttimeout()
|
|
69
|
+
socket.setdefaulttimeout(seconds)
|
|
70
|
+
try:
|
|
71
|
+
yield
|
|
72
|
+
finally:
|
|
73
|
+
socket.setdefaulttimeout(old_timeout)
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
_SECRET_PARAM_RE = re.compile(r"(?i)((?:api[_-]?key|token|secret|access[_-]?token)=)[^&\s]+")
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def scrub_secrets(msg: str) -> str:
|
|
80
|
+
"""Error text may embed request URLs (requests connection errors) — never leak keys
|
|
81
|
+
into stdout JSON."""
|
|
82
|
+
return _SECRET_PARAM_RE.sub(r"\1***", msg)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def json_safe(obj):
|
|
86
|
+
"""Replace non-finite floats (inf/-inf/nan, e.g. an all-flat P&L profit_loss_ratio)
|
|
87
|
+
with None so json.dumps never emits the non-standard Infinity/NaN tokens that
|
|
88
|
+
break strict JSON.parse hosts."""
|
|
89
|
+
if isinstance(obj, float):
|
|
90
|
+
return obj if math.isfinite(obj) else None
|
|
91
|
+
if isinstance(obj, dict):
|
|
92
|
+
return {k: json_safe(v) for k, v in obj.items()}
|
|
93
|
+
if isinstance(obj, list):
|
|
94
|
+
return [json_safe(v) for v in obj]
|
|
95
|
+
return obj
|
package/tools/alert_rules.py
CHANGED
|
@@ -7,11 +7,13 @@ Does NOT store history, does NOT push, does NOT schedule. Host agent decides whe
|
|
|
7
7
|
import argparse
|
|
8
8
|
import json
|
|
9
9
|
import sys
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
10
11
|
from datetime import datetime, timezone
|
|
11
12
|
from pathlib import Path
|
|
12
13
|
|
|
13
14
|
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
14
15
|
from _subproc import run_tool as _run_json # noqa: E402
|
|
16
|
+
from _subproc import utf8_stdio
|
|
15
17
|
from stock_data import detect_market # noqa: E402
|
|
16
18
|
|
|
17
19
|
RULE_TYPES = {
|
|
@@ -127,10 +129,22 @@ def check_rules(symbol: str, rules: list[dict]) -> dict:
|
|
|
127
129
|
needs_anom = any(r.get("type") == "anomaly" for r in rules)
|
|
128
130
|
needs_risk = any(r.get("type") in ("risk_veto", "risk_level_at_least") for r in rules)
|
|
129
131
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
132
|
+
# the fetches are independent subprocesses — fan out concurrently (same
|
|
133
|
+
# ThreadPoolExecutor pattern as gather._run_all), then read back in fixed order
|
|
134
|
+
jobs = {"quote": ("stock_data.py", ["quote", symbol])}
|
|
135
|
+
if needs_tech:
|
|
136
|
+
jobs["tech"] = ("technical.py", ["analyze", symbol, "--period", "daily", "--count", "60"])
|
|
137
|
+
if needs_anom:
|
|
138
|
+
jobs["anom"] = ("anomaly_detect.py", ["detect", symbol])
|
|
139
|
+
if needs_risk:
|
|
140
|
+
jobs["risk"] = ("risk_screening.py", ["screen", symbol])
|
|
141
|
+
with ThreadPoolExecutor(max_workers=len(jobs)) as pool:
|
|
142
|
+
futures = {key: pool.submit(_run_json, script, args) for key, (script, args) in jobs.items()}
|
|
143
|
+
fetched = {key: future.result() for key, future in futures.items()}
|
|
144
|
+
quote = fetched["quote"] or {}
|
|
145
|
+
tech = fetched.get("tech")
|
|
146
|
+
anom = fetched.get("anom")
|
|
147
|
+
risk = fetched.get("risk")
|
|
134
148
|
|
|
135
149
|
warnings = []
|
|
136
150
|
if not quote or quote.get("price") is None:
|
|
@@ -203,9 +217,5 @@ def main():
|
|
|
203
217
|
|
|
204
218
|
|
|
205
219
|
if __name__ == "__main__":
|
|
206
|
-
|
|
207
|
-
# Chinese text these tools emit — force UTF-8 so stdout never crashes there.
|
|
208
|
-
for _s in (sys.stdout, sys.stderr):
|
|
209
|
-
if hasattr(_s, "reconfigure"):
|
|
210
|
-
_s.reconfigure(encoding="utf-8")
|
|
220
|
+
utf8_stdio()
|
|
211
221
|
main()
|