quantlab-factor-agent 0.1.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.
- factor_agent/KUNQUANT_LICENSE +201 -0
- factor_agent/__init__.py +8 -0
- factor_agent/_acceptance_model.py +93 -0
- factor_agent/_admission.py +168 -0
- factor_agent/_expression_fold.py +48 -0
- factor_agent/_feedback.py +399 -0
- factor_agent/_max_drawdown.py +51 -0
- factor_agent/_model_cache.py +100 -0
- factor_agent/_scheduler.py +35 -0
- factor_agent/acceptance.py +808 -0
- factor_agent/accepted/__init__.py +1 -0
- factor_agent/aggregations.py +122 -0
- factor_agent/campaign.py +797 -0
- factor_agent/candidate.py +51 -0
- factor_agent/config.py +651 -0
- factor_agent/derived.py +98 -0
- factor_agent/evaluator.py +1096 -0
- factor_agent/events.py +343 -0
- factor_agent/exported.py +177 -0
- factor_agent/gate/__init__.py +359 -0
- factor_agent/gate/_canonical.py +331 -0
- factor_agent/gate/_checks.py +85 -0
- factor_agent/gate/_constraints.py +85 -0
- factor_agent/gate/_dimension.py +177 -0
- factor_agent/gate/_originality.py +146 -0
- factor_agent/gate/_sandbox.py +105 -0
- factor_agent/gate/graph.py +223 -0
- factor_agent/gate/stages.py +383 -0
- factor_agent/gate/vocabulary.py +1097 -0
- factor_agent/ledger.py +85 -0
- factor_agent/llm/__init__.py +0 -0
- factor_agent/llm/_common.py +18 -0
- factor_agent/llm/_raw.py +78 -0
- factor_agent/llm/anthropic.py +100 -0
- factor_agent/llm/base.py +124 -0
- factor_agent/llm/claude_code.py +101 -0
- factor_agent/llm/log.py +74 -0
- factor_agent/llm/openai_compatible.py +113 -0
- factor_agent/llm/replay.py +59 -0
- factor_agent/llm/scripted.py +39 -0
- factor_agent/period_lag.py +91 -0
- factor_agent/prompts.py +557 -0
- factor_agent/researcher.py +615 -0
- factor_agent/scoring.py +143 -0
- factor_agent/segments.py +184 -0
- factor_agent/session.py +500 -0
- factor_agent/snapshot.py +219 -0
- factor_agent/web/__init__.py +7 -0
- factor_agent/web/_acceptance.py +145 -0
- factor_agent/web/_config.py +51 -0
- factor_agent/web/_diagnosis.py +110 -0
- factor_agent/web/_files.py +78 -0
- factor_agent/web/_health.py +207 -0
- factor_agent/web/_ic.py +27 -0
- factor_agent/web/_ledger.py +293 -0
- factor_agent/web/_memory.py +42 -0
- factor_agent/web/_results.py +77 -0
- factor_agent/web/_round.py +219 -0
- factor_agent/web/_trials.py +112 -0
- factor_agent/web/app.py +118 -0
- factor_agent/web/run_view.py +329 -0
- factor_agent/web/static/assets/index-9QjjJgl3.css +1 -0
- factor_agent/web/static/assets/index-iOE9ei_S.js +74 -0
- factor_agent/web/static/index.html +13 -0
- factor_agent/zoo.py +136 -0
- quantlab_factor_agent-0.1.0.dist-info/METADATA +172 -0
- quantlab_factor_agent-0.1.0.dist-info/RECORD +72 -0
- quantlab_factor_agent-0.1.0.dist-info/WHEEL +5 -0
- quantlab_factor_agent-0.1.0.dist-info/entry_points.txt +2 -0
- quantlab_factor_agent-0.1.0.dist-info/licenses/LICENSE +21 -0
- quantlab_factor_agent-0.1.0.dist-info/licenses/factor_agent/KUNQUANT_LICENSE +201 -0
- quantlab_factor_agent-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -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.
|
factor_agent/__init__.py
ADDED
|
@@ -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))
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
"""The admission policy: a pure function of a candidate's metrics and the trial count.
|
|
2
|
+
|
|
3
|
+
A candidate states no direction: its direction is the sign of its training
|
|
4
|
+
IC (``direction``), and the statistics below are read in it. The checks run
|
|
5
|
+
in order and the first that fails is the reason:
|
|
6
|
+
|
|
7
|
+
1. on an average training day the candidate has a value on at least
|
|
8
|
+
``min_coverage`` of the members (its other statistics speak only for
|
|
9
|
+
the members it covers); the campaign adds to the refusal where the
|
|
10
|
+
graph loses its values (``coverage_cause``);
|
|
11
|
+
2. its training IC is a nonzero number, so it has a direction;
|
|
12
|
+
3. its correlation with every reference and accepted factor is at most
|
|
13
|
+
``max_correlation`` in absolute value, and so is its sampled correlation
|
|
14
|
+
with every known factor (on every ``KNOWN_SAMPLE_EVERY``-th scored date
|
|
15
|
+
of the Evaluator);
|
|
16
|
+
4. its partial IC, in its direction, has a Newey-West t at or above the
|
|
17
|
+
threshold for the number of evaluated trials so far;
|
|
18
|
+
5. its decile returns, in its direction, rise with the decile: their
|
|
19
|
+
Spearman correlation with the decile number is at least
|
|
20
|
+
``min_monotonicity``;
|
|
21
|
+
6. with a confirmation segment, its partial IC there, in its direction,
|
|
22
|
+
has a Newey-West t of at least ``confirm_t`` (``confirmed``); the
|
|
23
|
+
reason says so without a number, since no prompt shows a statistic of
|
|
24
|
+
that segment.
|
|
25
|
+
|
|
26
|
+
The threshold is a Bonferroni correction anchored at ``t_threshold``
|
|
27
|
+
(Harvey, Liu and Zhu 2016). The direction is read from the data, so each
|
|
28
|
+
trial is two tests, one per direction: the one-sided p-value of
|
|
29
|
+
``t_threshold`` is divided by twice the trial count n (3.0 becomes about
|
|
30
|
+
3.21 at one trial, 3.82 at 10, 4.35 at 100 and 4.73 at 600). With
|
|
31
|
+
``trial_exponent`` a below 1 it is divided by twice n to the a instead, a
|
|
32
|
+
threshold rising more slowly than Bonferroni's (at 0.5, 3.82 at 100 and
|
|
33
|
+
4.03 at 600).
|
|
34
|
+
"""
|
|
35
|
+
|
|
36
|
+
import math
|
|
37
|
+
from collections.abc import Callable, Sequence
|
|
38
|
+
|
|
39
|
+
import numpy as np
|
|
40
|
+
from scipy import stats
|
|
41
|
+
|
|
42
|
+
from factor_agent.config import AdmissionConfig
|
|
43
|
+
from factor_agent.evaluator import KNOWN_SAMPLE_EVERY, Metrics, NodeCoverage
|
|
44
|
+
|
|
45
|
+
#: The dates a known factor's correlation is sampled on, as the reason says.
|
|
46
|
+
_SAMPLED_DATES = f"one training date in {KNOWN_SAMPLE_EVERY}"
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def t_threshold(config: AdmissionConfig, trials: int) -> float:
|
|
50
|
+
"""The partial-IC Newey-West t a candidate needs as the ``trials``-th evaluated trial."""
|
|
51
|
+
return float(stats.norm.isf(stats.norm.sf(config.t_threshold) / (2 * max(trials, 1) ** config.trial_exponent)))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def direction(ic_mean: float) -> int:
|
|
55
|
+
"""A factor's direction: +1 when a higher value went with a higher training return, -1 when lower, 0 when neither."""
|
|
56
|
+
return int(np.sign(ic_mean)) if math.isfinite(ic_mean) else 0
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def monotonicity(decile_returns, sign: int) -> float:
|
|
60
|
+
"""The Spearman correlation of the decile number with the decile returns, signed by ``sign``."""
|
|
61
|
+
returns = np.asarray(decile_returns, dtype=float)
|
|
62
|
+
if not np.isfinite(returns).all() or np.ptp(returns) == 0:
|
|
63
|
+
return float("nan")
|
|
64
|
+
return sign * float(stats.spearmanr(np.arange(len(returns)), returns).statistic)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
#: What each admission reason starts with, and the kind of refusal it is (``reason_kind``).
|
|
68
|
+
_KINDS = (
|
|
69
|
+
("coverage ", "coverage"),
|
|
70
|
+
("the training IC ", "no direction"),
|
|
71
|
+
("cross-sectional correlation ", "correlation"),
|
|
72
|
+
("the partial IC's ", "partial IC"),
|
|
73
|
+
("decile monotonicity ", "monotonicity"),
|
|
74
|
+
("the factor did not hold on the confirmation period", "confirmation"),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
#: Why a candidate that passed every other check is refused when its partial IC does not hold on the
|
|
78
|
+
#: confirmation segment: without a number, since no prompt may show a statistic of that segment.
|
|
79
|
+
NOT_CONFIRMED = (
|
|
80
|
+
"the factor did not hold on the confirmation period, a later part of the training data whose "
|
|
81
|
+
"statistics the search is not shown: its residual IC there was too weak or went the other way"
|
|
82
|
+
)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def confirmed(ic_mean: float, confirmation_partial_t: float, config: AdmissionConfig) -> bool:
|
|
86
|
+
"""Whether the partial IC on the confirmation segment holds in the direction of the training ``ic_mean``."""
|
|
87
|
+
return direction(ic_mean) * confirmation_partial_t >= config.confirm_t
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def reason_kind(reason: str) -> str:
|
|
91
|
+
"""The kind of an admission reason ``reasons`` wrote: coverage, no direction, correlation, partial IC or monotonicity."""
|
|
92
|
+
return next((kind for start, kind in _KINDS if reason.startswith(start)), "other")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def coverage_cause(trace: Sequence[NodeCoverage], render: Callable[[int], str], min_coverage: float) -> str:
|
|
96
|
+
"""Where a candidate refused for its coverage loses its values, from its ``trace`` (``Evaluator.trace_coverage``).
|
|
97
|
+
|
|
98
|
+
The step named is the first traced node below ``min_coverage`` whose
|
|
99
|
+
traced inputs are all at or above it, with the coverage of those inputs
|
|
100
|
+
and the share on which the step or an input is infinite; a data column
|
|
101
|
+
below it is named as the data it reads. ``render`` writes a node as
|
|
102
|
+
candidate code writes it. The text continues an admission reason; it is
|
|
103
|
+
empty when no such node is traced.
|
|
104
|
+
"""
|
|
105
|
+
by_node = {t.node: t for t in trace}
|
|
106
|
+
for t in trace:
|
|
107
|
+
given = [by_node[j] for j in t.inputs]
|
|
108
|
+
if t.coverage >= min_coverage or any(g.coverage < min_coverage for g in given):
|
|
109
|
+
continue
|
|
110
|
+
if t.column:
|
|
111
|
+
return f"; the data column {render(t.node)} has a value on {t.coverage:.2f} of the member days"
|
|
112
|
+
cause = f"; it falls at {render(t.node)}, to {t.coverage:.2f}"
|
|
113
|
+
if given:
|
|
114
|
+
cause += " from " + ", ".join(f"{g.coverage:.2f} for {render(g.node)}" for g in given)
|
|
115
|
+
infinite = [(f"{render(g.node)} is", g) for g in given if g.infinite > 0]
|
|
116
|
+
if t.infinite > 0:
|
|
117
|
+
infinite = [("it is", t)]
|
|
118
|
+
for subject, g in infinite:
|
|
119
|
+
cause += (
|
|
120
|
+
f"; {subject} infinite on {_share(g.infinite)} of the member days and on {_share(g.infinite_days)} "
|
|
121
|
+
f"of the days at least once"
|
|
122
|
+
)
|
|
123
|
+
if infinite:
|
|
124
|
+
cause += " (a division by zero is infinite)"
|
|
125
|
+
return cause
|
|
126
|
+
return ""
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _share(fraction: float) -> str:
|
|
130
|
+
"""A share as a percentage, with a decimal below 1%, so a small nonzero share does not read 0%."""
|
|
131
|
+
return f"{fraction:.1%}" if fraction < 0.01 else f"{fraction:.0%}"
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def reasons(metrics: Metrics, trials: int, config: AdmissionConfig) -> list[str]:
|
|
135
|
+
"""Why a candidate with ``metrics`` is refused, as one reason, or nothing when it is accepted."""
|
|
136
|
+
sign = direction(metrics.ic_mean)
|
|
137
|
+
if not metrics.coverage >= config.min_coverage:
|
|
138
|
+
return [
|
|
139
|
+
f"coverage {metrics.coverage:.2f} (the mean daily share of the members with a value) "
|
|
140
|
+
f"is below {config.min_coverage:g}"
|
|
141
|
+
]
|
|
142
|
+
if sign == 0:
|
|
143
|
+
return [f"the training IC {metrics.ic_mean:+.4f} gives the factor no direction"]
|
|
144
|
+
if abs(metrics.nearest_correlation) > config.max_correlation:
|
|
145
|
+
return [
|
|
146
|
+
f"cross-sectional correlation {metrics.nearest_correlation:+.2f} with {metrics.nearest} "
|
|
147
|
+
f"is above {config.max_correlation:g} in absolute value"
|
|
148
|
+
]
|
|
149
|
+
if abs(metrics.nearest_known_correlation) > config.max_correlation:
|
|
150
|
+
return [
|
|
151
|
+
f"cross-sectional correlation {metrics.nearest_known_correlation:+.2f} with {metrics.nearest_known}, "
|
|
152
|
+
f"sampled on {_SAMPLED_DATES}, is above {config.max_correlation:g} in absolute value"
|
|
153
|
+
]
|
|
154
|
+
threshold = t_threshold(config, trials)
|
|
155
|
+
partial_t = sign * metrics.partial_ic_t
|
|
156
|
+
if not partial_t >= threshold:
|
|
157
|
+
return [
|
|
158
|
+
f"the partial IC's Newey-West t {partial_t:.2f} (residualised against the reference set and "
|
|
159
|
+
f"the accepted factors, in the factor's direction) is below the threshold {threshold:.2f} "
|
|
160
|
+
f"at {trials} evaluated trial(s), each counted in both directions"
|
|
161
|
+
]
|
|
162
|
+
rising = monotonicity(metrics.decile_returns, sign)
|
|
163
|
+
if not rising >= config.min_monotonicity:
|
|
164
|
+
return [
|
|
165
|
+
f"decile monotonicity {rising:.2f} (Spearman correlation of the decile returns with the decile, "
|
|
166
|
+
f"in the factor's direction) is below {config.min_monotonicity:g}"
|
|
167
|
+
]
|
|
168
|
+
return []
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
"""KunQuant's expression folding, with operators compared as graphs.
|
|
2
|
+
|
|
3
|
+
KunQuant's ``expr_fold`` pass merges equal operators. Two whose hashes match
|
|
4
|
+
and whose inputs are not the same objects it tells apart by walking both as
|
|
5
|
+
trees (``OpBase.items``), which visits a value once for every path to it: a
|
|
6
|
+
graph that reuses its values, as ``x / Scale(x)`` reuses ``x``, nested a few
|
|
7
|
+
times under an EW beta, takes longer to compare than any round can wait (an
|
|
8
|
+
evaluation of arm A2's round 6 ran for hours). ``patch`` makes the comparison
|
|
9
|
+
the same walk over the graph, side by side and with a stack, visiting each pair
|
|
10
|
+
of operators once; it is the fix proposed to KunQuant
|
|
11
|
+
(https://github.com/Menooker/KunQuant/pull/83), and a KunQuant that has it is
|
|
12
|
+
left as it is.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from KunQuant.passes import ExprFold
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _same(x, y) -> bool:
|
|
19
|
+
"""Whether ``x.items()`` and ``y.items()`` are equal."""
|
|
20
|
+
stack = [(x, {}, y, {})]
|
|
21
|
+
visited = set()
|
|
22
|
+
while stack:
|
|
23
|
+
a, a_args, b, b_args = stack.pop()
|
|
24
|
+
if a is b and a_args.keys() == b_args.keys() and all(a_args[k] is b_args[k] for k in a_args):
|
|
25
|
+
continue
|
|
26
|
+
key = (id(a), id(b), *((k, id(v)) for k, v in a_args.items()), *((k, id(v)) for k, v in b_args.items()))
|
|
27
|
+
if key in visited:
|
|
28
|
+
continue
|
|
29
|
+
visited.add(key)
|
|
30
|
+
if a.__class__ is not b.__class__ or a.attrs != b.attrs:
|
|
31
|
+
return False
|
|
32
|
+
a_inputs, b_inputs = a.get_args(True, **a_args), b.get_args(True, **b_args)
|
|
33
|
+
if len(a_inputs) != len(b_inputs):
|
|
34
|
+
return False
|
|
35
|
+
stack += [(c, c_args, d, d_args) for (c, c_args), (d, d_args) in zip(a_inputs, b_inputs)]
|
|
36
|
+
return True
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _equal(self, other) -> bool:
|
|
40
|
+
if self.parent != other.parent or self.op.__class__ != other.op.__class__ or self.op.attrs != other.op.attrs:
|
|
41
|
+
return False
|
|
42
|
+
return self.op.inputs == other.op.inputs or _same(self.op, other.op)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def patch() -> None:
|
|
46
|
+
"""Make KunQuant's expression folding compare operators as graphs, unless it already does; calling it again does nothing."""
|
|
47
|
+
if not hasattr(ExprFold, "_is_same"):
|
|
48
|
+
ExprFold._OpProxy.__eq__ = _equal
|