quantlab-factor-agent 0.1.0__tar.gz

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 (121) hide show
  1. quantlab_factor_agent-0.1.0/LICENSE +21 -0
  2. quantlab_factor_agent-0.1.0/PKG-INFO +172 -0
  3. quantlab_factor_agent-0.1.0/README.md +137 -0
  4. quantlab_factor_agent-0.1.0/factor_agent/KUNQUANT_LICENSE +201 -0
  5. quantlab_factor_agent-0.1.0/factor_agent/__init__.py +8 -0
  6. quantlab_factor_agent-0.1.0/factor_agent/_acceptance_model.py +93 -0
  7. quantlab_factor_agent-0.1.0/factor_agent/_admission.py +168 -0
  8. quantlab_factor_agent-0.1.0/factor_agent/_expression_fold.py +48 -0
  9. quantlab_factor_agent-0.1.0/factor_agent/_feedback.py +399 -0
  10. quantlab_factor_agent-0.1.0/factor_agent/_max_drawdown.py +51 -0
  11. quantlab_factor_agent-0.1.0/factor_agent/_model_cache.py +100 -0
  12. quantlab_factor_agent-0.1.0/factor_agent/_scheduler.py +35 -0
  13. quantlab_factor_agent-0.1.0/factor_agent/acceptance.py +808 -0
  14. quantlab_factor_agent-0.1.0/factor_agent/accepted/__init__.py +1 -0
  15. quantlab_factor_agent-0.1.0/factor_agent/aggregations.py +122 -0
  16. quantlab_factor_agent-0.1.0/factor_agent/campaign.py +797 -0
  17. quantlab_factor_agent-0.1.0/factor_agent/candidate.py +51 -0
  18. quantlab_factor_agent-0.1.0/factor_agent/config.py +651 -0
  19. quantlab_factor_agent-0.1.0/factor_agent/derived.py +98 -0
  20. quantlab_factor_agent-0.1.0/factor_agent/evaluator.py +1096 -0
  21. quantlab_factor_agent-0.1.0/factor_agent/events.py +343 -0
  22. quantlab_factor_agent-0.1.0/factor_agent/exported.py +177 -0
  23. quantlab_factor_agent-0.1.0/factor_agent/gate/__init__.py +359 -0
  24. quantlab_factor_agent-0.1.0/factor_agent/gate/_canonical.py +331 -0
  25. quantlab_factor_agent-0.1.0/factor_agent/gate/_checks.py +85 -0
  26. quantlab_factor_agent-0.1.0/factor_agent/gate/_constraints.py +85 -0
  27. quantlab_factor_agent-0.1.0/factor_agent/gate/_dimension.py +177 -0
  28. quantlab_factor_agent-0.1.0/factor_agent/gate/_originality.py +146 -0
  29. quantlab_factor_agent-0.1.0/factor_agent/gate/_sandbox.py +105 -0
  30. quantlab_factor_agent-0.1.0/factor_agent/gate/graph.py +223 -0
  31. quantlab_factor_agent-0.1.0/factor_agent/gate/stages.py +383 -0
  32. quantlab_factor_agent-0.1.0/factor_agent/gate/vocabulary.py +1097 -0
  33. quantlab_factor_agent-0.1.0/factor_agent/ledger.py +85 -0
  34. quantlab_factor_agent-0.1.0/factor_agent/llm/__init__.py +0 -0
  35. quantlab_factor_agent-0.1.0/factor_agent/llm/_common.py +18 -0
  36. quantlab_factor_agent-0.1.0/factor_agent/llm/_raw.py +78 -0
  37. quantlab_factor_agent-0.1.0/factor_agent/llm/anthropic.py +100 -0
  38. quantlab_factor_agent-0.1.0/factor_agent/llm/base.py +124 -0
  39. quantlab_factor_agent-0.1.0/factor_agent/llm/claude_code.py +101 -0
  40. quantlab_factor_agent-0.1.0/factor_agent/llm/log.py +74 -0
  41. quantlab_factor_agent-0.1.0/factor_agent/llm/openai_compatible.py +113 -0
  42. quantlab_factor_agent-0.1.0/factor_agent/llm/replay.py +59 -0
  43. quantlab_factor_agent-0.1.0/factor_agent/llm/scripted.py +39 -0
  44. quantlab_factor_agent-0.1.0/factor_agent/period_lag.py +91 -0
  45. quantlab_factor_agent-0.1.0/factor_agent/prompts.py +557 -0
  46. quantlab_factor_agent-0.1.0/factor_agent/researcher.py +615 -0
  47. quantlab_factor_agent-0.1.0/factor_agent/scoring.py +143 -0
  48. quantlab_factor_agent-0.1.0/factor_agent/segments.py +184 -0
  49. quantlab_factor_agent-0.1.0/factor_agent/session.py +500 -0
  50. quantlab_factor_agent-0.1.0/factor_agent/snapshot.py +219 -0
  51. quantlab_factor_agent-0.1.0/factor_agent/web/__init__.py +7 -0
  52. quantlab_factor_agent-0.1.0/factor_agent/web/_acceptance.py +145 -0
  53. quantlab_factor_agent-0.1.0/factor_agent/web/_config.py +51 -0
  54. quantlab_factor_agent-0.1.0/factor_agent/web/_diagnosis.py +110 -0
  55. quantlab_factor_agent-0.1.0/factor_agent/web/_files.py +78 -0
  56. quantlab_factor_agent-0.1.0/factor_agent/web/_health.py +207 -0
  57. quantlab_factor_agent-0.1.0/factor_agent/web/_ic.py +27 -0
  58. quantlab_factor_agent-0.1.0/factor_agent/web/_ledger.py +293 -0
  59. quantlab_factor_agent-0.1.0/factor_agent/web/_memory.py +42 -0
  60. quantlab_factor_agent-0.1.0/factor_agent/web/_results.py +77 -0
  61. quantlab_factor_agent-0.1.0/factor_agent/web/_round.py +219 -0
  62. quantlab_factor_agent-0.1.0/factor_agent/web/_trials.py +112 -0
  63. quantlab_factor_agent-0.1.0/factor_agent/web/app.py +118 -0
  64. quantlab_factor_agent-0.1.0/factor_agent/web/run_view.py +329 -0
  65. quantlab_factor_agent-0.1.0/factor_agent/web/static/assets/index-9QjjJgl3.css +1 -0
  66. quantlab_factor_agent-0.1.0/factor_agent/web/static/assets/index-iOE9ei_S.js +74 -0
  67. quantlab_factor_agent-0.1.0/factor_agent/web/static/index.html +13 -0
  68. quantlab_factor_agent-0.1.0/factor_agent/zoo.py +136 -0
  69. quantlab_factor_agent-0.1.0/pyproject.toml +82 -0
  70. quantlab_factor_agent-0.1.0/quantlab_factor_agent.egg-info/PKG-INFO +172 -0
  71. quantlab_factor_agent-0.1.0/quantlab_factor_agent.egg-info/SOURCES.txt +119 -0
  72. quantlab_factor_agent-0.1.0/quantlab_factor_agent.egg-info/dependency_links.txt +1 -0
  73. quantlab_factor_agent-0.1.0/quantlab_factor_agent.egg-info/entry_points.txt +2 -0
  74. quantlab_factor_agent-0.1.0/quantlab_factor_agent.egg-info/requires.txt +9 -0
  75. quantlab_factor_agent-0.1.0/quantlab_factor_agent.egg-info/top_level.txt +1 -0
  76. quantlab_factor_agent-0.1.0/setup.cfg +4 -0
  77. quantlab_factor_agent-0.1.0/tests/test_acceptance.py +677 -0
  78. quantlab_factor_agent-0.1.0/tests/test_admission_threshold.py +54 -0
  79. quantlab_factor_agent-0.1.0/tests/test_campaign.py +634 -0
  80. quantlab_factor_agent-0.1.0/tests/test_campaign_lineage.py +179 -0
  81. quantlab_factor_agent-0.1.0/tests/test_campaign_loop.py +502 -0
  82. quantlab_factor_agent-0.1.0/tests/test_campaign_prompts.py +436 -0
  83. quantlab_factor_agent-0.1.0/tests/test_config.py +318 -0
  84. quantlab_factor_agent-0.1.0/tests/test_confirmation.py +112 -0
  85. quantlab_factor_agent-0.1.0/tests/test_derived_columns.py +76 -0
  86. quantlab_factor_agent-0.1.0/tests/test_evaluator.py +646 -0
  87. quantlab_factor_agent-0.1.0/tests/test_events.py +23 -0
  88. quantlab_factor_agent-0.1.0/tests/test_expression_fold.py +133 -0
  89. quantlab_factor_agent-0.1.0/tests/test_gate.py +550 -0
  90. quantlab_factor_agent-0.1.0/tests/test_high_frequency_family.py +85 -0
  91. quantlab_factor_agent-0.1.0/tests/test_import.py +5 -0
  92. quantlab_factor_agent-0.1.0/tests/test_intraday_acceptance.py +173 -0
  93. quantlab_factor_agent-0.1.0/tests/test_intraday_example.py +125 -0
  94. quantlab_factor_agent-0.1.0/tests/test_intraday_family.py +170 -0
  95. quantlab_factor_agent-0.1.0/tests/test_intraday_fields.py +155 -0
  96. quantlab_factor_agent-0.1.0/tests/test_intraday_gate.py +155 -0
  97. quantlab_factor_agent-0.1.0/tests/test_intraday_prompt.py +99 -0
  98. quantlab_factor_agent-0.1.0/tests/test_intraday_vocabulary.py +171 -0
  99. quantlab_factor_agent-0.1.0/tests/test_intraday_windows.py +137 -0
  100. quantlab_factor_agent-0.1.0/tests/test_llm_backends.py +525 -0
  101. quantlab_factor_agent-0.1.0/tests/test_max_drawdown.py +60 -0
  102. quantlab_factor_agent-0.1.0/tests/test_period_lag.py +211 -0
  103. quantlab_factor_agent-0.1.0/tests/test_proposal_groups.py +214 -0
  104. quantlab_factor_agent-0.1.0/tests/test_run_acceptance.py +139 -0
  105. quantlab_factor_agent-0.1.0/tests/test_run_config.py +71 -0
  106. quantlab_factor_agent-0.1.0/tests/test_run_diagnosis.py +171 -0
  107. quantlab_factor_agent-0.1.0/tests/test_run_factors.py +167 -0
  108. quantlab_factor_agent-0.1.0/tests/test_run_health.py +254 -0
  109. quantlab_factor_agent-0.1.0/tests/test_run_ic.py +58 -0
  110. quantlab_factor_agent-0.1.0/tests/test_run_intraday.py +52 -0
  111. quantlab_factor_agent-0.1.0/tests/test_run_round.py +225 -0
  112. quantlab_factor_agent-0.1.0/tests/test_run_snapshot.py +162 -0
  113. quantlab_factor_agent-0.1.0/tests/test_run_trials.py +113 -0
  114. quantlab_factor_agent-0.1.0/tests/test_run_view.py +198 -0
  115. quantlab_factor_agent-0.1.0/tests/test_session_columns.py +78 -0
  116. quantlab_factor_agent-0.1.0/tests/test_session_factor.py +469 -0
  117. quantlab_factor_agent-0.1.0/tests/test_sharadar_fundamentals.py +206 -0
  118. quantlab_factor_agent-0.1.0/tests/test_stage_split.py +143 -0
  119. quantlab_factor_agent-0.1.0/tests/test_themes.py +242 -0
  120. quantlab_factor_agent-0.1.0/tests/test_vocabulary.py +427 -0
  121. quantlab_factor_agent-0.1.0/tests/test_web.py +263 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Zhaorong Dai
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,172 @@
1
+ Metadata-Version: 2.4
2
+ Name: quantlab-factor-agent
3
+ Version: 0.1.0
4
+ Summary: LLM-driven, mechanism-first formulaic factor research on quantlab, evaluated with KunQuant.
5
+ Author: Zhaorong Dai
6
+ License-Expression: MIT AND Apache-2.0
7
+ Project-URL: Homepage, https://github.com/ZhaorongDai/quantlab-factor-agent
8
+ Project-URL: Repository, https://github.com/ZhaorongDai/quantlab-factor-agent
9
+ Project-URL: Documentation, https://zhaorongdai.github.io/quantlab-factor-agent/
10
+ Project-URL: Issues, https://github.com/ZhaorongDai/quantlab-factor-agent/issues
11
+ Project-URL: Changelog, https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/CHANGELOG.md
12
+ Keywords: quant,factor,alpha,llm,agent,kunquant,quantlab
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Financial and Insurance Industry
15
+ Classifier: Intended Audience :: Science/Research
16
+ Classifier: Operating System :: MacOS
17
+ Classifier: Operating System :: POSIX :: Linux
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Office/Business :: Financial :: Investment
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Requires-Python: >=3.13
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ License-File: factor_agent/KUNQUANT_LICENSE
26
+ Requires-Dist: anthropic>=2.3.0
27
+ Requires-Dist: openai>=3.37.0
28
+ Requires-Dist: psutil>=7.2.2
29
+ Requires-Dist: pyyaml>=6.0.3
30
+ Requires-Dist: quantlab-py>=0.3.1
31
+ Provides-Extra: web
32
+ Requires-Dist: fastapi>=0.162.0; extra == "web"
33
+ Requires-Dist: uvicorn>=0.54.0; extra == "web"
34
+ Dynamic: license-file
35
+
36
+ <p align="center">
37
+ <img src="https://raw.githubusercontent.com/ZhaorongDai/quantlab-factor-agent/main/docs/_static/logo.svg" alt="quantlab-factor-agent logo" width="112">
38
+ </p>
39
+
40
+ <h1 align="center">quantlab-factor-agent</h1>
41
+
42
+ <p align="center">
43
+ <a href="https://github.com/ZhaorongDai/quantlab-factor-agent/actions/workflows/ci.yml"><img alt="CI" src="https://img.shields.io/github/actions/workflow/status/ZhaorongDai/quantlab-factor-agent/ci.yml?branch=main&label=ci"></a>
44
+ <a href="https://zhaorongdai.github.io/quantlab-factor-agent/"><img alt="Docs" src="https://img.shields.io/badge/docs-online-3776ab"></a>
45
+ <a href="https://pypi.org/project/quantlab-factor-agent/"><img alt="PyPI" src="https://img.shields.io/pypi/v/quantlab-factor-agent?label=pypi&color=3776ab"></a>
46
+ <a href="https://www.python.org/downloads/"><img alt="Python 3.13+" src="https://img.shields.io/badge/python-3.13%2B-3776ab?logo=python&logoColor=white"></a>
47
+ <a href="https://zhaorongdai.github.io/quantlab-factor-agent/getting-started/installation.html"><img alt="Platform: Linux and macOS" src="https://img.shields.io/badge/platform-Linux%20%7C%20macOS-3776ab"></a>
48
+ <a href="https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/LICENSE"><img alt="License: MIT and Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2B%20Apache--2.0-green"></a>
49
+ <a href="https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/CHANGELOG.md"><img alt="Changelog" src="https://img.shields.io/badge/changelog-latest-3776ab"></a>
50
+ <img alt="Status: alpha" src="https://img.shields.io/badge/status-alpha-orange">
51
+ <a href="https://github.com/ZhaorongDai/quantlab"><img alt="Built on quantlab" src="https://img.shields.io/badge/built%20on-quantlab-3776ab"></a>
52
+ <a href="https://github.com/Menooker/KunQuant"><img alt="Factors: KunQuant" src="https://img.shields.io/badge/factors-KunQuant-0ea5e9"></a>
53
+ </p>
54
+
55
+ <p align="center">English | <a href="https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/README.zh-CN.md">简体中文</a></p>
56
+
57
+ quantlab-factor-agent mines daily stock factors with language models, mechanism first. A
58
+ model states an economic mechanism and writes the factor it implies as KunQuant code. Fixed
59
+ checks and statistics from [quantlab](https://github.com/ZhaorongDai/quantlab) then decide
60
+ whether the factor is new and adds to the factors you already have. The model only proposes
61
+ and reviews, and it sees nothing but the training segment.
62
+
63
+ [Documentation](https://zhaorongdai.github.io/quantlab-factor-agent/) ·
64
+ [Example configs](https://github.com/ZhaorongDai/quantlab-factor-agent/tree/main/configs/) · [Changelog](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/CHANGELOG.md)
65
+
66
+ > **Status: alpha (0.x).** The API, the config format and the run directory's layout may
67
+ > change between minor versions.
68
+
69
+ ## How it works
70
+
71
+ <p align="center">
72
+ <img src="https://raw.githubusercontent.com/ZhaorongDai/quantlab-factor-agent/main/docs/_static/research-loop.svg" alt="Each round: the planner picks directions, the proposer writes candidates, the Gate checks them in a sandbox, the reviewer checks that hypothesis and code agree, the Evaluator scores them on the training segment and admission decides; trials go to the ledger for the next round. After the campaign, acceptance validates, opens the hold-out once and exports." width="100%">
73
+ </p>
74
+
75
+ A campaign runs in rounds. The planner picks one research direction per slot, and the
76
+ proposer writes a hypothesis, a description and KunQuant code for each. The Gate builds the
77
+ code in a sandbox and refuses rewrites of existing factors; the reviewer checks that
78
+ hypothesis and code describe the same factor. The Evaluator then scores what is left on the
79
+ training segment, and admission accepts or rejects it. After the campaign, `Acceptance`
80
+ trains a quantlab return model with and without the accepted factors, opens the hold-out
81
+ once and exports the chosen factors.
82
+
83
+ - **Mechanism first.** The Gate compares KunQuant graphs and refuses
84
+ rewrites, parameter-only variants and large shared subtrees of every reference, known and
85
+ accepted factor.
86
+ - **No look-ahead.** Prompts carry training-segment statistics only: no return, no date, no
87
+ validation or hold-out metric. The hold-out opens once, behind a lock.
88
+ - **Only code accepts.** The Evaluator scores candidates on quantlab's
89
+ whole-market panels, masked to each day's members, and the partial-IC t threshold
90
+ tightens with every evaluated trial.
91
+ - **Nothing hard-coded about the market.** Fields, operators, prompts, mechanism types and
92
+ scoring come from the config's files, so a new input family is a new field file.
93
+ - **Any provider, replayable.** Each role picks its backend: OpenAI-compatible endpoints
94
+ (DeepSeek, OpenAI, vLLM, ...), Anthropic or Claude Code. Every call is logged, and the
95
+ `replay` backend reproduces a run byte for byte without a provider.
96
+ - **Resumable.** `run()` picks up from the run directory after a crash or an exhausted
97
+ balance.
98
+
99
+ The diagram below shows how the parts fit together: what the models search, what each
100
+ judge refuses, how every trial feeds the next round, and where the data the models see
101
+ ends. [How the agent mines factors](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/mechanism.md) explains it in full.
102
+
103
+ <p align="center">
104
+ <img src="https://raw.githubusercontent.com/ZhaorongDai/quantlab-factor-agent/main/docs/_static/mining-mechanism.svg" alt="The four parts of the mechanism: language models search over mechanism types and directions; the Gate, the reviewer, the Evaluator and admission each refuse what is not valid, consistent, new or significant; accepted factors join the zoo and pool and every trial feeds back to the planner; the models see only training-segment statistics, and the hold-out opens once behind a lock." width="100%">
105
+ </p>
106
+
107
+ With themes turned on, the planner also reads a map of the directions tried so far; see
108
+ [the direction map](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/mechanism.md#3-learning-every-trial-shapes-the-next-round).
109
+
110
+ ## Install
111
+
112
+ You need Python 3.13+ and a C++ compiler on the `PATH` (KunQuant compiles factor graphs to
113
+ native code):
114
+
115
+ ```bash
116
+ pip install "quantlab-factor-agent[web]" # [web] adds the factor-agent-web frontend
117
+ ```
118
+
119
+ To work on the code, or to run the example configs and the offline test suite, install
120
+ from a checkout with [uv](https://docs.astral.sh/uv/), with quantlab's checkout beside it:
121
+
122
+ ```bash
123
+ git clone https://github.com/ZhaorongDai/quantlab.git
124
+ git clone https://github.com/ZhaorongDai/quantlab-factor-agent.git
125
+ cd quantlab-factor-agent
126
+ uv sync --extra web
127
+ uv run pytest -n auto # offline: no LLM call, a synthetic market
128
+ ```
129
+
130
+ On macOS, xgboost also needs `brew install libomp`. Keys come from environment variables
131
+ only (`ANTHROPIC_API_KEY`, or the variable a role's `api_key_env` names), and a config that
132
+ holds a key is refused. See [installation](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/getting-started/installation.md).
133
+
134
+ ## Run a campaign
135
+
136
+ ```python
137
+ from factor_agent.acceptance import Acceptance
138
+ from factor_agent.campaign import Campaign
139
+ from factor_agent.config import CampaignConfig
140
+
141
+ config = CampaignConfig.from_file("configs/us3000_ret5.yaml")
142
+ result = Campaign(config).run() # resumes when run_dir already holds a state
143
+ print(result.stop, len(result.accepted), "accepted of", len(result.records))
144
+
145
+ report = Acceptance(config).validate() # baseline vs baseline + accepted, on validation
146
+ print(report.markdown())
147
+ ```
148
+
149
+ Point the config's data paths at your own quantlab stores first. A campaign runs for hours,
150
+ mostly waiting on the model, and needs no GPU; `Acceptance` uses CUDA when it is available.
151
+ Watch a run in the browser with `factor-agent-web` ([web frontend](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/web.md)).
152
+
153
+ ## Documentation
154
+
155
+ - [How the agent mines factors](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/mechanism.md): the search, the judges, the learning loop and what the models may see, in one diagram
156
+ - [First campaign](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/getting-started/quickstart.md): run one and read its outcome
157
+ - [Concepts](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/concepts.md): roles, factor sets, segments, what "accepted" means
158
+ - [The campaign config](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/campaign.md): every section, stopping and resuming
159
+ - [The vocabulary](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/vocabulary.md) and [prompts](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/prompts.md): what candidates may read and write, and what the models are told
160
+ - [LLM backends](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/llm-backends.md): providers, the LLM log, replay, cost
161
+ - [Gate, review and evaluation](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/evaluation.md) and [acceptance](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/acceptance.md): how a factor is judged
162
+
163
+ ## Contributing
164
+
165
+ Bug reports, questions and pull requests are welcome; see [CONTRIBUTING.md](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/CONTRIBUTING.md).
166
+ Report security problems privately, as [SECURITY.md](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/SECURITY.md) describes.
167
+
168
+ ## License
169
+
170
+ [MIT](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/LICENSE). `factor_agent/_max_drawdown.py` adapts code from
171
+ [KunQuant](https://github.com/Menooker/KunQuant) under the
172
+ [Apache License 2.0](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/factor_agent/KUNQUANT_LICENSE).
@@ -0,0 +1,137 @@
1
+ <p align="center">
2
+ <img src="https://raw.githubusercontent.com/ZhaorongDai/quantlab-factor-agent/main/docs/_static/logo.svg" alt="quantlab-factor-agent logo" width="112">
3
+ </p>
4
+
5
+ <h1 align="center">quantlab-factor-agent</h1>
6
+
7
+ <p align="center">
8
+ <a href="https://github.com/ZhaorongDai/quantlab-factor-agent/actions/workflows/ci.yml"><img alt="CI" src="https://img.shields.io/github/actions/workflow/status/ZhaorongDai/quantlab-factor-agent/ci.yml?branch=main&label=ci"></a>
9
+ <a href="https://zhaorongdai.github.io/quantlab-factor-agent/"><img alt="Docs" src="https://img.shields.io/badge/docs-online-3776ab"></a>
10
+ <a href="https://pypi.org/project/quantlab-factor-agent/"><img alt="PyPI" src="https://img.shields.io/pypi/v/quantlab-factor-agent?label=pypi&color=3776ab"></a>
11
+ <a href="https://www.python.org/downloads/"><img alt="Python 3.13+" src="https://img.shields.io/badge/python-3.13%2B-3776ab?logo=python&logoColor=white"></a>
12
+ <a href="https://zhaorongdai.github.io/quantlab-factor-agent/getting-started/installation.html"><img alt="Platform: Linux and macOS" src="https://img.shields.io/badge/platform-Linux%20%7C%20macOS-3776ab"></a>
13
+ <a href="https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/LICENSE"><img alt="License: MIT and Apache-2.0" src="https://img.shields.io/badge/license-MIT%20%2B%20Apache--2.0-green"></a>
14
+ <a href="https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/CHANGELOG.md"><img alt="Changelog" src="https://img.shields.io/badge/changelog-latest-3776ab"></a>
15
+ <img alt="Status: alpha" src="https://img.shields.io/badge/status-alpha-orange">
16
+ <a href="https://github.com/ZhaorongDai/quantlab"><img alt="Built on quantlab" src="https://img.shields.io/badge/built%20on-quantlab-3776ab"></a>
17
+ <a href="https://github.com/Menooker/KunQuant"><img alt="Factors: KunQuant" src="https://img.shields.io/badge/factors-KunQuant-0ea5e9"></a>
18
+ </p>
19
+
20
+ <p align="center">English | <a href="https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/README.zh-CN.md">简体中文</a></p>
21
+
22
+ quantlab-factor-agent mines daily stock factors with language models, mechanism first. A
23
+ model states an economic mechanism and writes the factor it implies as KunQuant code. Fixed
24
+ checks and statistics from [quantlab](https://github.com/ZhaorongDai/quantlab) then decide
25
+ whether the factor is new and adds to the factors you already have. The model only proposes
26
+ and reviews, and it sees nothing but the training segment.
27
+
28
+ [Documentation](https://zhaorongdai.github.io/quantlab-factor-agent/) ·
29
+ [Example configs](https://github.com/ZhaorongDai/quantlab-factor-agent/tree/main/configs/) · [Changelog](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/CHANGELOG.md)
30
+
31
+ > **Status: alpha (0.x).** The API, the config format and the run directory's layout may
32
+ > change between minor versions.
33
+
34
+ ## How it works
35
+
36
+ <p align="center">
37
+ <img src="https://raw.githubusercontent.com/ZhaorongDai/quantlab-factor-agent/main/docs/_static/research-loop.svg" alt="Each round: the planner picks directions, the proposer writes candidates, the Gate checks them in a sandbox, the reviewer checks that hypothesis and code agree, the Evaluator scores them on the training segment and admission decides; trials go to the ledger for the next round. After the campaign, acceptance validates, opens the hold-out once and exports." width="100%">
38
+ </p>
39
+
40
+ A campaign runs in rounds. The planner picks one research direction per slot, and the
41
+ proposer writes a hypothesis, a description and KunQuant code for each. The Gate builds the
42
+ code in a sandbox and refuses rewrites of existing factors; the reviewer checks that
43
+ hypothesis and code describe the same factor. The Evaluator then scores what is left on the
44
+ training segment, and admission accepts or rejects it. After the campaign, `Acceptance`
45
+ trains a quantlab return model with and without the accepted factors, opens the hold-out
46
+ once and exports the chosen factors.
47
+
48
+ - **Mechanism first.** The Gate compares KunQuant graphs and refuses
49
+ rewrites, parameter-only variants and large shared subtrees of every reference, known and
50
+ accepted factor.
51
+ - **No look-ahead.** Prompts carry training-segment statistics only: no return, no date, no
52
+ validation or hold-out metric. The hold-out opens once, behind a lock.
53
+ - **Only code accepts.** The Evaluator scores candidates on quantlab's
54
+ whole-market panels, masked to each day's members, and the partial-IC t threshold
55
+ tightens with every evaluated trial.
56
+ - **Nothing hard-coded about the market.** Fields, operators, prompts, mechanism types and
57
+ scoring come from the config's files, so a new input family is a new field file.
58
+ - **Any provider, replayable.** Each role picks its backend: OpenAI-compatible endpoints
59
+ (DeepSeek, OpenAI, vLLM, ...), Anthropic or Claude Code. Every call is logged, and the
60
+ `replay` backend reproduces a run byte for byte without a provider.
61
+ - **Resumable.** `run()` picks up from the run directory after a crash or an exhausted
62
+ balance.
63
+
64
+ The diagram below shows how the parts fit together: what the models search, what each
65
+ judge refuses, how every trial feeds the next round, and where the data the models see
66
+ ends. [How the agent mines factors](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/mechanism.md) explains it in full.
67
+
68
+ <p align="center">
69
+ <img src="https://raw.githubusercontent.com/ZhaorongDai/quantlab-factor-agent/main/docs/_static/mining-mechanism.svg" alt="The four parts of the mechanism: language models search over mechanism types and directions; the Gate, the reviewer, the Evaluator and admission each refuse what is not valid, consistent, new or significant; accepted factors join the zoo and pool and every trial feeds back to the planner; the models see only training-segment statistics, and the hold-out opens once behind a lock." width="100%">
70
+ </p>
71
+
72
+ With themes turned on, the planner also reads a map of the directions tried so far; see
73
+ [the direction map](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/mechanism.md#3-learning-every-trial-shapes-the-next-round).
74
+
75
+ ## Install
76
+
77
+ You need Python 3.13+ and a C++ compiler on the `PATH` (KunQuant compiles factor graphs to
78
+ native code):
79
+
80
+ ```bash
81
+ pip install "quantlab-factor-agent[web]" # [web] adds the factor-agent-web frontend
82
+ ```
83
+
84
+ To work on the code, or to run the example configs and the offline test suite, install
85
+ from a checkout with [uv](https://docs.astral.sh/uv/), with quantlab's checkout beside it:
86
+
87
+ ```bash
88
+ git clone https://github.com/ZhaorongDai/quantlab.git
89
+ git clone https://github.com/ZhaorongDai/quantlab-factor-agent.git
90
+ cd quantlab-factor-agent
91
+ uv sync --extra web
92
+ uv run pytest -n auto # offline: no LLM call, a synthetic market
93
+ ```
94
+
95
+ On macOS, xgboost also needs `brew install libomp`. Keys come from environment variables
96
+ only (`ANTHROPIC_API_KEY`, or the variable a role's `api_key_env` names), and a config that
97
+ holds a key is refused. See [installation](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/getting-started/installation.md).
98
+
99
+ ## Run a campaign
100
+
101
+ ```python
102
+ from factor_agent.acceptance import Acceptance
103
+ from factor_agent.campaign import Campaign
104
+ from factor_agent.config import CampaignConfig
105
+
106
+ config = CampaignConfig.from_file("configs/us3000_ret5.yaml")
107
+ result = Campaign(config).run() # resumes when run_dir already holds a state
108
+ print(result.stop, len(result.accepted), "accepted of", len(result.records))
109
+
110
+ report = Acceptance(config).validate() # baseline vs baseline + accepted, on validation
111
+ print(report.markdown())
112
+ ```
113
+
114
+ Point the config's data paths at your own quantlab stores first. A campaign runs for hours,
115
+ mostly waiting on the model, and needs no GPU; `Acceptance` uses CUDA when it is available.
116
+ Watch a run in the browser with `factor-agent-web` ([web frontend](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/web.md)).
117
+
118
+ ## Documentation
119
+
120
+ - [How the agent mines factors](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/mechanism.md): the search, the judges, the learning loop and what the models may see, in one diagram
121
+ - [First campaign](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/getting-started/quickstart.md): run one and read its outcome
122
+ - [Concepts](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/concepts.md): roles, factor sets, segments, what "accepted" means
123
+ - [The campaign config](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/campaign.md): every section, stopping and resuming
124
+ - [The vocabulary](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/vocabulary.md) and [prompts](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/prompts.md): what candidates may read and write, and what the models are told
125
+ - [LLM backends](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/llm-backends.md): providers, the LLM log, replay, cost
126
+ - [Gate, review and evaluation](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/evaluation.md) and [acceptance](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/docs/user-guide/acceptance.md): how a factor is judged
127
+
128
+ ## Contributing
129
+
130
+ Bug reports, questions and pull requests are welcome; see [CONTRIBUTING.md](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/CONTRIBUTING.md).
131
+ Report security problems privately, as [SECURITY.md](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/SECURITY.md) describes.
132
+
133
+ ## License
134
+
135
+ [MIT](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/LICENSE). `factor_agent/_max_drawdown.py` adapts code from
136
+ [KunQuant](https://github.com/Menooker/KunQuant) under the
137
+ [Apache License 2.0](https://github.com/ZhaorongDai/quantlab-factor-agent/blob/main/factor_agent/KUNQUANT_LICENSE).
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,8 @@
1
+ """LLM-driven, mechanism-first formulaic factor research on quantlab."""
2
+
3
+ from factor_agent import _expression_fold, _max_drawdown
4
+
5
+ __version__ = "0.1.0"
6
+
7
+ _expression_fold.patch()
8
+ _max_drawdown.patch()
@@ -0,0 +1,93 @@
1
+ """The acceptance model: a quantlab model template that Acceptance fills in and trains.
2
+
3
+ ``acceptance.model`` is the component config (a ``get_config()`` dict) of a
4
+ quantlab ``BaseModel``, or of a ``ModelEnsemble`` whose ``members`` are such
5
+ configs. A model's ``factors`` are the baseline: entries as the campaign
6
+ config's ``reference`` lists them, or empty (or absent) for the reference set
7
+ itself. Everything else of the template, its ``hyperparameters`` above all,
8
+ is the model's own.
9
+
10
+ ``build`` fills the template in: each model (each member of an ensemble) gets
11
+ its baseline followed by the factors added, and the fields Acceptance owns
12
+ (``FILLED``: the label, the save directory, the read strategies, the
13
+ windows, ``val_size``, the scored split and the seed) replace whatever the
14
+ template says of them, so a config copied from a trained run's
15
+ ``config.json`` is a template as it is. A ``SeedEnsemble`` template is
16
+ refused: Acceptance trains every model once per ``acceptance.seeds``.
17
+ """
18
+
19
+ import dataclasses
20
+ from collections.abc import Callable
21
+
22
+ from quantlab.core.component import get_cls_from_path, rebuild
23
+ from quantlab.model.base import BaseModel
24
+ from quantlab.model.config import ModelConfig
25
+ from quantlab.model.predefined.model_ensemble import ModelEnsemble
26
+ from quantlab.model.predefined.seed_ensemble import SeedEnsemble
27
+
28
+ #: The ``ModelConfig`` fields Acceptance sets in every model, whatever the template says.
29
+ FILLED = (
30
+ "labels", "model_save_dir", "factor_data_strategy", "label_data_strategy", "start_date", "end_date",
31
+ "train_start", "train_end", "test_start", "test_end", "val_size", "metric_splits", "random_seed",
32
+ )
33
+ #: The ``ModelConfig`` fields a template may give.
34
+ _FIELDS = {f.name for f in dataclasses.fields(ModelConfig)}
35
+
36
+
37
+ def check(template: dict) -> None:
38
+ """Refuse a template that ``build`` cannot fill in, before anything is read or trained.
39
+
40
+ Raises
41
+ ------
42
+ ValueError
43
+ If the template is a ``SeedEnsemble`` (seeds are ``acceptance.seeds``).
44
+ TypeError
45
+ If it names no class, a class that is neither a ``BaseModel`` nor a
46
+ ``ModelEnsemble``, or a model with a key ``ModelConfig`` lacks.
47
+ """
48
+ if not isinstance(template, dict) or "name" not in template:
49
+ raise TypeError("acceptance.model: the model's component config needs its class path as name")
50
+ cls = get_cls_from_path(template["name"])
51
+ if not isinstance(cls, type):
52
+ raise TypeError(f"acceptance.model: {template['name']} is not a BaseModel or a ModelEnsemble")
53
+ if issubclass(cls, SeedEnsemble):
54
+ raise ValueError(
55
+ "acceptance.model: a SeedEnsemble is not a template; give its model and set the seeds as acceptance.seeds"
56
+ )
57
+ if issubclass(cls, ModelEnsemble):
58
+ unknown = set(template) - {"name", "members"}
59
+ if unknown:
60
+ raise TypeError(f"acceptance.model: the ModelEnsemble has unknown key(s) {sorted(unknown)}")
61
+ for member in template.get("members") or ():
62
+ check(member)
63
+ return
64
+ if not issubclass(cls, BaseModel):
65
+ raise TypeError(f"acceptance.model: {template['name']} is not a BaseModel or a ModelEnsemble")
66
+ unknown = set(template) - _FIELDS
67
+ if unknown:
68
+ raise TypeError(f"acceptance.model: {template['name']} has key(s) {sorted(unknown)} ModelConfig lacks")
69
+
70
+
71
+ def build(template: dict, baseline: Callable[[tuple], list], added: list, filled: dict):
72
+ """The model (or ``ModelEnsemble``) of ``template``, filled in and untrained.
73
+
74
+ Parameters
75
+ ----------
76
+ template : dict
77
+ ``acceptance.model``; see the module docstring.
78
+ baseline : callable
79
+ A model's ``factors`` entries (empty for the reference set) to its baseline features.
80
+ added : list
81
+ The features added to every model after its baseline.
82
+ filled : dict
83
+ A value for each of ``FILLED``, set in every model.
84
+ """
85
+ check(template)
86
+ cls = get_cls_from_path(template["name"])
87
+ if issubclass(cls, ModelEnsemble):
88
+ return cls([build(member, baseline, added, filled) for member in template.get("members") or ()])
89
+ fields = {key: value for key, value in template.items() if key not in ("name", *FILLED)}
90
+ if "tracker" in fields:
91
+ fields["tracker"] = rebuild(fields["tracker"])
92
+ fields["factors"] = [*baseline(tuple(fields.get("factors") or ())), *added]
93
+ return cls(ModelConfig(**fields, **filled))