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.
- QuantNodes/__init__.py +15 -0
- QuantNodes/__main__.py +14 -0
- QuantNodes/agent/__init__.py +158 -0
- QuantNodes/agent/agents/__init__.py +13 -0
- QuantNodes/agent/agents/definition.py +180 -0
- QuantNodes/agent/agents/manager.py +73 -0
- QuantNodes/agent/config/__init__.py +34 -0
- QuantNodes/agent/config/executor.py +958 -0
- QuantNodes/agent/config/loader.py +427 -0
- QuantNodes/agent/config/templates/bollinger_bands.yaml +84 -0
- QuantNodes/agent/config/templates/dual_ma.yaml +72 -0
- QuantNodes/agent/config/templates/empty.yaml +56 -0
- QuantNodes/agent/config/templates/mean_reversion.yaml +47 -0
- QuantNodes/agent/config/templates/mean_reversion_zscore.yaml +90 -0
- QuantNodes/agent/config/templates/momentum.yaml +81 -0
- QuantNodes/agent/config/templates/momentum_breakout.yaml +84 -0
- QuantNodes/agent/config/templates/rsi_strategy.yaml +72 -0
- QuantNodes/agent/config/templates/volume_price.yaml +86 -0
- QuantNodes/agent/config/types.py +156 -0
- QuantNodes/agent/config_mapper.py +293 -0
- QuantNodes/agent/core/__init__.py +19 -0
- QuantNodes/agent/core/dream.py +47 -0
- QuantNodes/agent/core/quant_dream.py +274 -0
- QuantNodes/agent/cron_jobs.py +314 -0
- QuantNodes/agent/nanobot_bridge.py +242 -0
- QuantNodes/agent/permission/__init__.py +30 -0
- QuantNodes/agent/permission/defaults.py +36 -0
- QuantNodes/agent/permission/evaluate.py +41 -0
- QuantNodes/agent/permission/models.py +59 -0
- QuantNodes/agent/permission/service.py +133 -0
- QuantNodes/agent/providers/__init__.py +11 -0
- QuantNodes/agent/providers/base.py +102 -0
- QuantNodes/agent/providers/quantnodes.py +610 -0
- QuantNodes/agent/providers/rate_limiter.py +326 -0
- QuantNodes/agent/providers/registry.py +163 -0
- QuantNodes/agent/skills/__init__.py +20 -0
- QuantNodes/agent/skills/base.py +118 -0
- QuantNodes/agent/skills/bridge.py +73 -0
- QuantNodes/agent/skills/factor/__init__.py +14 -0
- QuantNodes/agent/skills/factor/correlation.py +99 -0
- QuantNodes/agent/skills/factor/group_backtest.py +114 -0
- QuantNodes/agent/skills/factor/ic_analysis.py +106 -0
- QuantNodes/agent/skills/loader.py +107 -0
- QuantNodes/agent/skills/registry.py +105 -0
- QuantNodes/agent/skills/strategy/__init__.py +16 -0
- QuantNodes/agent/skills/strategy/bollinger.py +86 -0
- QuantNodes/agent/skills/strategy/dual_ma.py +82 -0
- QuantNodes/agent/skills/strategy/momentum.py +74 -0
- QuantNodes/agent/skills/strategy/rsi_reversal.py +99 -0
- QuantNodes/agent/skills_quant/__init__.py +14 -0
- QuantNodes/agent/skills_quant/backtest-analyze/SKILL.md +42 -0
- QuantNodes/agent/skills_quant/config-driven/SKILL.md +72 -0
- QuantNodes/agent/skills_quant/factor-research/SKILL.md +40 -0
- QuantNodes/agent/skills_quant/quant-dream/SKILL.md +55 -0
- QuantNodes/agent/skills_quant/risk-management/SKILL.md +45 -0
- QuantNodes/agent/skills_quant/strategy-design/SKILL.md +43 -0
- QuantNodes/agent/templates/__init__.py +4 -0
- QuantNodes/agent/tools/__init__.py +173 -0
- QuantNodes/agent/tools/_workspace.py +51 -0
- QuantNodes/agent/tools/alpha_backtest.py +328 -0
- QuantNodes/agent/tools/alpha_evaluate.py +493 -0
- QuantNodes/agent/tools/backtest.py +226 -0
- QuantNodes/agent/tools/base.py +133 -0
- QuantNodes/agent/tools/code_search.py +207 -0
- QuantNodes/agent/tools/config_backtest.py +401 -0
- QuantNodes/agent/tools/context.py +97 -0
- QuantNodes/agent/tools/dream_skill.py +77 -0
- QuantNodes/agent/tools/echo.py +38 -0
- QuantNodes/agent/tools/factor.py +231 -0
- QuantNodes/agent/tools/file_ops.py +201 -0
- QuantNodes/agent/tools/git_ops.py +190 -0
- QuantNodes/agent/tools/operator_lookup.py +218 -0
- QuantNodes/agent/tools/output_truncation.py +77 -0
- QuantNodes/agent/tools/path_check.py +43 -0
- QuantNodes/agent/tools/pipeline.py +62 -0
- QuantNodes/agent/tools/registry.py +150 -0
- QuantNodes/agent/tools/sandbox.py +62 -0
- QuantNodes/agent/tools/shell_safety.py +63 -0
- QuantNodes/agent/tools/strategy.py +106 -0
- QuantNodes/agent/tools/task.py +171 -0
- QuantNodes/agent/tools/web_fetch.py +142 -0
- QuantNodes/agent/tools/web_search.py +114 -0
- QuantNodes/agent/tools/wiki.py +370 -0
- QuantNodes/agent/utils/__init__.py +11 -0
- QuantNodes/agent/utils/helpers.py +43 -0
- QuantNodes/agent/utils/prompt_templates.py +30 -0
- QuantNodes/agent/workflows/__init__.py +20 -0
- QuantNodes/agent/workflows/implementations/__init__.py +8 -0
- QuantNodes/agent/workflows/implementations/alpha_gpt.py +508 -0
- QuantNodes/agent/workflows/implementations/mcts.py +442 -0
- QuantNodes/agent/workflows/parsers.py +44 -0
- QuantNodes/agent/workflows/registry.py +119 -0
- QuantNodes/agent/workflows/step_agent.py +219 -0
- QuantNodes/agent/workflows/tool.py +198 -0
- QuantNodes/ai/__init__.py +93 -0
- QuantNodes/ai/llm/__init__.py +75 -0
- QuantNodes/ai/llm/base.py +233 -0
- QuantNodes/ai/llm/decorators.py +281 -0
- QuantNodes/ai/llm/gateway.py +571 -0
- QuantNodes/ai/llm/null.py +76 -0
- QuantNodes/ai/llm/openai.py +435 -0
- QuantNodes/ai/optimizer.py +405 -0
- QuantNodes/ai/prompts/__init__.py +229 -0
- QuantNodes/ai/sandbox.py +371 -0
- QuantNodes/ai/sandbox_pandas_bridge.py +150 -0
- QuantNodes/ai/strategy_gen.py +396 -0
- QuantNodes/backtest/__init__.py +64 -0
- QuantNodes/backtest/backtest_node.py +188 -0
- QuantNodes/backtest/broker_node.py +378 -0
- QuantNodes/backtest/config_runner.py +397 -0
- QuantNodes/backtest/config_strategy.py +64 -0
- QuantNodes/backtest/risk_node.py +360 -0
- QuantNodes/backtest/strategy_node.py +268 -0
- QuantNodes/cache_node/__init__.py +19 -0
- QuantNodes/cache_node/base.py +244 -0
- QuantNodes/cache_node/cache_store.py +99 -0
- QuantNodes/cache_node/metadata.py +100 -0
- QuantNodes/cli/__init__.py +109 -0
- QuantNodes/cli/_helpers.py +511 -0
- QuantNodes/cli/command.py +110 -0
- QuantNodes/cli/commands/__init__.py +69 -0
- QuantNodes/cli/commands/agent.py +158 -0
- QuantNodes/cli/commands/alpha.py +951 -0
- QuantNodes/cli/commands/chat.py +38 -0
- QuantNodes/cli/commands/evolve.py +120 -0
- QuantNodes/cli/commands/factor.py +569 -0
- QuantNodes/cli/commands/init.py +190 -0
- QuantNodes/cli/commands/run.py +259 -0
- QuantNodes/cli/commands/serve.py +398 -0
- QuantNodes/cli/commands/version.py +120 -0
- QuantNodes/cli/enhanced.py +146 -0
- QuantNodes/conf_node/__init__.py +37 -0
- QuantNodes/conf_node/base.py +120 -0
- QuantNodes/conf_node/env_config.py +132 -0
- QuantNodes/conf_node/ini_config.py +70 -0
- QuantNodes/conf_node/json_config.py +69 -0
- QuantNodes/conf_node/yaml_config.py +78 -0
- QuantNodes/constants.py +17 -0
- QuantNodes/core/__init__.py +196 -0
- QuantNodes/core/_lookback_helpers.py +49 -0
- QuantNodes/core/ast_parser.py +198 -0
- QuantNodes/core/base.py +61 -0
- QuantNodes/core/cache_manager.py +344 -0
- QuantNodes/core/cache_utils.py +150 -0
- QuantNodes/core/cond_builder.py +53 -0
- QuantNodes/core/config.py +170 -0
- QuantNodes/core/constants.py +48 -0
- QuantNodes/core/control.py +412 -0
- QuantNodes/core/data_preprocessing.py +453 -0
- QuantNodes/core/data_source.py +46 -0
- QuantNodes/core/events.py +178 -0
- QuantNodes/core/evolution/__init__.py +22 -0
- QuantNodes/core/evolution/loop.py +583 -0
- QuantNodes/core/evolution/operators.py +289 -0
- QuantNodes/core/evolution/settings.py +44 -0
- QuantNodes/core/expression.py +841 -0
- QuantNodes/core/feedback/__init__.py +38 -0
- QuantNodes/core/feedback/channels.py +182 -0
- QuantNodes/core/feedback/collector.py +91 -0
- QuantNodes/core/feedback/dataclass.py +239 -0
- QuantNodes/core/feedback/llm_judge.py +138 -0
- QuantNodes/core/knowledge/__init__.py +69 -0
- QuantNodes/core/knowledge/knowledge_base.py +217 -0
- QuantNodes/core/knowledge/lineage_compress.py +196 -0
- QuantNodes/core/knowledge/lineage_expand.py +123 -0
- QuantNodes/core/knowledge/metrics/__init__.py +43 -0
- QuantNodes/core/knowledge/metrics/evaluator.py +176 -0
- QuantNodes/core/knowledge/metrics/metrics.py +220 -0
- QuantNodes/core/knowledge/rag_prompt.py +196 -0
- QuantNodes/core/knowledge/retriever.py +209 -0
- QuantNodes/core/lambda_node.py +81 -0
- QuantNodes/core/monitoring/__init__.py +22 -0
- QuantNodes/core/monitoring/collector.py +292 -0
- QuantNodes/core/monitoring/dashboard.py +365 -0
- QuantNodes/core/node.py +375 -0
- QuantNodes/core/pandas_utils.py +504 -0
- QuantNodes/core/parallel/__init__.py +15 -0
- QuantNodes/core/parallel/worker.py +140 -0
- QuantNodes/core/parallel/worker_process.py +265 -0
- QuantNodes/core/path_utils.py +73 -0
- QuantNodes/core/pipeline.py +328 -0
- QuantNodes/core/plugin.py +135 -0
- QuantNodes/core/quality_gate/__init__.py +32 -0
- QuantNodes/core/quality_gate/complexity.py +94 -0
- QuantNodes/core/quality_gate/consistency.py +26 -0
- QuantNodes/core/quality_gate/node.py +97 -0
- QuantNodes/core/quality_gate/redundancy.py +51 -0
- QuantNodes/core/quality_gate/settings.py +43 -0
- QuantNodes/core/quality_gate/zoo.py +98 -0
- QuantNodes/core/serializable.py +116 -0
- QuantNodes/core/serialization.py +673 -0
- QuantNodes/core/tools.py +333 -0
- QuantNodes/core/trajectory/__init__.py +25 -0
- QuantNodes/core/trajectory/entry.py +116 -0
- QuantNodes/core/trajectory/lineage.py +67 -0
- QuantNodes/core/trajectory/pool.py +211 -0
- QuantNodes/core/trajectory/selector.py +140 -0
- QuantNodes/core/visualization/__init__.py +33 -0
- QuantNodes/core/visualization/builder.py +233 -0
- QuantNodes/core/visualization/gate_breakdown.py +140 -0
- QuantNodes/core/visualization/lineage_dag.py +203 -0
- QuantNodes/core/visualization/metric_distribution.py +125 -0
- QuantNodes/core/visualization/report.py +68 -0
- QuantNodes/database_node/__init__.py +69 -0
- QuantNodes/database_node/base.py +135 -0
- QuantNodes/database_node/clickhouse_node.py +272 -0
- QuantNodes/database_node/csv_node.py +83 -0
- QuantNodes/database_node/duckdb_node.py +86 -0
- QuantNodes/database_node/factory.py +83 -0
- QuantNodes/database_node/mysql_node.py +100 -0
- QuantNodes/database_node/parquet_node.py +75 -0
- QuantNodes/database_node/sqlite_node.py +67 -0
- QuantNodes/factor_node/__init__.py +50 -0
- QuantNodes/factor_node/factor.py +563 -0
- QuantNodes/factor_node/factor_db.py +421 -0
- QuantNodes/factor_node/factor_functions/__init__.py +252 -0
- QuantNodes/factor_node/factor_functions/_helpers.py +358 -0
- QuantNodes/factor_node/factor_functions/_helpers_debug.py +317 -0
- QuantNodes/factor_node/factor_functions/composite_ops.py +136 -0
- QuantNodes/factor_node/factor_functions/math_ops.py +433 -0
- QuantNodes/factor_node/factor_functions/section_ops.py +290 -0
- QuantNodes/factor_node/factor_functions/talib_ops.py +1293 -0
- QuantNodes/factor_node/factor_functions/time_ops.py +535 -0
- QuantNodes/factor_node/factor_operation.py +1115 -0
- QuantNodes/factor_node/factor_table.py +1073 -0
- QuantNodes/factor_node/quant_nodes_object.py +60 -0
- QuantNodes/mcp_server/__init__.py +27 -0
- QuantNodes/mcp_server/__main__.py +4 -0
- QuantNodes/mcp_server/server.py +272 -0
- QuantNodes/methods/__init__.py +28 -0
- QuantNodes/methods/pipeline.py +100 -0
- QuantNodes/methods/sandbox.py +102 -0
- QuantNodes/monitor/__init__.py +27 -0
- QuantNodes/monitor/agent_tools/__init__.py +5 -0
- QuantNodes/monitor/agent_tools/monitor_tool.py +98 -0
- QuantNodes/monitor/agent_tools/schedule_tool.py +98 -0
- QuantNodes/monitor/agent_tools/version_tool.py +133 -0
- QuantNodes/monitor/monitor/__init__.py +6 -0
- QuantNodes/monitor/monitor/alerter.py +60 -0
- QuantNodes/monitor/monitor/collector.py +164 -0
- QuantNodes/monitor/monitor/dashboard.py +115 -0
- QuantNodes/monitor/monitor/drift.py +190 -0
- QuantNodes/monitor/scheduler/__init__.py +4 -0
- QuantNodes/monitor/scheduler/runner.py +133 -0
- QuantNodes/monitor/scheduler/scheduler.py +184 -0
- QuantNodes/monitor/storage/__init__.py +16 -0
- QuantNodes/monitor/storage/models.py +70 -0
- QuantNodes/monitor/storage/repository.py +407 -0
- QuantNodes/monitor/version/__init__.py +4 -0
- QuantNodes/monitor/version/diff.py +81 -0
- QuantNodes/monitor/version/version_manager.py +182 -0
- QuantNodes/operator_node/__init__.py +28 -0
- QuantNodes/operator_node/base.py +97 -0
- QuantNodes/operator_node/query_node.py +129 -0
- QuantNodes/operator_node/sql_builder.py +125 -0
- QuantNodes/operator_node/sql_utils.py +172 -0
- QuantNodes/operator_node/transform.py +130 -0
- QuantNodes/operators/__init__.py +90 -0
- QuantNodes/operators/_engine.py +108 -0
- QuantNodes/operators/composite.py +161 -0
- QuantNodes/operators/composite_dag.py +667 -0
- QuantNodes/operators/composite_dag_ops.py +343 -0
- QuantNodes/operators/composite_dag_pandas_ops.py +382 -0
- QuantNodes/operators/custom.py +408 -0
- QuantNodes/operators/facade.py +164 -0
- QuantNodes/operators/math.py +163 -0
- QuantNodes/operators/proxy.py +29 -0
- QuantNodes/operators/registry.py +144 -0
- QuantNodes/operators/section.py +99 -0
- QuantNodes/operators/talib.py +757 -0
- QuantNodes/operators/templates.py +95 -0
- QuantNodes/operators/time_series.py +136 -0
- QuantNodes/prompts/__init__.py +20 -0
- QuantNodes/prompts/backtest/__init__.py +12 -0
- QuantNodes/prompts/backtest/factor_based.py +86 -0
- QuantNodes/prompts/backtest/standard.py +73 -0
- QuantNodes/prompts/factor/__init__.py +14 -0
- QuantNodes/prompts/factor/correlation.py +77 -0
- QuantNodes/prompts/factor/group_backtest.py +86 -0
- QuantNodes/prompts/factor/ic_analysis.py +91 -0
- QuantNodes/prompts/strategy/__init__.py +18 -0
- QuantNodes/prompts/strategy/market_neutral.py +96 -0
- QuantNodes/prompts/strategy/mean_reversion.py +107 -0
- QuantNodes/prompts/strategy/momentum.py +160 -0
- QuantNodes/prompts/strategy/pairs_trading.py +107 -0
- QuantNodes/prompts/strategy/trend_following.py +96 -0
- QuantNodes/research/README.md +106 -0
- QuantNodes/research/__init__.py +154 -0
- QuantNodes/research/_legacy_3c/__init__.py +61 -0
- QuantNodes/research/_legacy_3c/auto_researcher.py +289 -0
- QuantNodes/research/_legacy_3c/factor_evaluator.py +560 -0
- QuantNodes/research/_legacy_3c/factor_miner.py +318 -0
- QuantNodes/research/_legacy_3c/mcts_search.py +324 -0
- QuantNodes/research/factor_test/__init__.py +25 -0
- QuantNodes/research/factor_test/config.py +184 -0
- QuantNodes/research/factor_test/config_builder.py +276 -0
- QuantNodes/research/factor_test/e2e/data_prep.py +163 -0
- QuantNodes/research/factor_test/e2e/run_evolution_e2e.py +309 -0
- QuantNodes/research/factor_test/evolution_adapter.py +231 -0
- QuantNodes/research/factor_test/feedback_wrapper.py +102 -0
- QuantNodes/research/factor_test/ifind_db/__init__.py +7 -0
- QuantNodes/research/factor_test/ifind_db/fetcher.py +224 -0
- QuantNodes/research/factor_test/ifind_db/ifind_database.py +689 -0
- QuantNodes/research/factor_test/nodes/__init__.py +1 -0
- QuantNodes/research/factor_test/nodes/_base.py +91 -0
- QuantNodes/research/factor_test/nodes/adjust_date_node.py +48 -0
- QuantNodes/research/factor_test/nodes/configs.py +240 -0
- QuantNodes/research/factor_test/nodes/factor_neutralize_node.py +87 -0
- QuantNodes/research/factor_test/nodes/factor_preprocess_node.py +222 -0
- QuantNodes/research/factor_test/nodes/factor_score_node.py +141 -0
- QuantNodes/research/factor_test/nodes/factor_test_report_node.py +153 -0
- QuantNodes/research/factor_test/nodes/group_analyzer_node.py +317 -0
- QuantNodes/research/factor_test/nodes/ic_analyzer_node.py +112 -0
- QuantNodes/research/factor_test/nodes/load_data_node.py +100 -0
- QuantNodes/research/factor_test/nodes/long_short_node.py +93 -0
- QuantNodes/research/factor_test/nodes/neutralizers.py +222 -0
- QuantNodes/research/factor_test/nodes/preprocess_strategies.py +277 -0
- QuantNodes/research/factor_test/nodes/risk_correlation_node.py +112 -0
- QuantNodes/research/factor_test/nodes/sample_pool_filter_node.py +110 -0
- QuantNodes/research/factor_test/nodes/tradability_filter_node.py +92 -0
- QuantNodes/research/factor_test/pipeline_runner.py +305 -0
- QuantNodes/research/factor_test/pipeline_spec.py +216 -0
- QuantNodes/research/factor_test/utils/__init__.py +26 -0
- QuantNodes/research/factor_test/utils/constants.py +86 -0
- QuantNodes/research/factor_test/utils/data_loader.py +141 -0
- QuantNodes/research/factor_test/utils/date_utils.py +232 -0
- QuantNodes/research/factor_test/utils/file_loaders.py +150 -0
- QuantNodes/research/factor_test/utils/labels.py +37 -0
- QuantNodes/research/factor_test/utils/metrics_extractor.py +55 -0
- QuantNodes/research/factor_test/utils/performance_metrics.py +175 -0
- QuantNodes/research/factor_test/utils/safe_load.py +106 -0
- QuantNodes/research/quant_alpha/CHANGELOG.md +80 -0
- QuantNodes/research/quant_alpha/README.md +142 -0
- QuantNodes/research/quant_alpha/__init__.py +45 -0
- QuantNodes/research/quant_alpha/adapters/__init__.py +99 -0
- QuantNodes/research/quant_alpha/adapters/calculator.py +503 -0
- QuantNodes/research/quant_alpha/adapters/expression.py +387 -0
- QuantNodes/research/quant_alpha/alpha101_design/__init__.py +50 -0
- QuantNodes/research/quant_alpha/alpha101_design/few_shot_examples.py +243 -0
- QuantNodes/research/quant_alpha/alpha101_design/philosophy.py +474 -0
- QuantNodes/research/quant_alpha/alpha158_design/__init__.py +63 -0
- QuantNodes/research/quant_alpha/alpha158_design/few_shot_examples.py +219 -0
- QuantNodes/research/quant_alpha/alpha158_design/philosophy.py +240 -0
- QuantNodes/research/quant_alpha/evaluation/__init__.py +47 -0
- QuantNodes/research/quant_alpha/evaluation/baselines/__init__.py +8 -0
- QuantNodes/research/quant_alpha/evaluation/baselines/g1_handcrafted.py +135 -0
- QuantNodes/research/quant_alpha/evaluation/baselines/g2_llm_only.py +269 -0
- QuantNodes/research/quant_alpha/evaluation/baselines/g3_alpha_gpt.py +152 -0
- QuantNodes/research/quant_alpha/evaluation/clickhouse_data_loader.py +227 -0
- QuantNodes/research/quant_alpha/evaluation/contracts.py +376 -0
- QuantNodes/research/quant_alpha/evaluation/evaluators/__init__.py +6 -0
- QuantNodes/research/quant_alpha/evaluation/evaluators/polars_evaluator.py +545 -0
- QuantNodes/research/quant_alpha/evaluation/mock_data_loader.py +226 -0
- QuantNodes/research/quant_alpha/evaluation/runner.py +243 -0
- QuantNodes/research/quant_alpha/llm/__init__.py +38 -0
- QuantNodes/research/quant_alpha/llm/parser.py +681 -0
- QuantNodes/research/quant_alpha/logic_driven_pipeline.py +411 -0
- QuantNodes/research/quant_alpha/logic_mining/__init__.py +74 -0
- QuantNodes/research/quant_alpha/logic_mining/compiler.py +457 -0
- QuantNodes/research/quant_alpha/logic_mining/generator.py +366 -0
- QuantNodes/research/quant_alpha/logic_mining/models.py +252 -0
- QuantNodes/research/quant_alpha/logic_mining/parser.py +287 -0
- QuantNodes/research/quant_alpha/logic_mining/pipelines.py +297 -0
- QuantNodes/research/quant_alpha/logic_mining/sources.py +149 -0
- QuantNodes/research/quant_alpha/mcts/__init__.py +66 -0
- QuantNodes/research/quant_alpha/mcts/cache.py +262 -0
- QuantNodes/research/quant_alpha/mcts/extension_ops.py +320 -0
- QuantNodes/research/quant_alpha/mcts/feedback.py +825 -0
- QuantNodes/research/quant_alpha/mcts/op_prior.py +180 -0
- QuantNodes/research/quant_alpha/mcts/search.py +540 -0
- QuantNodes/research/quant_alpha/mcts/tree.py +201 -0
- QuantNodes/research/quant_alpha/operator_vocab/__init__.py +50 -0
- QuantNodes/research/quant_alpha/operator_vocab/config.py +54 -0
- QuantNodes/research/quant_alpha/operator_vocab/metadata.py +263 -0
- QuantNodes/research/quant_alpha/operator_vocab/vocabulary.py +481 -0
- QuantNodes/research/quant_alpha/pipeline.py +1027 -0
- QuantNodes/research/quant_alpha/types/__init__.py +27 -0
- QuantNodes/research/quant_alpha/types/constants.py +28 -0
- QuantNodes/research/quant_alpha/types/state.py +205 -0
- QuantNodes/research/quant_alpha/workflow/__init__.py +32 -0
- QuantNodes/research/quant_alpha/workflow/alpha_gpt.py +911 -0
- QuantNodes/research/quant_alpha/workflow/alpha_logics.py +416 -0
- QuantNodes/research/quant_alpha/workflow/state.py +27 -0
- QuantNodes/research/report_reproducer.py +485 -0
- QuantNodes/research/wiki.py +1155 -0
- QuantNodes/symbolic/__init__.py +51 -0
- QuantNodes/symbolic/compiler.py +113 -0
- QuantNodes/symbolic/dialect.py +260 -0
- QuantNodes/symbolic/executor.py +147 -0
- QuantNodes/symbolic/expression.py +234 -0
- QuantNodes/symbolic/functions.py +433 -0
- QuantNodes/symbolic/optimizer.py +165 -0
- QuantNodes/ui_node/__init__.py +30 -0
- QuantNodes/ui_node/base.py +222 -0
- quantnodes-3.0.0.dist-info/METADATA +463 -0
- quantnodes-3.0.0.dist-info/RECORD +399 -0
- quantnodes-3.0.0.dist-info/WHEEL +5 -0
- quantnodes-3.0.0.dist-info/entry_points.txt +24 -0
- quantnodes-3.0.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
# coding: utf-8
|
|
2
|
+
"""Node 10: 市值行业分层打分 / Factor Score Node
|
|
3
|
+
|
|
4
|
+
Migrated from factor_performance.py:730-877 score_by_size_ind()
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
import numpy as np
|
|
9
|
+
import pandas as pd
|
|
10
|
+
|
|
11
|
+
from QuantNodes.research.factor_test.nodes._base import PydanticConfigNode
|
|
12
|
+
from QuantNodes.research.factor_test.nodes.configs import ScoreNodeConfig
|
|
13
|
+
from QuantNodes.research.factor_test.utils.performance_metrics import evaluation, cal_net_simple
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class FactorScoreNode(PydanticConfigNode):
|
|
17
|
+
"""市值行业分层打分 (3 市值组 × 29 中信行业 × N 分位)
|
|
18
|
+
|
|
19
|
+
输入: factor_neutral, mv, industry, price
|
|
20
|
+
输出: {fac_group, daily_net, eva, ...}
|
|
21
|
+
"""
|
|
22
|
+
|
|
23
|
+
ConfigSchema = ScoreNodeConfig
|
|
24
|
+
_ALIASES = {
|
|
25
|
+
"_enabled": "enabled",
|
|
26
|
+
"_n_industries": "n_industries",
|
|
27
|
+
"_n_size_groups": "n_size_groups",
|
|
28
|
+
"_n_quantile_groups": "n_quantile_groups",
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
def _execute(self, input_data=None, **kwargs) -> dict:
|
|
32
|
+
if not self._enabled:
|
|
33
|
+
return {}
|
|
34
|
+
|
|
35
|
+
context = kwargs.get('context', {})
|
|
36
|
+
factor_data = self._factor_data(context)
|
|
37
|
+
mv = self._ctx_load(context, 'mv_float')
|
|
38
|
+
industry = self._ctx_load(context, 'id_citic1')
|
|
39
|
+
price = self._ctx_load(context, 'price')
|
|
40
|
+
factor_ori = context.get('GroupAnalyzer', {}).get('factor_direction', 1)
|
|
41
|
+
|
|
42
|
+
if factor_data is None or mv is None or industry is None or price is None:
|
|
43
|
+
raise ValueError("市值行业分层打分需要因子、市值、行业、价格数据")
|
|
44
|
+
|
|
45
|
+
return self._score_by_size_ind(factor_data, mv, industry, price, factor_ori)
|
|
46
|
+
|
|
47
|
+
def _score_by_size_ind(self, factor_data, mv, industry, price, factor_ori):
|
|
48
|
+
"""市值行业分层打分"""
|
|
49
|
+
# H15: 全部可配置 (config.get 已在 __init__)
|
|
50
|
+
group = self._n_quantile_groups
|
|
51
|
+
n_size = self._n_size_groups
|
|
52
|
+
n_ind = self._n_industries
|
|
53
|
+
adj_dates = factor_data.index.tolist()
|
|
54
|
+
|
|
55
|
+
# 对齐
|
|
56
|
+
mv_adj = mv.loc[mv.index.isin(adj_dates)]
|
|
57
|
+
ind_adj = industry.loc[industry.index.isin(adj_dates)]
|
|
58
|
+
ind_adj = ind_adj.astype('int')
|
|
59
|
+
|
|
60
|
+
# 因子分组
|
|
61
|
+
fac_group = factor_data.copy() * np.nan
|
|
62
|
+
mv_group = mv.copy() * np.nan
|
|
63
|
+
|
|
64
|
+
def my_qcut(x, n):
|
|
65
|
+
if len(x.dropna().unique()) >= (n - 1):
|
|
66
|
+
return pd.qcut(x.rank(method='first'), n, labels=range(1, n + 1), duplicates='drop')
|
|
67
|
+
return x * np.nan
|
|
68
|
+
|
|
69
|
+
for i in range(len(factor_data)):
|
|
70
|
+
t_i = factor_data.index[i]
|
|
71
|
+
nonan = factor_data.loc[t_i].notna().sum()
|
|
72
|
+
# H15: 最低有效股票数 = 市值组数 × 行业数 × 分位组数
|
|
73
|
+
if nonan == 0 or nonan < n_size * n_ind * group:
|
|
74
|
+
if i > 0:
|
|
75
|
+
fac_group.loc[t_i] = fac_group.iloc[i - 1]
|
|
76
|
+
continue
|
|
77
|
+
|
|
78
|
+
mv_group.loc[t_i] = pd.qcut(
|
|
79
|
+
mv_adj.loc[t_i], n_size, labels=range(1, n_size + 1),
|
|
80
|
+
)
|
|
81
|
+
fac_group.loc[t_i] = factor_data.loc[t_i].groupby(
|
|
82
|
+
[mv_group.loc[t_i], ind_adj.loc[t_i]]
|
|
83
|
+
).apply(lambda x: my_qcut(x, group))
|
|
84
|
+
|
|
85
|
+
# 计算各组净值
|
|
86
|
+
price_full = price.loc[adj_dates[0]:adj_dates[-1]]
|
|
87
|
+
group_daily_ret = pd.DataFrame(np.nan, index=price_full.index, columns=range(1, group + 1))
|
|
88
|
+
group_daily_ret.iloc[0] = 0
|
|
89
|
+
|
|
90
|
+
for i in range(len(adj_dates) - 1):
|
|
91
|
+
t_i = adj_dates[i]
|
|
92
|
+
t_ii = adj_dates[i + 1]
|
|
93
|
+
if t_i not in fac_group.index:
|
|
94
|
+
continue
|
|
95
|
+
fg = fac_group.loc[t_i].dropna()
|
|
96
|
+
if fg.empty:
|
|
97
|
+
continue
|
|
98
|
+
cycle = price_full.loc[t_i:t_ii] / price_full.loc[t_i]
|
|
99
|
+
for g in range(1, group + 1):
|
|
100
|
+
stocks = fg[fg == g].index
|
|
101
|
+
valid = [s for s in stocks if s in cycle.columns]
|
|
102
|
+
if valid:
|
|
103
|
+
gn = cycle[valid].mean(axis=1)
|
|
104
|
+
group_daily_ret.loc[gn.index[1:], g] = gn.pct_change(fill_method=None).iloc[1:]
|
|
105
|
+
|
|
106
|
+
group_daily_net_cmp = (group_daily_ret + 1).cumprod()
|
|
107
|
+
group_daily_net_simp = group_daily_net_cmp.copy() * np.nan
|
|
108
|
+
for g in range(group):
|
|
109
|
+
group_daily_net_simp.iloc[:, g] = cal_net_simple(
|
|
110
|
+
group_daily_net_cmp.iloc[:, g], adj_dates
|
|
111
|
+
)
|
|
112
|
+
|
|
113
|
+
# 多空净值
|
|
114
|
+
if factor_ori == 1:
|
|
115
|
+
long_n, short_n = group, 1
|
|
116
|
+
else:
|
|
117
|
+
long_n, short_n = 1, group
|
|
118
|
+
|
|
119
|
+
group_daily_net_simp['longshort'] = (
|
|
120
|
+
group_daily_net_simp[long_n] - group_daily_net_simp[short_n] + 1
|
|
121
|
+
)
|
|
122
|
+
|
|
123
|
+
# 评价
|
|
124
|
+
eva = pd.DataFrame()
|
|
125
|
+
eva_yearly = {}
|
|
126
|
+
for col in group_daily_net_simp.columns:
|
|
127
|
+
eva_g = evaluation(group_daily_net_simp[col], adj_dates)
|
|
128
|
+
eva = pd.concat([eva, eva_g.iloc[0, :].to_frame()], axis=1)
|
|
129
|
+
eva_yearly[col] = eva_g.iloc[1:] if len(eva_g) > 1 else pd.DataFrame()
|
|
130
|
+
|
|
131
|
+
eva.columns = group_daily_net_simp.columns.tolist()
|
|
132
|
+
if 'Year' in eva.index:
|
|
133
|
+
eva = eva.drop('Year')
|
|
134
|
+
|
|
135
|
+
return {
|
|
136
|
+
'fac_group': fac_group,
|
|
137
|
+
'daily_net_simp': group_daily_net_simp,
|
|
138
|
+
'daily_net_cmp': group_daily_net_cmp,
|
|
139
|
+
'eva': eva,
|
|
140
|
+
'eva_yearly': eva_yearly,
|
|
141
|
+
}
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
# coding: utf-8
|
|
2
|
+
"""Node 12: 汇总报告 / Factor Test Report Node
|
|
3
|
+
|
|
4
|
+
Migrated from factor_output.py:539-616 save_testresult()
|
|
5
|
+
Output: Parquet/JSON instead of xlwings Excel
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from datetime import datetime
|
|
10
|
+
|
|
11
|
+
import pandas as pd
|
|
12
|
+
import numpy as np
|
|
13
|
+
|
|
14
|
+
from QuantNodes.research.factor_test.nodes._base import PydanticConfigNode
|
|
15
|
+
from QuantNodes.research.factor_test.nodes.configs import ReportNodeConfig
|
|
16
|
+
from QuantNodes.core.path_utils import ensure_dir, resolve_path
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Union
|
|
19
|
+
|
|
20
|
+
logger = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class FactorTestReportNode(PydanticConfigNode):
|
|
24
|
+
"""汇总所有分析结果, 输出到文件
|
|
25
|
+
|
|
26
|
+
输入: context 中所有分析结果
|
|
27
|
+
输出: FactorTestReport (dict)
|
|
28
|
+
"""
|
|
29
|
+
|
|
30
|
+
ConfigSchema = ReportNodeConfig
|
|
31
|
+
_ALIASES = {"_output_format": "format"}
|
|
32
|
+
|
|
33
|
+
def __init__(self, name: str = "FactorTestReport",
|
|
34
|
+
config: Union[dict, ReportNodeConfig, None] = None, **kwargs):
|
|
35
|
+
super().__init__(name, config, **kwargs)
|
|
36
|
+
# P-1: 路径优先级 env QUANTNODES_OUTPUT_DIR > expanduser > default
|
|
37
|
+
self._output_dir = resolve_path(self.cfg.dir, "QUANTNODES_OUTPUT_DIR")
|
|
38
|
+
|
|
39
|
+
def _execute(self, input_data=None, **kwargs) -> dict:
|
|
40
|
+
context = kwargs.get('context', {})
|
|
41
|
+
|
|
42
|
+
report = {
|
|
43
|
+
'factor_name': self._ctx_load(context, 'factor', pd.DataFrame()).columns[0]
|
|
44
|
+
if hasattr(self._ctx_load(context, 'factor', pd.DataFrame()), 'columns')
|
|
45
|
+
else 'unknown',
|
|
46
|
+
'timestamp': datetime.now().isoformat(),
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
# 收集各分析结果
|
|
50
|
+
if 'ICAnalyzer' in context:
|
|
51
|
+
ic = context['ICAnalyzer']
|
|
52
|
+
report['ic'] = {
|
|
53
|
+
'ic_mean': float(ic['ic_result'].get('IC均值', np.nan)),
|
|
54
|
+
'ic_std': float(ic['ic_result'].get('IC标准差', np.nan)),
|
|
55
|
+
'icir': float(ic['ic_result'].get('ICIR', np.nan)),
|
|
56
|
+
'rank_ic_mean': float(ic['rank_ic_result'].get('rankIC均值', np.nan)),
|
|
57
|
+
'rank_icir': float(ic['rank_ic_result'].get('rankICIR', np.nan)),
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
if 'GroupAnalyzer' in context:
|
|
61
|
+
ga = context['GroupAnalyzer']
|
|
62
|
+
report['group'] = {
|
|
63
|
+
'n_groups': ga.get('n_groups', 0),
|
|
64
|
+
'group_eva_exc': ga.get('group_eva_exc', pd.DataFrame()).to_dict()
|
|
65
|
+
if isinstance(ga.get('group_eva_exc'), pd.DataFrame) else {},
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
if 'LongShort' in context:
|
|
69
|
+
ls = context['LongShort']
|
|
70
|
+
if isinstance(ls.get('eva_total'), pd.DataFrame):
|
|
71
|
+
report['longshort'] = {
|
|
72
|
+
'eva': ls['eva_total'].to_dict(),
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
if 'FactorScore' in context and context['FactorScore']:
|
|
76
|
+
sc = context['FactorScore']
|
|
77
|
+
report['score'] = {
|
|
78
|
+
'eva': sc.get('eva', pd.DataFrame()).to_dict()
|
|
79
|
+
if isinstance(sc.get('eva'), pd.DataFrame) else {},
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if 'RiskCorrelation' in context:
|
|
83
|
+
rc = context['RiskCorrelation']
|
|
84
|
+
report['risk_corr'] = {
|
|
85
|
+
'mean': rc.get('mean', pd.DataFrame()).to_dict()
|
|
86
|
+
if isinstance(rc.get('mean'), pd.DataFrame) else {},
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
# 输出到文件
|
|
90
|
+
self._save_report(report, context)
|
|
91
|
+
|
|
92
|
+
return report
|
|
93
|
+
|
|
94
|
+
def _save_report(self, report, context):
|
|
95
|
+
"""保存报告到文件
|
|
96
|
+
|
|
97
|
+
L3 (2026-06-21): 未知 format 改为运行时 raise ValueError.
|
|
98
|
+
|
|
99
|
+
修复: 原循环中, 不在 ``{'json', 'parquet'}`` 内的 fmt 会被
|
|
100
|
+
静默 skip — 用户写 ``format=['html']`` 不报错, 也不生成文件,
|
|
101
|
+
易被误判为"配置没生效". 修复后, 未知 fmt 显式 raise, 错误信息
|
|
102
|
+
列出所有合法值.
|
|
103
|
+
|
|
104
|
+
Raises:
|
|
105
|
+
ValueError: ``fmt`` 不在 ``{'json', 'parquet'}`` 内.
|
|
106
|
+
"""
|
|
107
|
+
output_dir = Path(self._output_dir)
|
|
108
|
+
ensure_dir(output_dir)
|
|
109
|
+
|
|
110
|
+
factor_name = report.get('factor_name', 'factor')
|
|
111
|
+
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
|
112
|
+
|
|
113
|
+
for fmt in self._output_format:
|
|
114
|
+
if fmt == 'json':
|
|
115
|
+
import json
|
|
116
|
+
# 转换不可序列化的对象
|
|
117
|
+
def default_serializer(obj):
|
|
118
|
+
if isinstance(obj, (pd.Series, pd.DataFrame)):
|
|
119
|
+
return obj.to_dict()
|
|
120
|
+
if isinstance(obj, np.integer):
|
|
121
|
+
return int(obj)
|
|
122
|
+
if isinstance(obj, np.floating):
|
|
123
|
+
return float(obj)
|
|
124
|
+
if isinstance(obj, np.ndarray):
|
|
125
|
+
return obj.tolist()
|
|
126
|
+
return str(obj)
|
|
127
|
+
|
|
128
|
+
path = output_dir / f"factor_test_{factor_name}_{timestamp}.json"
|
|
129
|
+
with open(path, 'w', encoding='utf-8') as f:
|
|
130
|
+
json.dump(report, f, ensure_ascii=False, indent=2, default=default_serializer)
|
|
131
|
+
logger.info(f"报告已保存: {path}")
|
|
132
|
+
|
|
133
|
+
elif fmt == 'parquet':
|
|
134
|
+
# 保存各分析结果为 parquet
|
|
135
|
+
for key, value in context.items():
|
|
136
|
+
if key.startswith('_'):
|
|
137
|
+
continue
|
|
138
|
+
if isinstance(value, dict):
|
|
139
|
+
for sub_key, sub_val in value.items():
|
|
140
|
+
if isinstance(sub_val, pd.DataFrame) and not sub_val.empty:
|
|
141
|
+
path = output_dir / f"{factor_name}_{key}_{sub_key}.parquet"
|
|
142
|
+
sub_val.to_parquet(path)
|
|
143
|
+
elif isinstance(value, pd.DataFrame) and not value.empty:
|
|
144
|
+
path = output_dir / f"{factor_name}_{key}.parquet"
|
|
145
|
+
value.to_parquet(path)
|
|
146
|
+
logger.info(f"Parquet 文件已保存至: {output_dir}")
|
|
147
|
+
|
|
148
|
+
else:
|
|
149
|
+
# L3 (2026-06-21): 未知 format 显式 raise (修复 silent skip).
|
|
150
|
+
raise ValueError(
|
|
151
|
+
f"FactorTestReport 不支持的 format: {fmt!r}, "
|
|
152
|
+
f"仅支持 'json' / 'parquet'"
|
|
153
|
+
)
|
|
@@ -0,0 +1,317 @@
|
|
|
1
|
+
# coding: utf-8
|
|
2
|
+
"""Node 8: 分组分析 / Group Analyzer Node
|
|
3
|
+
|
|
4
|
+
Migrated from factor_performance.py:361-560 cal_group_ret()
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
import logging
|
|
9
|
+
from typing import Literal
|
|
10
|
+
|
|
11
|
+
import numpy as np
|
|
12
|
+
import pandas as pd
|
|
13
|
+
|
|
14
|
+
from QuantNodes.research.factor_test.nodes._base import PydanticConfigNode
|
|
15
|
+
from QuantNodes.research.factor_test.nodes.configs import GroupAnalyzerNodeConfig
|
|
16
|
+
from QuantNodes.research.factor_test.utils.performance_metrics import (
|
|
17
|
+
evaluation, cal_net_simple
|
|
18
|
+
)
|
|
19
|
+
from QuantNodes.research.factor_test.utils.constants import INDEX_CP_MAPPING
|
|
20
|
+
|
|
21
|
+
logger = logging.getLogger(__name__)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
FactorKind = Literal["ranked", "discrete"]
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _classify_factor(row: pd.Series, n_groups: int) -> FactorKind:
|
|
28
|
+
"""按 dtype + n_unique 判别因子分桶策略。
|
|
29
|
+
|
|
30
|
+
Returns:
|
|
31
|
+
"discrete" — bool dtype, 或 n_unique <= 2(捕获 float-cast 二值)
|
|
32
|
+
"ranked" — 其余(连续或轻度 ties, 走 rank('first') + qcut)
|
|
33
|
+
|
|
34
|
+
注: n_unique >= 3 的整数 dtype 因子走 ranked 分支, 因为
|
|
35
|
+
_group_discrete 按 value 比例分配组段, 对 n_unique > n_groups 的
|
|
36
|
+
输入无法产出恰好 n_groups 个组 (会产生 n_unique 个组)。
|
|
37
|
+
"""
|
|
38
|
+
n_unique = row.nunique()
|
|
39
|
+
if pd.api.types.is_bool_dtype(row):
|
|
40
|
+
return "discrete"
|
|
41
|
+
if n_unique <= 2:
|
|
42
|
+
return "discrete"
|
|
43
|
+
return "ranked"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def _group_ranked(series: pd.Series, n_groups: int) -> pd.Series:
|
|
47
|
+
"""通用 rank('first') + qcut: 处理连续和轻度 ties 因子。
|
|
48
|
+
|
|
49
|
+
修复 pd.qcut(duplicates='drop') 在 ties 下抛 "Bin labels must be
|
|
50
|
+
one fewer than the number of bin edges" 的 bug (alpha-004 等场景:
|
|
51
|
+
7 unique × 50 行有大量 ties)。
|
|
52
|
+
|
|
53
|
+
对无 ties 的纯连续因子, rank('first') 产出 1..n 唯一序号,
|
|
54
|
+
qcut 在序号上的分位点与原 qcut(series) 上的分位点对应同一组
|
|
55
|
+
元素 (单调变换保序), 行为 bitwise 等价 (零回归)。
|
|
56
|
+
"""
|
|
57
|
+
return pd.qcut(
|
|
58
|
+
series.rank(method='first'),
|
|
59
|
+
n_groups,
|
|
60
|
+
labels=range(1, n_groups + 1),
|
|
61
|
+
duplicates='drop'
|
|
62
|
+
)
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def _group_discrete(
|
|
66
|
+
series: pd.Series, n_groups: int, date_int: int
|
|
67
|
+
) -> pd.Series:
|
|
68
|
+
"""bool / 离散因子 (n_unique <= 2): 按 value 比例分配组段 + 内部 seeded shuffle。
|
|
69
|
+
|
|
70
|
+
算法:
|
|
71
|
+
1. sorted unique values, 按 count/len*n_groups 比例 round 分配组数
|
|
72
|
+
2. 最后一个 value 用减法 (n_groups - sum(prev)) 强制补齐, 避免累计漂移
|
|
73
|
+
3. np.random.seed(date_int % 2**31) 每日同 seed → 可复现
|
|
74
|
+
4. value 内部 shuffle 后用整数除法 j * n_g // n_v 均分到所属组段
|
|
75
|
+
|
|
76
|
+
Args:
|
|
77
|
+
series: 单日 50 只股票的 factor values (dropna 后)
|
|
78
|
+
n_groups: 总组数 (默认 5)
|
|
79
|
+
date_int: yyyymmdd 整数, 用作 shuffle seed
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
pd.Series: index=series.index, values ∈ {1, ..., n_groups}
|
|
83
|
+
"""
|
|
84
|
+
unique_vals = sorted(series.unique())
|
|
85
|
+
n_total = len(series)
|
|
86
|
+
counts = {v: int((series == v).sum()) for v in unique_vals}
|
|
87
|
+
|
|
88
|
+
n_g_list: list[int] = []
|
|
89
|
+
for v in unique_vals[:-1]:
|
|
90
|
+
n_g_list.append(max(1, round(counts[v] / n_total * n_groups)))
|
|
91
|
+
n_g_list.append(max(1, n_groups - sum(n_g_list)))
|
|
92
|
+
|
|
93
|
+
starts: list[int] = [1]
|
|
94
|
+
for ng in n_g_list[:-1]:
|
|
95
|
+
starts.append(starts[-1] + ng)
|
|
96
|
+
|
|
97
|
+
np.random.seed(int(date_int) % (2**31))
|
|
98
|
+
groups = pd.Series(np.nan, index=series.index)
|
|
99
|
+
for v, ng, g_start in zip(unique_vals, n_g_list, starts):
|
|
100
|
+
if ng <= 0:
|
|
101
|
+
continue
|
|
102
|
+
val_idx = list(series[series == v].index)
|
|
103
|
+
np.random.shuffle(val_idx)
|
|
104
|
+
n_v = len(val_idx)
|
|
105
|
+
for j, idx in enumerate(val_idx):
|
|
106
|
+
g_within = min(ng - 1, j * ng // n_v) if n_v > 0 else 0
|
|
107
|
+
groups[idx] = g_start + g_within
|
|
108
|
+
return groups
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
class GroupAnalyzerNode(PydanticConfigNode):
|
|
112
|
+
"""N 分位分组 + 各组收益/净值/评价
|
|
113
|
+
|
|
114
|
+
输入: factor_neutral, price, index_cp
|
|
115
|
+
输出: {fac_group, group_num, group_ret, daily_net_simp, daily_excnet_simp,
|
|
116
|
+
group_eva_abs, group_eva_exc, turnover, ...}
|
|
117
|
+
"""
|
|
118
|
+
|
|
119
|
+
ConfigSchema = GroupAnalyzerNodeConfig
|
|
120
|
+
_ALIASES = {
|
|
121
|
+
"_groups": "groups",
|
|
122
|
+
"_factor_direction": "factor_direction",
|
|
123
|
+
"_floor_mode": "floor_mode",
|
|
124
|
+
"_hedge": "hedge",
|
|
125
|
+
"_hedge_path": "hedge_path",
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
def _execute(self, input_data=None, **kwargs) -> dict:
|
|
129
|
+
context = kwargs.get('context', {})
|
|
130
|
+
factor_data = self._factor_data(context)
|
|
131
|
+
price = self._ctx_load(context, 'price')
|
|
132
|
+
index_cp = self._ctx_load(context, 'index_cp')
|
|
133
|
+
|
|
134
|
+
if factor_data is None or price is None:
|
|
135
|
+
raise ValueError("因子或价格数据缺失")
|
|
136
|
+
|
|
137
|
+
return self._calc_group_return(
|
|
138
|
+
factor_data, price, index_cp,
|
|
139
|
+
self._groups, self._factor_direction,
|
|
140
|
+
self._floor_mode, self._hedge, self._hedge_path
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
def _calc_group_return(self, factor_data, price, index_cp,
|
|
144
|
+
group, factor_ori, floor_mode, hedge, hedge_path):
|
|
145
|
+
"""计算分组收益"""
|
|
146
|
+
adj_dates = factor_data.index.tolist()
|
|
147
|
+
n_groups = group
|
|
148
|
+
|
|
149
|
+
# 分组标签
|
|
150
|
+
fac_group = factor_data.copy() * np.nan
|
|
151
|
+
for i in range(len(factor_data)):
|
|
152
|
+
t_i = factor_data.index[i]
|
|
153
|
+
row = factor_data.loc[t_i].dropna()
|
|
154
|
+
nonan = len(row)
|
|
155
|
+
if nonan == 0 or nonan < group:
|
|
156
|
+
if floor_mode == 'group' or i == 0:
|
|
157
|
+
continue
|
|
158
|
+
elif floor_mode == 'last':
|
|
159
|
+
fac_group.loc[t_i] = fac_group.iloc[i - 1]
|
|
160
|
+
continue
|
|
161
|
+
|
|
162
|
+
kind = _classify_factor(row, group)
|
|
163
|
+
if kind == "discrete":
|
|
164
|
+
fac_group.loc[t_i] = _group_discrete(row, group, int(t_i))
|
|
165
|
+
else:
|
|
166
|
+
fac_group.loc[t_i] = _group_ranked(row, group)
|
|
167
|
+
|
|
168
|
+
# 各期每组收益
|
|
169
|
+
price_adj = price.loc[price.index.isin(adj_dates)]
|
|
170
|
+
stock_cycle_ret = price_adj.pct_change(fill_method=None).shift(-1)
|
|
171
|
+
|
|
172
|
+
group_num = pd.DataFrame(np.nan, index=adj_dates, columns=range(1, n_groups + 1))
|
|
173
|
+
group_ret = group_num.copy()
|
|
174
|
+
group_winratio = group_num.copy()
|
|
175
|
+
group_winloss = group_num.copy()
|
|
176
|
+
|
|
177
|
+
for t_i in adj_dates[:-1]:
|
|
178
|
+
if t_i not in fac_group.index or t_i not in stock_cycle_ret.index:
|
|
179
|
+
continue
|
|
180
|
+
fg = fac_group.loc[t_i].dropna()
|
|
181
|
+
if fg.empty:
|
|
182
|
+
continue
|
|
183
|
+
ret_i = stock_cycle_ret.loc[t_i]
|
|
184
|
+
temp = ret_i.groupby(fg).agg(['count', 'mean'])
|
|
185
|
+
for g in range(1, n_groups + 1):
|
|
186
|
+
if g in temp.index:
|
|
187
|
+
group_num.loc[t_i, g] = temp.loc[g, 'count']
|
|
188
|
+
group_ret.loc[t_i, g] = temp.loc[g, 'mean']
|
|
189
|
+
mask = fg[fg == g].index
|
|
190
|
+
vals = ret_i.reindex(mask).dropna()
|
|
191
|
+
if len(vals) > 0:
|
|
192
|
+
group_winratio.loc[t_i, g] = (vals > 0).mean()
|
|
193
|
+
pos = vals[vals > 0].mean()
|
|
194
|
+
neg = vals[vals < 0].mean()
|
|
195
|
+
has_valid_neg = pd.notna(neg) and neg != 0
|
|
196
|
+
group_winloss.loc[t_i, g] = pos / neg * -1 if has_valid_neg else np.nan
|
|
197
|
+
|
|
198
|
+
# 各组日度净值 (单利)
|
|
199
|
+
price_full = price.loc[adj_dates[0]:adj_dates[-1]]
|
|
200
|
+
group_daily_ret = pd.DataFrame(
|
|
201
|
+
np.nan, index=price_full.index, columns=range(1, n_groups + 1)
|
|
202
|
+
)
|
|
203
|
+
group_daily_ret.iloc[0] = 0
|
|
204
|
+
|
|
205
|
+
for i in range(len(adj_dates) - 1):
|
|
206
|
+
t_i = adj_dates[i]
|
|
207
|
+
t_ii = adj_dates[i + 1]
|
|
208
|
+
if t_i not in fac_group.index:
|
|
209
|
+
continue
|
|
210
|
+
fg = fac_group.loc[t_i].dropna()
|
|
211
|
+
if fg.empty:
|
|
212
|
+
continue
|
|
213
|
+
cycle_net = price_full.loc[t_i:t_ii] / price_full.loc[t_i]
|
|
214
|
+
# 向量化:一次 groupby 替代内层 for g 循环 (6x 提速)
|
|
215
|
+
group_mean = cycle_net.T.groupby(fg).mean().T
|
|
216
|
+
group_pct = group_mean.pct_change(fill_method=None).iloc[1:]
|
|
217
|
+
group_daily_ret.loc[group_pct.index] = group_pct.values
|
|
218
|
+
|
|
219
|
+
group_daily_net_cmp = (group_daily_ret + 1).cumprod()
|
|
220
|
+
group_daily_net_simp = group_daily_net_cmp.copy() * np.nan
|
|
221
|
+
for g in range(n_groups):
|
|
222
|
+
group_daily_net_simp.iloc[:, g] = cal_net_simple(
|
|
223
|
+
group_daily_net_cmp.iloc[:, g], adj_dates
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
# 对冲基准
|
|
227
|
+
benchmark = self._get_benchmark(hedge, hedge_path, index_cp, price_full,
|
|
228
|
+
factor_data, adj_dates)
|
|
229
|
+
if benchmark is not None:
|
|
230
|
+
benchmark_cmp = benchmark / benchmark.iloc[0]
|
|
231
|
+
benchmark_simp = cal_net_simple(benchmark_cmp, adj_dates)
|
|
232
|
+
|
|
233
|
+
# 超额净值
|
|
234
|
+
group_daily_excnet_simp = group_daily_net_simp.sub(benchmark_simp.values, axis=0) + 1
|
|
235
|
+
group_daily_excnet_cmp = group_daily_net_cmp.sub(benchmark_cmp.values, axis=0) + 1
|
|
236
|
+
else:
|
|
237
|
+
group_daily_excnet_simp = group_daily_net_simp.copy()
|
|
238
|
+
group_daily_excnet_cmp = group_daily_net_cmp.copy()
|
|
239
|
+
|
|
240
|
+
# 评价
|
|
241
|
+
group_eva_abs = pd.DataFrame()
|
|
242
|
+
group_eva_exc = pd.DataFrame()
|
|
243
|
+
group_eva_abs_yearly = {}
|
|
244
|
+
group_eva_exc_yearly = {}
|
|
245
|
+
|
|
246
|
+
for g in range(1, n_groups + 1):
|
|
247
|
+
# 换手率
|
|
248
|
+
turn = ((fac_group == g) & (fac_group.diff(-1) != 0)).sum(axis=1) / (
|
|
249
|
+
(fac_group == g).sum(axis=1) * 2
|
|
250
|
+
)
|
|
251
|
+
turn.name = g
|
|
252
|
+
|
|
253
|
+
result_g = evaluation(group_daily_net_simp[g], adj_dates)
|
|
254
|
+
result_exc_g = evaluation(group_daily_excnet_simp[g], adj_dates)
|
|
255
|
+
|
|
256
|
+
group_eva_abs = pd.concat([group_eva_abs, result_g.iloc[0, 1:].to_frame()], axis=1)
|
|
257
|
+
group_eva_exc = pd.concat([group_eva_exc, result_exc_g.iloc[0, 1:].to_frame()], axis=1)
|
|
258
|
+
group_eva_abs_yearly[g] = result_g.iloc[1:]
|
|
259
|
+
group_eva_exc_yearly[g] = result_exc_g.iloc[1:]
|
|
260
|
+
|
|
261
|
+
group_eva_abs.columns = range(1, n_groups + 1)
|
|
262
|
+
group_eva_exc.columns = range(1, n_groups + 1)
|
|
263
|
+
|
|
264
|
+
return {
|
|
265
|
+
'adjust_dates': adj_dates,
|
|
266
|
+
'fac_group': fac_group,
|
|
267
|
+
'group_num': group_num,
|
|
268
|
+
'group_ret': group_ret,
|
|
269
|
+
'group_winratio': group_winratio,
|
|
270
|
+
'group_winloss': group_winloss,
|
|
271
|
+
'daily_net_simp': group_daily_net_simp,
|
|
272
|
+
'daily_net_cmp': group_daily_net_cmp,
|
|
273
|
+
'daily_excnet_simp': group_daily_excnet_simp,
|
|
274
|
+
'daily_excnet_cmp': group_daily_excnet_cmp,
|
|
275
|
+
'group_eva_abs': group_eva_abs,
|
|
276
|
+
'group_eva_exc': group_eva_exc,
|
|
277
|
+
'group_eva_abs_yearly': group_eva_abs_yearly,
|
|
278
|
+
'group_eva_exc_yearly': group_eva_exc_yearly,
|
|
279
|
+
'turnover': pd.DataFrame() if 'turn' not in dir() else turn,
|
|
280
|
+
'n_groups': n_groups,
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
def _get_benchmark(self, hedge, hedge_path, index_cp, price_full, factor_data, adj_dates):
|
|
284
|
+
"""获取对冲基准净值"""
|
|
285
|
+
if hedge == 'equal':
|
|
286
|
+
# 等权基准: 所有有因子值的股票收益等权
|
|
287
|
+
benchmark = pd.Series(np.nan, index=price_full.index)
|
|
288
|
+
benchmark.iloc[0] = 0
|
|
289
|
+
for i in range(len(adj_dates) - 1):
|
|
290
|
+
t_i = adj_dates[i]
|
|
291
|
+
t_ii = adj_dates[i + 1]
|
|
292
|
+
if t_i not in factor_data.index:
|
|
293
|
+
continue
|
|
294
|
+
stocks_with_factor = factor_data.loc[t_i].dropna().index
|
|
295
|
+
cycle = price_full.loc[t_i:t_ii] / price_full.loc[t_i]
|
|
296
|
+
valid = [s for s in stocks_with_factor if s in cycle.columns]
|
|
297
|
+
if valid:
|
|
298
|
+
benchmark.loc[cycle.index[1:]] = (
|
|
299
|
+
cycle[valid].mean(axis=1).pct_change(fill_method=None).iloc[1:]
|
|
300
|
+
)
|
|
301
|
+
return (benchmark + 1).cumprod()
|
|
302
|
+
|
|
303
|
+
elif hedge in INDEX_CP_MAPPING and index_cp is not None:
|
|
304
|
+
key = INDEX_CP_MAPPING[hedge]
|
|
305
|
+
if key in index_cp.columns:
|
|
306
|
+
return index_cp.loc[price_full.index, key]
|
|
307
|
+
|
|
308
|
+
elif hedge == 'custom' and hedge_path:
|
|
309
|
+
try:
|
|
310
|
+
from QuantNodes.research.factor_test.utils.data_loader import DataLoader
|
|
311
|
+
loader = DataLoader()
|
|
312
|
+
custom = loader.load_custom(('', hedge_path))
|
|
313
|
+
return custom.iloc[:, 0]
|
|
314
|
+
except Exception as e:
|
|
315
|
+
logger.warning("GroupAnalyzerNode: 自定义对冲加载失败 (%s): %s", hedge_path, e)
|
|
316
|
+
|
|
317
|
+
return None
|