quantnodes 3.0.0__py3-none-any.whl

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.
Files changed (399) hide show
  1. QuantNodes/__init__.py +15 -0
  2. QuantNodes/__main__.py +14 -0
  3. QuantNodes/agent/__init__.py +158 -0
  4. QuantNodes/agent/agents/__init__.py +13 -0
  5. QuantNodes/agent/agents/definition.py +180 -0
  6. QuantNodes/agent/agents/manager.py +73 -0
  7. QuantNodes/agent/config/__init__.py +34 -0
  8. QuantNodes/agent/config/executor.py +958 -0
  9. QuantNodes/agent/config/loader.py +427 -0
  10. QuantNodes/agent/config/templates/bollinger_bands.yaml +84 -0
  11. QuantNodes/agent/config/templates/dual_ma.yaml +72 -0
  12. QuantNodes/agent/config/templates/empty.yaml +56 -0
  13. QuantNodes/agent/config/templates/mean_reversion.yaml +47 -0
  14. QuantNodes/agent/config/templates/mean_reversion_zscore.yaml +90 -0
  15. QuantNodes/agent/config/templates/momentum.yaml +81 -0
  16. QuantNodes/agent/config/templates/momentum_breakout.yaml +84 -0
  17. QuantNodes/agent/config/templates/rsi_strategy.yaml +72 -0
  18. QuantNodes/agent/config/templates/volume_price.yaml +86 -0
  19. QuantNodes/agent/config/types.py +156 -0
  20. QuantNodes/agent/config_mapper.py +293 -0
  21. QuantNodes/agent/core/__init__.py +19 -0
  22. QuantNodes/agent/core/dream.py +47 -0
  23. QuantNodes/agent/core/quant_dream.py +274 -0
  24. QuantNodes/agent/cron_jobs.py +314 -0
  25. QuantNodes/agent/nanobot_bridge.py +242 -0
  26. QuantNodes/agent/permission/__init__.py +30 -0
  27. QuantNodes/agent/permission/defaults.py +36 -0
  28. QuantNodes/agent/permission/evaluate.py +41 -0
  29. QuantNodes/agent/permission/models.py +59 -0
  30. QuantNodes/agent/permission/service.py +133 -0
  31. QuantNodes/agent/providers/__init__.py +11 -0
  32. QuantNodes/agent/providers/base.py +102 -0
  33. QuantNodes/agent/providers/quantnodes.py +610 -0
  34. QuantNodes/agent/providers/rate_limiter.py +326 -0
  35. QuantNodes/agent/providers/registry.py +163 -0
  36. QuantNodes/agent/skills/__init__.py +20 -0
  37. QuantNodes/agent/skills/base.py +118 -0
  38. QuantNodes/agent/skills/bridge.py +73 -0
  39. QuantNodes/agent/skills/factor/__init__.py +14 -0
  40. QuantNodes/agent/skills/factor/correlation.py +99 -0
  41. QuantNodes/agent/skills/factor/group_backtest.py +114 -0
  42. QuantNodes/agent/skills/factor/ic_analysis.py +106 -0
  43. QuantNodes/agent/skills/loader.py +107 -0
  44. QuantNodes/agent/skills/registry.py +105 -0
  45. QuantNodes/agent/skills/strategy/__init__.py +16 -0
  46. QuantNodes/agent/skills/strategy/bollinger.py +86 -0
  47. QuantNodes/agent/skills/strategy/dual_ma.py +82 -0
  48. QuantNodes/agent/skills/strategy/momentum.py +74 -0
  49. QuantNodes/agent/skills/strategy/rsi_reversal.py +99 -0
  50. QuantNodes/agent/skills_quant/__init__.py +14 -0
  51. QuantNodes/agent/skills_quant/backtest-analyze/SKILL.md +42 -0
  52. QuantNodes/agent/skills_quant/config-driven/SKILL.md +72 -0
  53. QuantNodes/agent/skills_quant/factor-research/SKILL.md +40 -0
  54. QuantNodes/agent/skills_quant/quant-dream/SKILL.md +55 -0
  55. QuantNodes/agent/skills_quant/risk-management/SKILL.md +45 -0
  56. QuantNodes/agent/skills_quant/strategy-design/SKILL.md +43 -0
  57. QuantNodes/agent/templates/__init__.py +4 -0
  58. QuantNodes/agent/tools/__init__.py +173 -0
  59. QuantNodes/agent/tools/_workspace.py +51 -0
  60. QuantNodes/agent/tools/alpha_backtest.py +328 -0
  61. QuantNodes/agent/tools/alpha_evaluate.py +493 -0
  62. QuantNodes/agent/tools/backtest.py +226 -0
  63. QuantNodes/agent/tools/base.py +133 -0
  64. QuantNodes/agent/tools/code_search.py +207 -0
  65. QuantNodes/agent/tools/config_backtest.py +401 -0
  66. QuantNodes/agent/tools/context.py +97 -0
  67. QuantNodes/agent/tools/dream_skill.py +77 -0
  68. QuantNodes/agent/tools/echo.py +38 -0
  69. QuantNodes/agent/tools/factor.py +231 -0
  70. QuantNodes/agent/tools/file_ops.py +201 -0
  71. QuantNodes/agent/tools/git_ops.py +190 -0
  72. QuantNodes/agent/tools/operator_lookup.py +218 -0
  73. QuantNodes/agent/tools/output_truncation.py +77 -0
  74. QuantNodes/agent/tools/path_check.py +43 -0
  75. QuantNodes/agent/tools/pipeline.py +62 -0
  76. QuantNodes/agent/tools/registry.py +150 -0
  77. QuantNodes/agent/tools/sandbox.py +62 -0
  78. QuantNodes/agent/tools/shell_safety.py +63 -0
  79. QuantNodes/agent/tools/strategy.py +106 -0
  80. QuantNodes/agent/tools/task.py +171 -0
  81. QuantNodes/agent/tools/web_fetch.py +142 -0
  82. QuantNodes/agent/tools/web_search.py +114 -0
  83. QuantNodes/agent/tools/wiki.py +370 -0
  84. QuantNodes/agent/utils/__init__.py +11 -0
  85. QuantNodes/agent/utils/helpers.py +43 -0
  86. QuantNodes/agent/utils/prompt_templates.py +30 -0
  87. QuantNodes/agent/workflows/__init__.py +20 -0
  88. QuantNodes/agent/workflows/implementations/__init__.py +8 -0
  89. QuantNodes/agent/workflows/implementations/alpha_gpt.py +508 -0
  90. QuantNodes/agent/workflows/implementations/mcts.py +442 -0
  91. QuantNodes/agent/workflows/parsers.py +44 -0
  92. QuantNodes/agent/workflows/registry.py +119 -0
  93. QuantNodes/agent/workflows/step_agent.py +219 -0
  94. QuantNodes/agent/workflows/tool.py +198 -0
  95. QuantNodes/ai/__init__.py +93 -0
  96. QuantNodes/ai/llm/__init__.py +75 -0
  97. QuantNodes/ai/llm/base.py +233 -0
  98. QuantNodes/ai/llm/decorators.py +281 -0
  99. QuantNodes/ai/llm/gateway.py +571 -0
  100. QuantNodes/ai/llm/null.py +76 -0
  101. QuantNodes/ai/llm/openai.py +435 -0
  102. QuantNodes/ai/optimizer.py +405 -0
  103. QuantNodes/ai/prompts/__init__.py +229 -0
  104. QuantNodes/ai/sandbox.py +371 -0
  105. QuantNodes/ai/sandbox_pandas_bridge.py +150 -0
  106. QuantNodes/ai/strategy_gen.py +396 -0
  107. QuantNodes/backtest/__init__.py +64 -0
  108. QuantNodes/backtest/backtest_node.py +188 -0
  109. QuantNodes/backtest/broker_node.py +378 -0
  110. QuantNodes/backtest/config_runner.py +397 -0
  111. QuantNodes/backtest/config_strategy.py +64 -0
  112. QuantNodes/backtest/risk_node.py +360 -0
  113. QuantNodes/backtest/strategy_node.py +268 -0
  114. QuantNodes/cache_node/__init__.py +19 -0
  115. QuantNodes/cache_node/base.py +244 -0
  116. QuantNodes/cache_node/cache_store.py +99 -0
  117. QuantNodes/cache_node/metadata.py +100 -0
  118. QuantNodes/cli/__init__.py +109 -0
  119. QuantNodes/cli/_helpers.py +511 -0
  120. QuantNodes/cli/command.py +110 -0
  121. QuantNodes/cli/commands/__init__.py +69 -0
  122. QuantNodes/cli/commands/agent.py +158 -0
  123. QuantNodes/cli/commands/alpha.py +951 -0
  124. QuantNodes/cli/commands/chat.py +38 -0
  125. QuantNodes/cli/commands/evolve.py +120 -0
  126. QuantNodes/cli/commands/factor.py +569 -0
  127. QuantNodes/cli/commands/init.py +190 -0
  128. QuantNodes/cli/commands/run.py +259 -0
  129. QuantNodes/cli/commands/serve.py +398 -0
  130. QuantNodes/cli/commands/version.py +120 -0
  131. QuantNodes/cli/enhanced.py +146 -0
  132. QuantNodes/conf_node/__init__.py +37 -0
  133. QuantNodes/conf_node/base.py +120 -0
  134. QuantNodes/conf_node/env_config.py +132 -0
  135. QuantNodes/conf_node/ini_config.py +70 -0
  136. QuantNodes/conf_node/json_config.py +69 -0
  137. QuantNodes/conf_node/yaml_config.py +78 -0
  138. QuantNodes/constants.py +17 -0
  139. QuantNodes/core/__init__.py +196 -0
  140. QuantNodes/core/_lookback_helpers.py +49 -0
  141. QuantNodes/core/ast_parser.py +198 -0
  142. QuantNodes/core/base.py +61 -0
  143. QuantNodes/core/cache_manager.py +344 -0
  144. QuantNodes/core/cache_utils.py +150 -0
  145. QuantNodes/core/cond_builder.py +53 -0
  146. QuantNodes/core/config.py +170 -0
  147. QuantNodes/core/constants.py +48 -0
  148. QuantNodes/core/control.py +412 -0
  149. QuantNodes/core/data_preprocessing.py +453 -0
  150. QuantNodes/core/data_source.py +46 -0
  151. QuantNodes/core/events.py +178 -0
  152. QuantNodes/core/evolution/__init__.py +22 -0
  153. QuantNodes/core/evolution/loop.py +583 -0
  154. QuantNodes/core/evolution/operators.py +289 -0
  155. QuantNodes/core/evolution/settings.py +44 -0
  156. QuantNodes/core/expression.py +841 -0
  157. QuantNodes/core/feedback/__init__.py +38 -0
  158. QuantNodes/core/feedback/channels.py +182 -0
  159. QuantNodes/core/feedback/collector.py +91 -0
  160. QuantNodes/core/feedback/dataclass.py +239 -0
  161. QuantNodes/core/feedback/llm_judge.py +138 -0
  162. QuantNodes/core/knowledge/__init__.py +69 -0
  163. QuantNodes/core/knowledge/knowledge_base.py +217 -0
  164. QuantNodes/core/knowledge/lineage_compress.py +196 -0
  165. QuantNodes/core/knowledge/lineage_expand.py +123 -0
  166. QuantNodes/core/knowledge/metrics/__init__.py +43 -0
  167. QuantNodes/core/knowledge/metrics/evaluator.py +176 -0
  168. QuantNodes/core/knowledge/metrics/metrics.py +220 -0
  169. QuantNodes/core/knowledge/rag_prompt.py +196 -0
  170. QuantNodes/core/knowledge/retriever.py +209 -0
  171. QuantNodes/core/lambda_node.py +81 -0
  172. QuantNodes/core/monitoring/__init__.py +22 -0
  173. QuantNodes/core/monitoring/collector.py +292 -0
  174. QuantNodes/core/monitoring/dashboard.py +365 -0
  175. QuantNodes/core/node.py +375 -0
  176. QuantNodes/core/pandas_utils.py +504 -0
  177. QuantNodes/core/parallel/__init__.py +15 -0
  178. QuantNodes/core/parallel/worker.py +140 -0
  179. QuantNodes/core/parallel/worker_process.py +265 -0
  180. QuantNodes/core/path_utils.py +73 -0
  181. QuantNodes/core/pipeline.py +328 -0
  182. QuantNodes/core/plugin.py +135 -0
  183. QuantNodes/core/quality_gate/__init__.py +32 -0
  184. QuantNodes/core/quality_gate/complexity.py +94 -0
  185. QuantNodes/core/quality_gate/consistency.py +26 -0
  186. QuantNodes/core/quality_gate/node.py +97 -0
  187. QuantNodes/core/quality_gate/redundancy.py +51 -0
  188. QuantNodes/core/quality_gate/settings.py +43 -0
  189. QuantNodes/core/quality_gate/zoo.py +98 -0
  190. QuantNodes/core/serializable.py +116 -0
  191. QuantNodes/core/serialization.py +673 -0
  192. QuantNodes/core/tools.py +333 -0
  193. QuantNodes/core/trajectory/__init__.py +25 -0
  194. QuantNodes/core/trajectory/entry.py +116 -0
  195. QuantNodes/core/trajectory/lineage.py +67 -0
  196. QuantNodes/core/trajectory/pool.py +211 -0
  197. QuantNodes/core/trajectory/selector.py +140 -0
  198. QuantNodes/core/visualization/__init__.py +33 -0
  199. QuantNodes/core/visualization/builder.py +233 -0
  200. QuantNodes/core/visualization/gate_breakdown.py +140 -0
  201. QuantNodes/core/visualization/lineage_dag.py +203 -0
  202. QuantNodes/core/visualization/metric_distribution.py +125 -0
  203. QuantNodes/core/visualization/report.py +68 -0
  204. QuantNodes/database_node/__init__.py +69 -0
  205. QuantNodes/database_node/base.py +135 -0
  206. QuantNodes/database_node/clickhouse_node.py +272 -0
  207. QuantNodes/database_node/csv_node.py +83 -0
  208. QuantNodes/database_node/duckdb_node.py +86 -0
  209. QuantNodes/database_node/factory.py +83 -0
  210. QuantNodes/database_node/mysql_node.py +100 -0
  211. QuantNodes/database_node/parquet_node.py +75 -0
  212. QuantNodes/database_node/sqlite_node.py +67 -0
  213. QuantNodes/factor_node/__init__.py +50 -0
  214. QuantNodes/factor_node/factor.py +563 -0
  215. QuantNodes/factor_node/factor_db.py +421 -0
  216. QuantNodes/factor_node/factor_functions/__init__.py +252 -0
  217. QuantNodes/factor_node/factor_functions/_helpers.py +358 -0
  218. QuantNodes/factor_node/factor_functions/_helpers_debug.py +317 -0
  219. QuantNodes/factor_node/factor_functions/composite_ops.py +136 -0
  220. QuantNodes/factor_node/factor_functions/math_ops.py +433 -0
  221. QuantNodes/factor_node/factor_functions/section_ops.py +290 -0
  222. QuantNodes/factor_node/factor_functions/talib_ops.py +1293 -0
  223. QuantNodes/factor_node/factor_functions/time_ops.py +535 -0
  224. QuantNodes/factor_node/factor_operation.py +1115 -0
  225. QuantNodes/factor_node/factor_table.py +1073 -0
  226. QuantNodes/factor_node/quant_nodes_object.py +60 -0
  227. QuantNodes/mcp_server/__init__.py +27 -0
  228. QuantNodes/mcp_server/__main__.py +4 -0
  229. QuantNodes/mcp_server/server.py +272 -0
  230. QuantNodes/methods/__init__.py +28 -0
  231. QuantNodes/methods/pipeline.py +100 -0
  232. QuantNodes/methods/sandbox.py +102 -0
  233. QuantNodes/monitor/__init__.py +27 -0
  234. QuantNodes/monitor/agent_tools/__init__.py +5 -0
  235. QuantNodes/monitor/agent_tools/monitor_tool.py +98 -0
  236. QuantNodes/monitor/agent_tools/schedule_tool.py +98 -0
  237. QuantNodes/monitor/agent_tools/version_tool.py +133 -0
  238. QuantNodes/monitor/monitor/__init__.py +6 -0
  239. QuantNodes/monitor/monitor/alerter.py +60 -0
  240. QuantNodes/monitor/monitor/collector.py +164 -0
  241. QuantNodes/monitor/monitor/dashboard.py +115 -0
  242. QuantNodes/monitor/monitor/drift.py +190 -0
  243. QuantNodes/monitor/scheduler/__init__.py +4 -0
  244. QuantNodes/monitor/scheduler/runner.py +133 -0
  245. QuantNodes/monitor/scheduler/scheduler.py +184 -0
  246. QuantNodes/monitor/storage/__init__.py +16 -0
  247. QuantNodes/monitor/storage/models.py +70 -0
  248. QuantNodes/monitor/storage/repository.py +407 -0
  249. QuantNodes/monitor/version/__init__.py +4 -0
  250. QuantNodes/monitor/version/diff.py +81 -0
  251. QuantNodes/monitor/version/version_manager.py +182 -0
  252. QuantNodes/operator_node/__init__.py +28 -0
  253. QuantNodes/operator_node/base.py +97 -0
  254. QuantNodes/operator_node/query_node.py +129 -0
  255. QuantNodes/operator_node/sql_builder.py +125 -0
  256. QuantNodes/operator_node/sql_utils.py +172 -0
  257. QuantNodes/operator_node/transform.py +130 -0
  258. QuantNodes/operators/__init__.py +90 -0
  259. QuantNodes/operators/_engine.py +108 -0
  260. QuantNodes/operators/composite.py +161 -0
  261. QuantNodes/operators/composite_dag.py +667 -0
  262. QuantNodes/operators/composite_dag_ops.py +343 -0
  263. QuantNodes/operators/composite_dag_pandas_ops.py +382 -0
  264. QuantNodes/operators/custom.py +408 -0
  265. QuantNodes/operators/facade.py +164 -0
  266. QuantNodes/operators/math.py +163 -0
  267. QuantNodes/operators/proxy.py +29 -0
  268. QuantNodes/operators/registry.py +144 -0
  269. QuantNodes/operators/section.py +99 -0
  270. QuantNodes/operators/talib.py +757 -0
  271. QuantNodes/operators/templates.py +95 -0
  272. QuantNodes/operators/time_series.py +136 -0
  273. QuantNodes/prompts/__init__.py +20 -0
  274. QuantNodes/prompts/backtest/__init__.py +12 -0
  275. QuantNodes/prompts/backtest/factor_based.py +86 -0
  276. QuantNodes/prompts/backtest/standard.py +73 -0
  277. QuantNodes/prompts/factor/__init__.py +14 -0
  278. QuantNodes/prompts/factor/correlation.py +77 -0
  279. QuantNodes/prompts/factor/group_backtest.py +86 -0
  280. QuantNodes/prompts/factor/ic_analysis.py +91 -0
  281. QuantNodes/prompts/strategy/__init__.py +18 -0
  282. QuantNodes/prompts/strategy/market_neutral.py +96 -0
  283. QuantNodes/prompts/strategy/mean_reversion.py +107 -0
  284. QuantNodes/prompts/strategy/momentum.py +160 -0
  285. QuantNodes/prompts/strategy/pairs_trading.py +107 -0
  286. QuantNodes/prompts/strategy/trend_following.py +96 -0
  287. QuantNodes/research/README.md +106 -0
  288. QuantNodes/research/__init__.py +154 -0
  289. QuantNodes/research/_legacy_3c/__init__.py +61 -0
  290. QuantNodes/research/_legacy_3c/auto_researcher.py +289 -0
  291. QuantNodes/research/_legacy_3c/factor_evaluator.py +560 -0
  292. QuantNodes/research/_legacy_3c/factor_miner.py +318 -0
  293. QuantNodes/research/_legacy_3c/mcts_search.py +324 -0
  294. QuantNodes/research/factor_test/__init__.py +25 -0
  295. QuantNodes/research/factor_test/config.py +184 -0
  296. QuantNodes/research/factor_test/config_builder.py +276 -0
  297. QuantNodes/research/factor_test/e2e/data_prep.py +163 -0
  298. QuantNodes/research/factor_test/e2e/run_evolution_e2e.py +309 -0
  299. QuantNodes/research/factor_test/evolution_adapter.py +231 -0
  300. QuantNodes/research/factor_test/feedback_wrapper.py +102 -0
  301. QuantNodes/research/factor_test/ifind_db/__init__.py +7 -0
  302. QuantNodes/research/factor_test/ifind_db/fetcher.py +224 -0
  303. QuantNodes/research/factor_test/ifind_db/ifind_database.py +689 -0
  304. QuantNodes/research/factor_test/nodes/__init__.py +1 -0
  305. QuantNodes/research/factor_test/nodes/_base.py +91 -0
  306. QuantNodes/research/factor_test/nodes/adjust_date_node.py +48 -0
  307. QuantNodes/research/factor_test/nodes/configs.py +240 -0
  308. QuantNodes/research/factor_test/nodes/factor_neutralize_node.py +87 -0
  309. QuantNodes/research/factor_test/nodes/factor_preprocess_node.py +222 -0
  310. QuantNodes/research/factor_test/nodes/factor_score_node.py +141 -0
  311. QuantNodes/research/factor_test/nodes/factor_test_report_node.py +153 -0
  312. QuantNodes/research/factor_test/nodes/group_analyzer_node.py +317 -0
  313. QuantNodes/research/factor_test/nodes/ic_analyzer_node.py +112 -0
  314. QuantNodes/research/factor_test/nodes/load_data_node.py +100 -0
  315. QuantNodes/research/factor_test/nodes/long_short_node.py +93 -0
  316. QuantNodes/research/factor_test/nodes/neutralizers.py +222 -0
  317. QuantNodes/research/factor_test/nodes/preprocess_strategies.py +277 -0
  318. QuantNodes/research/factor_test/nodes/risk_correlation_node.py +112 -0
  319. QuantNodes/research/factor_test/nodes/sample_pool_filter_node.py +110 -0
  320. QuantNodes/research/factor_test/nodes/tradability_filter_node.py +92 -0
  321. QuantNodes/research/factor_test/pipeline_runner.py +305 -0
  322. QuantNodes/research/factor_test/pipeline_spec.py +216 -0
  323. QuantNodes/research/factor_test/utils/__init__.py +26 -0
  324. QuantNodes/research/factor_test/utils/constants.py +86 -0
  325. QuantNodes/research/factor_test/utils/data_loader.py +141 -0
  326. QuantNodes/research/factor_test/utils/date_utils.py +232 -0
  327. QuantNodes/research/factor_test/utils/file_loaders.py +150 -0
  328. QuantNodes/research/factor_test/utils/labels.py +37 -0
  329. QuantNodes/research/factor_test/utils/metrics_extractor.py +55 -0
  330. QuantNodes/research/factor_test/utils/performance_metrics.py +175 -0
  331. QuantNodes/research/factor_test/utils/safe_load.py +106 -0
  332. QuantNodes/research/quant_alpha/CHANGELOG.md +80 -0
  333. QuantNodes/research/quant_alpha/README.md +142 -0
  334. QuantNodes/research/quant_alpha/__init__.py +45 -0
  335. QuantNodes/research/quant_alpha/adapters/__init__.py +99 -0
  336. QuantNodes/research/quant_alpha/adapters/calculator.py +503 -0
  337. QuantNodes/research/quant_alpha/adapters/expression.py +387 -0
  338. QuantNodes/research/quant_alpha/alpha101_design/__init__.py +50 -0
  339. QuantNodes/research/quant_alpha/alpha101_design/few_shot_examples.py +243 -0
  340. QuantNodes/research/quant_alpha/alpha101_design/philosophy.py +474 -0
  341. QuantNodes/research/quant_alpha/alpha158_design/__init__.py +63 -0
  342. QuantNodes/research/quant_alpha/alpha158_design/few_shot_examples.py +219 -0
  343. QuantNodes/research/quant_alpha/alpha158_design/philosophy.py +240 -0
  344. QuantNodes/research/quant_alpha/evaluation/__init__.py +47 -0
  345. QuantNodes/research/quant_alpha/evaluation/baselines/__init__.py +8 -0
  346. QuantNodes/research/quant_alpha/evaluation/baselines/g1_handcrafted.py +135 -0
  347. QuantNodes/research/quant_alpha/evaluation/baselines/g2_llm_only.py +269 -0
  348. QuantNodes/research/quant_alpha/evaluation/baselines/g3_alpha_gpt.py +152 -0
  349. QuantNodes/research/quant_alpha/evaluation/clickhouse_data_loader.py +227 -0
  350. QuantNodes/research/quant_alpha/evaluation/contracts.py +376 -0
  351. QuantNodes/research/quant_alpha/evaluation/evaluators/__init__.py +6 -0
  352. QuantNodes/research/quant_alpha/evaluation/evaluators/polars_evaluator.py +545 -0
  353. QuantNodes/research/quant_alpha/evaluation/mock_data_loader.py +226 -0
  354. QuantNodes/research/quant_alpha/evaluation/runner.py +243 -0
  355. QuantNodes/research/quant_alpha/llm/__init__.py +38 -0
  356. QuantNodes/research/quant_alpha/llm/parser.py +681 -0
  357. QuantNodes/research/quant_alpha/logic_driven_pipeline.py +411 -0
  358. QuantNodes/research/quant_alpha/logic_mining/__init__.py +74 -0
  359. QuantNodes/research/quant_alpha/logic_mining/compiler.py +457 -0
  360. QuantNodes/research/quant_alpha/logic_mining/generator.py +366 -0
  361. QuantNodes/research/quant_alpha/logic_mining/models.py +252 -0
  362. QuantNodes/research/quant_alpha/logic_mining/parser.py +287 -0
  363. QuantNodes/research/quant_alpha/logic_mining/pipelines.py +297 -0
  364. QuantNodes/research/quant_alpha/logic_mining/sources.py +149 -0
  365. QuantNodes/research/quant_alpha/mcts/__init__.py +66 -0
  366. QuantNodes/research/quant_alpha/mcts/cache.py +262 -0
  367. QuantNodes/research/quant_alpha/mcts/extension_ops.py +320 -0
  368. QuantNodes/research/quant_alpha/mcts/feedback.py +825 -0
  369. QuantNodes/research/quant_alpha/mcts/op_prior.py +180 -0
  370. QuantNodes/research/quant_alpha/mcts/search.py +540 -0
  371. QuantNodes/research/quant_alpha/mcts/tree.py +201 -0
  372. QuantNodes/research/quant_alpha/operator_vocab/__init__.py +50 -0
  373. QuantNodes/research/quant_alpha/operator_vocab/config.py +54 -0
  374. QuantNodes/research/quant_alpha/operator_vocab/metadata.py +263 -0
  375. QuantNodes/research/quant_alpha/operator_vocab/vocabulary.py +481 -0
  376. QuantNodes/research/quant_alpha/pipeline.py +1027 -0
  377. QuantNodes/research/quant_alpha/types/__init__.py +27 -0
  378. QuantNodes/research/quant_alpha/types/constants.py +28 -0
  379. QuantNodes/research/quant_alpha/types/state.py +205 -0
  380. QuantNodes/research/quant_alpha/workflow/__init__.py +32 -0
  381. QuantNodes/research/quant_alpha/workflow/alpha_gpt.py +911 -0
  382. QuantNodes/research/quant_alpha/workflow/alpha_logics.py +416 -0
  383. QuantNodes/research/quant_alpha/workflow/state.py +27 -0
  384. QuantNodes/research/report_reproducer.py +485 -0
  385. QuantNodes/research/wiki.py +1155 -0
  386. QuantNodes/symbolic/__init__.py +51 -0
  387. QuantNodes/symbolic/compiler.py +113 -0
  388. QuantNodes/symbolic/dialect.py +260 -0
  389. QuantNodes/symbolic/executor.py +147 -0
  390. QuantNodes/symbolic/expression.py +234 -0
  391. QuantNodes/symbolic/functions.py +433 -0
  392. QuantNodes/symbolic/optimizer.py +165 -0
  393. QuantNodes/ui_node/__init__.py +30 -0
  394. QuantNodes/ui_node/base.py +222 -0
  395. quantnodes-3.0.0.dist-info/METADATA +463 -0
  396. quantnodes-3.0.0.dist-info/RECORD +399 -0
  397. quantnodes-3.0.0.dist-info/WHEEL +5 -0
  398. quantnodes-3.0.0.dist-info/entry_points.txt +24 -0
  399. quantnodes-3.0.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,387 @@
1
+ # coding=utf-8
2
+ """
3
+ adapters/expression.py - 极简 Expression AST(AlphaGen 兼容子集)
4
+
5
+ AlphaGen (KDD 2023) 使用 token 化的 Expression AST 表示因子公式。
6
+ 本模块提供极简子集,足以让 PolarsAlphaCalculator 正常工作。
7
+
8
+ 完整的 AlphaGen Expression 包含 ~22 个算子:
9
+ Ref, Add, Sub, Mul, Div, Greater, Less, Neg, Abs, Log, Sign, Sqrt,
10
+ Mean, Std, Var, Skew, Kurt, Max, Min, Sum, Med, Mad,
11
+ Rank, Delta, Quantile, Condition, ...
12
+
13
+ 本子集(11 个)覆盖 AlphaGen 80% 用例:
14
+ - Feature: 引用基础字段
15
+ - Ref: 时序滞后
16
+ - BinaryOp (Add/Sub/Mul/Div/Greater/Less)
17
+ - UnaryOp (Abs/Neg/Log/Sign/Sqrt)
18
+ - RollingOp (Mean/Std/Sum/Max/Min/Skew/Kurt/Med/Rank/Delta)
19
+
20
+ 对未覆盖的算子,PolarsAlphaCalculator.expression_to_formula() 会
21
+ fallback 到通用算子映射。
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ from abc import ABC, abstractmethod
27
+ from typing import Any, List, Optional, Union
28
+
29
+
30
+ class Expression(ABC):
31
+ """因子表达式抽象基类
32
+
33
+ 所有 Expression 必须实现:
34
+ - to_string(): 转为 QuantNodes 公式字符串(给 OperatorVocab)
35
+ - children: 子表达式列表(用于递归遍历)
36
+ """
37
+
38
+ @abstractmethod
39
+ def to_string(self) -> str:
40
+ """转为 QuantNodes 公式字符串
41
+
42
+ Returns:
43
+ 公式字符串(如 "close - close.shift(5)")
44
+ """
45
+ raise NotImplementedError
46
+
47
+ @property
48
+ @abstractmethod
49
+ def children(self) -> List["Expression"]:
50
+ """子表达式列表"""
51
+ raise NotImplementedError
52
+
53
+ def __repr__(self) -> str:
54
+ return f"Expr({self.to_string()})"
55
+
56
+
57
+ # ==============================================================================
58
+ # 基础表达式
59
+ # ==============================================================================
60
+
61
+
62
+ class Feature(Expression):
63
+ """基础字段引用:$close, $open, $high, $low, $vwap, $volume
64
+
65
+ Examples:
66
+ Feature("close") # → "$close" / "close"
67
+ """
68
+ def __init__(self, field: str):
69
+ self.field = field
70
+
71
+ def to_string(self) -> str:
72
+ return self.field
73
+
74
+ @property
75
+ def children(self) -> List[Expression]:
76
+ return []
77
+
78
+
79
+ class Literal(Expression):
80
+ """字面量值
81
+
82
+ Examples:
83
+ Literal(1e-12) # → "1e-12"
84
+ Literal(0.5) # → "0.5"
85
+ """
86
+ def __init__(self, value: Union[int, float]):
87
+ self.value = value
88
+
89
+ def to_string(self) -> str:
90
+ # 整数直接显示,浮点保留精度
91
+ if isinstance(self.value, int) or (
92
+ isinstance(self.value, float) and self.value.is_integer()
93
+ ):
94
+ return str(int(self.value))
95
+ return repr(self.value)
96
+
97
+ @property
98
+ def children(self) -> List[Expression]:
99
+ return []
100
+
101
+
102
+ def _to_expr(x: Any) -> Expression:
103
+ """自动把字面量转 Expression"""
104
+ if isinstance(x, Expression):
105
+ return x
106
+ if isinstance(x, (int, float)):
107
+ return Literal(x)
108
+ raise TypeError(f"Cannot convert {type(x).__name__} to Expression")
109
+
110
+
111
+ class Ref(Expression):
112
+ """时序滞后:Ref($close, 5) = 5 日前 close
113
+
114
+ Examples:
115
+ Ref(Feature("close"), 5) # → "close.shift(5)"
116
+ """
117
+ def __init__(self, expr: Expression, lag: int):
118
+ self.expr = expr
119
+ self.lag = lag
120
+
121
+ def to_string(self) -> str:
122
+ return f"{self.expr.to_string()}.shift({self.lag})"
123
+
124
+ @property
125
+ def children(self) -> List[Expression]:
126
+ return [self.expr]
127
+
128
+
129
+ # ==============================================================================
130
+ # 二元操作
131
+ # ==============================================================================
132
+
133
+
134
+ class BinaryOp(Expression):
135
+ """二元操作:add, sub, mul, div, gt, lt, signedpower"""
136
+ _OP_MAP = {
137
+ "add": "+",
138
+ "sub": "-",
139
+ "mul": "*",
140
+ "div": "/",
141
+ "gt": ">",
142
+ "lt": "<",
143
+ "signedpower": "**",
144
+ }
145
+
146
+ def __init__(self, left, right, op: str):
147
+ if op not in self._OP_MAP:
148
+ raise ValueError(
149
+ f"Unsupported op: {op}. Supported: {list(self._OP_MAP.keys())}"
150
+ )
151
+ self.left = _to_expr(left)
152
+ self.right = _to_expr(right)
153
+ self.op = op
154
+
155
+ def to_string(self) -> str:
156
+ symbol = self._OP_MAP[self.op]
157
+ return f"({self.left.to_string()} {symbol} {self.right.to_string()})"
158
+
159
+ @property
160
+ def children(self) -> List[Expression]:
161
+ return [self.left, self.right]
162
+
163
+
164
+ # 便捷构造(接受 Expression 或字面量)
165
+ def Add(left, right) -> BinaryOp:
166
+ return BinaryOp(left, right, "add")
167
+
168
+
169
+ def Sub(left, right) -> BinaryOp:
170
+ return BinaryOp(left, right, "sub")
171
+
172
+
173
+ def Mul(left, right) -> BinaryOp:
174
+ return BinaryOp(left, right, "mul")
175
+
176
+
177
+ def Div(left, right) -> BinaryOp:
178
+ return BinaryOp(left, right, "div")
179
+
180
+
181
+ def Greater(left, right) -> BinaryOp:
182
+ return BinaryOp(left, right, "gt")
183
+
184
+
185
+ def Less(left, right) -> BinaryOp:
186
+ return BinaryOp(left, right, "lt")
187
+
188
+
189
+ # ==============================================================================
190
+ # 一元操作
191
+ # ==============================================================================
192
+
193
+
194
+ class UnaryOp(Expression):
195
+ """一元操作:abs, neg, log, sign, sqrt, rank, zscore, winsorize"""
196
+ _OP_MAP = {
197
+ "abs": "abs",
198
+ "neg": "-", # 一元负号特殊处理
199
+ "log": "log",
200
+ "sign": "sign",
201
+ "sqrt": "sqrt",
202
+ "rank": "rank",
203
+ "zscore": "zscore",
204
+ "winsorize": "winsorize",
205
+ }
206
+
207
+ def __init__(self, expr, op: str):
208
+ if op not in self._OP_MAP:
209
+ raise ValueError(
210
+ f"Unsupported op: {op}. Supported: {list(self._OP_MAP.keys())}"
211
+ )
212
+ self.expr = _to_expr(expr)
213
+ self.op = op
214
+
215
+ def to_string(self) -> str:
216
+ op_str = self._OP_MAP[self.op]
217
+ if self.op == "neg":
218
+ return f"(-{self.expr.to_string()})"
219
+ return f"{op_str}({self.expr.to_string()})"
220
+
221
+ @property
222
+ def children(self) -> List[Expression]:
223
+ return [self.expr]
224
+
225
+
226
+ # 便捷构造
227
+ def Abs(expr: Expression) -> UnaryOp:
228
+ return UnaryOp(expr, "abs")
229
+
230
+
231
+ def Neg(expr: Expression) -> UnaryOp:
232
+ return UnaryOp(expr, "neg")
233
+
234
+
235
+ def Log(expr: Expression) -> UnaryOp:
236
+ return UnaryOp(expr, "log")
237
+
238
+
239
+ def Sign(expr: Expression) -> UnaryOp:
240
+ return UnaryOp(expr, "sign")
241
+
242
+
243
+ def Sqrt(expr: Expression) -> UnaryOp:
244
+ return UnaryOp(expr, "sqrt")
245
+
246
+
247
+ def Rank(expr: Expression) -> UnaryOp:
248
+ return UnaryOp(expr, "rank")
249
+
250
+
251
+ def Zscore(expr: Expression) -> UnaryOp:
252
+ return UnaryOp(expr, "zscore")
253
+
254
+
255
+ def Winsorize(expr: Expression) -> UnaryOp:
256
+ return UnaryOp(expr, "winsorize")
257
+
258
+
259
+ def Rank(expr: Expression) -> UnaryOp:
260
+ return UnaryOp(expr, "rank")
261
+
262
+
263
+ def Zscore(expr: Expression) -> UnaryOp:
264
+ return UnaryOp(expr, "zscore")
265
+
266
+
267
+ def Winsorize(expr: Expression) -> UnaryOp:
268
+ return UnaryOp(expr, "winsorize")
269
+
270
+
271
+ # ==============================================================================
272
+ # 滚动操作
273
+ # ==============================================================================
274
+
275
+
276
+ class RollingOp(Expression):
277
+ """滚动操作:mean, std, var, max, min, sum, skew, kurt, median, rank, delta, corr, cov
278
+
279
+ Examples:
280
+ RollingOp(Feature("close"), window=20, op="mean")
281
+ # → "ts_mean(close, 20)"
282
+ """
283
+ _OP_MAP = {
284
+ "mean": "ts_mean",
285
+ "std": "ts_std",
286
+ "var": "ts_var",
287
+ "max": "ts_max",
288
+ "min": "ts_min",
289
+ "sum": "ts_sum",
290
+ "skew": "ts_skew",
291
+ "kurt": "ts_kurt",
292
+ "median": "ts_median",
293
+ "rank": "ts_rank",
294
+ "delta": "ts_delta",
295
+ "corr": "ts_corr",
296
+ "cov": "ts_cov",
297
+ }
298
+
299
+ def __init__(self, expr, window: int, op: str):
300
+ if op not in self._OP_MAP:
301
+ raise ValueError(
302
+ f"Unsupported rolling op: {op}. "
303
+ f"Supported: {list(self._OP_MAP.keys())}"
304
+ )
305
+ self.expr = _to_expr(expr)
306
+ self.window = window
307
+ self.op = op
308
+
309
+ def to_string(self) -> str:
310
+ func = self._OP_MAP[self.op]
311
+ return f"{func}({self.expr.to_string()}, {self.window})"
312
+
313
+ @property
314
+ def children(self) -> List[Expression]:
315
+ return [self.expr]
316
+
317
+
318
+ # 便捷构造
319
+ def Mean(expr: Expression, window: int) -> RollingOp:
320
+ return RollingOp(expr, window, "mean")
321
+
322
+
323
+ def Std(expr: Expression, window: int) -> RollingOp:
324
+ return RollingOp(expr, window, "std")
325
+
326
+
327
+ def Sum(expr: Expression, window: int) -> RollingOp:
328
+ return RollingOp(expr, window, "sum")
329
+
330
+
331
+ def Max(expr: Expression, window: int) -> RollingOp:
332
+ return RollingOp(expr, window, "max")
333
+
334
+
335
+ def Min(expr: Expression, window: int) -> RollingOp:
336
+ return RollingOp(expr, window, "min")
337
+
338
+
339
+ def Delta(expr: Expression, window: int) -> RollingOp:
340
+ return RollingOp(expr, window, "delta")
341
+
342
+
343
+ # ==============================================================================
344
+ # 工具函数
345
+ # ==============================================================================
346
+
347
+
348
+ def expression_to_formula(expr: Expression) -> str:
349
+ """便利函数:Expression → 公式字符串
350
+
351
+ Args:
352
+ expr: Expression 对象
353
+
354
+ Returns:
355
+ QuantNodes 公式字符串
356
+ """
357
+ return expr.to_string()
358
+
359
+
360
+ def collect_feature_fields(expr: Expression) -> List[str]:
361
+ """递归收集表达式中所有 Feature 字段"""
362
+ fields: List[str] = []
363
+
364
+ def _walk(e: Expression) -> None:
365
+ if isinstance(e, Feature):
366
+ if e.field not in fields:
367
+ fields.append(e.field)
368
+ for child in e.children:
369
+ _walk(child)
370
+
371
+ _walk(expr)
372
+ return fields
373
+
374
+
375
+ def collect_rolling_windows(expr: Expression) -> List[int]:
376
+ """递归收集表达式中所有 RollingOp 的窗口"""
377
+ windows: List[int] = []
378
+
379
+ def _walk(e: Expression) -> None:
380
+ if isinstance(e, RollingOp):
381
+ if e.window not in windows:
382
+ windows.append(e.window)
383
+ for child in e.children:
384
+ _walk(child)
385
+
386
+ _walk(expr)
387
+ return windows
@@ -0,0 +1,50 @@
1
+ # coding=utf-8
2
+ """
3
+ alpha101_design - Alpha 101 设计哲学借鉴(M3 PR)
4
+
5
+ Alpha 101 (Kakushadze 2015, arXiv:1601.00991) 提供了 101 个公式化 alpha
6
+ 因子的设计范式。本子包**借鉴其设计哲学**而非直接移植公式集
7
+ (实际因子集由 llmwikify 在他处生成)。
8
+
9
+ 内容:
10
+ - DESIGN_PHILOSOPHY: Alpha 101 核心设计原则(8 条)
11
+ - CORE_OPERATORS: 10-20 个核心算子子集(经济意义)
12
+ - FEW_SHOT_EXAMPLES: 5-10 个示例公式(用于 Alpha-GPT 启动 prompt)
13
+
14
+ M3 范围:仅做借鉴(设计文档 + few-shot)。
15
+ 完整因子集实现 → 路线 6 (Alpha-GPT) 阶段。
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ from QuantNodes.research.quant_alpha.alpha101_design.philosophy import (
21
+ DESIGN_PHILOSOPHY,
22
+ CORE_OPERATORS,
23
+ A_SHARE_COMPATIBILITY,
24
+ get_philosophy_by_id,
25
+ get_operator_by_name,
26
+ get_a_share_compatible_count,
27
+ )
28
+ from QuantNodes.research.quant_alpha.alpha101_design.few_shot_examples import (
29
+ ALPHA101_FEW_SHOT_EXAMPLES,
30
+ list_examples,
31
+ get_example,
32
+ get_few_shot_prompt,
33
+ get_categories,
34
+ )
35
+
36
+ __all__ = [
37
+ # 设计哲学
38
+ "DESIGN_PHILOSOPHY",
39
+ "CORE_OPERATORS",
40
+ "A_SHARE_COMPATIBILITY",
41
+ "get_philosophy_by_id",
42
+ "get_operator_by_name",
43
+ "get_a_share_compatible_count",
44
+ # few-shot 示例
45
+ "ALPHA101_FEW_SHOT_EXAMPLES",
46
+ "list_examples",
47
+ "get_example",
48
+ "get_few_shot_prompt",
49
+ "get_categories",
50
+ ]
@@ -0,0 +1,243 @@
1
+ # coding=utf-8
2
+ """
3
+ few_shot_examples.py - Alpha 101 few-shot 示例(用于 Alpha-GPT 启动 prompt)
4
+
5
+ 提供 5-10 个代表性公式示例,供 M5+ 的 Alpha-GPT 路线使用。
6
+ 本 M3 PR 仅做示例定义,不做实际评估(评估由 Alpha-GPT 路线完成)。
7
+
8
+ 示例选样标准:
9
+ - 覆盖 8 条设计原则
10
+ - 覆盖 16 个核心算子
11
+ - A 股可移植(避开 Delay-0)
12
+ - 复杂度从简单(1-2 算子)到复杂(5+ 算子)
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from dataclasses import dataclass, field
18
+ from typing import Any, Dict, List, Optional
19
+
20
+
21
+ @dataclass
22
+ class FewShotExample:
23
+ """Alpha 101 few-shot 示例"""
24
+ id: str # 示例 ID (EX1-EX10)
25
+ name: str # 简短名称
26
+ formula: str # 公式
27
+ description: str # 含义
28
+ category: str # momentum / reversal / volume_price / volatility / intraday
29
+ design_principles: List[str] # 引用的设计原则 ID (P1-P8)
30
+ operators_used: List[str] # 使用的核心算子
31
+ alpha101_ref: str # Alpha 101 #N 引用
32
+ a_share_compatible: bool = True
33
+ metadata: Dict[str, Any] = field(default_factory=dict)
34
+
35
+
36
+ # ==============================================================================
37
+ # 10 个精选 few-shot 示例
38
+ # ==============================================================================
39
+
40
+ ALPHA101_FEW_SHOT_EXAMPLES: List[FewShotExample] = [
41
+ # ============ 简单示例(1-2 算子)============
42
+ FewShotExample(
43
+ id="EX1",
44
+ name="日内动量",
45
+ formula="(close - open) / ((high - low) + 0.001)",
46
+ description=(
47
+ "日内收益率除以日内振幅。"
48
+ "衡量收盘相对开盘的优势,结合日内波动率标准化。"
49
+ "值越大表示日内动量越强。"
50
+ ),
51
+ category="intraday",
52
+ design_principles=["P1", "P2"],
53
+ operators_used=["point:pointwise"],
54
+ alpha101_ref="#101",
55
+ a_share_compatible=True,
56
+ ),
57
+ FewShotExample(
58
+ id="EX2",
59
+ name="截面动量(5 日)",
60
+ formula="rank(close / ts_lag(close, 5) - 1)",
61
+ description=(
62
+ "5 日动量做截面 rank。"
63
+ "捕捉过去 5 天涨幅最大的股票,趋势跟随策略。"
64
+ ),
65
+ category="momentum",
66
+ design_principles=["P2", "P3"],
67
+ operators_used=["ts_lag", "rank"],
68
+ alpha101_ref="#N/A",
69
+ a_share_compatible=True,
70
+ ),
71
+ FewShotExample(
72
+ id="EX3",
73
+ name="量价背离",
74
+ formula="-1 * ts_corr(open, vol, 10)",
75
+ description=(
76
+ "开盘价与成交量的 10 日滚动相关系数取负。"
77
+ "捕捉量价背离现象:股价涨但成交量不增时,预示反转。"
78
+ ),
79
+ category="volume_price",
80
+ design_principles=["P2", "P8"],
81
+ operators_used=["ts_corr"],
82
+ alpha101_ref="#6",
83
+ a_share_compatible=True,
84
+ ),
85
+
86
+ # ============ 中等示例(3-4 算子)============
87
+ FewShotExample(
88
+ id="EX4",
89
+ name="Alpha 101 #1 简化版",
90
+ formula="rank(ts_argmax(signedpower(close, 2), 5)) - 0.5",
91
+ description=(
92
+ "5 日内 close² 最大值出现的位置做截面 rank 并居中。"
93
+ "极端值在最近 = 强动量;5 天前 = 弱动量。"
94
+ "体现了 signedpower 保留符号 + argmax 提取位置的核心思想。"
95
+ ),
96
+ category="momentum",
97
+ design_principles=["P3", "P4", "P5"],
98
+ operators_used=["rank", "ts_argmax", "signedpower"],
99
+ alpha101_ref="#1 (简化版)",
100
+ a_share_compatible=True,
101
+ ),
102
+ FewShotExample(
103
+ id="EX5",
104
+ name="量增价跌反转",
105
+ formula="sign(ts_delta(vol, 1)) * (-1 * ts_delta(close, 1))",
106
+ description=(
107
+ "量增 + 价跌 = -1(卖出信号)。"
108
+ "量缩 + 价涨 = +1(买入信号)。"
109
+ "其他情况 = 0(无信号)。"
110
+ "这是 Alpha 101 #12 完整版。"
111
+ ),
112
+ category="volume_price",
113
+ design_principles=["P1", "P2"],
114
+ operators_used=["sign", "ts_delta"],
115
+ alpha101_ref="#12",
116
+ a_share_compatible=True,
117
+ ),
118
+ FewShotExample(
119
+ id="EX6",
120
+ name="波动率加权动量",
121
+ formula="rank(ts_mean(close, 8) - ts_mean(close, 21) + ts_std(close, 8))",
122
+ description=(
123
+ "8 日均线相对 21 日均线的偏离度,加上 8 日波动率。"
124
+ "高偏离 + 高波动 = 强动量或反转信号。"
125
+ "(Alpha 101 #21 简化版)"
126
+ ),
127
+ category="momentum",
128
+ design_principles=["P1", "P3"],
129
+ operators_used=["rank", "ts_mean", "ts_std"],
130
+ alpha101_ref="#21 (简化版)",
131
+ a_share_compatible=True,
132
+ ),
133
+
134
+ # ============ 复杂示例(5+ 算子)============
135
+ FewShotExample(
136
+ id="EX7",
137
+ name="波动率反转(ArgMax 提取)",
138
+ formula="rank(ts_argmax(signedpower(close, 2), 5) - ts_argmax(signedpower(close, 2), 20))",
139
+ description=(
140
+ "5 日 vs 20 日的 signedpower 极值位置差。"
141
+ "差值大 = 最近 5 日的极值更新(趋势延续或反转)。"
142
+ "差值小 = 20 日前就有极值(趋势已成熟)。"
143
+ ),
144
+ category="reversal",
145
+ design_principles=["P3", "P4", "P5"],
146
+ operators_used=["rank", "ts_argmax", "signedpower"],
147
+ alpha101_ref="#N/A (派生)",
148
+ a_share_compatible=True,
149
+ ),
150
+ FewShotExample(
151
+ id="EX8",
152
+ name="量价加权反转",
153
+ formula="ts_corr(close, vol, 10) * ts_mean(vol, 20)",
154
+ description=(
155
+ "10 日量价相关 + 20 日均量。"
156
+ "捕捉量价同向 + 高量能时的反转机会。"
157
+ ),
158
+ category="volume_price",
159
+ design_principles=["P1", "P2"],
160
+ operators_used=["ts_corr", "ts_mean"],
161
+ alpha101_ref="#N/A (派生)",
162
+ a_share_compatible=True,
163
+ ),
164
+ FewShotExample(
165
+ id="EX9",
166
+ name="线性加权动量",
167
+ formula="rank(decay_linear(close / ts_lag(close, 5) - 1, 10))",
168
+ description=(
169
+ "5 日收益率做 10 日线性衰减加权(近期权重高)。"
170
+ "捕捉短期动量的持续性。"
171
+ ),
172
+ category="momentum",
173
+ design_principles=["P2", "P3", "P6"],
174
+ operators_used=["rank", "decay_linear", "ts_lag"],
175
+ alpha101_ref="#N/A (派生)",
176
+ a_share_compatible=True,
177
+ ),
178
+ FewShotExample(
179
+ id="EX10",
180
+ name="Alpha 101 #89 完整版",
181
+ formula="rank(decay_linear(ts_sum(close, 10) / 10, 10))",
182
+ description=(
183
+ "10 日 close 求和 / 10 = 10 日均价(与 ts_mean 等价)。"
184
+ "再 10 日线性衰减加权(近期权重高)。"
185
+ "最后截面 rank。"
186
+ "这是 Alpha 101 #89 的 polars 表达。"
187
+ ),
188
+ category="momentum",
189
+ design_principles=["P3", "P6"],
190
+ operators_used=["rank", "decay_linear", "ts_sum"],
191
+ alpha101_ref="#89",
192
+ a_share_compatible=True,
193
+ ),
194
+ ]
195
+
196
+
197
+ # ==============================================================================
198
+ # 辅助函数
199
+ # ==============================================================================
200
+
201
+
202
+ def list_examples(category: Optional[str] = None) -> List[FewShotExample]:
203
+ """列出所有示例(可按 category 过滤)"""
204
+ if category is None:
205
+ return list(ALPHA101_FEW_SHOT_EXAMPLES)
206
+ return [e for e in ALPHA101_FEW_SHOT_EXAMPLES if e.category == category]
207
+
208
+
209
+ def get_example(example_id: str) -> Optional[FewShotExample]:
210
+ """按 ID 查示例"""
211
+ for e in ALPHA101_FEW_SHOT_EXAMPLES:
212
+ if e.id == example_id:
213
+ return e
214
+ return None
215
+
216
+
217
+ def get_few_shot_prompt(
218
+ n: int = 5,
219
+ category: Optional[str] = None,
220
+ ) -> str:
221
+ """构造 few-shot prompt(用于 Alpha-GPT 启动 prompt)
222
+
223
+ Args:
224
+ n: 示例数量
225
+ category: 可选 category 过滤
226
+
227
+ Returns:
228
+ 多行字符串,每行一个示例
229
+ """
230
+ examples = list_examples(category)[:n]
231
+ lines = []
232
+ for e in examples:
233
+ lines.append(
234
+ f"# {e.id} {e.name}\n"
235
+ f"formula: {e.formula}\n"
236
+ f"description: {e.description}\n"
237
+ )
238
+ return "\n".join(lines)
239
+
240
+
241
+ def get_categories() -> List[str]:
242
+ """获取所有 category"""
243
+ return list(set(e.category for e in ALPHA101_FEW_SHOT_EXAMPLES))