@weaxs/openclaw-stock-analysis 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 CHANGED
@@ -1,6 +1,6 @@
1
1
  # Stock Analysis — OpenClaw Plugin
2
2
 
3
- A股 / 港股 / 美股 / 日股 / 韩股 / 台股 行情、技术分析、筛选与回测。OpenClaw Gateway 加载后即可在对话中调用 67 个工具。
3
+ A股 / 港股 / 美股 / 日股 / 韩股 / 台股 行情、技术分析、筛选与回测。OpenClaw Gateway 加载后即可在对话中调用 68 个工具。
4
4
 
5
5
  ## 安装
6
6
 
package/dist/index.js CHANGED
@@ -55,7 +55,8 @@ var cli_budgets_default = {
55
55
  l2_workers: 6,
56
56
  watchlist_item: 480,
57
57
  "stateless_analysis.py:event_study": 300,
58
- "stateless_analysis.py:robustness": 660
58
+ "stateless_analysis.py:robustness": 660,
59
+ "trend_strategy.py:fetch": 660
59
60
  };
60
61
 
61
62
  // scripts/cli-timeout.mjs
@@ -4939,7 +4940,7 @@ var index_default = definePluginEntry({
4939
4940
  });
4940
4941
  api.registerTool({
4941
4942
  name: "get_technical_analysis",
4942
- description: "\u83B7\u53D6\u80A1\u7968\u6280\u672F\u9762\u5206\u6790\uFF08MA/MACD/RSI/BOLL/KDJ/\u6210\u4EA4\u91CF\u7B49\u6307\u6807 + 100\u5206\u7EFC\u5408\u8BC4\u5206 + 6\u7EA7\u4E70\u5356\u4FE1\u53F7 + \u8D8B\u52BF/\u504F\u79BB\u5EA6/\u652F\u6491\u538B\u529B\u4F4D\uFF1B\u591A\u5468\u671F\u5171\u632F\u65F6 resonance.direction \u2208 aligned_bullish/aligned_bearish/divergent\uFF09\u3002\u4E2A\u80A1\u6280\u672F\u9762\u7EFC\u5408\u5224\u65AD\u4E0E\u4E70\u5356\u65F6\u673A\u5206\u6790\u7684\u9996\u9009\uFF1B\u53EA\u8981\u5747\u7EBF\u6570\u503C\u6216\u81EA\u5B9A\u4E49\u5468\u671F\u7528 calculate_ma\uFF0C\u4E13\u95EE\u91CF\u4EF7\u7528 get_volume_analysis\uFF0C\u626B\u5F53\u65E5\u5F02\u52A8\u7528 detect_anomaly",
4943
+ description: "\u83B7\u53D6\u80A1\u7968\u6280\u672F\u9762\u5206\u6790\uFF08MA/MACD/RSI/BOLL/KDJ/\u6210\u4EA4\u91CF\u7B49\u6307\u6807 + 100\u5206\u7EFC\u5408\u8BC4\u5206 + 6\u7EA7\u4E70\u5356\u4FE1\u53F7 + \u8D8B\u52BF/\u504F\u79BB\u5EA6/\u652F\u6491\u538B\u529B\u4F4D\uFF1B\u9644 trend_temperature\uFF08\u5B9E\u9A8C\u6027EMA\u5DEE/ATR\u63CF\u8FF0\uFF1Bdirection\u4E3A\u5747\u7EBF\u65B9\u5411\uFF1Bvalidation_status=not_validated\uFF0C\u975E\u661F\u7403\u6307\u6807\uFF0C\u4E03\u6863\u4E0D\u4F5C\u5165\u573A\u4F9D\u636E\uFF1B\u53E6\u9644 trend_horizons\uFF1A21/63/252\u6839\u65E5K\u6708\u5EA6\u52A8\u91CF\uFF0C\u5EFA\u8BAEcount=360\uFF0C\u975E\u6982\u7387\u3001\u672A\u9A8C\u8BC1\uFF09\uFF1B\u591A\u5468\u671F\u5171\u632F\u65F6 resonance.direction \u2208 aligned_bullish/aligned_bearish/divergent\uFF09\u3002\u4E2A\u80A1\u6280\u672F\u9762\u7EFC\u5408\u5224\u65AD\u4E0E\u4E70\u5356\u65F6\u673A\u5206\u6790\u7684\u9996\u9009\uFF1B\u53EA\u8981\u5747\u7EBF\u6570\u503C\u6216\u81EA\u5B9A\u4E49\u5468\u671F\u7528 calculate_ma\uFF0C\u4E13\u95EE\u91CF\u4EF7\u7528 get_volume_analysis\uFF0C\u626B\u5F53\u65E5\u5F02\u52A8\u7528 detect_anomaly",
4943
4944
  parameters: typebox_exports.Object({
4944
4945
  symbol: typebox_exports.String({ description: "\u80A1\u7968\u4EE3\u7801\uFF08A\u80A1\u5982600519\uFF0C\u7F8E\u80A1\u5982AAPL\uFF0C\u6E2F\u80A1\u598200700.HK\uFF09" }),
4945
4946
  period: typebox_exports.Optional(
@@ -5262,9 +5263,23 @@ var index_default = definePluginEntry({
5262
5263
  return asText(out);
5263
5264
  }
5264
5265
  });
5266
+ api.registerTool({
5267
+ name: "analyze_trend_strategy",
5268
+ description: "\u6708\u5EA6\u53F3\u4FA7\u8D8B\u52BF\u7B56\u7565\uFF1A\u76F4\u63A5\u4F20\u540C\u5E02\u573AA/HK/US\u80A1\u7968\u4EE3\u7801\uFF0C\u81EA\u52A8\u83B7\u53D6\u65E5K\uFF0C\u8F93\u51FA\u6708\u5EA6\u65B0\u5165/\u6301\u6709/\u9000\u51FA\u4E0E\u9006\u6CE2\u52A8\u9884\u7B97\u3002as_of\u9ED8\u8BA4\u6700\u8FD1\u5DF2\u6536\u76D8\u4EA4\u6613\u65E5\uFF0C\u6301\u4ED3\u53EF\u9009\u4E14\u4E0D\u4FDD\u5B58\uFF0C\u4E0D\u81EA\u52A8\u4E0B\u5355\uFF1B\u8DE8\u6837\u672C\u4ECDnot_validated\u3002",
5269
+ parameters: typebox_exports.Object({
5270
+ symbols: typebox_exports.Array(typebox_exports.String(), { description: "\u540C\u4E00\u5E02\u573A\u7684\u5B8C\u6574\u80A1\u7968\u6C60\uFF0C1..100\u53EA\uFF1BA\u5982600036\uFF0CHK\u59820700.HK\uFF0CUS\u5982AAPL" }),
5271
+ as_of: typebox_exports.Optional(typebox_exports.String({ description: "\u53EF\u9009\u5DF2\u6536\u76D8\u622A\u6B62\u65E5\u671FYYYY-MM-DD\uFF0C\u9ED8\u8BA4\u8BE5\u5E02\u573A\u6700\u8FD1\u5DF2\u6536\u76D8\u4EA4\u6613\u65E5" })),
5272
+ held_symbols: typebox_exports.Optional(typebox_exports.Array(typebox_exports.String(), { description: "\u53EF\u9009\uFF0Cas_of\u65F6\u771F\u5B9E\u6301\u80A1\u4EE3\u7801\uFF0C\u5FC5\u987B\u5728\u80A1\u7968\u6C60\u4E2D\uFF1B\u7701\u7565\u4EE3\u8868\u521D\u59CB\u7A7A\u4ED3\uFF0C\u4E0D\u4FDD\u5B58\u8D26\u6237" })),
5273
+ pending_exit_symbols: typebox_exports.Optional(typebox_exports.Array(typebox_exports.String(), { description: "\u53EF\u9009\uFF0C\u771F\u5B9E\u6301\u80A1\u4E2D\u6B64\u524D\u5DF2\u9501\u5B9A\u4E14\u672A\u6210\u4EA4\u7684\u9000\u51FA\u4EE3\u7801" })),
5274
+ slots: typebox_exports.Optional(typebox_exports.Number({ description: "\u53EF\u9009\u56FA\u5B9A\u5BB9\u91CFK\uFF0C\u9ED8\u8BA4ceil(N/3)\uFF0C\u4E0D\u5F97\u5C0F\u4E8E\u771F\u5B9E\u6301\u80A1\u6570\u91CF" }))
5275
+ }, { additionalProperties: false }),
5276
+ async execute(_id, params) {
5277
+ return asText(await withJsonInput(params, (path) => runPy("trend_strategy.py", ["fetch", "--input", path])));
5278
+ }
5279
+ });
5265
5280
  api.registerTool({
5266
5281
  name: "run_backtest",
5267
- description: "\u7B56\u7565\u56DE\u6D4B\uFF08AlphaEvo\uFF09\u3002\u8BFB\u53D6YAML\u7B56\u7565\u5B9A\u4E49\uFF0C\u5728\u5386\u53F2\u6570\u636E\u4E0A\u6A21\u62DF\u4EA4\u6613\uFF0C\u8F93\u51FA\u6536\u76CA\u7387/\u56DE\u64A4/\u80DC\u7387\u7B49\u6307\u6807\u3002\u53EA\u60F3\u77E5\u9053\u5355\u4E2A\u6280\u672F\u4FE1\u53F7\u7684\u5386\u53F2\u80DC\u7387\u7528\u66F4\u8F7B\u91CF\u7684 evaluate_signal\u3002period\u4E3A\u5B9E\u9645\u6570\u636E\u671F\u95F4\uFF0Crequested_period\u4FDD\u7559\u8BF7\u6C42\u671F\u95F4\uFF0Cwarnings\u63D0\u793A\u8986\u76D6\u5DEE\u5F02\uFF1B\u5E74\u5316\u6309\u5B9E\u9645\u671F\u95F4\u8BA1\u7B97\u3002\u9ED8\u8BA4\u524D\u65E5\u6536\u76D8\u4FE1\u53F7\u3001\u6B21\u65E5\u5F00\u76D8\u6210\u4EA4\uFF1BYAML simulation.execution=same_close\u53EF\u590D\u73B0\u65E7\u5047\u8BBE\u3002execution\u8FD4\u56DE\u6A21\u578B\u3001\u963B\u6B62\u6210\u4EA4\u6B21\u6570\u548C\u672A\u6A21\u62DF\u7EA6\u675F\uFF1B\u96F6\u6210\u4EA4\u91CF\u53CA\u5E26\u5386\u53F2\u9650\u4EF7\u7684\u4E00\u5B57\u677F\u4E0D\u6210\u4EA4\u3002",
5282
+ description: "\u7B56\u7565\u56DE\u6D4B\uFF08AlphaEvo\uFF09\u3002\u8BFB\u53D6YAML\u7B56\u7565\u5B9A\u4E49\uFF0C\u5728\u5386\u53F2\u6570\u636E\u4E0A\u6A21\u62DF\u4EA4\u6613\uFF0C\u8F93\u51FA\u6536\u76CA\u7387/\u56DE\u64A4/\u80DC\u7387\u7B49\u6307\u6807\u3002\u53EA\u60F3\u77E5\u9053\u5355\u4E2A\u6280\u672F\u4FE1\u53F7\u7684\u5386\u53F2\u80DC\u7387\u7528\u66F4\u8F7B\u91CF\u7684 evaluate_signal\u3002period\u4E3A\u5B9E\u9645\u6570\u636E\u671F\u95F4\uFF0Crequested_period\u4FDD\u7559\u8BF7\u6C42\u671F\u95F4\uFF0Cwarnings\u63D0\u793A\u8986\u76D6\u5DEE\u5F02\uFF1B\u5E74\u5316\u6309\u5B9E\u9645\u671F\u95F4\u8BA1\u7B97\u3002\u9ED8\u8BA4\u524D\u65E5\u6536\u76D8\u4FE1\u53F7\u3001\u6B21\u65E5\u5F00\u76D8\u6210\u4EA4\uFF1BYAML simulation.execution=same_close\u53EF\u590D\u73B0\u65E7\u5047\u8BBE\u3002execution\u8FD4\u56DE\u6A21\u578B\u3001\u963B\u6B62\u6210\u4EA4\u6B21\u6570\u548C\u672A\u6A21\u62DF\u7EA6\u675F\uFF1B\u96F6\u6210\u4EA4\u91CF\u53CA\u5E26\u5386\u53F2\u9650\u4EF7\u7684\u4E00\u5B57\u677F\u4E0D\u6210\u4EA4\u3002\u652F\u6301 monthly_momentum\uFF1A\u6708\u521D\u9996\u6839\u6709\u6548\u65E5K\u6536\u76D8\u89C2\u5BDF\u8FC7\u53BBperiod\u6839\u5BF9\u6570\u6536\u76CA\uFF0C\u6B21\u65E5\u5F00\u76D8\uFF1B\u957F\u5468\u671F\u9700\u9884\u70ED\u3002",
5268
5283
  parameters: typebox_exports.Object({
5269
5284
  strategy: typebox_exports.String({ description: "\u7B56\u7565YAML\u6587\u4EF6\u8DEF\u5F84" }),
5270
5285
  symbol: typebox_exports.String({ description: "\u80A1\u7968\u4EE3\u7801\uFF08A\u80A1\u5982600519\uFF0C\u7F8E\u80A1\u5982AAPL\uFF0C\u6E2F\u80A1\u598200700.HK\uFF09" }),
package/index.ts CHANGED
@@ -494,7 +494,7 @@ export default definePluginEntry({
494
494
  api.registerTool({
495
495
  name: "get_technical_analysis",
496
496
  description:
497
- "获取股票技术面分析(MA/MACD/RSI/BOLL/KDJ/成交量等指标 + 100分综合评分 + 6级买卖信号 + 趋势/偏离度/支撑压力位;多周期共振时 resonance.direction ∈ aligned_bullish/aligned_bearish/divergent)。个股技术面综合判断与买卖时机分析的首选;只要均线数值或自定义周期用 calculate_ma,专问量价用 get_volume_analysis,扫当日异动用 detect_anomaly",
497
+ "获取股票技术面分析(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",
498
498
  parameters: Type.Object({
499
499
  symbol: Type.String({ description: "股票代码(A股如600519,美股如AAPL,港股如00700.HK)" }),
500
500
  period: Type.Optional(
@@ -851,10 +851,26 @@ export default definePluginEntry({
851
851
  },
852
852
  });
853
853
 
854
+ api.registerTool({
855
+ name: "analyze_trend_strategy",
856
+ description: "月度右侧趋势策略:直接传同市场A/HK/US股票代码,自动获取日K,输出月度新入/持有/退出与逆波动预算。as_of默认最近已收盘交易日,持仓可选且不保存,不自动下单;跨样本仍not_validated。",
857
+ parameters: Type.Object({
858
+ symbols: Type.Array(Type.String(), { description: "同一市场的完整股票池,1..100只;A如600036,HK如0700.HK,US如AAPL" }),
859
+ as_of: Type.Optional(Type.String({ description: "可选已收盘截止日期YYYY-MM-DD,默认该市场最近已收盘交易日" })),
860
+ held_symbols: Type.Optional(Type.Array(Type.String(), { description: "可选,as_of时真实持股代码,必须在股票池中;省略代表初始空仓,不保存账户" })),
861
+ pending_exit_symbols: Type.Optional(Type.Array(Type.String(), { description: "可选,真实持股中此前已锁定且未成交的退出代码" })),
862
+ slots: Type.Optional(Type.Number({ description: "可选固定容量K,默认ceil(N/3),不得小于真实持股数量" })),
863
+ }, { additionalProperties: false }),
864
+ async execute(_id, params) {
865
+ return asText(await withJsonInput(params, (path: string) =>
866
+ runPy("trend_strategy.py", ["fetch", "--input", path])));
867
+ },
868
+ });
869
+
854
870
  api.registerTool({
855
871
  name: "run_backtest",
856
872
  description:
857
- "策略回测(AlphaEvo)。读取YAML策略定义,在历史数据上模拟交易,输出收益率/回撤/胜率等指标。只想知道单个技术信号的历史胜率用更轻量的 evaluate_signal。period为实际数据期间,requested_period保留请求期间,warnings提示覆盖差异;年化按实际期间计算。默认前日收盘信号、次日开盘成交;YAML simulation.execution=same_close可复现旧假设。execution返回模型、阻止成交次数和未模拟约束;零成交量及带历史限价的一字板不成交。",
873
+ "策略回测(AlphaEvo)。读取YAML策略定义,在历史数据上模拟交易,输出收益率/回撤/胜率等指标。只想知道单个技术信号的历史胜率用更轻量的 evaluate_signal。period为实际数据期间,requested_period保留请求期间,warnings提示覆盖差异;年化按实际期间计算。默认前日收盘信号、次日开盘成交;YAML simulation.execution=same_close可复现旧假设。execution返回模型、阻止成交次数和未模拟约束;零成交量及带历史限价的一字板不成交。支持 monthly_momentum:月初首根有效日K收盘观察过去period根对数收益,次日开盘;长周期需预热。",
858
874
  parameters: Type.Object({
859
875
  strategy: Type.String({ description: "策略YAML文件路径" }),
860
876
  symbol: Type.String({ description: "股票代码(A股如600519,美股如AAPL,港股如00700.HK)" }),
@@ -70,7 +70,8 @@
70
70
  "calculate_position_size",
71
71
  "analyze_event_study",
72
72
  "validate_backtest",
73
- "compare_analysis_snapshots"
73
+ "compare_analysis_snapshots",
74
+ "analyze_trend_strategy"
74
75
  ]
75
76
  },
76
77
  "activation": {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@weaxs/openclaw-stock-analysis",
3
- "version": "0.2.7",
3
+ "version": "0.2.8",
4
4
  "description": "OpenClaw plugin for stock analysis, screening, and strategy backtesting across A/HK/US/JP/KR/TW markets",
5
5
  "type": "module",
6
6
  "main": "./index.ts",
@@ -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 bollinger_series, ema_series, ma_series, macd_series, rsi_series
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
- period = _coerce_int(cond.get("period"))
231
- fast = _coerce_int(cond.get("fast_period"))
232
- slow = _coerce_int(cond.get("slow_period"))
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(df: pd.DataFrame, strategy: dict, capital: float, symbol: str) -> dict:
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
 
@@ -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},
@@ -22,5 +22,6 @@
22
22
  "l2_workers": 6,
23
23
  "watchlist_item": 480,
24
24
  "stateless_analysis.py:event_study": 300,
25
- "stateless_analysis.py:robustness": 660
25
+ "stateless_analysis.py:robustness": 660,
26
+ "trend_strategy.py:fetch": 660
26
27
  }
@@ -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())