stock-analysis-plugin 0.2.7 → 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 +20 -9
- package/package.json +1 -1
- package/pi/index.ts +51 -2
- 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/strategy-backtest/SKILL.md +10 -0
- package/tools/backtest.py +70 -5
- package/tools/capabilities.py +4 -0
- package/tools/cli_budgets.json +2 -1
- package/tools/technical.py +186 -0
- package/tools/trend_strategy.py +365 -0
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ A 股 / 港股 / 美股 / 日股 / 韩股 / 台股综合分析、多因子选股
|
|
|
32
32
|
|
|
33
33
|
## 功能概览
|
|
34
34
|
|
|
35
|
-
- **
|
|
35
|
+
- **68 个工具** — 行情数据、技术分析、K 线形态、资金流向、估值历史、财报日历、股东/ETF/股息、新闻舆情、风险筛查、市场状态等
|
|
36
36
|
- **20 个 Skills** — 综合分析、全市场选股、策略回测 + 17 个策略方法论(缠论、波浪、龙头、情绪周期等)
|
|
37
37
|
- **策略回测引擎** — YAML DSL 定义策略,参数化条件组合,自动诊断,按需进行有限轮参数优化
|
|
38
38
|
- **多数据源 Failover** — 11 个数据源自动容灾切换(akshare / tushare / efinance / 腾讯行情 / 新浪行情 / pytdx / baostock / yfinance / finnhub / longbridge / alphavantage),A 股链路带粘性优选(最近成功的数据源下次优先尝试)
|
|
@@ -70,7 +70,7 @@ npm install @weaxs/stock-analysis-plugin
|
|
|
70
70
|
|
|
71
71
|
Pi 启动后自动加载,输入 `/skills` 确认。详见 [Pi Agent 接入指南](docs/pi-integration.md)([English](docs/pi-integration.en.md))。
|
|
72
72
|
|
|
73
|
-
新版 Pi(已核验 1.2.0)提供原生 `tool_search` 时,插件自动启用按需工具发现,
|
|
73
|
+
新版 Pi(已核验 1.2.0)提供原生 `tool_search` 时,插件自动启用按需工具发现,68 项能力保留注册,仅命中工具加载完整定义。缺少原生发现接口的旧版 Pi 或 SDK 宿主保持全量暴露。检索使用英文关键词或工具名,例如 `get_quote`、`get_financials`。
|
|
74
74
|
|
|
75
75
|
### Hermes Agent Plugin
|
|
76
76
|
|
|
@@ -95,7 +95,7 @@ register(ctx)
|
|
|
95
95
|
openclaw plugins install clawhub:@weaxs/openclaw-stock-analysis
|
|
96
96
|
```
|
|
97
97
|
|
|
98
|
-
OpenClaw Gateway 启动后自动加载并注册
|
|
98
|
+
OpenClaw Gateway 启动后自动加载并注册 68 个 tool。安装时 postinstall 会自动建 `.venv` 并装好 Python 依赖(前提:本机有 `python3 >= 3.10`)。
|
|
99
99
|
|
|
100
100
|
详见 [OpenClaw 接入指南](docs/openclaw-integration.md),或 plugin 自身说明 [`openclaw/README.md`](openclaw/README.md)。
|
|
101
101
|
|
|
@@ -106,7 +106,7 @@ dsh plugin --profile <你的profile> add @weaxs/dsh-stock-analysis
|
|
|
106
106
|
dsh --profile <你的profile>
|
|
107
107
|
```
|
|
108
108
|
|
|
109
|
-
作为 dsh bundle 安装:`dsh plugin add` 会把 `cordis.patch.yml` 叠加进 profile 组合,注册
|
|
109
|
+
作为 dsh bundle 安装:`dsh plugin add` 会把 `cordis.patch.yml` 叠加进 profile 组合,注册 68 个 tool + 20 个 skill。postinstall 自动建 `.venv`(pnpm 需在 profile 的 `pnpm-workspace.yaml` 里给本包配 `allowBuilds`,否则回退系统 `python3`)。
|
|
110
110
|
|
|
111
111
|
新版 dsh 的原生函数调用模式默认通过 `stock_tool_search` 按 Agent 搜索、加载所需工具,支持中文关键词或工具名;旧接口、搜索入口不可用时保留全量暴露。可设置 `toolDiscovery: false` 关闭,配置与 PTC 模式边界见下方接入文档。
|
|
112
112
|
|
|
@@ -274,13 +274,22 @@ Agent 会自动调用行情 → 技术面 → 基本面 → 资金面 → 消息
|
|
|
274
274
|
|
|
275
275
|
| 工具 | 说明 |
|
|
276
276
|
|------|------|
|
|
277
|
-
| `
|
|
277
|
+
| `analyze_trend_strategy` | 月度右侧趋势策略:单市场股票池筛选、真实旧仓保持/退出与逆波动新仓预算;直接传股票代码、自动取行情,无持仓存储,仍为not_validated |
|
|
278
|
+
| `get_technical_analysis` | 全面技术指标分析(MA/MACD/RSI/BOLL/KDJ;附实验性 trend_horizons 多期限月度趋势及独立趋势温度 trend_temperature;多周期共振时 resonance.direction ∈ aligned_bullish/aligned_bearish/divergent) |
|
|
278
279
|
| `analyze_pattern` | K 线形态识别 |
|
|
279
280
|
| `calculate_ma` | 多周期均线计算 |
|
|
280
281
|
| `get_volume_analysis` | 量价分析 |
|
|
281
282
|
| `evaluate_signal` | 历史信号胜率回测 |
|
|
282
283
|
| `detect_anomaly` | 当日技术、量价与资金异动扫描 |
|
|
283
284
|
|
|
285
|
+
`trend_temperature` 是独立趋势温度指标:`(EMA20-EMA60)/ATR14`,ATR 使用包含跳空的真实波幅简单均值。附分数、EMA差方向 `direction`、七档研究标签、前一期信息、数据日期和价格口径;`validation_status=not_validated`,真实股票试验未支持默认温度交易映射。方向按零轴计算,“平”标签不代表零方向;默认需 60 根预热,零 ATR 或坏行情返回不可用。±0.5/±1.5/±3 的分档尚未校准,不是趋势动物公式、肥尾指标、上涨概率或自动买卖信号,也不修改原综合评分。无需个人持仓存储;[公式、边界及回测说明](skills/bull-trend/references/trend-temperature.md)。
|
|
286
|
+
|
|
287
|
+
月度右侧趋势策略,通过 `analyze_trend_strategy(symbols, ...)` 调用:月初200日线上行入场、真实旧仓优先、63日波动预算;[输入格式与完整规则](skills/bull-trend/references/monthly-trend-strategy.md)。扩展及历史样本尚未通过完整效果门槛;直接提供股票代码即可自动取日K,输出信号与预算计划;实际成交/股数和共享资金回测另行核实,不自动保存持仓或下单。
|
|
288
|
+
|
|
289
|
+
趋势研究另返回 `trend_horizons`(daily、建议count=360):21/63/252根日K过去对数收益,在月初首根有效日K收盘观察并保持;显示期限组成、方向及观察日期,不强凑七档。与回测 `monthly_momentum` 共用计算,仍为 `not_validated`;[方法、预热与验证局限](skills/bull-trend/references/trend-horizons.md)。
|
|
290
|
+
|
|
291
|
+
市场只约束新开仓的三期限实验可运行 [market_trend.py](skills/bull-trend/scripts/market_trend.py),输入带预热的个股/同市场宽基daily OHLCV JSON,复用同一Python核心。月度入场、次日开盘、已有持仓按个股趋势退出;不会自动保存持仓或下单。[使用与当前验证边界](skills/bull-trend/references/trend-horizons.md#市场环境入场实验)。
|
|
292
|
+
|
|
284
293
|
### 筛选与回测
|
|
285
294
|
|
|
286
295
|
| 工具 | 说明 |
|
|
@@ -434,6 +443,8 @@ position:
|
|
|
434
443
|
| `volume_ratio` | 量比 | 是(默认 5) |
|
|
435
444
|
| `price_change` | 涨跌幅(%) | 否 |
|
|
436
445
|
| `bollinger_position` | 布林带位置(0=下轨, 1=上轨) | 是(默认 20) |
|
|
446
|
+
| `trend_score` | 独立实验趋势强度,默认 (EMA20−EMA60)/ATR14;fast_period/slow_period 控制 EMA | period 为 ATR 根数(默认 14) |
|
|
447
|
+
| `monthly_momentum` | 月初首根有效日K收盘观察过去 period 根对数收益,保持到下一观察;零成交量不计根数 | 是(默认63,要求正整数) |
|
|
437
448
|
| `close` / `volume` | 收盘价 / 成交量 | 否 |
|
|
438
449
|
|
|
439
450
|
### 可用运算符
|
|
@@ -552,20 +563,20 @@ GitHub Actions 的 `e2e-host` 使用 Pi、Hermes、OpenClaw、dsh 的真实运
|
|
|
552
563
|
```
|
|
553
564
|
stock-analysis/
|
|
554
565
|
├── pi/ # Pi Agent Extension
|
|
555
|
-
│ └── index.ts # 注册
|
|
566
|
+
│ └── index.ts # 注册 68 个工具 + 20 个 skill
|
|
556
567
|
├── hermes/ # Hermes Agent Plugin
|
|
557
568
|
│ ├── plugin.yaml # 插件清单
|
|
558
569
|
│ ├── __init__.py # register(ctx) 入口
|
|
559
570
|
│ ├── schemas.py # 工具 JSON Schema 定义
|
|
560
|
-
│ └── tools.py #
|
|
571
|
+
│ └── tools.py # 68 个 handler → subprocess 调 CLI
|
|
561
572
|
├── openclaw/ # OpenClaw Plugin
|
|
562
573
|
│ ├── openclaw.plugin.json # manifest(contracts.tools)
|
|
563
574
|
│ ├── package.json # 含 openclaw 块(pluginApi/SDK 版本)
|
|
564
|
-
│ └── index.ts # definePluginEntry + registerTool ×
|
|
575
|
+
│ └── index.ts # definePluginEntry + registerTool ×68
|
|
565
576
|
├── dsh/ # DeepSeek Harness (dsh) Plugin
|
|
566
577
|
│ ├── cordis.patch.yml # bundle patch(insert 插件入口)
|
|
567
578
|
│ ├── package.json # 含 dsh.bundle 块(bundle manifest)
|
|
568
|
-
│ └── index.ts # cordis apply(ctx) + defineTool ×
|
|
579
|
+
│ └── index.ts # cordis apply(ctx) + defineTool ×68
|
|
569
580
|
│
|
|
570
581
|
├── tools/ # 共享 Python CLI 工具
|
|
571
582
|
│ ├── stock_data.py # 行情 / 资金流 / 新闻 / 财务 / 短线情绪
|
package/package.json
CHANGED
package/pi/index.ts
CHANGED
|
@@ -1186,7 +1186,7 @@ export default (pi: ExtensionAPI) => {
|
|
|
1186
1186
|
registerTool({
|
|
1187
1187
|
name: "get_technical_analysis",
|
|
1188
1188
|
description:
|
|
1189
|
-
"获取股票技术面分析(MA/MACD/RSI/BOLL/KDJ/成交量等指标 + 100分综合评分 + 6级买卖信号 +
|
|
1189
|
+
"获取股票技术面分析(MA/MACD/RSI/BOLL/KDJ/成交量等指标 + 100分综合评分 + 6级买卖信号 + 趋势/偏离度/支撑压力位;附 trend_temperature(实验性EMA差/ATR描述;direction为均线方向;validation_status=not_validated,非星球指标,七档不作入场依据;另附 trend_horizons:21/63/252根日K月度动量,建议count=360,非概率、未验证);多周期共振时 resonance.direction ∈ aligned_bullish/aligned_bearish/divergent)。个股技术面综合判断与买卖时机分析的首选;只要均线数值或自定义周期用 calculate_ma,专问量价用 get_volume_analysis,扫当日异动用 detect_anomaly",
|
|
1190
1190
|
parameters: {
|
|
1191
1191
|
type: "object",
|
|
1192
1192
|
properties: {
|
|
@@ -1605,10 +1605,59 @@ export default (pi: ExtensionAPI) => {
|
|
|
1605
1605
|
},
|
|
1606
1606
|
});
|
|
1607
1607
|
|
|
1608
|
+
registerTool({
|
|
1609
|
+
name: "analyze_trend_strategy",
|
|
1610
|
+
description: "月度右侧趋势策略:直接传同市场A/HK/US股票代码,自动获取日K,输出月度新入/持有/退出与逆波动预算。as_of默认最近已收盘交易日,持仓可选且不保存,不自动下单;跨样本仍not_validated。",
|
|
1611
|
+
parameters: {
|
|
1612
|
+
"type": "object",
|
|
1613
|
+
"properties": {
|
|
1614
|
+
"symbols": {
|
|
1615
|
+
"type": "array",
|
|
1616
|
+
"items": {
|
|
1617
|
+
"type": "string"
|
|
1618
|
+
},
|
|
1619
|
+
"minItems": 1,
|
|
1620
|
+
"maxItems": 100,
|
|
1621
|
+
"description": "同一市场的完整股票池,1..100只;A如600036,HK如0700.HK,US如AAPL"
|
|
1622
|
+
},
|
|
1623
|
+
"as_of": {
|
|
1624
|
+
"type": "string",
|
|
1625
|
+
"description": "可选已收盘截止日期YYYY-MM-DD,默认该市场最近已收盘交易日"
|
|
1626
|
+
},
|
|
1627
|
+
"held_symbols": {
|
|
1628
|
+
"type": "array",
|
|
1629
|
+
"items": {
|
|
1630
|
+
"type": "string"
|
|
1631
|
+
},
|
|
1632
|
+
"description": "可选,as_of时真实持股代码,必须在股票池中;省略代表初始空仓,不保存账户"
|
|
1633
|
+
},
|
|
1634
|
+
"pending_exit_symbols": {
|
|
1635
|
+
"type": "array",
|
|
1636
|
+
"items": {
|
|
1637
|
+
"type": "string"
|
|
1638
|
+
},
|
|
1639
|
+
"description": "可选,真实持股中此前已锁定且未成交的退出代码"
|
|
1640
|
+
},
|
|
1641
|
+
"slots": {
|
|
1642
|
+
"type": "number",
|
|
1643
|
+
"description": "可选固定容量K,默认ceil(N/3),不得小于真实持股数量"
|
|
1644
|
+
}
|
|
1645
|
+
},
|
|
1646
|
+
"required": [
|
|
1647
|
+
"symbols"
|
|
1648
|
+
],
|
|
1649
|
+
"additionalProperties": false
|
|
1650
|
+
},
|
|
1651
|
+
async execute(_id, params) {
|
|
1652
|
+
return asText(await withJsonInput(params, async (path: string) =>
|
|
1653
|
+
(await py("trend_strategy.py", ["fetch", "--input", path])).stdout));
|
|
1654
|
+
},
|
|
1655
|
+
});
|
|
1656
|
+
|
|
1608
1657
|
registerTool({
|
|
1609
1658
|
name: "run_backtest",
|
|
1610
1659
|
description:
|
|
1611
|
-
"策略回测(AlphaEvo)。读取YAML策略定义,在历史数据上模拟交易,输出收益率/回撤/胜率等指标。只想知道单个技术信号的历史胜率用更轻量的 evaluate_signal。period为实际数据期间,requested_period保留请求期间,warnings提示覆盖差异;年化按实际期间计算。默认前日收盘信号、次日开盘成交;YAML simulation.execution=same_close可复现旧假设。execution
|
|
1660
|
+
"策略回测(AlphaEvo)。读取YAML策略定义,在历史数据上模拟交易,输出收益率/回撤/胜率等指标。只想知道单个技术信号的历史胜率用更轻量的 evaluate_signal。period为实际数据期间,requested_period保留请求期间,warnings提示覆盖差异;年化按实际期间计算。默认前日收盘信号、次日开盘成交;YAML simulation.execution=same_close可复现旧假设。execution返回模型、阻止成交次数和未模拟约束;零成交量及带历史限价的一字板不成交。支持 monthly_momentum:月初首根有效日K收盘观察过去period根对数收益,次日开盘;长周期需预热。",
|
|
1612
1661
|
parameters: {
|
|
1613
1662
|
type: "object",
|
|
1614
1663
|
properties: {
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: bull-trend
|
|
3
|
-
description:
|
|
3
|
+
description: 趋势交易:识别中长期趋势,制定入场、持仓和退出规则。用于趋势温度计算、趋势股持有、规则化趋势策略或肥尾收益分析。
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# 趋势追踪分析
|
|
@@ -13,6 +13,10 @@ description: 趋势交易:识别中长期趋势,制定入场、持仓和退
|
|
|
13
13
|
|
|
14
14
|
仅解释肥尾概念时,到此完成;下述流程用于具体标的的趋势分析。
|
|
15
15
|
|
|
16
|
+
用户要求运行股票池月度右侧趋势策略时,MUST 先读取 [月度右侧趋势策略](references/monthly-trend-strategy.md),将股票名称解析为代码、按市场分组,直接调用 `analyze_trend_strategy(symbols, ...)` 自动取行情;仅在用户提供时传入真实持股集合,报告动作、原因与新仓预算。MUST 保留 `not_validated` 及跨样本失败边界;用户明确采用的规则可输出条件计划,实际成交和个人持仓由调用方核实。
|
|
17
|
+
|
|
18
|
+
仅要求解释多期限方向或复核旧温度时,先读取 [多期限月度趋势](references/trend-horizons.md),调用 `get_technical_analysis` 的 daily、count=360,优先解释 `trend_horizons` 的21/63/252期限组成、方向与观察日期。当前仍为 `not_validated`,MUST 说明交易有效性未被完整验证,MUST NOT 自行转换成交易建议。七档温度或旧模型复核才读取 [独立趋势温度](references/trend-temperature.md)并解释兼容字段 `trend_temperature`;仅用户明确要求七档时展示研究标签,不能把“平”当作零方向。这些都不是趋势动物、肥尾 κ、原综合评分或市场复盘温度;用户自定条件的研究回测仍可运行。
|
|
19
|
+
|
|
16
20
|
## 执行流程
|
|
17
21
|
|
|
18
22
|
### 1. 采集数据
|
|
@@ -25,6 +29,8 @@ python3 scripts/gather.py <symbol>
|
|
|
25
29
|
|
|
26
30
|
确认数据日期、周期和复权口径;120 根日K线用于近期趋势判断。肥尾分支按参考文件另取历史收益,报告实际取得的区间和样本量。
|
|
27
31
|
|
|
32
|
+
多期限分支报告 `model/validation_status/components/positive_count/negative_count/neutral_count/direction/decision_as_of/as_of/price_basis`;不足月初预热时先解释不可用,不能改用零值。通用采集脚本仍默认120根,不能据它声称已完成252根趋势判断,需另取daily、count=360。旧温度分支报告模型、EMA差方向、分数、日期及口径;七档只按明确请求补充。先确认观察K线收盘,未知价格口径需说明;不把样本不足当中性趋势。
|
|
33
|
+
|
|
28
34
|
### 2. 趋势确认
|
|
29
35
|
|
|
30
36
|
**多头趋势确认条件**:
|
|
@@ -79,3 +85,7 @@ python3 scripts/gather.py <symbol>
|
|
|
79
85
|
4. 入场/持有/离场建议
|
|
80
86
|
5. 初始风险、保护位和退出触发条件
|
|
81
87
|
6. 数据或成交限制;肥尾分支附计算口径和不确定性
|
|
88
|
+
|
|
89
|
+
### 市场环境入场实验
|
|
90
|
+
|
|
91
|
+
用户要求验证宽基右侧条件如何约束趋势入场时,读取[多期限参考中的市场环境实验](references/trend-horizons.md#市场环境入场实验),准备带足预热的个股/同市场宽基daily OHLCV JSON,再运行 `scripts/market_trend.py`。该脚本调用共享Python核心,输出真实规则的三期限研究结果。MUST 分清初始空仓与已有持仓、观察与成交、开发集与新标的复核;不得拿七档标签代替入场条件,或将通过单次历史门槛称为稳定有效。
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# 月度右侧趋势策略:上行SMA200与波动预算
|
|
2
|
+
|
|
3
|
+
开发样本曾通过效果门槛,扩展及历史样本仍未通过;`validation_status=not_validated`。采用它表示使用这套确定的规则,不表示已经验证未来收益。它不是趋势动物的私有温度公式。
|
|
4
|
+
|
|
5
|
+
## 调用
|
|
6
|
+
|
|
7
|
+
直接告诉Agent股票池即可,例如“用月度右侧趋势策略分析招商银行、工商银行和中国神华”。Agent解析代码后,调用四宿主共同的 `analyze_trend_strategy`:
|
|
8
|
+
|
|
9
|
+
```json
|
|
10
|
+
{
|
|
11
|
+
"symbols": ["600036", "601398", "601088"],
|
|
12
|
+
"held_symbols": ["600036"]
|
|
13
|
+
}
|
|
14
|
+
```
|
|
15
|
+
|
|
16
|
+
`symbols`为必填,其他字段均可选。插件自动获取整个股票池的日K,不要求用户准备文件或手工提供行情。混合市场由Agent按A/HK/US分组调用,各市场资金/币种独立。
|
|
17
|
+
|
|
18
|
+
|字段|要求|
|
|
19
|
+
|---|---|
|
|
20
|
+
|`symbols`|同一个市场的完整股票池,1–100只;A用六位代码,HK如`0700.HK`/`00700.HK`,US如`AAPL`;大小写与HK补零统一识别,同股不能重复|
|
|
21
|
+
|`as_of`|可选已收盘截止日期`YYYY-MM-DD`,默认交易所最近已收盘交易日;盘中排除当天未收盘K线,按实际日历处理夏令时与半日市|
|
|
22
|
+
|`held_symbols`|可选,as_of时真实持股代码,须在股票池中;省略表示初始空仓,Agent明确这个假设,挂买单不算持仓|
|
|
23
|
+
|`pending_exit_symbols`|可选,已发出但未成交的退出锁,必须在真实持仓内,价格恢复不撤销|
|
|
24
|
+
|`slots`|可选固定容量K,默认ceil(N/3),不得小于当前真实持股数量|
|
|
25
|
+
|
|
26
|
+
默认取至少360根daily;历史截止日期会增加取数长度以保留预热,接口有历史总量上限。有效价格不足221根时不填零,也不发明入场条件。所有数据沿现有行情源故障切换;任一成员取数失败,返回`incomplete_pool`和失败代码,不生成缩小股票池的计划。已取数据不合格则返回`invalid_market_data`。核对返回的`as_of/quote_as_of/price_basis`,停牌或报价未更新的成员仍显式列出。持仓只作为本次输入,不保存账户。
|
|
27
|
+
|
|
28
|
+
### 离线复核
|
|
29
|
+
|
|
30
|
+
开发者需要复现冻结研究时,CLI仍支持 `python3 tools/trend_strategy.py --input snapshot.json`。离线快照包含market/as_of/histories及可选held_symbols/pending_exit_symbols/slots,每条历史需要date/close/volume,可保留adjusted;日期递增唯一,价格为正且有限,量非负,最大32 MiB普通文件。该入口只用于已有行情的离线复核,正常插件工具使用上面的股票代码参数。
|
|
31
|
+
|
|
32
|
+
## 固定规则
|
|
33
|
+
|
|
34
|
+
1. 以股票池正成交量日期并集中的每月第一根收盘为观察点。当天不能按该收盘立即成交,最早是后续有效开盘。月中返回`waiting_for_monthly_observation`,只显示当前条件,不用今天持仓倒推月初交易。
|
|
35
|
+
2. 新入同时要求:close>SMA200,且SMA200高于21根有效价格以前的SMA200。按`log(close)-log(SMA200)`降序,代码破同分。
|
|
36
|
+
3. 真实旧仓优先占K槽。个股仍在200线上就保持原股份,排名下降或均线斜率转负不触发换仓;无有效报价时保持并占槽。已有200失效则给出`exit_next_valid_open`。已锁定退出始终返回`exit_pending`。
|
|
37
|
+
4. 每股sigma63为过去63段对数收益的样本标准差,需64根有效价格。参考中位数取观察日整个固定池有当日报价、sigma有限且>0的股票,包括尚不满足入场资格者。
|
|
38
|
+
5. 新入预算系数=`0.8704/K × min(1, median_sigma63 / stock_sigma63)`。低波动不扩大原槽,高波动折减;真实旧仓不按这个比例重新等权,不补仓。0.8704沿用已拟合的开发参数。
|
|
39
|
+
6. 没有合格新股可保持现金;空槽不必填满。选择新股不代表已经有可用现金或腾出槽位,须先确认退出真实成交。
|
|
40
|
+
|
|
41
|
+
## 输出和执行边界
|
|
42
|
+
|
|
43
|
+
报告`model/validation_status/status/as_of/observation_date/selected/reference_volatility/stocks`。每股有价格口径、报价日期、SMA200及21根前均线、distance、sigma63、资格、action、reason及new_budget_fraction。无充分旧仓历史时返回`insufficient_held_history`,不生成新的交易计划;先补齐历史。
|
|
44
|
+
|
|
45
|
+
`new_budget_fraction` 是下一执行批次开盘净值乘数,买入费用包含在预算内,**不是目标持仓权重,也不是买入股数**。真实成交还要核对可用现金、已完成卖出、实际整手、停牌/涨跌停/禁售、费用与结算;此工具没有订单簿、现金账本或成交模拟,不会自动下单。不使用复权close直接计算真实股数,不因一笔新仓没成交就当作已持有。
|
|
46
|
+
|
|
47
|
+
单股`get_technical_analysis`的`trend_temperature`与`trend_horizons`仍可辅助解释,但不是这套组合规则。普通单股YAML回测也不能代替共享资金、旧仓保留和整池风险中位数。本工具不计算历史组合收益,不把信号计划冒充组合回测。
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
# 多期限趋势
|
|
2
|
+
|
|
3
|
+
通过现有get_technical_analysis请求daily、count=360,读取trend_horizons。模型用21/63/252根日K约代表1/3/12个月,不强凑七档标签,不是星球公式或肥尾预测。
|
|
4
|
+
|
|
5
|
+
## 计算与解释
|
|
6
|
+
|
|
7
|
+
每期限过去对数收益为 log(close_t)-log(close_(t-h))。每个月第一根可见、正成交量日K的收盘形成观察,其后保持到下个月首根有效日K收盘。未提供volume时只能沿输入记录观察;提供volume时零成交量记录不计回溯根数。观察K线必须已收盘,任何研究成交使用之后的开盘。
|
|
8
|
+
|
|
9
|
+
components逐一返回period与log_return,positive_count/negative_count/neutral_count统计三期限方向;至少2个为正/负则direction为up/down,全部零为flat,其他为mixed。它们是已发生路径的描述,MUST NOT 解释为独立投票概率、未来涨跌概率或自动配置比例。相关期限不能当作独立样本。
|
|
10
|
+
|
|
11
|
+
仅支持daily输入。最长需在月度观察时已有253根有效收盘;最新已有253根而当月首根尚不足时仍不可用,不能用最新日重新计算冒充月度观察。建议请求360根,报告实际history_start、as_of、decision_as_of及price_basis。数据不足、混用调整标记或坏日期必须报告unavailable_reason,不伪造中性。多周期摘要保留整个trend_horizons,周/月K返回requires_daily_bars。
|
|
12
|
+
|
|
13
|
+
当前validation_status=not_validated。旧trend_temperature为兼容的EMA/ATR研究描述;不再将它的七档视为默认趋势模型。新字段也不能覆盖原综合评分或买卖信号。
|
|
14
|
+
|
|
15
|
+
## 回测与证据边界
|
|
16
|
+
|
|
17
|
+
DSL指标monthly_momentum复用相同Python计算,period默认63。它是单期限信号。三期限研究组合从相同起点分别给初始资金三分之一,独立留存盈亏、权重漂移,并没有每月等权再平衡;并行买卖分别计费,没有跨子账户净额撮合。研究另外拟合了一个跨市场共用的初始活跃资金比例0.8704,剩余现金不动;这是2022–2025研究集风险拟合结果,MUST NOT 作为用户账户默认仓位。
|
|
18
|
+
|
|
19
|
+
新12股复核:A/HK路径回报较旧规则提高,美股回报接近、回撤较小;但港股最大回撤恶化约6.1个百分点,未通过预设5个百分点门槛。因此没有建立跨市场统一优势,MUST NOT 称为已验证策略。A股研究用了供应商AdjClose因子OHLC,不等于完整投资者总回报;产品A股输入通常仍为qfq,不能直接照搬该收益。
|
|
20
|
+
|
|
21
|
+
原核心固定止损/止盈默认值不变;省略配置不代表禁用。单份普通YAML回测不会自动复制三子策略和预热协议。
|
|
22
|
+
|
|
23
|
+
研究背景:[Hurst/Ooi/Pedersen原文](https://www.aqr.com/-/media/AQR/Documents/Insights/Journal-Article/AQR-JPM-Fall-2017.pdf)讨论1/3/12个月趋势组合。本实现的个股多头、月初观察、正成交量过滤、资金漂移和风险拟合均为本项目假设,不是论文复现或七档背书。
|
|
24
|
+
|
|
25
|
+
## 市场环境入场实验
|
|
26
|
+
|
|
27
|
+
需复现“市场只限制新开仓”的研究时,使用同一skill的 `scripts/market_trend.py`,无需新增宿主工具或个人持仓数据库。输入是两份已取得的daily OHLCV JSON数组(个股、同市场宽基),包含date/open/high/low/close/volume;调整口径须在各自序列内一致。market-symbol标识调用者提供的市场输入,不自动下载或验证标的归属。研究代理固定A510300、HK2800.HK、US SPY;自换代理属于另一项实验。
|
|
28
|
+
|
|
29
|
+
```bash
|
|
30
|
+
python3 scripts/market_trend.py stock-daily.json market-daily.json \
|
|
31
|
+
--symbol AAPL --market-symbol SPY --start 2022-01-01 --end 2025-12-31 \
|
|
32
|
+
--capital 10000000 --allocation 0.8704
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
两份输入必须含评估开始之前的预热历史:个股最长252根过去收益在观察时需253根有效收盘,市场SMA200需200根。预热只计算指标,不建立虚拟持仓或产生收益。起点前最后有效收盘,以已知月度个股方向和当日市场条件初始化空仓目标;之后只在月度观察给出新开仓许可,次日有效开盘执行。市场close>SMA200允许新的月度正动量子策略进入;弱市不强制退出已持仓,个股月度动量<0仍退出。待买订单遇到下月许可失效会取消,不能冒充已持仓豁免。
|
|
36
|
+
|
|
37
|
+
脚本默认allocation=1,0.8704只为显式复现前轮研究,不是账户建议。21/63/252初始各分三份、按分向下取整,余款留现金,利润各自保留而非每月等权重置。费用固定佣金/滑点各每边0.1%,税与现金利息0;输出明确参数、资金、评估开始/预热开始、交易、净值和指标。采用本地JSON输入,不保存个人仓位、不下单。普通 `run_backtest` 的单份YAML不会自动执行这个三子策略或抓市场预热;不要冒充二者完全相同。
|
|
38
|
+
|
|
39
|
+
当前方法尚未通过完整跨市场效果门槛,`validation_status=not_validated`。MUST NOT 将局部样本上涨或相对旧模型改善称为稳定的跨市场交易优势。
|
|
40
|
+
|
|
41
|
+
## 温度状态与切换事件
|
|
42
|
+
|
|
43
|
+
解读星球信号或设计入场协议时,MUST 区分当前状态和新发生的切换事件:“今天仍热”不等于“今天温转热”。当前月度方向策略按状态选股,不是官方事件策略。事件协议须明确可得时间、有效期限和重复事件加仓条件;无合格新事件时,卖出所得留在现金。预热不产生新事件或虚拟持仓。外部同名温度的计算公式未公开,不能将成员筛选条件或自述收益作为官方规则或验证结果。
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
# 独立趋势温度
|
|
2
|
+
|
|
3
|
+
用于用户要求计算趋势温度、寒凉温热状态或复核趋势强度时。调用现有 `get_technical_analysis`,读取 `trend_temperature`;skill 的采集脚本也会在 `technical.trend_temperature` 返回同一结果。无需配置外部温度接口,不保存个人持仓。
|
|
4
|
+
|
|
5
|
+
## 来源与定位
|
|
6
|
+
|
|
7
|
+
这是本项目可重复计算的研究基线,`experimental=true`。它不是趋势动物算法,不是塔勒布肥尾指标,也不是原有 100 分综合评分或复盘市场温度。连续分数描述均线相对真实波幅的分离;七档是未经收益校准的显示假设。MUST 同时报告模型、周期、分数、数据日期及实验性质,MUST NOT 将其称为上涨概率、已验证的交易优势或星球官方信号。
|
|
8
|
+
|
|
9
|
+
`validation_status=not_validated`:真实股票检验没有建立默认入场规则的优势;降低门槛、延长慢线和通道对照也未通过修订研究门槛。默认解释 `direction` 与连续分数,MUST NOT 自行把七档或零轴转换成交易建议。仅在用户明确要求七档时展示研究标签;用户自定条件的回测是研究,不代表推荐。
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
## 公式与数据
|
|
13
|
+
|
|
14
|
+
```text
|
|
15
|
+
TR_t = max(high_t-low_t, abs(high_t-close_(t-1)), abs(low_t-close_(t-1)))
|
|
16
|
+
ATR14_t = 最近14个有效TR的简单均值
|
|
17
|
+
score_t = (EMA20(close)_t - EMA60(close)_t) / ATR14_t
|
|
18
|
+
EMA_p,t = (2/(p+1))*close_t + (1-2/(p+1))*EMA_p,t-1
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
EMA 用输入首个收盘价初始化(adjust=False),前收缺失的首根 TR 不计算;ATR 使用简单平均,不是 Wilder 平滑。默认至少 60 根 K 线才有分数,至少 61 根才可能有前一期状态。周期按根数:周线即 20/60 周及 14 周波幅,不能与日线信号混称。
|
|
22
|
+
|
|
23
|
+
`direction/previous_direction` 仅按 EMA 差的正负返回 up/down/flat,未预热或无有效分数时为 null;不是预测方向。七档的“平”包含正负分数,不能代替方向;`previous_state` 和 `transition` 仍只表示显示档位变化。多周期摘要附 `trend_score`、`trend_temperature_state`、`trend_temperature_direction`、`trend_temperature_validation_status`、`trend_temperature_as_of`、`trend_temperature_price_basis` 和 `trend_temperature_unavailable_reason`。各周期日期和价格口径分别核验,不能用顶层日线日期代替周线或月线日期;原 `resonance` 仍基于既有均线方向,不能称为七档温度共振。
|
|
24
|
+
|
|
25
|
+
价格需有限且为正,满足 low ≤ close ≤ high;日期唯一且递增。技术分析入口会先按日期排序;明确混用复权标记时温度不可用。`price_basis=unknown` 仍需核实价格口径;没有标记不代表已确认复权。保留 `history_start`,输入历史起点不同会影响 EMA 初始化和当前分数。缺失交易日和停牌不能仅靠日期排序鉴别;`previous_as_of` 是输入的前一根 K 线日期,不保证是交易所的上一交易日。
|
|
26
|
+
|
|
27
|
+
零 ATR、不足预热或无效行情输出 `score/state=null` 和 `unavailable_reason`,不伪造为平。最新 K 线可能尚未收盘,MUST 先确认数据时点再按收盘纪律判断。分数不要求正态分布,但 ATR 和 EMA 都会受极端波动及观察窗口影响;波幅放大也可能使分数降档。
|
|
28
|
+
|
|
29
|
+
## 七档显示
|
|
30
|
+
|
|
31
|
+
| score | 状态 |
|
|
32
|
+
| --- | --- |
|
|
33
|
+
| 小于 -3 | 冻 |
|
|
34
|
+
| [-3, -1.5) | 寒 |
|
|
35
|
+
| [-1.5, -0.5) | 凉 |
|
|
36
|
+
| [-0.5, 0.5] | 平 |
|
|
37
|
+
| (0.5, 1.5] | 温 |
|
|
38
|
+
| (1.5, 3] | 热 |
|
|
39
|
+
| 大于 3 | 沸 |
|
|
40
|
+
|
|
41
|
+
`previous_score/previous_state` 只取前一根,不跳过不可用记录;`transition` 仅在本根和前根均可用且状态不同时返回。它们由本次行情计算,不需要跨日保存账户。
|
|
42
|
+
|
|
43
|
+
温/热/沸表示本基线的正向分离程度,不等于星球的同名状态。沸不证明已经过热或将反转;平不表示没有波动。MUST 将描述与用户的入场、退出规则分开,不照搬星球“温转热开仓、危险全平”等标签动作,也不由本字段自动覆盖原 `buy_signal`。
|
|
44
|
+
|
|
45
|
+
## 历史检验
|
|
46
|
+
|
|
47
|
+
回测 DSL 可使用 `indicator: trend_score`;默认参数与技术分析相同。既有 `fast_period/slow_period` 调整 EMA,`period` 调整 ATR;快线必须短于慢线且均为正整数。修改参数后七档阈值不自动校准。
|
|
48
|
+
|
|
49
|
+
不提供默认温度入场示例。用户指定研究规则后,仍须说明原引擎默认 stop_loss=-0.10、take_profit=0.50,省略不代表禁用。预热/零 ATR 为 NaN 时条件不成立,不能凭首个有效分数声称发生穿越。默认次日开盘成交,保留 signal_date/date;涨跌停、跳空及其他限制沿用原引擎。
|
|
50
|
+
|
|
51
|
+
用户要求检验时按 [策略回测](../../strategy-backtest/SKILL.md)先固定规则,再做时间样本外与跨标的比较,报告反复切换、成本、回撤和交易数量。滚动验证每段重新初始化,测试窗口必须足够覆盖预热及评估期。结合已有 [肥尾收益诊断](fat-tails.md)检查大赢家贡献,不把正偏或集中度当作正收益证明。
|
|
52
|
+
|
|
53
|
+
理论参考:[Time Series Momentum](https://www.aqr.com/Insights/Research/Journal-Article/Time-Series-Momentum)提供历史收益趋势研究依据,不验证本模型的 20/60/14 参数和阈值;[Taleb κ](https://arxiv.org/html/1802.05495)衡量样本聚合稳定性,不输出趋势方向。
|
|
54
|
+
|
|
55
|
+
## 使用入口
|
|
56
|
+
|
|
57
|
+
当前趋势研究优先使用[多期限月度趋势](trend-horizons.md)的trend_horizons,daily、count=360。独立趋势温度继续保留供兼容和既有计算复现,不将七档作为默认趋势判断。多期限趋势也尚未通过全部跨市场风险门槛,不是自动入场信号。
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Stateless monthly trend experiment from stock and market OHLCV JSON arrays."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
import numpy as np
|
|
10
|
+
|
|
11
|
+
sys.path.insert(0, str(Path(__file__).resolve().parents[3] / "tools"))
|
|
12
|
+
from _subproc import json_safe, utf8_stdio # noqa: E402
|
|
13
|
+
from backtest import compute_metrics, simulate_monthly_market # noqa: E402
|
|
14
|
+
from technical import calc_trend_horizons, to_dataframe # noqa: E402
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Parser(argparse.ArgumentParser):
|
|
18
|
+
def error(self, message):
|
|
19
|
+
raise ValueError(message)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def read_prices(path):
|
|
23
|
+
records = json.loads(Path(path).read_text(encoding="utf-8"))
|
|
24
|
+
if not isinstance(records, list) or not records or any(not isinstance(row, dict) for row in records):
|
|
25
|
+
raise ValueError("Expected a nonempty OHLCV JSON array")
|
|
26
|
+
frame = to_dataframe(records)
|
|
27
|
+
fields = ["open", "high", "low", "close", "volume"]
|
|
28
|
+
if "date" not in frame or any(field not in frame for field in fields):
|
|
29
|
+
raise ValueError("OHLCV input requires date, open, high, low, close and volume")
|
|
30
|
+
if not np.isfinite(frame[fields]).all().all() or (frame[fields[:4]] <= 0).any().any():
|
|
31
|
+
raise ValueError("OHLCV input requires finite positive prices")
|
|
32
|
+
if (
|
|
33
|
+
(frame.low > frame.close) | (frame.close > frame.high) | (frame.low > frame.open) | (frame.open > frame.high)
|
|
34
|
+
).any():
|
|
35
|
+
raise ValueError("OHLCV input requires low <= open/close <= high")
|
|
36
|
+
return frame
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def main():
|
|
40
|
+
parser = Parser(description=__doc__)
|
|
41
|
+
parser.add_argument("prices")
|
|
42
|
+
parser.add_argument("market_prices")
|
|
43
|
+
parser.add_argument("--symbol", required=True)
|
|
44
|
+
parser.add_argument("--market-symbol", required=True)
|
|
45
|
+
parser.add_argument("--start", required=True)
|
|
46
|
+
parser.add_argument("--end")
|
|
47
|
+
parser.add_argument("--capital", type=float, default=1000000)
|
|
48
|
+
parser.add_argument("--allocation", type=float, default=1)
|
|
49
|
+
try:
|
|
50
|
+
args = parser.parse_args()
|
|
51
|
+
prices, market = read_prices(args.prices), read_prices(args.market_prices)
|
|
52
|
+
if args.end:
|
|
53
|
+
prices = prices[prices.date <= args.end].copy()
|
|
54
|
+
result = simulate_monthly_market(prices, market, args.capital, args.symbol, args.start, args.allocation)
|
|
55
|
+
result.update(symbol=args.symbol, market_symbol=args.market_symbol, trend_horizons=calc_trend_horizons(prices))
|
|
56
|
+
start = result["start"]
|
|
57
|
+
result["equity_curve"] = [row for row in result["equity_curve"] if row["date"] >= start]
|
|
58
|
+
end = result["equity_curve"][-1]["date"]
|
|
59
|
+
result["metrics"] = compute_metrics(
|
|
60
|
+
result["trades"], result["equity_curve"], args.capital, result["final_equity"], start, end
|
|
61
|
+
)
|
|
62
|
+
result["warnings"] = [
|
|
63
|
+
"Research only: market close>SMA200 gates new monthly entries, not existing exits. "
|
|
64
|
+
"Need stock 253 and market 200 valid closes before observation; verify all bars are closed. "
|
|
65
|
+
"Three initially equal sleeves drift; costs are commission/slippage 0.1% each side, tax/interest zero. "
|
|
66
|
+
"Historical splits/dividends, actual board lots, limits and liquidity need separate verification. "
|
|
67
|
+
"Passing one small historical cohort is not stable cross-market validation."
|
|
68
|
+
]
|
|
69
|
+
except Exception as exc:
|
|
70
|
+
print(json.dumps({"error": str(exc)}, ensure_ascii=False))
|
|
71
|
+
return 1
|
|
72
|
+
print(json.dumps(json_safe(result), ensure_ascii=False, allow_nan=False))
|
|
73
|
+
return 0
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
if __name__ == "__main__":
|
|
77
|
+
utf8_stdio()
|
|
78
|
+
sys.exit(main())
|
|
@@ -5,6 +5,8 @@ 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 的资金比例。
|
|
@@ -58,6 +60,12 @@ position:
|
|
|
58
60
|
|
|
59
61
|
**可用指标**:rsi, ma, ema, macd_dif, macd_dea, macd, volume_ratio, price_change, bollinger_position, close, volume
|
|
60
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
|
+
|
|
61
69
|
**可用运算符**:`>`, `<`, `>=`, `<=`, `==`, `cross_above`, `cross_below`
|
|
62
70
|
|
|
63
71
|
### 第二步:运行回测
|
|
@@ -150,3 +158,5 @@ python3 tools/backtest.py run <path.yaml> <symbol> --start <date> --end <date>
|
|
|
150
158
|
参考 `{baseDir}/strategies/examples/` 目录中的示例:
|
|
151
159
|
- `rsi_oversold.yaml` — RSI 超卖反弹
|
|
152
160
|
- `ma_crossover.yaml` — 均线金叉
|
|
161
|
+
|
|
162
|
+
市场环境只限制新开仓的三期限月度实验,使用 [bull-trend参考](../bull-trend/references/trend-horizons.md#市场环境入场实验) 与 `../bull-trend/scripts/market_trend.py`,输入两份带预热的daily OHLCV JSON。普通单期限YAML不会自动提供该组合或市场数据;未知市场历史禁止新入,市场转弱不冒充个股退出。初始投资时不能把预热虚拟信号当实际持仓。
|
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
|
|
|
@@ -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),
|
|
@@ -227,9 +240,11 @@ def evaluate_conditions(df: pd.DataFrame, conditions: list, logic: str, idx: int
|
|
|
227
240
|
reasons = []
|
|
228
241
|
for cond in conditions:
|
|
229
242
|
ind_name = cond["indicator"]
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
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)
|
|
233
248
|
|
|
234
249
|
cache_key = f"{ind_name}_{period}_{fast}_{slow}"
|
|
235
250
|
if cache_key not in cache:
|
|
@@ -253,7 +268,9 @@ def evaluate_conditions(df: pd.DataFrame, conditions: list, logic: str, idx: int
|
|
|
253
268
|
# --------------- Simulation ---------------
|
|
254
269
|
|
|
255
270
|
|
|
256
|
-
def simulate(
|
|
271
|
+
def simulate(
|
|
272
|
+
df: pd.DataFrame, strategy: dict, capital: float, symbol: str, *, entry_gate: pd.Series | None = None
|
|
273
|
+
) -> dict:
|
|
257
274
|
if not math.isfinite(capital) or capital <= 0:
|
|
258
275
|
raise ValueError("capital must be finite and positive")
|
|
259
276
|
if not np.isfinite(df["close"]).all() or (df["close"] <= 0).any():
|
|
@@ -261,6 +278,10 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
261
278
|
dates = pd.to_datetime(df["date"], errors="coerce")
|
|
262
279
|
if dates.isna().any() or dates.duplicated().any() or not dates.is_monotonic_increasing:
|
|
263
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)
|
|
264
285
|
market = detect_market(symbol)
|
|
265
286
|
lot_size = 100 if market == "A" else 1
|
|
266
287
|
sim_cfg = strategy.get("simulation", {})
|
|
@@ -330,6 +351,8 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
330
351
|
hit, reason = evaluate_conditions(df, entry_conditions, entry_logic, signal_idx, cache)
|
|
331
352
|
if pending:
|
|
332
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
|
|
333
356
|
if hit and not tradable(row, "buy"):
|
|
334
357
|
pending = (reason, signal_date)
|
|
335
358
|
blocked_orders += 1
|
|
@@ -464,6 +487,48 @@ def simulate(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> d
|
|
|
464
487
|
}
|
|
465
488
|
|
|
466
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
|
+
|
|
467
532
|
# --------------- Metrics ---------------
|
|
468
533
|
|
|
469
534
|
|
package/tools/capabilities.py
CHANGED
|
@@ -18,6 +18,10 @@ 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
|
+
},
|
|
21
25
|
# Explicit-input analytics; data acquisition retains each provider's market limits.
|
|
22
26
|
"compare_stocks": {"markets": ALL_MARKETS, "reason": None},
|
|
23
27
|
"analyze_disclosure_changes": {"markets": ALL_MARKETS, "reason": None},
|
package/tools/cli_budgets.json
CHANGED
package/tools/technical.py
CHANGED
|
@@ -47,6 +47,182 @@ def ema_series(close: pd.Series, period: int) -> pd.Series:
|
|
|
47
47
|
return close.ewm(span=period, adjust=False).mean()
|
|
48
48
|
|
|
49
49
|
|
|
50
|
+
def _trend_prices(df: pd.DataFrame) -> tuple[pd.Series, pd.Series]:
|
|
51
|
+
if "date" not in df or "close" not in df:
|
|
52
|
+
raise ValueError("monthly_momentum requires date and close")
|
|
53
|
+
dates = pd.to_datetime(df["date"], errors="coerce")
|
|
54
|
+
if dates.isna().any() or dates.duplicated().any() or not dates.is_monotonic_increasing:
|
|
55
|
+
raise ValueError("monthly_momentum dates must be valid, unique and increasing")
|
|
56
|
+
close = pd.to_numeric(df["close"], errors="coerce")
|
|
57
|
+
if not np.isfinite(close).all() or (close <= 0).any():
|
|
58
|
+
raise ValueError("monthly_momentum requires finite positive close prices")
|
|
59
|
+
if "adjusted" in df and df["adjusted"].fillna("unknown").astype(str).nunique() > 1:
|
|
60
|
+
raise ValueError("monthly_momentum requires a consistent adjustment basis")
|
|
61
|
+
if "volume" in df:
|
|
62
|
+
volume = pd.to_numeric(df["volume"], errors="coerce")
|
|
63
|
+
if not np.isfinite(volume).all() or (volume < 0).any():
|
|
64
|
+
raise ValueError("monthly_momentum requires finite nonnegative volume")
|
|
65
|
+
close, dates = close[volume > 0], dates[volume > 0]
|
|
66
|
+
return close, dates
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def monthly_momentum_series(df: pd.DataFrame, period: int = 63) -> pd.Series:
|
|
70
|
+
"""Past log return observed on each month's first visible close, then held; never a price forecast."""
|
|
71
|
+
if isinstance(period, bool) or not isinstance(period, int) or period < 1:
|
|
72
|
+
raise ValueError("monthly_momentum requires a positive integer period")
|
|
73
|
+
close, dates = _trend_prices(df)
|
|
74
|
+
month = dates.dt.to_period("M")
|
|
75
|
+
first_bar = month.ne(month.shift())
|
|
76
|
+
return (np.log(close) - np.log(close.shift(period))).where(first_bar).reindex(df.index).ffill()
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def monthly_market_entry_series(
|
|
80
|
+
df: pd.DataFrame, market: pd.DataFrame, period: int = 63, *, activation: pd.Timestamp | None = None
|
|
81
|
+
) -> pd.Series:
|
|
82
|
+
"""Monthly entry permission; a weak market never cancels an existing positive stock trend."""
|
|
83
|
+
momentum = monthly_momentum_series(df, period)
|
|
84
|
+
_, dates = _trend_prices(df)
|
|
85
|
+
market_close, market_dates = _trend_prices(market)
|
|
86
|
+
context = pd.DataFrame({"date": market_dates, "allowed": market_close > ma_series(market_close, 200)})
|
|
87
|
+
known = pd.merge_asof(pd.DataFrame({"date": dates}), context, on="date", direction="backward")
|
|
88
|
+
allowed = pd.Series(known.allowed.to_numpy(), index=dates.index).reindex(df.index).eq(True)
|
|
89
|
+
months = dates.dt.to_period("M")
|
|
90
|
+
observe = months.ne(months.shift()).reindex(df.index).eq(True)
|
|
91
|
+
active = pd.to_datetime(df.date).ge(activation) if activation is not None else pd.Series(True, index=df.index)
|
|
92
|
+
if activation is not None:
|
|
93
|
+
observe |= pd.to_datetime(df.date).eq(activation)
|
|
94
|
+
permission = ((momentum > 0) & allowed).astype("boolean").where(observe & active, pd.NA)
|
|
95
|
+
return permission.ffill().where(active & momentum.notna(), pd.NA)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def calc_trend_horizons(df: pd.DataFrame, period: str = "daily") -> dict:
|
|
99
|
+
result = {
|
|
100
|
+
"model": "monthly_momentum",
|
|
101
|
+
"experimental": True,
|
|
102
|
+
"validation_status": "not_validated",
|
|
103
|
+
"as_of": str(df["date"].iloc[-1].date()),
|
|
104
|
+
"history_start": str(df["date"].iloc[0].date()),
|
|
105
|
+
"price_basis": str(df["adjusted"].iloc[-1])
|
|
106
|
+
if "adjusted" in df and pd.notna(df["adjusted"].iloc[-1])
|
|
107
|
+
else "unknown",
|
|
108
|
+
"decision_as_of": None,
|
|
109
|
+
"positive_count": None,
|
|
110
|
+
"negative_count": None,
|
|
111
|
+
"neutral_count": None,
|
|
112
|
+
"direction": None,
|
|
113
|
+
"components": [],
|
|
114
|
+
"unavailable_reason": None,
|
|
115
|
+
"warnings": [
|
|
116
|
+
"Descriptive past-return directions, not probabilities or an automatic allocation. "
|
|
117
|
+
"Observed at each month's first visible daily close; any trade uses a later open. "
|
|
118
|
+
"Need 253 closes at the monthly observation; verify the observation bar is closed. "
|
|
119
|
+
"No stable cross-market trading advantage has been established."
|
|
120
|
+
],
|
|
121
|
+
}
|
|
122
|
+
if period != "daily":
|
|
123
|
+
result["unavailable_reason"] = "requires_daily_bars"
|
|
124
|
+
return result
|
|
125
|
+
try:
|
|
126
|
+
for horizon in (21, 63, 252):
|
|
127
|
+
value = monthly_momentum_series(df, horizon).iloc[-1]
|
|
128
|
+
result["components"].append({"period": horizon, "log_return": float(value) if np.isfinite(value) else None})
|
|
129
|
+
except ValueError as exc:
|
|
130
|
+
result["unavailable_reason"] = str(exc)
|
|
131
|
+
return result
|
|
132
|
+
dates = df.loc[df["volume"] > 0, "date"] if "volume" in df else df["date"]
|
|
133
|
+
month = dates.dt.to_period("M")
|
|
134
|
+
if not dates.empty:
|
|
135
|
+
result["decision_as_of"] = str(dates.loc[month.ne(month.shift())].iloc[-1].date())
|
|
136
|
+
values = [component["log_return"] for component in result["components"]]
|
|
137
|
+
if any(value is None for value in values):
|
|
138
|
+
result["unavailable_reason"] = "insufficient_history_at_monthly_observation"
|
|
139
|
+
return result
|
|
140
|
+
positive = sum(value > 0 for value in values)
|
|
141
|
+
negative = sum(value < 0 for value in values)
|
|
142
|
+
result.update(positive_count=positive, negative_count=negative, neutral_count=3 - positive - negative)
|
|
143
|
+
result["direction"] = (
|
|
144
|
+
"up" if positive >= 2 else "down" if negative >= 2 else "flat" if not positive + negative else "mixed"
|
|
145
|
+
)
|
|
146
|
+
return result
|
|
147
|
+
|
|
148
|
+
|
|
149
|
+
def trend_score_series(df: pd.DataFrame, fast: int = 20, slow: int = 60, atr_period: int = 14) -> pd.Series:
|
|
150
|
+
"""Causal EMA spread / SMA true range; an independent, uncalibrated research baseline."""
|
|
151
|
+
if any(isinstance(n, bool) or not isinstance(n, int) or n < 1 for n in (fast, slow, atr_period)) or fast >= slow:
|
|
152
|
+
raise ValueError("trend_score requires positive integer periods and fast_period < slow_period")
|
|
153
|
+
if any(field not in df for field in ("high", "low", "close")):
|
|
154
|
+
raise ValueError("trend_score requires high, low and close")
|
|
155
|
+
prices = df[["high", "low", "close"]].apply(pd.to_numeric, errors="coerce")
|
|
156
|
+
if not np.isfinite(prices).all().all() or (prices <= 0).any().any():
|
|
157
|
+
raise ValueError("trend_score requires finite positive prices")
|
|
158
|
+
high, low, close = prices["high"], prices["low"], prices["close"]
|
|
159
|
+
if ((low > close) | (close > high)).any():
|
|
160
|
+
raise ValueError("trend_score requires low <= close <= high")
|
|
161
|
+
if "date" in df:
|
|
162
|
+
dates = pd.to_datetime(df["date"], errors="coerce")
|
|
163
|
+
if dates.isna().any() or dates.duplicated().any() or not dates.is_monotonic_increasing:
|
|
164
|
+
raise ValueError("trend_score dates must be valid, unique and increasing")
|
|
165
|
+
if "adjusted" in df and df["adjusted"].fillna("unknown").astype(str).nunique() > 1:
|
|
166
|
+
raise ValueError("trend_score requires a consistent adjustment basis")
|
|
167
|
+
previous = close.shift(1)
|
|
168
|
+
true_range = pd.concat([high - low, (high - previous).abs(), (low - previous).abs()], axis=1).max(
|
|
169
|
+
axis=1, skipna=False
|
|
170
|
+
)
|
|
171
|
+
atr = true_range.rolling(atr_period).mean()
|
|
172
|
+
score = (ema_series(close, fast) - ema_series(close, slow)) / atr.replace(0, np.nan)
|
|
173
|
+
return score.where(np.arange(len(df)) >= max(slow, atr_period + 1) - 1).replace([np.inf, -np.inf], np.nan)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def calc_trend_temperature(df: pd.DataFrame) -> dict:
|
|
177
|
+
thresholds = [0.5, 1.5, 3.0]
|
|
178
|
+
result = {
|
|
179
|
+
"model": "ema_atr",
|
|
180
|
+
"experimental": True,
|
|
181
|
+
"validation_status": "not_validated",
|
|
182
|
+
"parameters": {"fast_period": 20, "slow_period": 60, "atr_period": 14, "atr_method": "sma_true_range"},
|
|
183
|
+
"thresholds": thresholds,
|
|
184
|
+
"price_basis": str(df["adjusted"].iloc[-1])
|
|
185
|
+
if "adjusted" in df and pd.notna(df["adjusted"].iloc[-1])
|
|
186
|
+
else "unknown",
|
|
187
|
+
"history_start": str(df["date"].iloc[0].date()),
|
|
188
|
+
"score": None,
|
|
189
|
+
"state": None,
|
|
190
|
+
"direction": None,
|
|
191
|
+
"previous_score": None,
|
|
192
|
+
"previous_state": None,
|
|
193
|
+
"previous_direction": None,
|
|
194
|
+
"transition": None,
|
|
195
|
+
"as_of": str(df["date"].iloc[-1].date()),
|
|
196
|
+
"previous_as_of": str(df["date"].iloc[-2].date()) if len(df) > 1 else None,
|
|
197
|
+
"unavailable_reason": None,
|
|
198
|
+
"warnings": [
|
|
199
|
+
"Independent research baseline, not Trend Animal temperature or a Taleb fat-tail metric. "
|
|
200
|
+
"Thresholds are uncalibrated, not probabilities or automatic trade signals. "
|
|
201
|
+
"State labels are not entry rules; direction is only the EMA-spread sign. "
|
|
202
|
+
"EMA initialization depends on the supplied history; periods count bars, not calendar days. "
|
|
203
|
+
"Verify the latest bar is closed and the OHLC adjustment basis is consistent."
|
|
204
|
+
],
|
|
205
|
+
}
|
|
206
|
+
try:
|
|
207
|
+
scores = trend_score_series(df)
|
|
208
|
+
except ValueError as exc:
|
|
209
|
+
result["unavailable_reason"] = str(exc)
|
|
210
|
+
return result
|
|
211
|
+
for prefix, idx in (("", -1), ("previous_", -2)):
|
|
212
|
+
if len(scores) < abs(idx) or not np.isfinite(scores.iloc[idx]):
|
|
213
|
+
continue
|
|
214
|
+
value = float(scores.iloc[idx])
|
|
215
|
+
magnitude = sum(abs(value) > threshold for threshold in thresholds)
|
|
216
|
+
result[f"{prefix}score"] = value
|
|
217
|
+
result[f"{prefix}direction"] = "up" if value > 0 else "down" if value < 0 else "flat"
|
|
218
|
+
result[f"{prefix}state"] = (("平", "温", "热", "沸") if value >= 0 else ("平", "凉", "寒", "冻"))[magnitude]
|
|
219
|
+
if result["score"] is None:
|
|
220
|
+
result["unavailable_reason"] = "insufficient_history" if len(df) < 60 else "zero_or_nonfinite_atr_or_score"
|
|
221
|
+
elif result["previous_state"] is not None and result["previous_state"] != result["state"]:
|
|
222
|
+
result["transition"] = f"{result['previous_state']}→{result['state']}"
|
|
223
|
+
return result
|
|
224
|
+
|
|
225
|
+
|
|
50
226
|
def macd_series(close: pd.Series) -> tuple:
|
|
51
227
|
"""Full (dif, dea, macd) series: dif = EMA12-EMA26, dea = EMA9(dif), macd = 2*(dif-dea)."""
|
|
52
228
|
dif = ema_series(close, 12) - ema_series(close, 26)
|
|
@@ -599,6 +775,14 @@ def _period_summary(result: dict) -> dict:
|
|
|
599
775
|
return {
|
|
600
776
|
"period": result["period"],
|
|
601
777
|
"trend_overall": result["trend"]["overall"],
|
|
778
|
+
"trend_score": result["trend_temperature"]["score"],
|
|
779
|
+
"trend_temperature_state": result["trend_temperature"]["state"],
|
|
780
|
+
"trend_temperature_direction": result["trend_temperature"]["direction"],
|
|
781
|
+
"trend_temperature_validation_status": result["trend_temperature"]["validation_status"],
|
|
782
|
+
"trend_temperature_as_of": result["trend_temperature"]["as_of"],
|
|
783
|
+
"trend_temperature_price_basis": result["trend_temperature"]["price_basis"],
|
|
784
|
+
"trend_temperature_unavailable_reason": result["trend_temperature"]["unavailable_reason"],
|
|
785
|
+
"trend_horizons": result["trend_horizons"],
|
|
602
786
|
"ma_arrangement": result["moving_averages"]["ma_arrangement"],
|
|
603
787
|
"macd_signal": result["macd"]["signal"],
|
|
604
788
|
"rsi_signal": result["rsi"]["signal"],
|
|
@@ -697,6 +881,8 @@ def analyze_records(symbol: str, records: list, period: str = "daily") -> dict:
|
|
|
697
881
|
"volume": vol_data,
|
|
698
882
|
"support_resistance": sr_data,
|
|
699
883
|
"trend": trend_data,
|
|
884
|
+
"trend_temperature": calc_trend_temperature(df),
|
|
885
|
+
"trend_horizons": calc_trend_horizons(df, period),
|
|
700
886
|
"bias": bias_data,
|
|
701
887
|
"signal_score": score_data["signal_score"],
|
|
702
888
|
"buy_signal": score_data["buy_signal"],
|
|
@@ -0,0 +1,365 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Stateless monthly signal plans with SMA200 eligibility and volatility budgets."""
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import math
|
|
7
|
+
import re
|
|
8
|
+
import stat
|
|
9
|
+
import sys
|
|
10
|
+
from concurrent.futures import ThreadPoolExecutor, as_completed
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import pandas as pd
|
|
15
|
+
|
|
16
|
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
|
17
|
+
|
|
18
|
+
from _subproc import run_tool, utf8_stdio
|
|
19
|
+
from stock_data import detect_market
|
|
20
|
+
from technical import _trend_prices, ma_series
|
|
21
|
+
|
|
22
|
+
MODEL = "sma200_risk_budget"
|
|
23
|
+
ALLOCATION = 0.8704
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def iso_date(value):
|
|
27
|
+
if not isinstance(value, str) or not re.fullmatch(r"\d{4}-\d{2}-\d{2}", value):
|
|
28
|
+
raise ValueError("as_of and price dates require YYYY-MM-DD")
|
|
29
|
+
day = pd.Timestamp(value)
|
|
30
|
+
if pd.isna(day) or str(day.date()) != value:
|
|
31
|
+
raise ValueError("Invalid date")
|
|
32
|
+
return day
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def symbol_set(payload, key, names):
|
|
36
|
+
values = payload.get(key, [])
|
|
37
|
+
if not isinstance(values, list) or any(type(n) is not str for n in values):
|
|
38
|
+
raise ValueError(f"{key} must be a list of unique pool symbols")
|
|
39
|
+
if len(values) != len(set(values)) or not set(values) <= names:
|
|
40
|
+
raise ValueError(f"{key} must contain unique pool symbols")
|
|
41
|
+
return set(values)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def symbol_identity(name, market):
|
|
45
|
+
return int(name[:-3]) if market == "HK" else name.replace(".", "-")
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def pool_members(symbols, market):
|
|
49
|
+
patterns = {"A": r"\d{6}", "HK": r"\d{4,5}\.HK", "US": r"[A-Z][A-Z0-9.-]{0,14}"}
|
|
50
|
+
if market not in patterns:
|
|
51
|
+
raise ValueError("Rule62 supports a single A, HK or US stock pool")
|
|
52
|
+
if not isinstance(symbols, list) or not 1 <= len(symbols) <= 100:
|
|
53
|
+
raise ValueError("A pool requires 1..100 distinct stocks")
|
|
54
|
+
if any(type(n) is not str or not re.fullmatch(patterns[market], n) or detect_market(n) != market for n in symbols):
|
|
55
|
+
raise ValueError("Symbols must be stocks from the declared single market")
|
|
56
|
+
names = sorted(symbols, key=lambda n: symbol_identity(n, market))
|
|
57
|
+
if len({symbol_identity(n, market) for n in names}) != len(names):
|
|
58
|
+
raise ValueError("Duplicate symbol aliases")
|
|
59
|
+
return names
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def pool_state(payload, names):
|
|
63
|
+
held = symbol_set(payload, "held_symbols", set(names))
|
|
64
|
+
pending = symbol_set(payload, "pending_exit_symbols", set(names))
|
|
65
|
+
if not pending <= held:
|
|
66
|
+
raise ValueError("pending_exit_symbols must be real held_symbols")
|
|
67
|
+
slots = payload.get("slots", math.ceil(len(names) / 3))
|
|
68
|
+
if type(slots) not in (int, float) or not 1 <= slots <= len(names) or int(slots) != slots or len(held) > slots:
|
|
69
|
+
raise ValueError("slots requires an integer in 1..N and cannot be below actual held count")
|
|
70
|
+
return held, pending, int(slots)
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def analyze(payload):
|
|
74
|
+
allowed = {"market", "as_of", "histories", "slots", "held_symbols", "pending_exit_symbols"}
|
|
75
|
+
if not isinstance(payload, dict) or set(payload) - allowed:
|
|
76
|
+
raise ValueError("Expected strategy input with only documented fields; corporate actions are not supported")
|
|
77
|
+
market = payload["market"]
|
|
78
|
+
as_of = iso_date(payload["as_of"])
|
|
79
|
+
histories = payload["histories"]
|
|
80
|
+
if not isinstance(histories, dict):
|
|
81
|
+
raise ValueError("histories requires distinct stocks")
|
|
82
|
+
names = pool_members(list(histories), market)
|
|
83
|
+
held, pending, slots = pool_state(payload, names)
|
|
84
|
+
stocks, calendar, known_vol = {}, set(), {}
|
|
85
|
+
for name in names:
|
|
86
|
+
records = histories[name]
|
|
87
|
+
if not isinstance(records, list) or not 1 <= len(records) <= 20000:
|
|
88
|
+
raise ValueError("Each history requires 1..20000 dated price rows")
|
|
89
|
+
for row in records:
|
|
90
|
+
if not isinstance(row, dict) or not {"date", "close", "volume"} <= row.keys():
|
|
91
|
+
raise ValueError("Each price row requires date, close and volume")
|
|
92
|
+
iso_date(row["date"])
|
|
93
|
+
if any(type(row[k]) not in (int, float) for k in ("close", "volume")):
|
|
94
|
+
raise ValueError("close and volume must be numbers, excluding booleans")
|
|
95
|
+
frame = pd.DataFrame(records)
|
|
96
|
+
frame["date"] = pd.to_datetime(frame.date)
|
|
97
|
+
# Validate chronology before cutting the prefix; never silently sort duplicate/bad input.
|
|
98
|
+
_trend_prices(frame)
|
|
99
|
+
frame = frame.loc[frame.date <= as_of]
|
|
100
|
+
if frame.empty:
|
|
101
|
+
raise ValueError("Every pool member needs history at or before as_of")
|
|
102
|
+
close, dates = _trend_prices(frame)
|
|
103
|
+
calendar.update(dates)
|
|
104
|
+
average = ma_series(close, 200)
|
|
105
|
+
returns = np.log(close).diff()
|
|
106
|
+
sigma = returns.rolling(63).std(ddof=1)
|
|
107
|
+
sigma = sigma.mask(returns.rolling(63).min().eq(returns.rolling(63).max()), 0.0)
|
|
108
|
+
available = not dates.empty and dates.iloc[-1] == as_of
|
|
109
|
+
|
|
110
|
+
def last(series, available=available):
|
|
111
|
+
value = series.iloc[-1] if available and not series.empty else np.nan
|
|
112
|
+
return float(value) if np.isfinite(value) else None
|
|
113
|
+
|
|
114
|
+
score = last(np.log(close) - np.log(average))
|
|
115
|
+
volatility = last(sigma)
|
|
116
|
+
if volatility is not None and volatility > 0:
|
|
117
|
+
known_vol[name] = volatility
|
|
118
|
+
basis = str(frame.adjusted.iloc[-1]) if "adjusted" in frame and pd.notna(frame.adjusted.iloc[-1]) else "unknown"
|
|
119
|
+
stocks[name] = {
|
|
120
|
+
"quote_available": bool(available),
|
|
121
|
+
"quote_as_of": str(dates.iloc[-1].date()) if not dates.empty else None,
|
|
122
|
+
"price_basis": basis,
|
|
123
|
+
"valid_bars": len(close),
|
|
124
|
+
"close": last(close),
|
|
125
|
+
"sma200": last(average),
|
|
126
|
+
"sma200_21_bars_ago": last(average.shift(21)),
|
|
127
|
+
"distance": score,
|
|
128
|
+
"sigma63": volatility,
|
|
129
|
+
"rising_sma200": bool(available and len(close) >= 221 and average.iloc[-1] > average.shift(21).iloc[-1]),
|
|
130
|
+
"new_entry_eligible": False,
|
|
131
|
+
"action": "wait",
|
|
132
|
+
"reason": "not_monthly_observation",
|
|
133
|
+
"new_budget_fraction": 0.0,
|
|
134
|
+
}
|
|
135
|
+
stocks[name]["new_entry_eligible"] = bool(
|
|
136
|
+
score is not None and score > 0 and stocks[name]["rising_sma200"] and name in known_vol
|
|
137
|
+
)
|
|
138
|
+
month_dates = [day for day in calendar if day.to_period("M") == as_of.to_period("M")]
|
|
139
|
+
monthly = bool(month_dates and min(month_dates) == as_of)
|
|
140
|
+
selected = []
|
|
141
|
+
reference = float(np.median(list(known_vol.values()))) if known_vol else None
|
|
142
|
+
insufficient_held = any(stocks[n]["quote_available"] and stocks[n]["sma200"] is None for n in held - pending)
|
|
143
|
+
status = "monthly_observation" if monthly else "waiting_for_monthly_observation"
|
|
144
|
+
if insufficient_held:
|
|
145
|
+
status = "insufficient_held_history"
|
|
146
|
+
if monthly and not insufficient_held:
|
|
147
|
+
retained = [
|
|
148
|
+
n for n in names if n in held - pending and (not stocks[n]["quote_available"] or stocks[n]["distance"] > 0)
|
|
149
|
+
]
|
|
150
|
+
ranked = sorted(
|
|
151
|
+
(n for n in names if n not in held and stocks[n]["new_entry_eligible"]),
|
|
152
|
+
key=lambda n: (-stocks[n]["distance"], symbol_identity(n, market)),
|
|
153
|
+
)
|
|
154
|
+
selected = retained + ranked[: max(0, slots - len(retained))]
|
|
155
|
+
for name, row in stocks.items():
|
|
156
|
+
if name in retained:
|
|
157
|
+
row.update(
|
|
158
|
+
action="hold",
|
|
159
|
+
reason="positive_stock_trend" if row["quote_available"] else "unobservable_held_reserves_slot",
|
|
160
|
+
)
|
|
161
|
+
elif name in held - pending:
|
|
162
|
+
row.update(action="exit_next_valid_open", reason="monthly_sma200_nonpositive")
|
|
163
|
+
elif name in selected:
|
|
164
|
+
row.update(
|
|
165
|
+
action="entry_candidate_next_valid_open",
|
|
166
|
+
reason="rising_sma200_ranked_vacancy",
|
|
167
|
+
new_budget_fraction=ALLOCATION / slots * min(1.0, reference / known_vol[name]),
|
|
168
|
+
)
|
|
169
|
+
else:
|
|
170
|
+
row["reason"] = "capacity_reserved" if row["new_entry_eligible"] else "entry_conditions_not_met"
|
|
171
|
+
for name in pending:
|
|
172
|
+
stocks[name].update(action="exit_pending", reason="previously_locked_exit")
|
|
173
|
+
return {
|
|
174
|
+
"model": MODEL,
|
|
175
|
+
"validation_status": "not_validated",
|
|
176
|
+
"kind": "monthly_signal_plan",
|
|
177
|
+
"market": market,
|
|
178
|
+
"as_of": str(as_of.date()),
|
|
179
|
+
"status": status,
|
|
180
|
+
"observation_date": str(as_of.date()) if monthly else None,
|
|
181
|
+
"last_available_date": str(max(calendar).date()) if calendar else None,
|
|
182
|
+
"portfolio_state": "explicit_held_symbols" if held else "initially_flat",
|
|
183
|
+
"slots": slots,
|
|
184
|
+
"allocation": ALLOCATION,
|
|
185
|
+
"reference_volatility": reference,
|
|
186
|
+
"selected": selected,
|
|
187
|
+
"stocks": stocks,
|
|
188
|
+
"execution": {
|
|
189
|
+
"requires_available_cash_and_capacity": True,
|
|
190
|
+
"budget_basis": "next_execution_batch_open_nav_times_new_budget_fraction_including_buy_costs",
|
|
191
|
+
"budget_is_not_target_weight": True,
|
|
192
|
+
"existing_holdings_are_not_resized": True,
|
|
193
|
+
"sell_before_buy": True,
|
|
194
|
+
"fills_or_quantities_calculated": False,
|
|
195
|
+
},
|
|
196
|
+
"validation": {
|
|
197
|
+
"development_gates": "passed",
|
|
198
|
+
"expanded_and_historical_pools": "failed",
|
|
199
|
+
"independent_validation": "not_completed",
|
|
200
|
+
},
|
|
201
|
+
"warnings": [
|
|
202
|
+
"Caller must provide complete daily history through a closed as_of bar, consistent adjusted prices and the real holdings at as_of. Missing pool members change ranking and the volatility median.",
|
|
203
|
+
"Only the first observed positive-volume stock-pool close of the month creates new plans. Mid-month output does not replay past decisions or reconstruct orders.",
|
|
204
|
+
"Budgets are conditional cash limits, not share quantities, target weights or fills. Locked exits require actual execution before cash/capacity is reused; no daily re-entry or averaging down.",
|
|
205
|
+
"Corporate-action conversion, raw-share lots, settlement, trading limits and fees require separate execution checks. No account is stored and no orders are submitted.",
|
|
206
|
+
"Development gates passed only on the development sample. Expanded and historical pools failed; allocation .8704 was fitted. This is not the private Trend Animal temperature or a forecast of fat-tail returns.",
|
|
207
|
+
],
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
|
|
211
|
+
def latest_closed_date(market, now=None):
|
|
212
|
+
import exchange_calendars as xcals
|
|
213
|
+
|
|
214
|
+
calendar = xcals.get_calendar({"A": "XSHG", "HK": "XHKG", "US": "XNYS"}[market])
|
|
215
|
+
now = pd.Timestamp.now(tz="UTC") if now is None else pd.Timestamp(now)
|
|
216
|
+
if now.tzinfo is None:
|
|
217
|
+
raise ValueError("Current time must include a timezone")
|
|
218
|
+
local_date = str(now.tz_convert(calendar.tz).date())
|
|
219
|
+
session = calendar.date_to_session(local_date, direction="previous")
|
|
220
|
+
# XHKG calendars end continuous trading; its closing auction can run ten more minutes.
|
|
221
|
+
close = calendar.session_close(session) + pd.Timedelta(minutes=10 if market == "HK" else 0)
|
|
222
|
+
if now <= close:
|
|
223
|
+
session = calendar.previous_session(session)
|
|
224
|
+
return str(session.date())
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
def request_symbol(name):
|
|
228
|
+
name = name.strip().upper()
|
|
229
|
+
if re.fullmatch(r"\d{4,5}\.HK", name):
|
|
230
|
+
return f"{int(name[:-3]):04d}.HK"
|
|
231
|
+
return name.replace(".", "-") if detect_market(name) == "US" else name
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
def _fetch_daily_history(symbol, count):
|
|
235
|
+
return run_tool("stock_data.py", ["kline", symbol, "--period", "daily", "--count", str(count)], timeout=30)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def fetch_plan(request):
|
|
239
|
+
allowed = {"symbols", "as_of", "held_symbols", "pending_exit_symbols", "slots"}
|
|
240
|
+
if not isinstance(request, dict) or set(request) - allowed:
|
|
241
|
+
raise ValueError("Expected symbols and optional as_of/held_symbols/pending_exit_symbols/slots")
|
|
242
|
+
symbols = request["symbols"]
|
|
243
|
+
if not isinstance(symbols, list) or not 1 <= len(symbols) <= 100 or any(type(n) is not str for n in symbols):
|
|
244
|
+
raise ValueError("symbols must be a nonempty list of stock codes")
|
|
245
|
+
symbols = [request_symbol(n) for n in symbols]
|
|
246
|
+
markets = {detect_market(n) for n in symbols}
|
|
247
|
+
if len(markets) != 1:
|
|
248
|
+
raise ValueError("A pool must contain a single market")
|
|
249
|
+
market = markets.pop()
|
|
250
|
+
names = pool_members(symbols, market)
|
|
251
|
+
state = {}
|
|
252
|
+
for key in ("held_symbols", "pending_exit_symbols"):
|
|
253
|
+
values = request.get(key, [])
|
|
254
|
+
if not isinstance(values, list) or any(type(n) is not str for n in values):
|
|
255
|
+
raise ValueError("Held and pending symbols require lists of codes")
|
|
256
|
+
state[key] = [request_symbol(n) for n in values]
|
|
257
|
+
if "slots" in request:
|
|
258
|
+
state["slots"] = request["slots"]
|
|
259
|
+
pool_state(state, names)
|
|
260
|
+
try:
|
|
261
|
+
closed = latest_closed_date(market)
|
|
262
|
+
except Exception:
|
|
263
|
+
return {
|
|
264
|
+
"error": "Exchange calendar unavailable; cannot identify a completed daily bar",
|
|
265
|
+
"error_code": "calendar_unavailable",
|
|
266
|
+
}
|
|
267
|
+
as_of = iso_date(request.get("as_of", closed))
|
|
268
|
+
if as_of > iso_date(closed):
|
|
269
|
+
raise ValueError("as_of must not be later than the most recently completed exchange session")
|
|
270
|
+
count = 360 + (iso_date(closed) - as_of).days
|
|
271
|
+
if count > 20000 or count * len(names) > 200000:
|
|
272
|
+
raise ValueError("Requested date exceeds the supported price history")
|
|
273
|
+
histories, failed = {}, []
|
|
274
|
+
with ThreadPoolExecutor(max_workers=min(6, len(names))) as pool:
|
|
275
|
+
futures = {pool.submit(_fetch_daily_history, name, count): name for name in names}
|
|
276
|
+
for future in as_completed(futures):
|
|
277
|
+
name = futures[future]
|
|
278
|
+
try:
|
|
279
|
+
records = future.result()
|
|
280
|
+
except Exception:
|
|
281
|
+
records = None
|
|
282
|
+
if not isinstance(records, list) or not records or len(records) > count:
|
|
283
|
+
failed.append(name)
|
|
284
|
+
else:
|
|
285
|
+
histories[name] = records
|
|
286
|
+
if failed:
|
|
287
|
+
return {
|
|
288
|
+
"error": "Cannot load the complete stock pool; no strategy plan was produced",
|
|
289
|
+
"error_code": "incomplete_pool",
|
|
290
|
+
"failed_symbols": sorted(failed),
|
|
291
|
+
}
|
|
292
|
+
try:
|
|
293
|
+
result = analyze({"market": market, "as_of": str(as_of.date()), "histories": histories, **state})
|
|
294
|
+
except (KeyError, TypeError, ValueError, OverflowError):
|
|
295
|
+
return {
|
|
296
|
+
"error": "Fetched daily prices failed validation; no strategy plan was produced",
|
|
297
|
+
"error_code": "invalid_market_data",
|
|
298
|
+
}
|
|
299
|
+
result["data_acquisition"] = {
|
|
300
|
+
"source": "stock_data.py:kline",
|
|
301
|
+
"symbols": names,
|
|
302
|
+
"requested_count": count,
|
|
303
|
+
"latest_closed_session": closed,
|
|
304
|
+
}
|
|
305
|
+
result["warnings"][0] = (
|
|
306
|
+
"Daily histories were fetched for the entire requested pool. Verify provider adjustment and quote dates; held_symbols must describe real holdings at as_of."
|
|
307
|
+
)
|
|
308
|
+
return result
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def unique_object(pairs):
|
|
312
|
+
result = {}
|
|
313
|
+
for key, value in pairs:
|
|
314
|
+
if key in result:
|
|
315
|
+
raise ValueError("Duplicate JSON object key")
|
|
316
|
+
result[key] = value
|
|
317
|
+
return result
|
|
318
|
+
|
|
319
|
+
|
|
320
|
+
class Parser(argparse.ArgumentParser):
|
|
321
|
+
def error(self, message):
|
|
322
|
+
raise ValueError(message)
|
|
323
|
+
|
|
324
|
+
|
|
325
|
+
def main():
|
|
326
|
+
utf8_stdio()
|
|
327
|
+
parser = Parser(description=__doc__)
|
|
328
|
+
parser.add_argument(
|
|
329
|
+
"action", nargs="?", choices=["fetch"], help="Fetch prices from stock codes; omit only for offline snapshots"
|
|
330
|
+
)
|
|
331
|
+
parser.add_argument("--input", required=True, help="Internal UTF-8 request JSON or offline snapshot file")
|
|
332
|
+
try:
|
|
333
|
+
args = parser.parse_args()
|
|
334
|
+
except ValueError:
|
|
335
|
+
print(
|
|
336
|
+
json.dumps({"error": "Invalid command arguments; use --help for usage", "error_code": "invalid_arguments"})
|
|
337
|
+
)
|
|
338
|
+
return 1
|
|
339
|
+
try:
|
|
340
|
+
path = Path(args.input)
|
|
341
|
+
info = path.stat()
|
|
342
|
+
limit = 32 * 1024 * 1024
|
|
343
|
+
if not stat.S_ISREG(info.st_mode) or info.st_size > limit:
|
|
344
|
+
raise ValueError("Input requires a regular JSON file up to 32 MiB")
|
|
345
|
+
with path.open("rb") as source:
|
|
346
|
+
raw = source.read(limit + 1)
|
|
347
|
+
if len(raw) > limit:
|
|
348
|
+
raise ValueError("Input JSON exceeds 32 MiB")
|
|
349
|
+
payload = json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object)
|
|
350
|
+
result = fetch_plan(payload) if args.action == "fetch" else analyze(payload)
|
|
351
|
+
except (KeyError, TypeError, ValueError, OverflowError, RecursionError):
|
|
352
|
+
result = {
|
|
353
|
+
"error": "Invalid stock-pool request; use one market and check codes, dates, holdings and slots"
|
|
354
|
+
if args.action == "fetch"
|
|
355
|
+
else "Invalid trend strategy input; check documented dates, symbols, prices, holdings and slots",
|
|
356
|
+
"error_code": "invalid_request" if args.action == "fetch" else "invalid_snapshot",
|
|
357
|
+
}
|
|
358
|
+
except OSError:
|
|
359
|
+
result = {"error": "Cannot read trend strategy input JSON file"}
|
|
360
|
+
print(json.dumps(result, ensure_ascii=False, allow_nan=False))
|
|
361
|
+
return 1 if "error" in result else 0
|
|
362
|
+
|
|
363
|
+
|
|
364
|
+
if __name__ == "__main__":
|
|
365
|
+
raise SystemExit(main())
|