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,219 @@
1
+ # coding=utf-8
2
+ """
3
+ few_shot_examples.py - Alpha 158/360 few-shot 示例(用于 Alpha-GPT 启动 prompt)
4
+
5
+ 提供 5-10 个代表性特征示例(覆盖 4 类),供 M5+ 的 Alpha-GPT 路线使用。
6
+ 本 M3 PR 仅做示例定义。
7
+
8
+ 示例选样标准:
9
+ - 覆盖 4 类(KBAR / Price / Volume / Rolling)
10
+ - 简单 → 复杂
11
+ - 经典 + 衍生
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from dataclasses import dataclass, field
17
+ from typing import Any, Dict, List, Optional
18
+
19
+
20
+ @dataclass
21
+ class FewShotExample:
22
+ """Alpha 158/360 few-shot 示例"""
23
+ id: str # 示例 ID (FX1-FX10)
24
+ name: str # 简短名称
25
+ formula: str # 公式
26
+ description: str # 含义
27
+ category: str # KBAR / Price / Volume / Rolling
28
+ operators_used: List[str] # 使用的算子
29
+ qlib_ref: str # Qlib 引用
30
+ alpha158_or_360: str = "alpha158" # 属于哪个特征集
31
+ metadata: Dict[str, Any] = field(default_factory=dict)
32
+
33
+
34
+ # ==============================================================================
35
+ # 10 个精选 few-shot 示例(覆盖 4 类)
36
+ # ==============================================================================
37
+
38
+
39
+ ALPHA158_FEW_SHOT_EXAMPLES: List[FewShotExample] = [
40
+ # ============ KBAR (2 个) ============
41
+ FewShotExample(
42
+ id="FX1",
43
+ name="日内实体占比 KMID",
44
+ formula="(close - open) / open",
45
+ description=(
46
+ "今日实体(close-open)占开盘价的比例。"
47
+ "正值=阳线,负值=阴线。"
48
+ "Alpha 158 KBAR 特征第 1 个。"
49
+ ),
50
+ category="KBAR",
51
+ operators_used=["point"],
52
+ qlib_ref="$KMID",
53
+ ),
54
+ FewShotExample(
55
+ id="FX2",
56
+ name="日内振幅 KLEN",
57
+ formula="(high - low) / open",
58
+ description=(
59
+ "日内最高减最低的振幅除以开盘价。"
60
+ "捕捉日内波动率。"
61
+ ),
62
+ category="KBAR",
63
+ operators_used=["point"],
64
+ qlib_ref="$KLEN",
65
+ ),
66
+
67
+ # ============ Price (2 个) ============
68
+ FewShotExample(
69
+ id="FX3",
70
+ name="昨日开盘相对今日收盘",
71
+ formula="open.shift(1) / close",
72
+ description=(
73
+ "昨日开盘价 / 今日收盘价。"
74
+ "捕捉隔夜 gap 和当日走势。"
75
+ ),
76
+ category="Price",
77
+ operators_used=["ts_lag"],
78
+ qlib_ref="$OPEN1",
79
+ ),
80
+ FewShotExample(
81
+ id="FX4",
82
+ name="3 日前最高相对今日收盘",
83
+ formula="high.shift(3) / close",
84
+ description=(
85
+ "3 日前最高价 / 今日收盘价。"
86
+ "Alpha 158 Price 特征 4 字段 × 5 延迟中的一个。"
87
+ ),
88
+ category="Price",
89
+ operators_used=["ts_lag"],
90
+ qlib_ref="$HIGH3",
91
+ ),
92
+
93
+ # ============ Volume (1 个) ============
94
+ FewShotExample(
95
+ id="FX5",
96
+ name="3 日前成交量比",
97
+ formula="volume.shift(3) / (volume + 1e-12)",
98
+ description=(
99
+ "3 日前成交量 / 今日成交量。"
100
+ "Alpha 158 Volume 5 特征之一。"
101
+ ),
102
+ category="Volume",
103
+ operators_used=["ts_lag"],
104
+ qlib_ref="$VOLUME3",
105
+ ),
106
+
107
+ # ============ Rolling (5 个) ============
108
+ FewShotExample(
109
+ id="FX6",
110
+ name="20 日均线",
111
+ formula="close.rolling(20).mean()",
112
+ description=(
113
+ "20 日收盘价简单移动平均。"
114
+ "Alpha 158 Rolling MA 之一(25 op × 5 window = 125 MA 类特征)。"
115
+ ),
116
+ category="Rolling",
117
+ operators_used=["ts_mean"],
118
+ qlib_ref="$MA20",
119
+ ),
120
+ FewShotExample(
121
+ id="FX7",
122
+ name="20 日变化率 ROC",
123
+ formula="close / close.shift(20) - 1",
124
+ description=(
125
+ "20 日收益率:今日 close / 20 日前 close - 1。"
126
+ "Alpha 158 Rolling ROC 之一。"
127
+ ),
128
+ category="Rolling",
129
+ operators_used=["ts_lag"],
130
+ qlib_ref="$ROC20",
131
+ ),
132
+ FewShotExample(
133
+ id="FX8",
134
+ name="20 日波动率 STD",
135
+ formula="close.rolling(20).std()",
136
+ description=(
137
+ "20 日收盘价标准差(年化前需 × sqrt(252))。"
138
+ "Alpha 158 Rolling STD 之一。"
139
+ ),
140
+ category="Rolling",
141
+ operators_used=["ts_std"],
142
+ qlib_ref="$STD20",
143
+ ),
144
+ FewShotExample(
145
+ id="FX9",
146
+ name="量价 20 日相关 CORR",
147
+ formula="close.rolling(20).corr(volume)",
148
+ description=(
149
+ "20 日量价滚动相关系数。"
150
+ "Alpha 158 Rolling CORR 之一。"
151
+ "量价同涨同跌为 +1,反向 -1。"
152
+ ),
153
+ category="Rolling",
154
+ operators_used=["ts_corr"],
155
+ qlib_ref="$CORR20",
156
+ ),
157
+ FewShotExample(
158
+ id="FX10",
159
+ name="20 日极值位置 IMAX",
160
+ formula="ts_argmax(high, 20)",
161
+ description=(
162
+ "20 日内最高价出现的位置(距今天数)。"
163
+ "值小(最近创新高)= 强动量。"
164
+ "Alpha 158 Rolling IMAX 之一。"
165
+ ),
166
+ category="Rolling",
167
+ operators_used=["ts_argmax"],
168
+ qlib_ref="$IMAX20",
169
+ ),
170
+ ]
171
+
172
+
173
+ # ==============================================================================
174
+ # 辅助函数
175
+ # ==============================================================================
176
+
177
+
178
+ def list_examples(category: Optional[str] = None) -> List[FewShotExample]:
179
+ """列出所有示例(可按 category 过滤)"""
180
+ if category is None:
181
+ return list(ALPHA158_FEW_SHOT_EXAMPLES)
182
+ return [e for e in ALPHA158_FEW_SHOT_EXAMPLES if e.category == category]
183
+
184
+
185
+ def get_example(example_id: str) -> Optional[FewShotExample]:
186
+ """按 ID 查示例"""
187
+ for e in ALPHA158_FEW_SHOT_EXAMPLES:
188
+ if e.id == example_id:
189
+ return e
190
+ return None
191
+
192
+
193
+ def get_few_shot_prompt(
194
+ n: int = 5,
195
+ category: Optional[str] = None,
196
+ ) -> str:
197
+ """构造 few-shot prompt(用于 Alpha-GPT 启动 prompt)
198
+
199
+ Args:
200
+ n: 示例数量
201
+ category: 可选 category 过滤
202
+
203
+ Returns:
204
+ 多行字符串,每行一个示例
205
+ """
206
+ examples = list_examples(category)[:n]
207
+ lines = []
208
+ for e in examples:
209
+ lines.append(
210
+ f"# {e.id} {e.name} [{e.category}]\n"
211
+ f"formula: {e.formula}\n"
212
+ f"description: {e.description}\n"
213
+ )
214
+ return "\n".join(lines)
215
+
216
+
217
+ def get_categories() -> List[str]:
218
+ """获取所有 category"""
219
+ return list(set(e.category for e in ALPHA158_FEW_SHOT_EXAMPLES))
@@ -0,0 +1,240 @@
1
+ # coding=utf-8
2
+ """
3
+ philosophy.py - Alpha 158/360 特征设计哲学 + 4 类模板
4
+
5
+ vs 直接移植 158/360 公式:本文件**仅做借鉴**,提取:
6
+ - 4 类特征的设计哲学(KBAR / Price / Volume / Rolling)
7
+ - 每类的公式模板(参数化)
8
+ - 类别间的依赖关系
9
+
10
+ 参考:
11
+ - Yang, X. et al. (2020). "Qlib." arXiv:2009.11189
12
+ - qlib.contrib.data.handler.Alpha158/Alpha360
13
+ - WeChat article: 四大量化因子库
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ from dataclasses import dataclass, field
19
+ from typing import Any, Dict, List, Optional
20
+
21
+
22
+ # 默认窗口
23
+ DEFAULT_WINDOWS = [5, 10, 20, 30, 60]
24
+
25
+ # Alpha 360 默认 lookback 范围
26
+ ALPHA360_LOOKBACK_RANGE = list(range(60)) # 0-59
27
+
28
+
29
+ @dataclass
30
+ class CategoryTemplate:
31
+ """特征类别的设计模板
32
+
33
+ Attributes:
34
+ name: 类别名
35
+ total_features: 该类别的特征总数(Alpha 158 子集)
36
+ philosophy: 设计哲学描述
37
+ formula_template: 公式模板(含 {field} / {window} 等占位符)
38
+ parameters: 可调参数
39
+ examples: 几个公式示例
40
+ category_id: 类别 ID
41
+ """
42
+ category_id: str # KBAR / Price / Volume / Rolling
43
+ name: str
44
+ total_features: int
45
+ philosophy: str
46
+ formula_template: str
47
+ parameters: Dict[str, List[Any]] = field(default_factory=dict)
48
+ examples: List[str] = field(default_factory=list)
49
+ metadata: Dict[str, Any] = field(default_factory=dict)
50
+
51
+
52
+ # ==============================================================================
53
+ # 4 类特征模板(Alpha 158)
54
+ # ==============================================================================
55
+
56
+ FEATURE_CATEGORIES: List[CategoryTemplate] = [
57
+ CategoryTemplate(
58
+ category_id="KBAR",
59
+ name="K线形态",
60
+ total_features=9,
61
+ philosophy=(
62
+ "KBAR 特征捕捉单根 K 线的几何信息(实体长度、上下影线、价格重心)。"
63
+ "所有 KBAR 特征都做归一化(除以 open 或 high-low 振幅),"
64
+ "消除价格水平影响。"
65
+ ),
66
+ formula_template=(
67
+ # 单根 K 线的几何特征
68
+ "({expr}) / {denominator}"
69
+ ),
70
+ parameters={
71
+ "denominator": ["open", "$close - $open + 1e-12", "high - low + 1e-12"],
72
+ },
73
+ examples=[
74
+ "KMID = (close - open) / open", # 实体占比
75
+ "KLEN = (high - low) / open", # 振幅
76
+ "KMID2 = (close - open) / ((high - low) + 1e-12)", # 实体占振幅
77
+ "KSFT = (2 * close - high - low) / open", # 重心偏移
78
+ "KUP = (high - max(open, close)) / open", # 上影线
79
+ "KLOW = (min(open, close) - low) / open", # 下影线
80
+ ],
81
+ metadata={"qlib": "KBAR", "factors": 9},
82
+ ),
83
+ CategoryTemplate(
84
+ category_id="Price",
85
+ name="价格时序",
86
+ total_features=20,
87
+ philosophy=(
88
+ "Price 特征是历史价格相对当前价格的归一化值。"
89
+ "形式:Ref($field, d) / $close,field ∈ {OPEN, HIGH, LOW, VWAP},"
90
+ "d ∈ {0, 1, 2, 3, 4}。4 字段 × 5 延迟 = 20 特征。"
91
+ "无截面算子(pure time-series)。"
92
+ ),
93
+ formula_template="Ref({field}, {delay}) / $close",
94
+ parameters={
95
+ "field": ["open", "high", "low", "vwap"],
96
+ "delay": [0, 1, 2, 3, 4],
97
+ },
98
+ examples=[
99
+ "OPEN0 = open / close", # 今日开盘 / 今日收盘
100
+ "OPEN1 = open.shift(1) / close", # 昨日开盘 / 今日收盘
101
+ "HIGH0 = high / close",
102
+ "LOW0 = low / close",
103
+ "VWAP0 = vwap / close",
104
+ ],
105
+ metadata={"qlib": "Price", "factors": 20},
106
+ ),
107
+ CategoryTemplate(
108
+ category_id="Volume",
109
+ name="成交量时序",
110
+ total_features=5,
111
+ philosophy=(
112
+ "Volume 特征是历史成交量相对当前成交量的比值。"
113
+ "形式:Ref($volume, d) / ($volume + 1e-12),d ∈ {0, 1, 2, 3, 4}。"
114
+ "捕捉量能变化:d=0 是今日成交;d=1-4 是历史成交。"
115
+ ),
116
+ formula_template="Ref({field}, {delay}) / ({field} + 1e-12)",
117
+ parameters={
118
+ "field": ["volume"],
119
+ "delay": [0, 1, 2, 3, 4],
120
+ },
121
+ examples=[
122
+ "VOL0 = volume / (volume + 1e-12)", # 今日量 / 今日量 ≈ 1
123
+ "VOL1 = volume.shift(1) / (volume + 1e-12)", # 昨日量 / 今日量
124
+ "VOL2 = volume.shift(2) / (volume + 1e-12)",
125
+ ],
126
+ metadata={"qlib": "Volume", "factors": 5},
127
+ ),
128
+ CategoryTemplate(
129
+ category_id="Rolling",
130
+ name="滚动统计",
131
+ total_features=124,
132
+ philosophy=(
133
+ "Rolling 特征是 25 种统计指标 × 5 个时间窗口(5/10/20/30/60)的笛卡尔积。"
134
+ "统计指标:ROC, MA, STD, BETA(Slope), RSQR, RESI, MAX, MIN, QTLU, QTLD, "
135
+ "RANK, RSV, IMAX, IMIN, IMXD, CORR, CORD, CNTP, CNTN, SUMP, SUMN, "
136
+ "VMA, VSTD, WVMA, VSUMP, VSUMN。"
137
+ "这些特征可同时喂给 LightGBM/XGBoost/LSTM 等 ML 模型。"
138
+ ),
139
+ formula_template=(
140
+ "rolling_{op}({field}, {window})"
141
+ ),
142
+ parameters={
143
+ "op": [
144
+ "roc", # 变化率: close / lag(close, w) - 1
145
+ "ma", # 移动平均
146
+ "std", # 标准差
147
+ "beta", # 斜率(回归系数)
148
+ "rsqr", # R²
149
+ "resi", # 残差
150
+ "max", # 最大值
151
+ "min", # 最小值
152
+ "qtlu", # 上分位数(0.7)
153
+ "qtld", # 下分位数(0.3)
154
+ "rank", # 滚动 rank
155
+ "rsv", # RSV (类 KDJ 随机指标)
156
+ "imax", # argmax 位置
157
+ "imin", # argmin 位置
158
+ "imxd", # argmax - argmin
159
+ "corr", # 相关(双字段)
160
+ "cntp", # count positive
161
+ "cntn", # count negative
162
+ "sump", # sum positive
163
+ "sumn", # sum negative
164
+ "vma", # 量能 MA
165
+ "vstd", # 量能 std
166
+ "wvma", # weighted VMA
167
+ "vsump", # 量能 sum positive
168
+ "vsumn", # 量能 sum negative
169
+ ],
170
+ "window": [5, 10, 20, 30, 60],
171
+ "field": ["close", "open", "high", "low", "vwap", "volume"],
172
+ },
173
+ examples=[
174
+ "ROC(close, 5) = close / close.shift(5) - 1",
175
+ "MA(close, 20) = close.rolling(20).mean()",
176
+ "STD(close, 20) = close.rolling(20).std()",
177
+ "BETA(close, volume, 20) = rolling_beta(close, volume, 20)",
178
+ "CORR(close, volume, 20) = rolling_corr(close, volume, 20)",
179
+ "CNTP(close, 20) = count(close > close.shift(1), 20)",
180
+ "IMAX(high, 30) = argmax(high, 30)",
181
+ ],
182
+ metadata={"qlib": "Rolling", "factors": 124, "ops": 25, "windows": 5},
183
+ ),
184
+ ]
185
+
186
+
187
+ # ==============================================================================
188
+ # Alpha 360 模板
189
+ # ==============================================================================
190
+
191
+
192
+ @dataclass
193
+ class Alpha360Template:
194
+ """Alpha 360 模板(6 字段 × 60 lookback = 360 特征)"""
195
+ fields: List[str] = field(default_factory=lambda: ["close", "open", "high", "low", "vwap", "volume"])
196
+ lookback_range: List[int] = field(default_factory=lambda: list(range(60)))
197
+ total_features: int = 360
198
+ philosophy: str = (
199
+ "Alpha 360 把 6 个原始字段在 60 个 lookback 时间步上的值作为特征。"
200
+ "价格字段除以当日 close 归一化,成交量字段除以当日成交量归一化。"
201
+ "形成 (60, 6) 的二维矩阵,天然适合序列深度学习模型(GRU/LSTM/Transformer)。"
202
+ )
203
+
204
+ def formula_template(self) -> str:
205
+ """公式模板"""
206
+ return "Ref({field}, {delay}) / {denominator}"
207
+
208
+
209
+ ALPHA360_TEMPLATE = Alpha360Template()
210
+
211
+
212
+ # ==============================================================================
213
+ # 辅助函数
214
+ # ==============================================================================
215
+
216
+
217
+ def get_template_by_category(category_id: str) -> Optional[CategoryTemplate]:
218
+ """按 category_id 查模板"""
219
+ for t in FEATURE_CATEGORIES:
220
+ if t.category_id == category_id:
221
+ return t
222
+ return None
223
+
224
+
225
+ def get_template_by_name(name: str) -> Optional[CategoryTemplate]:
226
+ """按 name 查模板"""
227
+ for t in FEATURE_CATEGORIES:
228
+ if t.name == name:
229
+ return t
230
+ return None
231
+
232
+
233
+ def list_categories() -> List[str]:
234
+ """列出所有 category_id"""
235
+ return [t.category_id for t in FEATURE_CATEGORIES]
236
+
237
+
238
+ def total_feature_count() -> int:
239
+ """Alpha 158 总特征数(=158)"""
240
+ return sum(t.total_features for t in FEATURE_CATEGORIES)
@@ -0,0 +1,47 @@
1
+ # coding=utf-8
2
+ """Table 4 复现的 evaluation 子包
3
+
4
+ Stage 1 mock + Stage 2 real 复用同一接口契约(contracts.py)。
5
+
6
+ 主要组件:
7
+ - contracts.py:4 dataclass + 4 ABC(接口契约)
8
+ - mock_data_loader.py:Stage 1 500 票 GBM 数据生成
9
+ - clickhouse_data_loader.py:Stage 2 ClickHouse 数据加载
10
+ - evaluators/polars_evaluator.py:基于 alpha_evaluate tool 的 PolarsEvaluator
11
+ - baselines/g1_handcrafted.py:动态从 OperatorVocab 生成 100 公式
12
+ - baselines/g2_llm_only.py:LLM 直接生成公式 (mock / 真实)
13
+ - baselines/g3_alpha_gpt.py:包 AlphaGptWorkflow(M5)
14
+ - runner.py:MockTable4Runner + RealTable4Runner 主入口
15
+ """
16
+
17
+ from .contracts import (
18
+ Baseline,
19
+ DataLoader,
20
+ Evaluator,
21
+ FactorMetrics,
22
+ FactorSpec,
23
+ Table4GroupResult,
24
+ Table4Report,
25
+ Table4Runner,
26
+ )
27
+ from .evaluators import PolarsAlphaCalculatorEvaluator
28
+ from .mock_data_loader import MOCK_INDUSTRIES, MockDataLoader
29
+ from .clickhouse_data_loader import ClickHouseDataLoader
30
+ from .runner import MockTable4Runner, RealTable4Runner
31
+
32
+ __all__ = [
33
+ "DataLoader",
34
+ "Evaluator",
35
+ "Baseline",
36
+ "Table4Runner",
37
+ "FactorSpec",
38
+ "FactorMetrics",
39
+ "Table4GroupResult",
40
+ "Table4Report",
41
+ "PolarsAlphaCalculatorEvaluator",
42
+ "MockDataLoader",
43
+ "ClickHouseDataLoader",
44
+ "MockTable4Runner",
45
+ "RealTable4Runner",
46
+ "MOCK_INDUSTRIES",
47
+ ]
@@ -0,0 +1,8 @@
1
+ # coding=utf-8
2
+ """Baselines 子包(G1 / G2 / G3)"""
3
+
4
+ from .g1_handcrafted import G1Handcrafted
5
+ from .g2_llm_only import G2LlmOnly
6
+ from .g3_alpha_gpt import G3AlphaGpt
7
+
8
+ __all__ = ["G1Handcrafted", "G2LlmOnly", "G3AlphaGpt"]
@@ -0,0 +1,135 @@
1
+ # coding=utf-8
2
+ """
3
+ g1_handcrafted.py - G1 baseline:动态从 OperatorVocab 生成 100 个手工公式
4
+
5
+ G1 = "手工构造(Handcrafted)",代表 101/158 等论文公开的算子组合。
6
+ Stage 1 动态生成(不硬编码),从 OperatorVocab 抽取合法组合。
7
+
8
+ 为什么动态生成:
9
+ - 避免硬编码 100 公式导致难以维护
10
+ - OperatorVocab 已注册 162 算子(M1),动态组合可生成大量候选
11
+ - 与 G2(mock LLM 直接生成)和 G3(AlphaGptWorkflow)形成对照
12
+
13
+ 公式生成规则(仅限 alpha_evaluate tool 支持的算子):
14
+ - 字段:close / vol / amount
15
+ - 时间窗口:ts_mean / ts_std / delta(window ∈ {3, 5, 10, 20})
16
+ - 二元组合:Add / Sub / Mul / Div
17
+ - 一元:abs / log / sign / neg
18
+ - 嵌套深度 ≤ 2
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import logging
24
+ import random
25
+ from typing import List, Optional
26
+
27
+ from ..contracts import Baseline, FactorSpec
28
+
29
+ logger = logging.getLogger(__name__)
30
+
31
+ __all__ = ["G1Handcrafted"]
32
+
33
+
34
+ FIELDS = ["close", "vol", "amount"]
35
+ WINDOWS = [3, 5, 10, 20]
36
+ TIME_OPS = ["ts_mean", "ts_std", "delta"]
37
+ CROSS_OPS = ["abs", "log", "sign", "sqrt"]
38
+ BINARY_OPS = ["Add", "Sub", "Mul", "Div"]
39
+
40
+
41
+ def _gen_leaf(rng: random.Random) -> str:
42
+ """生成叶子节点:字段或字段上的时间窗口算子"""
43
+ field = rng.choice(FIELDS)
44
+ if rng.random() < 0.7: # 70% 包时间窗口
45
+ op = rng.choice(TIME_OPS)
46
+ window = rng.choice(WINDOWS)
47
+ return f"{op}({field}, {window})"
48
+ return field
49
+
50
+
51
+ def _gen_formula(rng: random.Random, max_depth: int = 2) -> str:
52
+ """生成一条公式字符串"""
53
+ leaf_left = _gen_leaf(rng)
54
+ leaf_right = _gen_leaf(rng)
55
+
56
+ # 50% 应用 cross-sectional 算子
57
+ if rng.random() < 0.3:
58
+ cross = rng.choice(CROSS_OPS)
59
+ leaf_left = f"{cross}({leaf_left})"
60
+
61
+ if max_depth <= 1 or rng.random() < 0.6:
62
+ # 单层
63
+ if rng.random() < 0.5:
64
+ return leaf_left
65
+ op = rng.choice(BINARY_OPS)
66
+ return f"{op}({leaf_left}, {leaf_right})"
67
+ else:
68
+ # 双层嵌套
69
+ op1 = rng.choice(BINARY_OPS)
70
+ op2 = rng.choice(BINARY_OPS)
71
+ leaf3 = _gen_leaf(rng)
72
+ return f"{op1}({op2}({leaf_left}, {leaf_right}), {leaf3})"
73
+
74
+
75
+ class G1Handcrafted(Baseline):
76
+ """G1 Handcrafted baseline
77
+
78
+ 从 OperatorVocab 动态组合生成 n 个手工因子。
79
+ Stage 1 与 Stage 2 共用(不依赖数据 / LLM)。
80
+ """
81
+
82
+ def __init__(self, n: int = 100, seed: int = 42) -> None:
83
+ self.n = n
84
+ self.seed = seed
85
+
86
+ @property
87
+ def group_name(self) -> str:
88
+ return "G1_Handcrafted"
89
+
90
+ def generate_factors(self, n: Optional[int] = None) -> List[FactorSpec]:
91
+ """动态生成 n 个因子(formula_id 唯一)"""
92
+ n = n or self.n
93
+ rng = random.Random(self.seed)
94
+
95
+ factors: List[FactorSpec] = []
96
+ seen_formulas: set = set()
97
+
98
+ attempts = 0
99
+ while len(factors) < n and attempts < n * 5:
100
+ attempts += 1
101
+ formula = _gen_formula(rng)
102
+ if formula in seen_formulas:
103
+ continue
104
+ seen_formulas.add(formula)
105
+
106
+ category = self._infer_category(formula)
107
+ factors.append(
108
+ FactorSpec(
109
+ formula_id=f"G1_{len(factors):03d}",
110
+ formula=formula,
111
+ source="g1_handcrafted",
112
+ category=category,
113
+ complexity=formula.count("("),
114
+ meta={"seed": self.seed},
115
+ )
116
+ )
117
+
118
+ logger.info(
119
+ "[G1] generated %d factors (attempts=%d)", len(factors), attempts
120
+ )
121
+ return factors
122
+
123
+ @staticmethod
124
+ def _infer_category(formula: str) -> str:
125
+ if "ts_mean" in formula and "delta" not in formula:
126
+ return "momentum"
127
+ if "delta" in formula:
128
+ return "momentum"
129
+ if "ts_std" in formula:
130
+ return "volatility"
131
+ if "vol" in formula:
132
+ return "volume"
133
+ if "abs" in formula:
134
+ return "reversal"
135
+ return "value"