Initial public release

This commit is contained in:
kwyvern-gitea
2026-08-12 16:40:47 -07:00
commit e7877e6be2
34 changed files with 7906 additions and 0 deletions
+19
View File
@@ -0,0 +1,19 @@
*.key
.env
.venv/
venv/
__pycache__/
*.pyc
.pytest_cache/
.ruff_cache/
.agents/
.codex/
.claude/
build/
dist/
data/raw/
data/interim/
data/processed/
data/signal/
*.parquet
*.feather
+674
View File
@@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
+35
View File
@@ -0,0 +1,35 @@
package: global-live
files:
.gitignore sha256=0f1ec258a4670a5bda58f8d3fc13bf9451b98ec9139945ca949205854d0c955a
LICENSE sha256=3972dc9744f6499f0f9b2dbf76696f2ae7ad8af9b23dde66d6af86c9dfb36986
README.md sha256=9ba05c6cb4c0735e6e6ecf477120961eeafa1a40b8f50ffaf48f026e8c0c833f
config/blackrock_etfs.yaml sha256=7ba6ec3197979e5a161ea4175bf6a6e0eb7dbe0bfc1ff73a9414904a1bf16055
data/universe/manual_overrides.yaml sha256=29185b7882adc462f8c3a6b4fd850c529c3c590d482f10ec287db89c11153e90
requirements.txt sha256=81733191ad982cde34cb14c821f00343530d3d465683b0c18d592a5620a65064
scripts/data/__init__.py sha256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
scripts/data/build_global_daily_returns.py sha256=4d933a41b9849ad600643eedf203be7562dcee235ff0d97667c68beb377164f8
scripts/data/build_global_exclusion_table.py sha256=cd0889714a855bb4a5772cf90a8b9c975cd07acbfdc01e60c50aee4e59b52d43
scripts/data/build_regional_benchmarks.py sha256=56663bcebaf04dc69b946bf1cce28572bfb29270d1db7f0e7d37cd5fff142962
scripts/data/fetch_live_qmj_fundamentals.py sha256=5d755024a5291678749dc2547b6b724268bdd36c9527c6980bd368dec82024da
scripts/data/refresh_symbol_cache.py sha256=10dbd11d7ccfa3e70b391525207b64abb5d92822a5004f6ac4e3366a5d056dcd
scripts/live/build_global_universe.py sha256=ee8b7909a332f562a17608ebee28667d77b1b05a18621824f5e8b891b541feeb
scripts/live/warm_ohlcv_cache.py sha256=3191bede104d56b2f6eef15af8f438bb463154bb24244ce3aa91b2916258821e
scripts/public/run_global_live_signal.py sha256=7906134d10f4499809f0706e22acf1b85697d830530864eccd9bb21eb841fc98
src/__init__.py sha256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
src/data/__init__.py sha256=168fcdd85e05577ceacbec89a180ac9b2681326e31ab535a8cdc4fe8097c769e
src/data/benchmarks.py sha256=275a731b85bbc6aecdc2ffdf5f2754afe9e5113cb323618e329908772402079b
src/data/blackrock_holdings_fetcher.py sha256=04e905ce468232a075024ecce3d7bdf971389a1309b10fcc2f32be0c5dc2be0f
src/data/data_hygiene.py sha256=ea106be4493d80e5d7d54af7fc394c597ee83756a7c78c47bd21fe0604e9a571 documentation_redactions=project_owner:2
src/data/eodhd_client.py sha256=5285535c1394f2832f373c7b7562de90d33942d93a4df31248739a93b44cb1be
src/data/fundamentals.py sha256=0ca9912fee373743824d4e064b92f2c36a14782cf5cd837e3a815899835303fc
src/data/global_universe.py sha256=33710b71dc060f004622a0d46c5494824f3d7e7107eaec76cf1219c88ad09819
src/data/hard_excluded_tickers.py sha256=cddb38d19fa04f763c6c345f52ac522e437dbba61efaf78950606d5484d30412 documentation_redactions=project_owner:17
src/data/qmj.py sha256=695f0fa198c1aff0211ea1d77a97488e14789b84ff12eb1b526cbfe414bda0d4 documentation_redactions=project_owner:1
src/data/qmj_risk.py sha256=78d736b467076af1b4ff6f108dec6af8b07286182e2bc164c234b296c379c0c3 documentation_redactions=project_owner:1
src/data/ticker_resolver.py sha256=61ed41f5a3c630e4189515c35fbaa9a4903552b7f82d7a84cb657f3dc43f6178 documentation_redactions=project_owner:1
src/signals/__init__.py sha256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
src/signals/ex_ante_beta_fp.py sha256=d487d96bb0db7849f8ced1b73dbb2dc353451789873bb19ca056d27ae2e1e38f
src/signals/global_signal_panel.py sha256=fb8ee9240e6df41625555f67b08982bf8e7ca84f2fd620884317fec97d423b32
src/signals/multi_region_orchestrator.py sha256=8d087c6f28edacd04fdca89b70856451dfd45c654e13ee89a52a6878ffb3e211
src/signals/price_primitives.py sha256=55f467a34d057658454d0c51a1ff0c1f647e3564d4f5cbf5e7169e19da05bf58
src/signals/qmj_live.py sha256=575d1d03dea714653d3824ed0dbfe2d98cad52609a27beefa59260c7d9e085bb
+74
View File
@@ -0,0 +1,74 @@
# Global Live Signal
Use this package to create a global equity signal across all supported trading regions.
The scanner ranks developed-market equities globally. It produces traded US, EU, and JP rows plus informational Canadian rows.
## Performance summary
A source for survivorship-bias-free historical fundamental data was not found for multi-region backtesting. Therefore, no historical multi-region backtest is available.
The table reports the available US-only research and its SPY benchmark.
| Return stream | Window | CAGR | Sharpe | Sortino | Maximum drawdown | Hit rate |
|---|---|---:|---:|---:|---:|---:|
| US stock-selection research baseline | 2018-01 through 2026-04 | 22.47% | 0.997 | 1.137 | -35.35% | 61.62% |
| SPY buy-and-hold benchmark | 2018-01 through 2026-04 | 13.56% | 0.796 | 0.775 | -28.62% | 68.69% |
The simulation uses the US sleeve and rebalance schedule, and the same stock-selection method as this package.
Cross-regional studies, including Fama-French research, report fundamental-factor premiums across multiple regions. The implementation assumes that this evidence generalizes to its stock-selection signal. Therefore, the same signal is expected globally.
This expectation remains unverified because the implementation has no multi-region backtest.
The figures do not include fees, slippage, or market impact.
## Requirements
- Python 3.10 or later
- An EODHD API key for data refreshes
Create a virtual environment. Then install the package dependencies:
```powershell
python -m venv .venv
.venv\Scripts\python.exe -m pip install -r requirements.txt
```
Place the EODHD key in `eodhd_api.key` at the package root. Do not commit or share this file.
## Run the tool
Create the latest signal:
```powershell
.venv\Scripts\python.exe scripts\public\run_global_live_signal.py
```
Use existing local data when the current package already contains the required caches:
```powershell
.venv\Scripts\python.exe scripts\public\run_global_live_signal.py --use-cached
```
Pin a decision date when you need a reproducible rerun:
```powershell
.venv\Scripts\python.exe scripts\public\run_global_live_signal.py --date 2026-05-21 --use-cached
```
The command writes a CSV under `data/signal/`. Each traded row contains its normalized share of the regional equity sleeve as `target_weight`.
The target weights sum to `1.0` within each traded region.
## Method
The strategy applies the following selection steps:
- Local-currency trend-slope and maximum-drawdown ranking
- Trend Clarity top-quartile filtering
- Amihud illiquidity filtering
- The R&D-QMJ bottom-decile quality veto
- Per-region quotas and global prefix expansion
The runner evaluates every supported trading region during each selection run.
+29
View File
@@ -0,0 +1,29 @@
# Public universe source and priority.
universe_etfs: ["URTH"]
etfs:
URTH:
name: "iShares MSCI World ETF"
portfolio_id: 239696
listing: "NYSE Arca (US-listed)"
csv_url: "https://www.blackrock.com/varnish-api/blk-one01-product-data/product-data/api/v1/get-fund-document?appType=PRODUCT_PAGE&appSubType=ISHARES&targetSite=us-ishares&locale=en_US&portfolioId=239696&component=fundDownload&userType=individual"
expected_min_holdings: 1000
gated_regions:
US:
locations: ["United States"]
EU:
locations: ["United Kingdom", "Germany", "France", "Switzerland", "Netherlands",
"Sweden", "Denmark", "Norway", "Finland", "Spain", "Italy",
"Belgium", "Ireland", "Austria", "Portugal", "Luxembourg"]
JP:
locations: ["Japan"]
informational_regions:
CA:
locations: ["Canada"]
excluded_regions:
AU: ["Australia"]
CN_etc: ["China", "Hong Kong", "Korea", "Republic of Korea", "Taiwan",
"Israel", "Singapore", "New Zealand"]
+30
View File
@@ -0,0 +1,30 @@
# Public ticker mappings that the automatic resolver cannot infer reliably.
overrides:
- br_ticker: BRKB
br_exchange: NYSE
eodhd_ticker: BRK-B.US
- br_ticker: HEIA
br_exchange: NYSE
eodhd_ticker: HEI.US
- br_ticker: MOGA
br_exchange: NYSE
eodhd_ticker: MOG-A.US
- br_ticker: UHALB
br_exchange: NYSE
eodhd_ticker: UHAL-B.US
- br_ticker: BFB
br_exchange: NYSE
eodhd_ticker: BF-B.US
- br_ticker: BFA
br_exchange: NYSE
eodhd_ticker: BF-A.US
- br_ticker: ABXX
br_exchange: NLB
eodhd_ticker: ABXX.NEO
- br_ticker: BTQ
br_exchange: NLB
eodhd_ticker: BTQ.NEO
- br_ticker: HOMU
br_exchange: Toronto Stock Exchange
eodhd_ticker: HOM-U.TO
+6
View File
@@ -0,0 +1,6 @@
pandas>=2.1
numpy>=1.26
pyarrow>=14
requests>=2.31
lxml>=5.0
pyyaml>=6.0
View File
+178
View File
@@ -0,0 +1,178 @@
"""Build data/processed/global_daily_returns.parquet from the EODHD cache.
Reads the latest global universe parquet (from build_global_universe.py),
iterates each ticker's cached `data/raw/eodhd/eod/{ticker}.json`, concatenates
into a long-format daily-returns panel, and persists.
Schema (matches the US data/processed/daily_returns.parquet for compatibility
with existing hygiene detectors at src/data/data_hygiene.py):
date, ticker, open, high, low, close, adjusted_close, volume, ret_d
Reasonable to re-run any time the universe parquet is rebuilt or OHLCV cache
is refreshed via scripts/live/warm_ohlcv_cache.py.
Usage:
.venv/Scripts/python.exe scripts/data/build_global_daily_returns.py
.venv/Scripts/python.exe scripts/data/build_global_daily_returns.py --from 2020-01-01
"""
from __future__ import annotations
import argparse
import json
import logging
import sys
import time
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
import pandas as pd
from src.data.hard_excluded_tickers import apply_hard_exclusion_mask
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
logger = logging.getLogger("build_global_daily_returns")
_UNIVERSE_DIR = Path("data/universe")
_CACHE_DIR = Path("data/raw/eodhd/eod")
_OUT_PATH = Path("data/processed/global_daily_returns.parquet")
def _latest_universe_parquet() -> Path:
files = sorted(_UNIVERSE_DIR.glob("global_msci_world_imi_*.parquet"))
if not files:
raise FileNotFoundError(
f"No universe parquet in {_UNIVERSE_DIR} — run build_global_universe.py first"
)
return files[-1]
def _load_one_ticker(ticker: str) -> pd.DataFrame | None:
cache_path = _CACHE_DIR / f"{ticker}.json"
if not cache_path.is_file():
return None
try:
raw = json.loads(cache_path.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as exc:
logger.warning("Bad cache for %s: %s", ticker, exc)
return None
if not raw:
return None
df = pd.DataFrame(raw)
if df.empty or "date" not in df.columns:
return None
rename = {"adjustedClose": "adjusted_close"}
df = df.rename(columns=rename)
required = {"date", "close", "adjusted_close", "volume"}
missing = required - set(df.columns)
if missing:
logger.warning("%s missing required columns %s — skipping", ticker, missing)
return None
df["date"] = pd.to_datetime(df["date"])
df = df.sort_values("date").reset_index(drop=True)
df["ticker"] = ticker
# Remove manually verified bad-data `(ticker, date)` rows before the code
# calculates `ret_d`.
# This order prevents false returns across two ticker eras for a reused symbol.
# The first retained row from the second era therefore has a NaN `pct_change`.
# For example, see the first GMIN.TO era through 2024-04-04 in
# `src/data/hard_excluded_tickers.py`.
#
# With `bounded_ranges_only=True`, the live path applies only finite
# historical ranges.
# The live path skips permanent, date-bounded, and open-ended exclusions.
# Those exclusions block a current index member when that member reuses an old symbol.
# A finite manual range removes rows only within its start and end dates.
# The backtest path in `src/universe.py` applies the full registry.
excl = apply_hard_exclusion_mask(df, bounded_ranges_only=True)
if excl.any():
df = df[~excl].reset_index(drop=True)
if df.empty:
return None
df["ret_d"] = df["adjusted_close"].pct_change()
# The output uses the standard column order and includes `open`, `high`, and
# `low` when those columns exist in the input.
cols = ["date", "ticker", "open", "high", "low", "close", "adjusted_close", "volume", "ret_d"]
out = df[[c for c in cols if c in df.columns]]
return out
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--from-date", dest="from_date", default=None,
help="Filter rows to date >= from_date (YYYY-MM-DD)")
parser.add_argument("--to-date", dest="to_date", default=None,
help="Filter rows to date <= to_date (YYYY-MM-DD)")
parser.add_argument("--out", default=str(_OUT_PATH),
help=f"Output parquet path (default: {_OUT_PATH})")
args = parser.parse_args()
universe_path = _latest_universe_parquet()
universe = pd.read_parquet(universe_path)
tickers = sorted(universe["eodhd_ticker"].dropna().unique().tolist())
logger.info("Universe %s: %d tickers", universe_path.name, len(tickers))
frames: list[pd.DataFrame] = []
n_loaded = 0
n_missing = 0
start = time.monotonic()
for i, ticker in enumerate(tickers, 1):
df = _load_one_ticker(ticker)
if df is None:
n_missing += 1
continue
frames.append(df)
n_loaded += 1
if i % 500 == 0:
elapsed = time.monotonic() - start
logger.info("[%d/%d] loaded=%d missing=%d (%.1f s)",
i, len(tickers), n_loaded, n_missing, elapsed)
if not frames:
logger.error("No frames loaded — refusing to write empty panel")
sys.exit(1)
logger.info("Concatenating %d frames ...", len(frames))
panel = pd.concat(frames, ignore_index=True)
if args.from_date:
panel = panel[panel["date"] >= args.from_date]
if args.to_date:
panel = panel[panel["date"] <= args.to_date]
out_path = Path(args.out)
out_path.parent.mkdir(parents=True, exist_ok=True)
tmp = out_path.with_suffix(".tmp")
panel.to_parquet(tmp, index=False)
tmp.replace(out_path)
elapsed = time.monotonic() - start
logger.info("=" * 72)
logger.info("Saved %d rows × %d tickers to %s in %.1f s",
len(panel), panel["ticker"].nunique(), out_path, elapsed)
logger.info(
"Date range: %s -> %s | first ret_d: %s | tickers missing from cache: %d",
panel["date"].min().date(), panel["date"].max().date(),
panel["ret_d"].first_valid_index() is not None, n_missing,
)
by_region_top = (
universe.merge(
pd.DataFrame({"eodhd_ticker": panel["ticker"].unique()}),
on="eodhd_ticker",
)
.groupby("region_bucket")
.size()
.sort_index()
)
logger.info("Panel tickers per region: %s", by_region_top.to_dict())
if __name__ == "__main__":
main()
@@ -0,0 +1,110 @@
"""Generate data/processed/global_excluded_ticker_dates.parquet.
Runs the same three data-hygiene detectors as scripts/data/build_exclusion_table.py
(US) but against the global daily-returns panel built by
scripts/data/build_global_daily_returns.py.
Detectors (parameters mirror US build for consistency; threshold sensitivity
for non-US regimes — particularly Japan low-vol — may warrant review later):
- detect_frozen_runs (min_length=5)
- detect_combined_evidence_corruption (Tier 1)
- detect_round_trip_spikes (Tier 2; up_threshold=5.0, down_threshold=-0.90,
recovery_calendar_days=10)
Output:
data/processed/global_excluded_ticker_dates.parquet
"""
from __future__ import annotations
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # noqa: E402
import pandas as pd
from src.data.data_hygiene import ( # noqa: E402
detect_combined_evidence_corruption,
detect_frozen_runs,
detect_round_trip_spikes,
save_exclusion_ranges,
)
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
logger = logging.getLogger("build_global_exclusion_table")
_DAILY_PATH = Path("data/processed/global_daily_returns.parquet")
_OUT_PATH = Path("data/processed/global_excluded_ticker_dates.parquet")
# The detector window covers backtest and live dates from 2000 onward.
# Momentum signals use pre-2000 data only for the warmup period.
_FROM_DATE = "2000-01-01"
_TO_DATE = pd.Timestamp.today().strftime("%Y-%m-%d")
def main() -> None:
logger.info("Loading %s ...", _DAILY_PATH)
daily = pd.read_parquet(
_DAILY_PATH,
columns=["date", "ticker", "close", "adjusted_close", "volume", "ret_d"],
)
daily["date"] = pd.to_datetime(daily["date"])
pre_window = len(daily)
daily = daily[(daily["date"] >= _FROM_DATE) & (daily["date"] <= _TO_DATE)]
logger.info(
"Window %s..%s: %d rows (%d filtered out), %d tickers",
_FROM_DATE, _TO_DATE, len(daily), pre_window - len(daily), daily["ticker"].nunique(),
)
all_ranges: list[pd.DataFrame] = []
logger.info("Running detect_frozen_runs (min_length=5) ...")
frozen = detect_frozen_runs(daily, min_length=5)
all_ranges.append(frozen)
logger.info(" -> %d frozen-run ranges", len(frozen))
logger.info("Running detect_combined_evidence_corruption (Tier 1) ...")
combined = detect_combined_evidence_corruption(daily, frozen_runs=frozen)
all_ranges.append(combined[["ticker", "start_date", "end_date", "reason"]])
logger.info(" -> %d combined-evidence ranges", len(combined))
logger.info("Running detect_round_trip_spikes (Tier 2) ...")
round_trips = detect_round_trip_spikes(
daily, up_threshold=5.0, down_threshold=-0.90, recovery_calendar_days=10,
)
all_ranges.append(round_trips)
logger.info(" -> %d round-trip-spike ranges", len(round_trips))
out = pd.concat(all_ranges, ignore_index=True)
out["start_date"] = pd.to_datetime(out["start_date"])
out["end_date"] = pd.to_datetime(out["end_date"])
out = out.sort_values(["ticker", "start_date"]).reset_index(drop=True)
logger.info("=" * 72)
logger.info("Combined exclusion table: %d ranges across %d unique tickers",
len(out), out["ticker"].nunique())
logger.info("By reason: %s", out["reason"].value_counts().to_dict())
# Join the latest universe table to summarize exclusion ranges by region.
universe_files = sorted(Path("data/universe").glob("global_msci_world_imi_*.parquet"))
if universe_files:
universe = pd.read_parquet(universe_files[-1], columns=["eodhd_ticker", "region_bucket"])
out_with_region = out.merge(
universe, left_on="ticker", right_on="eodhd_ticker", how="left",
)
by_region = (
out_with_region.groupby("region_bucket").size().sort_index().to_dict()
)
logger.info("Exclusion ranges by region: %s", by_region)
save_exclusion_ranges(out, _OUT_PATH)
logger.info("Saved global exclusion table -> %s", _OUT_PATH)
if __name__ == "__main__":
main()
+76
View File
@@ -0,0 +1,76 @@
"""Build data/processed/regional_benchmarks_daily.parquet.
For each gated region, loads the benchmark price series from the EODHD cache
and computes daily returns. The benchmark per region is used downstream as:
- input to Goulding turning-point weight (monthly resampled benchmark returns)
- market series for BAB beta regression (daily benchmark returns)
- market series for CMR residual-momentum (daily benchmark returns)
Output schema (long format):
[date, region, benchmark_symbol, close, ret_d]
Regions and benchmarks (per cross-geography live push plan):
US -> GSPC.INDX (S&P 500)
EU -> SXXP.INDX (STOXX Europe 600)
JP -> N225.INDX (Nikkei 225)
CA -> GSPTSE.INDX (S&P/TSX Composite) -- informational only, not gated
"""
from __future__ import annotations
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent))
import pandas as pd
from src.data.eodhd_client import EODHDClient
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
logger = logging.getLogger("build_regional_benchmarks")
_REGION_BENCHMARKS = {
"US": "GSPC.INDX",
"EU": "SXXP.INDX",
"JP": "N225.INDX",
"CA": "GSPTSE.INDX",
}
_OUT_PATH = Path("data/processed/regional_benchmarks_daily.parquet")
def main() -> None:
client = EODHDClient()
frames: list[pd.DataFrame] = []
for region, symbol in _REGION_BENCHMARKS.items():
df = client.get_eod_prices(symbol)
if df.empty:
logger.error("No EOD data for %s — aborting", symbol)
sys.exit(1)
df = df.sort_values("date").reset_index(drop=True)
df["region"] = region
df["benchmark_symbol"] = symbol
df["ret_d"] = df["adjusted_close"].pct_change()
out = df[["date", "region", "benchmark_symbol", "adjusted_close", "ret_d"]].rename(
columns={"adjusted_close": "close"}
)
frames.append(out)
logger.info(
"%s (%s): %d rows, %s -> %s",
region, symbol, len(out), out["date"].min().date(), out["date"].max().date(),
)
panel = pd.concat(frames, ignore_index=True)
_OUT_PATH.parent.mkdir(parents=True, exist_ok=True)
tmp = _OUT_PATH.with_suffix(".tmp")
panel.to_parquet(tmp, index=False)
tmp.replace(_OUT_PATH)
logger.info("Saved %d rows -> %s", len(panel), _OUT_PATH)
if __name__ == "__main__":
main()
@@ -0,0 +1,89 @@
"""Live QMJ fundamentals fetch — rebuild-pipeline step (resumable, incremental).
Fetches EODHD fundamentals JSON for every ticker in the live global universe
(the scored cross-section in data/processed/global_daily_returns.parquet) that
is NOT already cached. Becomes step ~3.5 of the signal_long_global rebuild so
each monthly cycle only pays for newly-added names.
Behaviour:
- cache-skip: a name with an existing data/raw/eodhd/fundamentals/{t}.json is skipped.
- 4xx / not-found: an empty-dict sentinel is written so the call is never re-paid.
- transient (429/5xx): left uncached so the next run retries it.
Run: python scripts/data/fetch_live_qmj_fundamentals.py
"""
from __future__ import annotations
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # Add the repository root so Python imports `src`.
import pandas as pd # noqa: E402
from src.data.eodhd_client import EODHDClient, EODHDError # noqa: E402
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(message)s",
stream=sys.stderr,
)
logger = logging.getLogger("fetch_live_qmj_fundamentals")
_UNIVERSE_PATH = Path("data/processed/global_daily_returns.parquet")
_CACHE_DIR = Path("data/raw/eodhd/fundamentals")
def _live_universe() -> list[str]:
if not _UNIVERSE_PATH.is_file():
logger.error("Missing %s — run the global rebuild pipeline first.", _UNIVERSE_PATH)
sys.exit(2)
tickers = pd.read_parquet(_UNIVERSE_PATH, columns=["ticker"])["ticker"].astype(str)
return sorted(tickers.unique())
def main() -> None:
universe = _live_universe()
_CACHE_DIR.mkdir(parents=True, exist_ok=True)
to_fetch = [t for t in universe if not (_CACHE_DIR / f"{t}.json").is_file()]
n = len(to_fetch)
logger.info(
"Live QMJ fundamentals: %d universe tickers, %d already cached, %d to fetch (~%d credits)",
len(universe), len(universe) - n, n, n * 10,
)
if n == 0:
logger.info("Nothing to fetch — fundamentals cache is current.")
return
client = EODHDClient()
fetched = empty = errors = 0
for i, ticker in enumerate(to_fetch, 1):
cache_file = _CACHE_DIR / f"{ticker}.json"
try:
data = client.get_fundamentals(ticker, use_cache=True)
if data:
fetched += 1
else:
empty += 1
except EODHDError as exc:
if exc.status_code is not None and 400 <= exc.status_code < 500:
cache_file.write_text("{}", encoding="utf-8") # Store an empty-response sentinel for an HTTP 4xx error.
empty += 1
else:
errors += 1
logger.warning("Transient error for %s: %s (will retry next run)", ticker, exc)
if i % 100 == 0:
logger.info("progress %d/%d fetched=%d empty=%d err=%d", i, n, fetched, empty, errors)
logger.info(
"DONE %d tickers: fetched=%d empty/sentinel=%d errors=%d",
n, fetched, empty, errors,
)
if __name__ == "__main__":
main()
+55
View File
@@ -0,0 +1,55 @@
"""Force-refresh per-exchange EODHD symbol-list cache.
The TickerResolver and USD-returns builder both read from
``data/raw/eodhd/symbols/{EX}_active.json`` to map (a) BR tickers -> EODHD
codes and (b) tickers -> trading currency. ``EODHDClient.get_exchange_symbols``
uses ``use_cache=True`` in every production call site, which means once those
JSONs are on disk they are NEVER refetched — a new index constituent (IPO,
listing change) that postdates the cache silently drops out of the universe
and/or the USD panel.
This script bypasses the cache and refetches every gated exchange. Cheap:
19 exchanges × 1 API call each, ~10 s wall-clock and a trivial quota hit.
Invoked as step 1/9 of the monthly orchestrator so the cache is always
current at signal time.
Output: ``data/raw/eodhd/symbols/{EX}_active.json`` (overwritten in place).
"""
from __future__ import annotations
import logging
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent)) # noqa: E402
from src.data import GATED_EXCHANGES
from src.data.eodhd_client import EODHDClient, EODHDError
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s %(levelname)s %(name)s — %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
logger = logging.getLogger("refresh_symbol_cache")
def main() -> None:
client = EODHDClient()
total = 0
for ex in GATED_EXCHANGES:
try:
df = client.get_exchange_symbols(ex, delisted=False, use_cache=False)
except EODHDError as exc:
logger.error("Refresh failed for %s: %s", ex, exc)
sys.exit(1)
n = len(df)
total += n
logger.info("Refreshed %s: %d symbols", ex, n)
logger.info(
"Refreshed %d exchanges, %d total symbol rows", len(GATED_EXCHANGES), total
)
if __name__ == "__main__":
main()
+32
View File
@@ -0,0 +1,32 @@
#!/usr/bin/env python
"""Build the configured global-equity universe from BlackRock holdings.
Usage:
python scripts/live/build_global_universe.py
python scripts/live/build_global_universe.py --use-cached # skip live BlackRock fetch
"""
import argparse
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2])) # noqa: E402
from src.data.global_universe import build_global_universe
def main() -> None:
parser = argparse.ArgumentParser(
description="Build the configured global-equity universe from BlackRock holdings."
)
parser.add_argument(
"--use-cached",
action="store_true",
help="Use cached BlackRock fixtures instead of live fetch",
)
args = parser.parse_args()
build_global_universe(use_cached_fixtures=args.use_cached)
if __name__ == "__main__":
main()
+153
View File
@@ -0,0 +1,153 @@
"""Pre-warm EODHD OHLCV cache for every ticker in the latest global universe.
Run once per monthly cycle (or whenever the universe parquet is rebuilt) to
ensure the signal-generation pipeline reads from cache exclusively (no live
fetches during scoring). Tickers already cached are skipped.
Usage:
python scripts/live/warm_ohlcv_cache.py # actually fetch
python scripts/live/warm_ohlcv_cache.py --dry-run # show scope, don't fetch
python scripts/live/warm_ohlcv_cache.py --extend-to-today
"""
from __future__ import annotations
import argparse
import logging
import sys
import time
from datetime import date
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[2]))
import pandas as pd
from src.data.eodhd_client import EODHDClient, EODHDError
logger = logging.getLogger(__name__)
def _latest_universe_parquet(universe_dir: Path) -> Path:
files = sorted(universe_dir.glob("global_msci_world_imi_*.parquet"))
if not files:
raise FileNotFoundError(
f"No universe parquet in {universe_dir} — run build_global_universe.py first"
)
return files[-1]
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--dry-run", action="store_true",
help="Report what would be fetched without making any API calls",
)
parser.add_argument(
"--extend-to-today", action="store_true",
help="Force re-fetch for cached tickers whose cache max-date is before today",
)
parser.add_argument(
"--max-tickers", type=int, default=None,
help="Stop after N tickers (testing/throttling)",
)
parser.add_argument(
"--universe-dir", default="data/universe",
help="Directory containing global_msci_world_imi_*.parquet (default: data/universe)",
)
args = parser.parse_args()
logging.basicConfig(level=logging.WARNING, format="%(asctime)s %(levelname)s %(message)s")
universe_path = _latest_universe_parquet(Path(args.universe_dir))
universe = pd.read_parquet(universe_path)
tickers = sorted(universe["eodhd_ticker"].dropna().unique().tolist())
cache_dir = Path("data/raw/eodhd/eod")
cached = {p.stem for p in cache_dir.glob("*.json")} if cache_dir.is_dir() else set()
to_fetch = [t for t in tickers if t not in cached]
today_iso = date.today().isoformat()
print("=" * 80)
print(f"OHLCV cache warmer — {today_iso}")
print("=" * 80)
print(f"Universe parquet: {universe_path.name}")
print(f"Universe size: {len(tickers):,}")
print(f"Already cached: {len(cached & set(tickers)):,}")
print(f"To fetch: {len(to_fetch):,}")
if args.extend_to_today:
print(f"Extend-to-today: enabled (cached tickers will refresh to {today_iso})")
if args.max_tickers is not None:
print(f"Max tickers cap: {args.max_tickers:,}")
to_fetch = to_fetch[: args.max_tickers]
estimated_minutes = len(to_fetch) / 15 / 60
print(f"Estimated runtime (at ~15/sec rate limit): {estimated_minutes:.1f} min")
print(f"API quota cost: ~{len(to_fetch):,} calls "
f"({len(to_fetch) / 1000:.1f}% of 100k monthly quota)")
if args.dry_run:
print("\n[DRY RUN] — exiting without fetching")
return
if not to_fetch and not args.extend_to_today:
print("\nNothing to do — cache is up to date.")
return
client = EODHDClient()
n_ok = 0
n_fail = 0
failed: list[tuple[str, str]] = []
start = time.monotonic()
# This loop fetches data for new tickers.
for i, ticker in enumerate(to_fetch, 1):
try:
df = client.get_eod_prices(ticker)
if len(df) == 0:
logger.warning("Empty EOD for %s — kept cache slot but no data", ticker)
n_ok += 1
except EODHDError as exc:
n_fail += 1
failed.append((ticker, f"{exc.status_code} {exc.reason[:60]}"))
logger.warning("Failed %s: %s", ticker, exc)
if i % 100 == 0:
elapsed = time.monotonic() - start
rate = i / elapsed
eta = (len(to_fetch) - i) / rate / 60
print(f" [{i:>5}/{len(to_fetch):>5}] {rate:.1f}/sec ETA {eta:.1f} min")
# This loop refreshes cached tickers through today's date.
n_extended = 0
if args.extend_to_today:
already = sorted(cached & set(tickers))
if args.max_tickers is not None:
already = already[: args.max_tickers]
print(f"\nExtending {len(already):,} cached tickers to {today_iso} ...")
for i, ticker in enumerate(already, 1):
try:
client.get_eod_prices(ticker, extend_cache_to=today_iso)
n_extended += 1
except EODHDError as exc:
n_fail += 1
failed.append((ticker, f"extend: {exc.status_code} {exc.reason[:60]}"))
if i % 200 == 0:
print(f" [{i:>5}/{len(already):>5}] extended")
total_elapsed = time.monotonic() - start
print()
print(f"Done in {total_elapsed/60:.1f} min")
print(f" Newly fetched: {n_ok:,}")
print(f" Extended: {n_extended:,}")
print(f" Failed: {n_fail:,}")
if failed:
print("\nFirst 20 failures:")
for t, reason in failed[:20]:
print(f" {t:<15} {reason}")
# Save the complete failure list for review.
fail_path = Path("data/universe") / f"ohlcv_fetch_failures_{date.today().strftime('%Y%m%d')}.csv"
pd.DataFrame(failed, columns=["eodhd_ticker", "failure_reason"]).to_csv(fail_path, index=False)
print(f"Full failure list: {fail_path}")
if __name__ == "__main__":
main()
+132
View File
@@ -0,0 +1,132 @@
"""Create the global live stock-selection signal."""
from __future__ import annotations
import argparse
import subprocess
import sys
import time
from pathlib import Path
_PROJECT_ROOT = Path(__file__).resolve().parents[2]
if str(_PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(_PROJECT_ROOT))
import pandas as pd # noqa: E402
from src.signals.multi_region_orchestrator import run_multi_region_signal # noqa: E402
_OUTPUT_DIR = _PROJECT_ROOT / "data" / "signal"
_REBUILD_PIPELINE: tuple[tuple[str, tuple[str, ...]], ...] = (
("1/7 Refresh EODHD symbol lists", ("scripts/data/refresh_symbol_cache.py",)),
("2/7 Rebuild the configured equity universe", ("scripts/live/build_global_universe.py",)),
(
"3/7 Warm the OHLCV cache",
("scripts/live/warm_ohlcv_cache.py", "--extend-to-today"),
),
("4/7 Build local-currency returns", ("scripts/data/build_global_daily_returns.py",)),
(
"5/7 Fetch QMJ fundamentals",
("scripts/data/fetch_live_qmj_fundamentals.py",),
),
("6/7 Build regional benchmarks", ("scripts/data/build_regional_benchmarks.py",)),
(
"7/7 Build the data-hygiene table",
("scripts/data/build_global_exclusion_table.py",),
),
)
def _last_weekday() -> pd.Timestamp:
decision_date = pd.Timestamp.today().normalize()
while decision_date.weekday() >= 5:
decision_date -= pd.Timedelta(days=1)
return decision_date
def _parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--date", metavar="YYYY-MM-DD", help="Decision date")
parser.add_argument("--quota", type=int, default=25, metavar="N")
parser.add_argument("--workers", type=int, default=8, metavar="N")
parser.add_argument(
"--use-cached",
action="store_true",
help="Reuse existing panels instead of rebuilding data",
)
parser.add_argument(
"--veto",
choices=("bab", "qmj"),
default="qmj",
help="Select the QMJ live veto or BAB diagnostic veto",
)
return parser.parse_args()
def _run_rebuild_pipeline() -> None:
pipeline_started = time.monotonic()
for label, script_arguments in _REBUILD_PIPELINE:
step_started = time.monotonic()
print(label)
command = [sys.executable, *script_arguments]
try:
subprocess.run(command, cwd=_PROJECT_ROOT, check=True)
except subprocess.CalledProcessError as exc:
raise SystemExit(
f"The rebuild stopped at {label!r} with exit code {exc.returncode}."
) from exc
print(f"Completed in {time.monotonic() - step_started:.1f} seconds")
print(f"Rebuild completed in {(time.monotonic() - pipeline_started) / 60.0:.1f} minutes")
def _add_target_weights(csv_path: Path, picks: pd.DataFrame) -> None:
"""Add the public target-weight contract to the generated signal CSV."""
required_columns = {"position_pct_tc", "region", "traded_flag"}
missing_columns = required_columns - set(picks.columns)
if missing_columns:
raise ValueError(f"Signal output is missing required columns: {sorted(missing_columns)}")
public_signal = pd.read_csv(csv_path)
if len(public_signal) != len(picks):
raise ValueError("Signal CSV and target-weight rows have different lengths")
traded = picks["traded_flag"].astype(bool)
regional_weights = picks.loc[traded, "position_pct_tc"].astype(float)
regional_totals = regional_weights.groupby(picks.loc[traded, "region"]).transform("sum")
if regional_totals.isna().any() or (regional_totals <= 0.0).any():
raise ValueError("Each traded region must have a positive target-weight total")
target_weights = pd.Series(0.0, index=picks.index)
target_weights.loc[traded] = regional_weights / regional_totals
public_signal["target_weight"] = target_weights.to_numpy(dtype=float)
public_signal.to_csv(csv_path, index=False)
def main() -> None:
"""Build data when required, then create the global signal."""
args = _parse_args()
if not args.use_cached:
_run_rebuild_pipeline()
decision_date = pd.Timestamp(args.date) if args.date else _last_weekday()
picks = run_multi_region_signal(
decision_date=decision_date,
per_region_quota=args.quota,
output_dir=_OUTPUT_DIR,
n_workers=args.workers,
veto=args.veto,
apply_gate=False,
)
csv_path = _OUTPUT_DIR / f"signal_long_global_{decision_date:%Y%m%d}.csv"
_add_target_weights(csv_path, picks)
counts = picks["region"].value_counts().to_dict()
print(f"Saved {len(picks)} picks to {csv_path}")
print(
f"US: {counts.get('US', 0)} EU: {counts.get('EU', 0)} "
f"JP: {counts.get('JP', 0)} CA: {counts.get('CA', 0)}"
)
if __name__ == "__main__":
main()
View File
+13
View File
@@ -0,0 +1,13 @@
# Shared constants for the data layer.
#
# GATED_EXCHANGES — every EODHD exchange suffix the live pipeline expects to
# see in the resolved global universe (i.e. exchanges whose constituents
# survive the region filter). Used by:
# - scripts/data/refresh_symbol_cache.py (force-refreshes these exchanges)
# - src/signals/global_signal_panel._build_trading_ccy_lookup (per-ticker currency)
# Order is fixed for deterministic logs.
GATED_EXCHANGES: list[str] = [
"US", "TSE", "TO", "NEO", "LSE", "XETRA", "PA", "SW", "MI",
"OL", "MC", "AS", "CO", "BR", "HE", "VI", "LS", "IR", "ST",
]
+278
View File
@@ -0,0 +1,278 @@
"""Benchmark data loaders — SPY monthly returns and T-bill monthly returns.
Shared by run_phase4.py and live/signal_long.py; extracted here to avoid duplication.
SPY monthly returns: adjusted close, month-end resampled.
T-bill monthly returns: annualised yield (%) from US3M.GBOND → yield/100/12.
ETF daily closes (HYG, LQD, etc.): adjusted close, daily, cached as parquet.
"""
import logging
from pathlib import Path
import pandas as pd
from src.data.eodhd_client import EODHDClient, EODHDError
logger = logging.getLogger(__name__)
_SPY_TICKER = "SPY.US"
_TBILL_TICKER = "US3M.GBOND"
_SPY_CACHE = Path("data/processed/spy_monthly.parquet")
_SPY_CLOSE_CACHE = Path("data/processed/spy_monthly_close.parquet")
_SPY_DAILY_CLOSE_CACHE = Path("data/processed/spy_daily_close.parquet")
_HYG_DAILY_CLOSE_CACHE = Path("data/processed/hyg_daily_close.parquet")
_LQD_DAILY_CLOSE_CACHE = Path("data/processed/lqd_daily_close.parquet")
def _fetch_spy_monthly_prices(client: EODHDClient) -> pd.Series:
"""Fetch SPY daily prices from EODHD and resample to month-end adjusted closes.
Returns a pd.Series of month-end adjusted closes indexed by Timestamps,
name='adjusted_close'. Raises EODHDError on fetch failure or empty response.
"""
logger.info("Fetching %s daily prices from EODHD", _SPY_TICKER)
try:
daily = client.get_eod_prices(_SPY_TICKER, use_cache=True)
except EODHDError as exc:
logger.error("EODHD fetch failed for SPY: %s", exc)
raise
if daily.empty:
raise EODHDError(
endpoint=f"eod/{_SPY_TICKER}",
status_code=None,
reason="Empty response for SPY.US",
)
daily = daily.set_index("date").sort_index()
monthly_price = daily["adjusted_close"].resample("ME").last().dropna()
monthly_price.name = "adjusted_close"
return monthly_price
def load_spy_monthly_returns(
client: EODHDClient,
start: pd.Timestamp,
end: pd.Timestamp,
cache_path: Path = _SPY_CACHE,
) -> pd.Series:
"""Fetch or load cached SPY monthly returns (adjusted close, month-end resampled).
Returns a pd.Series indexed by month-end Timestamps, named 'ret_1m'.
Raises EODHDError on fetch failure or empty response.
"""
if cache_path.is_file():
logger.info("Loading cached SPY monthly returns from %s", cache_path)
df = pd.read_parquet(cache_path)
spy_ret = pd.Series(df["ret_1m"].values, index=pd.to_datetime(df["date"]))
spy_ret = spy_ret.sort_index()
if spy_ret.index.min() <= start and spy_ret.index.max() >= end:
return spy_ret
logger.info("Cache doesn't cover requested window; re-fetching SPY.")
monthly_price = _fetch_spy_monthly_prices(client)
spy_ret = monthly_price.pct_change().dropna()
spy_ret.name = "ret_1m"
cache_path.parent.mkdir(parents=True, exist_ok=True)
out = pd.DataFrame({"date": spy_ret.index, "ret_1m": spy_ret.values})
out.to_parquet(cache_path, index=False)
logger.info("SPY monthly returns cached: %d rows → %s", len(out), cache_path)
return spy_ret
def load_spy_monthly_closes(
client: EODHDClient,
start: pd.Timestamp,
end: pd.Timestamp,
cache_path: Path = _SPY_CLOSE_CACHE,
) -> pd.Series:
"""Fetch or load cached SPY month-end adjusted closes.
Returns a pd.Series indexed by month-end Timestamps, named 'adjusted_close'.
Needed by compute_csst_gate which operates on price levels, not returns.
Raises EODHDError on fetch failure or empty response.
"""
if cache_path.is_file():
logger.info("Loading cached SPY monthly closes from %s", cache_path)
df = pd.read_parquet(cache_path)
closes = pd.Series(df["adjusted_close"].values, index=pd.to_datetime(df["date"]))
closes = closes.sort_index()
closes.name = "adjusted_close"
if closes.index.min() <= start and closes.index.max() >= end:
return closes
logger.info("Cache doesn't cover requested window; re-fetching SPY closes.")
monthly_price = _fetch_spy_monthly_prices(client)
cache_path.parent.mkdir(parents=True, exist_ok=True)
out = pd.DataFrame({"date": monthly_price.index, "adjusted_close": monthly_price.values})
out.to_parquet(cache_path, index=False)
logger.info("SPY monthly closes cached: %d rows → %s", len(out), cache_path)
return monthly_price
def _fetch_spy_daily_prices(client: EODHDClient) -> pd.Series:
"""Fetch SPY daily prices from EODHD and return the full daily adjusted-close series.
Returns a pd.Series of daily adjusted closes indexed by Timestamps,
name='adjusted_close'. Raises EODHDError on fetch failure or empty response.
"""
logger.info("Fetching %s daily prices from EODHD (daily, no resample)", _SPY_TICKER)
try:
daily = client.get_eod_prices(_SPY_TICKER, use_cache=True)
except EODHDError as exc:
logger.error("EODHD fetch failed for SPY (daily): %s", exc)
raise
if daily.empty:
raise EODHDError(
endpoint=f"eod/{_SPY_TICKER}",
status_code=None,
reason="Empty response for SPY.US",
)
series = daily.set_index("date").sort_index()["adjusted_close"]
series.name = "adjusted_close"
return series
def load_spy_daily_closes(
client: EODHDClient,
start: pd.Timestamp,
end: pd.Timestamp,
cache_path: Path = _SPY_DAILY_CLOSE_CACHE,
) -> pd.Series:
"""Fetch or load cached SPY daily adjusted closes (no month-end resampling).
Returns a pd.Series indexed by daily Timestamps, named 'adjusted_close'.
Needed by compute_safari_ens_gate which interprets horizons as trading days.
Raises EODHDError on fetch failure or empty response.
"""
if cache_path.is_file():
logger.info("Loading cached SPY daily closes from %s", cache_path)
df = pd.read_parquet(cache_path)
closes = pd.Series(df["adjusted_close"].values, index=pd.to_datetime(df["date"]))
closes = closes.sort_index()
closes.name = "adjusted_close"
if closes.index.min() <= start and closes.index.max() >= end:
return closes
logger.info("Cache doesn't cover requested window; re-fetching SPY daily closes.")
daily_price = _fetch_spy_daily_prices(client)
cache_path.parent.mkdir(parents=True, exist_ok=True)
out = pd.DataFrame({"date": daily_price.index, "adjusted_close": daily_price.values})
out.to_parquet(cache_path, index=False)
logger.info("SPY daily closes cached: %d rows → %s", len(out), cache_path)
return daily_price
def load_etf_daily_closes(
client: EODHDClient,
ticker: str,
start: pd.Timestamp,
end: pd.Timestamp,
cache_path: Path,
) -> pd.Series:
"""Fetch or load cached daily adjusted closes for any ETF ticker.
Returns a pd.Series indexed by daily Timestamps, named 'adjusted_close'.
Cache schema: ["date", "adjusted_close"].
Raises EODHDError on fetch failure or empty response.
"""
if cache_path.is_file():
logger.info("[%s] cache HIT: %s", ticker, cache_path)
df = pd.read_parquet(cache_path)
closes = pd.Series(df["adjusted_close"].values, index=pd.to_datetime(df["date"]))
closes = closes.sort_index()
closes.name = "adjusted_close"
if closes.index.min() <= start and closes.index.max() >= end:
return closes
logger.info("[%s] cache doesn't cover requested window; re-fetching.", ticker)
logger.info("[%s] cache MISS — fetching from EODHD", ticker)
try:
daily = client.get_eod_prices(ticker, use_cache=True)
except EODHDError as exc:
logger.error("EODHD fetch failed for %s: %s", ticker, exc)
raise
if daily.empty:
raise EODHDError(
endpoint=f"eod/{ticker}",
status_code=None,
reason=f"Empty response for {ticker}",
)
series = daily.set_index("date").sort_index()["adjusted_close"]
series.name = "adjusted_close"
cache_path.parent.mkdir(parents=True, exist_ok=True)
out = pd.DataFrame({"date": series.index, "adjusted_close": series.values})
out.to_parquet(cache_path, index=False)
logger.info("[%s] daily closes cached: %d rows → %s", ticker, len(out), cache_path)
return series
def load_hyg_daily_closes(
client: EODHDClient,
start: pd.Timestamp,
end: pd.Timestamp,
cache_path: Path = _HYG_DAILY_CLOSE_CACHE,
) -> pd.Series:
"""Fetch or load cached HYG daily adjusted closes.
HYG inception 2007-04-04. Use adjusted_close for return computation.
"""
return load_etf_daily_closes(client, "HYG.US", start, end, cache_path)
def load_lqd_daily_closes(
client: EODHDClient,
start: pd.Timestamp,
end: pd.Timestamp,
cache_path: Path = _LQD_DAILY_CLOSE_CACHE,
) -> pd.Series:
"""Fetch or load cached LQD daily adjusted closes.
LQD inception 2002-07-22. Use adjusted_close for return computation.
"""
return load_etf_daily_closes(client, "LQD.US", start, end, cache_path)
def load_tbill_monthly_returns(
client: EODHDClient,
ticker: str = _TBILL_TICKER,
) -> pd.Series:
"""Fetch EODHD US3M.GBOND yield and convert to monthly simple return.
Annualised yield in percent → monthly simple return = yield_pct / 100 / 12.
Returns a pd.Series indexed by month-end Timestamps, named 'tbill_ret_1m'.
Raises EODHDError on fetch failure or empty response.
"""
logger.info("Fetching %s daily yield from EODHD", ticker)
try:
daily = client.get_eod_prices(ticker, use_cache=True)
except EODHDError as exc:
logger.error("EODHD fetch failed for T-bill yield (%s): %s", ticker, exc)
raise
if daily.empty:
raise EODHDError(
endpoint=f"eod/{ticker}",
status_code=None,
reason=f"Empty response for {ticker}",
)
daily = daily.set_index("date").sort_index()
yield_monthly = daily["close"].resample("ME").last().dropna()
tbill_ret = yield_monthly / 100.0 / 12.0
tbill_ret.name = "tbill_ret_1m"
logger.info(
"T-bill monthly returns: %d rows, mean=%.4f%%/mo",
len(tbill_ret),
tbill_ret.mean() * 100,
)
return tbill_ret
+428
View File
@@ -0,0 +1,428 @@
"""BlackRock iShares holdings fetcher — SpreadsheetML 2003 XML parser.
Downloads and parses the 'Holdings' worksheet from BlackRock's 'Detailed Holdings
and Analytics' endpoint. Files are SpreadsheetML 2003 XML (despite the URL containing
'fundDownload') and may have malformed XML (unescaped & in attributes). Uses lxml
with recover=True to handle this.
No fallbacks — a fetch failure is a structured error with enough context to fix
without re-running.
"""
import logging
from datetime import date
from pathlib import Path
from typing import Any
import pandas as pd
import requests
import yaml
from lxml import etree
logger = logging.getLogger(__name__)
_NS = "urn:schemas-microsoft-com:office:spreadsheet"
_NSS = {"ss": _NS}
_SHEET_NAME_ATTR = f"{{{_NS}}}Name"
_HOLDINGS_SHEET = "Holdings"
_MIN_CONTENT_BYTES = 100 * 1024 # 100 KB
_XML_HEADER_PREFIX = b"<?xml"
_HTML_MARKERS = (b"<html", b"<!DOCTYPE html", b"<!doctype html")
class BlackRockFetchError(RuntimeError):
"""Raised on any failed BlackRock holdings fetch or parse."""
def __init__(
self,
etf: str,
reason: str,
url: str | None = None,
status_code: int | None = None,
config_line_hint: str | None = None,
):
self.etf = etf
self.reason = reason
self.url = url
self.status_code = status_code
self.config_line_hint = config_line_hint
parts = [f"BlackRock fetch error for ETF '{etf}': {reason}"]
if url:
parts.append(f"URL: {url}")
if status_code is not None:
parts.append(f"status_code={status_code}")
if config_line_hint:
parts.append(f"Fix: {config_line_hint}")
super().__init__(" | ".join(parts))
def _strip_bom(data: bytes) -> bytes:
"""Strip one or more UTF-8 BOMs (handles doubled BOM in UK-variant files)."""
while data.startswith(b"\xef\xbb\xbf"):
data = data[3:]
return data
def _load_yaml_config(path: Path) -> dict[str, Any]:
with path.open("r", encoding="utf-8") as fh:
return yaml.safe_load(fh)
class BlackRockHoldingsFetcher:
def __init__(
self,
config_path: Path | str = "config/blackrock_etfs.yaml",
cache_dir: Path | str = "data/raw/blackrock_csv",
):
self._config_path = Path(config_path)
self._cache_dir = Path(cache_dir)
self._config: dict[str, Any] = _load_yaml_config(self._config_path)
self._etfs: dict[str, Any] = self._config.get("etfs", {})
self._session = requests.Session()
self._session.headers.update({"User-Agent": "Mozilla/5.0"})
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _etf_config(self, etf: str) -> dict[str, Any]:
if etf not in self._etfs:
raise BlackRockFetchError(
etf=etf,
reason=f"ETF '{etf}' not found in config",
config_line_hint=f"Add entry under 'etfs:' in {self._config_path}",
)
return self._etfs[etf]
def _cache_path_for(self, etf: str, date_str: str) -> Path:
self._cache_dir.mkdir(parents=True, exist_ok=True)
return self._cache_dir / f"{etf}_{date_str}.xml"
def _today_str(self) -> str:
return date.today().strftime("%Y%m%d")
def _find_holdings_sheet(self, root: etree._Element) -> etree._Element:
"""Locate the worksheet named 'Holdings' (never guess by size)."""
for ws in root.iter(f"{{{_NS}}}Worksheet"):
if ws.get(_SHEET_NAME_ATTR) == _HOLDINGS_SHEET:
return ws
names = [ws.get(_SHEET_NAME_ATTR) for ws in root.iter(f"{{{_NS}}}Worksheet")]
raise BlackRockFetchError(
etf="",
reason=f"No '{_HOLDINGS_SHEET}' worksheet found; available: {names}",
)
def _iter_row_text(self, row: etree._Element) -> list[str | None]:
"""Extract text values from all cells in a row; None for empty / missing Data."""
values: list[str | None] = []
for cell in row.findall(f"{{{_NS}}}Cell", _NSS):
data = cell.find(f"{{{_NS}}}Data", _NSS)
if data is None or (data.text is None):
values.append(None)
else:
text = (data.text or "").strip()
values.append(text if text else None)
return values
def _parse_sheet_rows(self, sheet: etree._Element) -> tuple[list[str], list[list[str | None]]]:
"""Return (header_cols, data_rows) from the Holdings sheet.
Header is the first row among the first 15 rows that contains the literal
'Ticker' or 'Issuer Ticker' in any cell.
"""
table = sheet.find(f"{{{_NS}}}Table", _NSS)
if table is None:
raise BlackRockFetchError(etf="", reason="Holdings sheet has no Table element")
all_rows = list(table.findall(f"{{{_NS}}}Row", _NSS))
header_idx: int | None = None
header_cols: list[str] = []
for i, row in enumerate(all_rows[:15]):
cells = self._iter_row_text(row)
non_none = [c for c in cells if c is not None]
if any(c in ("Ticker", "Issuer Ticker") for c in non_none):
header_idx = i
header_cols = [c if c is not None else "" for c in cells]
break
if header_idx is None:
raise BlackRockFetchError(
etf="",
reason="Could not locate header row (no 'Ticker' / 'Issuer Ticker' in first 15 rows)",
)
data_rows: list[list[str | None]] = []
for row in all_rows[header_idx + 1 :]:
cells = self._iter_row_text(row)
# Pad row to header width so column lookups are safe.
while len(cells) < len(header_cols):
cells.append(None)
data_rows.append(cells)
return header_cols, data_rows
def _rows_to_dataframe(
self, header: list[str], rows: list[list[str | None]], etf: str
) -> pd.DataFrame:
"""Convert header + raw rows into the canonical output DataFrame."""
# Map canonical output column names to possible header column names.
col_map: dict[str, list[str]] = {
"br_ticker": ["Ticker", "Issuer Ticker"],
"name": ["Name"],
"sector": ["Sector"],
"asset_class": ["Asset Class"],
"weight_pct": ["Weight (%)"],
"location": ["Location"],
"br_exchange": ["Exchange"],
"currency": ["Currency"],
}
# Build index for each required column.
header_index: dict[str, int] = {h: i for i, h in enumerate(header)}
def find_col(candidates: list[str]) -> int | None:
for c in candidates:
if c in header_index:
return header_index[c]
return None
col_indices: dict[str, int | None] = {
out_name: find_col(candidates) for out_name, candidates in col_map.items()
}
# Build list of dicts.
records: list[dict[str, Any]] = []
for row in rows:
rec: dict[str, Any] = {"etf": etf}
for out_name, idx in col_indices.items():
if idx is None:
rec[out_name] = None
else:
val = row[idx] if idx < len(row) else None
# Treat BlackRock null sentinel '--' as None.
rec[out_name] = None if val == "--" else val
records.append(rec)
df = pd.DataFrame(records)
# Filter to equity-only.
if "asset_class" in df.columns:
df = df[df["asset_class"].str.strip() == "Equity"].copy()
# Drop rows with empty / None br_ticker.
df = df[df["br_ticker"].notna() & (df["br_ticker"] != "")].copy()
# Convert weight_pct to float.
df["weight_pct"] = pd.to_numeric(df["weight_pct"], errors="coerce")
output_cols = ["etf", "br_ticker", "name", "sector", "asset_class", "weight_pct",
"location", "br_exchange", "currency"]
for col in output_cols:
if col not in df.columns:
df[col] = None
return df[output_cols].reset_index(drop=True)
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def fetch_raw(self, etf: str) -> bytes:
"""Download SpreadsheetML for an ETF; save atomically to cache; return bytes."""
cfg = self._etf_config(etf)
url: str = cfg["csv_url"]
today = self._today_str()
cache_file = self._cache_path_for(etf, today)
logger.info("Fetching BlackRock holdings for %s from %s", etf, url)
try:
resp = self._session.get(url, timeout=60)
except requests.RequestException as exc:
raise BlackRockFetchError(
etf=etf,
reason=f"Request failed: {exc}",
url=url,
config_line_hint=f"Check 'csv_url' under etfs.{etf} in {self._config_path}",
) from exc
if resp.status_code != 200:
logger.error(
"BlackRock fetch non-200 | etf=%s | url=%s | status=%s",
etf, url, resp.status_code,
)
raise BlackRockFetchError(
etf=etf,
reason=f"HTTP {resp.status_code}",
url=url,
status_code=resp.status_code,
config_line_hint=f"Update 'csv_url' under etfs.{etf} in {self._config_path}",
)
content = resp.content
probe = content[:500].lower()
# Detect HTML error page returned with status 200.
for marker in _HTML_MARKERS:
if marker in probe:
snippet = content[:200].decode("utf-8", errors="replace")
logger.error(
"BlackRock returned HTML instead of XML | etf=%s | url=%s | snippet=%r",
etf, url, snippet,
)
raise BlackRockFetchError(
etf=etf,
reason=f"Response is HTML, not SpreadsheetML XML (snippet: {snippet!r})",
url=url,
status_code=resp.status_code,
config_line_hint=(
f"URL is returning an error page — update 'csv_url' under "
f"etfs.{etf} in {self._config_path}"
),
)
# Check minimum content size before BOM strip (raw size).
if len(content) < _MIN_CONTENT_BYTES:
raise BlackRockFetchError(
etf=etf,
reason=(
f"Response is only {len(content):,} bytes (< {_MIN_CONTENT_BYTES:,}) — "
"likely a truncated download or error page"
),
url=url,
status_code=resp.status_code,
config_line_hint=f"Re-fetch or update 'csv_url' under etfs.{etf} in {self._config_path}",
)
stripped = _strip_bom(content)
if not stripped.lstrip().startswith(_XML_HEADER_PREFIX):
snippet = stripped[:200].decode("utf-8", errors="replace")
raise BlackRockFetchError(
etf=etf,
reason=f"Content does not start with '<?xml' after BOM strip (snippet: {snippet!r})",
url=url,
status_code=resp.status_code,
config_line_hint=f"Check 'csv_url' under etfs.{etf} in {self._config_path}",
)
# Atomic write: .tmp → rename.
tmp_file = cache_file.with_suffix(".tmp")
try:
tmp_file.write_bytes(content)
tmp_file.replace(cache_file)
except OSError as exc:
tmp_file.unlink(missing_ok=True)
raise BlackRockFetchError(
etf=etf,
reason=f"Failed to write cache file {cache_file}: {exc}",
url=url,
) from exc
logger.info(
"Saved BlackRock holdings for %s → %s (%s bytes)",
etf, cache_file, f"{len(content):,}",
)
return content
def parse_holdings(self, xml_bytes: bytes, etf: str) -> pd.DataFrame:
"""Parse the 'Holdings' worksheet from SpreadsheetML bytes."""
cfg = self._etf_config(etf)
min_holdings: int = cfg.get("expected_min_holdings", 0)
stripped = _strip_bom(xml_bytes)
parser = etree.XMLParser(recover=True, huge_tree=True, encoding="utf-8")
try:
root = etree.fromstring(stripped, parser=parser)
except etree.XMLSyntaxError as exc:
raise BlackRockFetchError(
etf=etf,
reason=f"lxml failed to parse XML even with recover=True: {exc}",
) from exc
try:
sheet = self._find_holdings_sheet(root)
except BlackRockFetchError as exc:
# Re-raise with ETF name attached.
raise BlackRockFetchError(
etf=etf,
reason=exc.reason,
url=exc.url,
status_code=exc.status_code,
config_line_hint=exc.config_line_hint,
) from exc
header, rows = self._parse_sheet_rows(sheet)
try:
df = self._rows_to_dataframe(header, rows, etf)
except BlackRockFetchError as exc:
raise BlackRockFetchError(
etf=etf,
reason=exc.reason,
url=exc.url,
status_code=exc.status_code,
config_line_hint=exc.config_line_hint,
) from exc
if len(df) < min_holdings:
raise BlackRockFetchError(
etf=etf,
reason=(
f"Only {len(df)} equity rows after filter; "
f"config requires >= {min_holdings}. "
"Likely a truncated download or unexpected format change."
),
config_line_hint=(
f"Re-fetch, or lower 'expected_min_holdings' under etfs.{etf} "
f"in {self._config_path} if the fund genuinely shrank."
),
)
logger.info("Parsed %d equity holdings for %s", len(df), etf)
return df
def fetch_and_parse(self, etf: str) -> pd.DataFrame:
"""Convenience: fetch_raw + parse_holdings."""
raw = self.fetch_raw(etf)
return self.parse_holdings(raw, etf)
def fetch_and_parse_all(self) -> pd.DataFrame:
"""Fetch + parse all ETFs in config; concat with etf column. Stops on first failure."""
frames: list[pd.DataFrame] = []
for etf in self._etfs:
df = self.fetch_and_parse(etf)
frames.append(df)
if not frames:
return pd.DataFrame()
return pd.concat(frames, ignore_index=True)
def load_cached(self, etf: str, date: str | None = None) -> bytes:
"""Load most recent cached XML for an ETF (or specific YYYYMMDD date string)."""
if date is not None:
path = self._cache_path_for(etf, date)
if not path.is_file():
raise BlackRockFetchError(
etf=etf,
reason=f"No cached file found at {path}",
config_line_hint=f"Run fetch_raw('{etf}') first, or check the date string.",
)
return path.read_bytes()
# Find the most recent file matching {etf}_*.xml.
candidates = sorted(self._cache_dir.glob(f"{etf}_*.xml"), reverse=True)
if not candidates:
raise BlackRockFetchError(
etf=etf,
reason=f"No cached files found for '{etf}' in {self._cache_dir}",
config_line_hint=f"Run fetch_raw('{etf}') to populate the cache.",
)
path = candidates[0]
logger.debug("load_cached(%s) → %s", etf, path)
return path.read_bytes()
+396
View File
@@ -0,0 +1,396 @@
"""Data-hygiene detectors that produce per-(ticker, date) exclusion ranges.
Each detector consumes the daily-returns slab and returns a DataFrame of
ranges (ticker, start_date, end_date, reason). The pipeline glues these
ranges into a single exclusion table consumed by the universe filter at
panel-build time and at live signal time.
Currently implemented:
- detect_frozen_runs: >= N consecutive trading days where
(close, adjusted_close, volume) are byte-identical to
the prior row. Per project owner 2026-05-17: "if 5 consecutive
dates have the exact same volume and price data,
assume those days had 0 volume."
- detect_combined_evidence_corruption:
A ticker that has BOTH a frozen run AND a
|ret_d| > spike_threshold event in its history is
"fully corrupted from the earliest anomaly onward".
Real catastrophes (SVB) and real moonshots (GME) have
spike events but no frozen runs — only data-corruption
tickers exhibit both.
Planned (Tier 2 + 3):
- detect_round_trip_spikes: spike day + reverse spike within 5 trading days
returning to within 2x of pre-spike price.
Catches IGL-style single-day phantom prints.
- detect_low_volume_drift: ≥10 consecutive days with share volume < 1000
AND price drift > 5x / < 0.2x. Catches the
SHS Oct-Nov 2014 drift from $58 frozen → $0.20.
Design notes
------------
Detectors return RANGES, not per-(ticker, date) row lists, so the artifact
stays small. The expansion to per-row masks happens lazily in
`build_exclusion_mask(panel, ranges)`.
The `reason` column lets us audit WHICH detector caught a given (ticker, date)
and tune detectors independently. Multiple detectors may flag the same date —
the universe filter only cares about ANY match.
"""
from __future__ import annotations
import functools
import logging
from pathlib import Path
import pandas as pd
logger = logging.getLogger(__name__)
# Reasons used by detectors here. Keep them short, lowercase, snake_case.
REASON_FROZEN_RUN = "frozen_run"
REASON_COMBINED_EVIDENCE = "combined_evidence_corruption"
REASON_ROUND_TRIP = "round_trip_spike"
REASON_LOW_VOL_DRIFT = "low_volume_drift"
def detect_frozen_runs(
daily: pd.DataFrame,
min_length: int = 5,
) -> pd.DataFrame:
"""Find runs of >= `min_length` consecutive trading days with identical
(close, adjusted_close, volume) for the same ticker.
Args:
daily: DataFrame with columns date, ticker, close, adjusted_close, volume.
Must be sortable by (ticker, date).
min_length: Minimum run length to flag (default 5).
Returns:
DataFrame with columns:
ticker — ticker symbol
start_date — first day of the frozen run
end_date — last day of the frozen run
run_length — number of consecutive trading days in the run
reason — always `REASON_FROZEN_RUN`
close, adjusted_close, volume — the frozen values (for audit)
"""
required = {"date", "ticker", "close", "adjusted_close", "volume"}
missing = required - set(daily.columns)
if missing:
raise ValueError(f"daily missing required columns: {sorted(missing)}")
df = daily.sort_values(["ticker", "date"]).reset_index(drop=True)
same_close = df["close"].eq(df["close"].shift(1))
same_ac = df["adjusted_close"].eq(df["adjusted_close"].shift(1))
same_vol = df["volume"].eq(df["volume"].shift(1))
same_tkr = df["ticker"].eq(df["ticker"].shift(1))
same_row = same_close & same_ac & same_vol & same_tkr
df["run_id"] = (~same_row).cumsum()
run_agg = df.groupby("run_id").agg(
ticker=("ticker", "first"),
start_date=("date", "first"),
end_date=("date", "last"),
run_length=("date", "size"),
close=("close", "first"),
adjusted_close=("adjusted_close", "first"),
volume=("volume", "first"),
)
long_runs = run_agg[run_agg["run_length"] >= min_length].copy()
long_runs["reason"] = REASON_FROZEN_RUN
logger.info(
"detect_frozen_runs: %d runs of length >= %d across %d tickers (%d ticker-days).",
len(long_runs),
min_length,
long_runs["ticker"].nunique() if len(long_runs) else 0,
int(long_runs["run_length"].sum()),
)
return long_runs[
["ticker", "start_date", "end_date", "run_length", "reason",
"close", "adjusted_close", "volume"]
].reset_index(drop=True)
def detect_round_trip_spikes(
daily: pd.DataFrame,
up_threshold: float = 5.0,
down_threshold: float = -0.90,
recovery_calendar_days: int = 10,
) -> pd.DataFrame:
"""Tier-2 detector: find pairs of (ret_d > up_threshold, ret_d < down_threshold)
on the same ticker within `recovery_calendar_days`. Order-agnostic — flags
both (up-then-down) and (down-then-up) patterns.
Captures IGL-style single-day phantom prints, where the close drops to a
bad value (e.g. $0.091 from $66 → ret_d ≈ -0.998) and bounces back the
next trading day (e.g. $66 again → ret_d ≈ +725).
Asymmetric thresholds are intentional:
- Up-direction +500% (ret_d > 5) basically never happens in real markets;
circuit-breakers and LULD bands stop this. Only bad data does.
- Down-direction -90% (ret_d < -0.90) does happen in real bankruptcies
(SVB, BBBYQ etc.) but it doesn't BOUNCE BACK to the prior price level
within 10 days. Pairing a -90% drop with a >500% recovery is what's
unique to data corruption.
Real one-direction extreme events (GME +500% pop without -90% retrace,
SVB -60% to -99% crash without +500% bounce) are NOT flagged because the
other direction never fires.
Args:
daily: DataFrame with columns date, ticker, ret_d.
up_threshold: ret_d threshold for "up spike" (default +500%).
down_threshold: ret_d threshold for "down spike" (default -90%).
recovery_calendar_days: max calendar-day gap between paired spikes.
Returns:
DataFrame with columns ticker, start_date, end_date, reason.
"""
required = {"date", "ticker", "ret_d"}
missing = required - set(daily.columns)
if missing:
raise ValueError(f"daily missing required columns: {sorted(missing)}")
# Each row that crosses either threshold is a candidate.
is_up = daily["ret_d"] > up_threshold
is_down = daily["ret_d"] < down_threshold
spike_mask = is_up | is_down
if not spike_mask.any():
return pd.DataFrame(columns=["ticker", "start_date", "end_date", "reason"])
spikes = daily.loc[spike_mask, ["ticker", "date", "ret_d"]].copy()
spikes["direction"] = 0 # 1 = up, -1 = down
spikes.loc[spikes["ret_d"] > up_threshold, "direction"] = 1
spikes.loc[spikes["ret_d"] < down_threshold, "direction"] = -1
spikes = spikes.sort_values(["ticker", "date"]).reset_index(drop=True)
out_rows: list[dict] = []
for ticker, grp in spikes.groupby("ticker", sort=False):
dates = grp["date"].to_numpy()
dirs = grp["direction"].to_numpy()
n = len(dates)
used = [False] * n
for i in range(n):
if used[i]:
continue
t_i = dates[i]
d_i = dirs[i]
for j in range(i + 1, n):
if used[j]:
continue
gap = (pd.Timestamp(dates[j]) - pd.Timestamp(t_i)).days
if gap > recovery_calendar_days:
break
if dirs[j] != d_i: # opposite direction
out_rows.append({
"ticker": ticker,
"start_date": pd.Timestamp(t_i),
"end_date": pd.Timestamp(dates[j]),
"reason": REASON_ROUND_TRIP,
})
used[i] = True
used[j] = True
break
out = pd.DataFrame(out_rows, columns=["ticker", "start_date", "end_date", "reason"])
logger.info(
"detect_round_trip_spikes: %d round-trip ranges across %d tickers "
"(up>%.1f, down<%.2f, window %d cal days).",
len(out),
out["ticker"].nunique() if len(out) else 0,
up_threshold,
down_threshold,
recovery_calendar_days,
)
return out
def detect_combined_evidence_corruption(
daily: pd.DataFrame,
frozen_runs: pd.DataFrame | None = None,
spike_abs_ret: float = 5.0,
min_frozen_length: int = 5,
) -> pd.DataFrame:
"""Tier-1 detector: a ticker that has BOTH a frozen run AND a daily-return
spike (|ret_d| > spike_abs_ret) in its history is treated as fully
corrupted from the EARLIEST anomaly onward.
Rationale (project owner 2026-05-17): real catastrophic crashes (SVB) and real
moonshots (GME) have spike events but no frozen runs. Real frozen periods
(mid-cap going quiet) don't spike. Only data-corruption tickers exhibit
both, so the combined evidence is high-confidence.
Args:
daily: DataFrame with columns date, ticker, ret_d (and the columns
needed by detect_frozen_runs if frozen_runs is None).
frozen_runs: Pre-computed frozen-runs DataFrame (output of
detect_frozen_runs). If None, detect_frozen_runs is run here.
spike_abs_ret: Threshold for a "spike day" (default 5.0 = +500% / -83%).
Use the .abs() of ret_d so both directions count.
min_frozen_length: passed through to detect_frozen_runs when needed.
Returns:
DataFrame with columns:
ticker, start_date (earliest of: first frozen start, first spike date),
end_date (last observed date for the ticker in `daily`),
reason (always REASON_COMBINED_EVIDENCE),
first_frozen_start, first_spike_date (audit columns).
"""
required = {"date", "ticker", "ret_d"}
missing = required - set(daily.columns)
if missing:
raise ValueError(f"daily missing required columns: {sorted(missing)}")
if frozen_runs is None:
frozen_runs = detect_frozen_runs(daily, min_length=min_frozen_length)
if frozen_runs.empty:
return pd.DataFrame(
columns=["ticker", "start_date", "end_date", "reason",
"first_frozen_start", "first_spike_date"]
)
earliest_frozen = frozen_runs.groupby("ticker")["start_date"].min()
abs_ret = daily["ret_d"].abs()
spike_rows = daily[abs_ret > spike_abs_ret][["ticker", "date"]]
if spike_rows.empty:
return pd.DataFrame(
columns=["ticker", "start_date", "end_date", "reason",
"first_frozen_start", "first_spike_date"]
)
earliest_spike = spike_rows.groupby("ticker")["date"].min()
# Intersect: tickers with BOTH a frozen run AND a spike.
both = pd.concat(
[
earliest_frozen.rename("first_frozen_start"),
earliest_spike.rename("first_spike_date"),
],
axis=1,
).dropna()
if both.empty:
return pd.DataFrame(
columns=["ticker", "start_date", "end_date", "reason",
"first_frozen_start", "first_spike_date"]
)
both["start_date"] = both[["first_frozen_start", "first_spike_date"]].min(axis=1)
# End of available data per ticker — last row in `daily`.
last_date = daily.groupby("ticker")["date"].max()
both["end_date"] = last_date.reindex(both.index)
both["reason"] = REASON_COMBINED_EVIDENCE
out = both.reset_index().rename(columns={"index": "ticker"})
logger.info(
"detect_combined_evidence_corruption: %d tickers flagged "
"(have both frozen runs and |ret_d| > %.1f spikes).",
len(out), spike_abs_ret,
)
return out[[
"ticker", "start_date", "end_date", "reason",
"first_frozen_start", "first_spike_date",
]]
def build_exclusion_mask(
panel: pd.DataFrame,
ranges: pd.DataFrame,
lookforward_days: int = 0,
) -> pd.Series:
"""Return a boolean mask (True = exclude) over `panel` rows.
A panel row at (ticker, date=D) is excluded if any range for that ticker
OVERLAPS the window [D, D + lookforward_days]. With lookforward_days=0,
this reduces to "D is inside [start_date, end_date]".
Why lookforward_days matters
----------------------------
Panel snapshots are at month-end (D), but cohorts get HELD over a forward
window (typically D+21 to D+50 for monthly rebalance). A
ticker with bad-data days at D+25 should be excluded at snapshot D even
though D itself is clean — its forward returns will be poisoned.
The check is equivalent to: range overlaps [D, D + lookforward] iff
start_date - lookforward <= D <= end_date.
Args:
panel: DataFrame with columns date, ticker.
ranges: DataFrame with columns ticker, start_date, end_date.
lookforward_days: how far past `date` the upcoming holding window
extends. Backtests should pass max-cycle-length
(e.g. 50 calendar days for monthly rebalance);
live signal can use 0 (no forward exposure).
Returns:
Boolean Series aligned to panel.index. True where the row is excluded.
"""
if "ticker" not in panel.columns or "date" not in panel.columns:
raise ValueError("panel must have 'ticker' and 'date' columns")
if ranges.empty:
return pd.Series(False, index=panel.index)
panel_with_idx = panel[["ticker", "date"]].copy()
panel_with_idx["_panel_idx"] = panel.index
panel_with_idx["date"] = pd.to_datetime(panel_with_idx["date"])
ranges_normalized = ranges[["ticker", "start_date", "end_date"]].copy()
ranges_normalized["start_date"] = pd.to_datetime(ranges_normalized["start_date"])
ranges_normalized["end_date"] = pd.to_datetime(ranges_normalized["end_date"])
if lookforward_days > 0:
# Shift effective start backwards so an overlap-with-forward-window
# check reduces to "D in [effective_start, end_date]".
ranges_normalized["start_date"] = ranges_normalized["start_date"] - pd.Timedelta(
days=lookforward_days
)
panel_tickers = set(panel_with_idx["ticker"].unique())
ranges_sub = ranges_normalized[ranges_normalized["ticker"].isin(panel_tickers)]
if ranges_sub.empty:
return pd.Series(False, index=panel.index)
merged = panel_with_idx.merge(ranges_sub, on="ticker", how="inner")
in_range = (merged["date"] >= merged["start_date"]) & (merged["date"] <= merged["end_date"])
hit_idx = merged.loc[in_range, "_panel_idx"].unique()
out = pd.Series(False, index=panel.index)
out.loc[hit_idx] = True
return out
@functools.lru_cache(maxsize=4)
def _load_exclusion_ranges_cached(path_str: str) -> pd.DataFrame:
"""Cached parquet load. Use the cache_clear() method on this function to
invalidate after rebuilding the exclusion table."""
return pd.read_parquet(path_str)
def save_exclusion_ranges(ranges: pd.DataFrame, out_path: Path | str) -> None:
"""Persist the exclusion ranges to parquet."""
out_path = Path(out_path)
out_path.parent.mkdir(parents=True, exist_ok=True)
ranges.to_parquet(out_path)
logger.info("Saved %d exclusion ranges to %s", len(ranges), out_path)
def load_exclusion_ranges(path: Path | str) -> pd.DataFrame:
"""Load the exclusion ranges. Returns empty DataFrame if file missing.
Backed by an LRU cache so the parquet is read at most once per process per
path — important for the per-cycle universe filter in backtests.
"""
path = Path(path)
if not path.is_file():
logger.warning("Exclusion ranges file not found: %s", path)
return pd.DataFrame(
columns=["ticker", "start_date", "end_date", "run_length", "reason"]
)
return _load_exclusion_ranges_cached(str(path))
+365
View File
@@ -0,0 +1,365 @@
"""EODHD API client — primary data source for KWPF Momentum.
No fallbacks. A fetch failure is a signal, not noise.
All raw responses are cached to data/raw/eodhd/ by file path.
"""
import json
import logging
import threading
import time
from pathlib import Path
from typing import Any
import pandas as pd
import requests
import requests.adapters
logger = logging.getLogger(__name__)
_MAX_429_RETRIES = 3
_429_DEFAULT_SLEEP = 5.0
class EODHDError(RuntimeError):
"""Raised on any failed EODHD API call."""
def __init__(self, endpoint: str, status_code: int | None, reason: str, params: dict | None = None):
self.endpoint = endpoint
self.status_code = status_code
self.reason = reason
self.params = params or {}
super().__init__(f"EODHD error [{status_code}] at {endpoint}: {reason}")
class TokenBucketRateLimiter:
"""Thread-safe token-bucket rate limiter.
Tokens refill continuously at `rate_per_minute / 60` per second, capped
at `burst_capacity`. `acquire()` blocks until a token is available.
"""
def __init__(self, rate_per_minute: float = 1000.0, burst_capacity: int = 50) -> None:
self._rate_per_sec = rate_per_minute / 60.0
self._capacity = float(burst_capacity)
self._tokens = float(burst_capacity)
self._last_refill = time.monotonic()
self._lock = threading.Lock()
def acquire(self, tokens: int = 1) -> None:
while True:
with self._lock:
now = time.monotonic()
elapsed = now - self._last_refill
self._tokens = min(self._capacity, self._tokens + elapsed * self._rate_per_sec)
self._last_refill = now
if self._tokens >= tokens:
self._tokens -= tokens
return
deficit = tokens - self._tokens
wait_sec = deficit / self._rate_per_sec
time.sleep(min(wait_sec, 0.5))
class EODHDClient:
def __init__(
self,
api_key_path: str | Path = "eodhd_api.key",
cache_dir: str | Path = "data/raw/eodhd",
base_url: str = "https://eodhd.com/api",
rate_limit_per_minute: float = 900.0,
):
self._api_key = Path(api_key_path).read_text(encoding="utf-8").strip()
self._cache_dir = Path(cache_dir)
self._base_url = base_url.rstrip("/")
self._limiter = TokenBucketRateLimiter(rate_per_minute=rate_limit_per_minute, burst_capacity=50)
adapter = requests.adapters.HTTPAdapter(pool_connections=32, pool_maxsize=32)
self._session = requests.Session()
self._session.mount("https://", adapter)
self._session.mount("http://", adapter)
# ------------------------------------------------------------------
# Internal helpers
# ------------------------------------------------------------------
def _get(self, endpoint: str, params: dict[str, Any]) -> Any:
"""Execute a GET request; raise EODHDError on non-200.
Rate-limited by the token bucket before the request fires.
429 responses are retried up to _MAX_429_RETRIES times with backoff.
"""
params = {**params, "api_token": self._api_key}
url = f"{self._base_url}/{endpoint.lstrip('/')}"
log_params = {k: v for k, v in params.items() if k != "api_token"}
log_params["api_token"] = "REDACTED"
self._limiter.acquire()
for attempt in range(_MAX_429_RETRIES + 1):
try:
resp = self._session.get(url, params=params, timeout=30)
except requests.RequestException as exc:
raise EODHDError(
endpoint=endpoint,
status_code=None,
reason=str(exc),
params=log_params,
) from exc
if resp.status_code == 429:
if attempt >= _MAX_429_RETRIES:
logger.error(
"EODHD 429 rate-limit exceeded after %d retries | endpoint=%s | params=%s",
_MAX_429_RETRIES, endpoint, log_params,
)
raise EODHDError(
endpoint=endpoint,
status_code=429,
reason=f"HTTP 429 after {_MAX_429_RETRIES} retries",
params=log_params,
)
retry_after_str = resp.headers.get("Retry-After", "")
try:
sleep_sec = float(retry_after_str)
except (ValueError, TypeError):
sleep_sec = _429_DEFAULT_SLEEP
logger.warning(
"EODHD 429 — sleeping %.1fs (Retry-After=%r) | attempt %d/%d | endpoint=%s",
sleep_sec, retry_after_str, attempt + 1, _MAX_429_RETRIES, endpoint,
)
time.sleep(sleep_sec)
self._limiter.acquire()
continue
if resp.status_code != 200:
snippet = resp.text[:300]
logger.error(
"EODHD fetch failed | endpoint=%s | params=%s | status=%s | snippet=%s",
endpoint, log_params, resp.status_code, snippet,
)
raise EODHDError(
endpoint=endpoint,
status_code=resp.status_code,
reason=f"HTTP {resp.status_code}: {snippet}",
params=log_params,
)
return resp.json()
# Unreachable — loop always returns or raises inside.
raise EODHDError(endpoint=endpoint, status_code=None, reason="unexpected loop exit", params=log_params)
def _cache_path(self, *parts: str) -> Path:
p = self._cache_dir.joinpath(*parts)
p.parent.mkdir(parents=True, exist_ok=True)
return p
def _load_cache(self, path: Path) -> Any | None:
if path.is_file():
return json.loads(path.read_text(encoding="utf-8"))
return None
def _write_cache(self, path: Path, data: Any) -> None:
path.write_text(json.dumps(data, ensure_ascii=False), encoding="utf-8")
# ------------------------------------------------------------------
# Public API
# ------------------------------------------------------------------
def get_eod_prices(
self,
symbol: str,
from_date: str | None = None,
to_date: str | None = None,
use_cache: bool = True,
extend_cache_to: str | None = None,
) -> pd.DataFrame:
"""Daily EOD prices for a symbol in TICKER.EXCHANGE format (e.g. MCD.US).
Returns DataFrame with columns:
date (datetime64), open, high, low, close, adjusted_close, volume
extend_cache_to: if set and cache exists with max_date < extend_cache_to,
fetch the gap (max_date+1 .. extend_cache_to) and merge into cache.
On fetch failure the existing cache is returned unchanged.
"""
cache_file = self._cache_path("eod", f"{symbol}.json")
if use_cache:
cached = self._load_cache(cache_file)
if cached is not None and cached:
# Non-empty cache hit.
if extend_cache_to is not None:
cached = self._extend_cache(
symbol=symbol,
cache_file=cache_file,
cached=cached,
extend_cache_to=extend_cache_to,
)
return self._parse_eod(cached)
if cached is not None and not cached:
# Empty cached list — treat as cache miss, fall through to full fetch.
logger.debug("Empty cache for %s — treating as cache miss", symbol)
params: dict[str, Any] = {"fmt": "json"}
if from_date:
params["from"] = from_date
if to_date:
params["to"] = to_date
data = self._get(f"eod/{symbol}", params)
self._write_cache(cache_file, data)
return self._parse_eod(data)
def _extend_cache(
self,
symbol: str,
cache_file: Path,
cached: list[dict],
extend_cache_to: str,
) -> list[dict]:
"""Fetch the gap between cached max date and extend_cache_to, merge, write back.
Returns the (possibly extended) list — always the cached data on any failure.
"""
date_vals = [row["date"] for row in cached if row.get("date")]
if not date_vals:
return cached
cached_max = max(date_vals)
if cached_max >= extend_cache_to:
return cached
# Advance one calendar day past the last cached date.
from datetime import date, timedelta
gap_from = (date.fromisoformat(cached_max) + timedelta(days=1)).isoformat()
logger.info(
"Extending EOD cache for %s: %s → %s",
symbol,
cached_max,
extend_cache_to,
)
try:
new_rows = self._get(
f"eod/{symbol}",
{"fmt": "json", "from": gap_from, "to": extend_cache_to},
)
except EODHDError as exc:
logger.warning(
"EOD extension fetch failed for %s — returning existing cache. error=%s",
symbol,
exc,
)
return cached
if not new_rows:
logger.debug("No new rows for %s in gap %s → %s", symbol, gap_from, extend_cache_to)
return cached
# Merge: existing rows win on date conflict (don't overwrite historical adj_close).
existing_dates = {row["date"] for row in cached if row.get("date")}
additions = [r for r in new_rows if r.get("date") and r["date"] not in existing_dates]
merged = sorted(cached + additions, key=lambda r: r.get("date", ""))
# Atomic write: .tmp then rename to guard against partial-write corruption.
tmp_file = cache_file.with_suffix(".tmp")
try:
tmp_file.write_text(json.dumps(merged, ensure_ascii=False), encoding="utf-8")
tmp_file.replace(cache_file)
except OSError as exc:
logger.warning("Failed to write extended cache for %s: %s", symbol, exc)
tmp_file.unlink(missing_ok=True)
return cached
logger.info("Extended cache for %s: +%d rows (total %d)", symbol, len(additions), len(merged))
return merged
def _parse_eod(self, data: list[dict]) -> pd.DataFrame:
if not data:
return pd.DataFrame(
columns=["date", "open", "high", "low", "close", "adjusted_close", "volume"]
)
df = pd.DataFrame(data)
df["date"] = pd.to_datetime(df["date"])
# Normalise column names — EODHD returns camelCase or snake_case depending on version
rename = {
"adjusted_close": "adjusted_close",
"adjustedClose": "adjusted_close",
}
df.rename(columns=rename, inplace=True)
cols = ["date", "open", "high", "low", "close", "adjusted_close", "volume"]
return df[[c for c in cols if c in df.columns]].reset_index(drop=True)
def get_exchange_symbols(
self,
exchange: str,
delisted: bool = False,
use_cache: bool = True,
) -> pd.DataFrame:
"""Active or delisted ticker listing for an exchange (e.g. 'NYSE', 'NASDAQ').
URL: /exchange-symbol-list/{exchange}?api_token=KEY&fmt=json[&delisted=1]
Returns DataFrame with whatever columns the API supplies (typically:
Code, Name, Country, Exchange, Currency, Type, Isin).
"""
suffix = "delisted" if delisted else "active"
cache_file = self._cache_path("symbols", f"{exchange}_{suffix}.json")
if use_cache:
cached = self._load_cache(cache_file)
if cached is not None:
return pd.DataFrame(cached)
params: dict[str, Any] = {"fmt": "json"}
if delisted:
params["delisted"] = 1
data = self._get(f"exchange-symbol-list/{exchange}", params)
self._write_cache(cache_file, data)
return pd.DataFrame(data)
def get_fundamentals(self, symbol: str, use_cache: bool = True) -> dict:
"""Full fundamentals JSON for a symbol in TICKER.EXCHANGE format.
URL: /v1.1/fundamentals/{symbol}?api_token=KEY&fmt=json
Returns the raw parsed dict; downstream code is responsible for navigation.
"""
cache_file = self._cache_path("fundamentals", f"{symbol}.json")
if use_cache:
cached = self._load_cache(cache_file)
if cached is not None:
return cached
data = self._get(f"v1.1/fundamentals/{symbol}", {"fmt": "json"})
self._write_cache(cache_file, data)
return data
def get_eod_prices_with_retry(
self,
symbol: str,
from_date: str | None = None,
to_date: str | None = None,
use_cache: bool = True,
max_attempts: int = 3,
backoff_seconds: float = 2.0,
) -> pd.DataFrame:
"""Same as get_eod_prices but with simple exponential retry on transient errors."""
last_exc: EODHDError | None = None
for attempt in range(max_attempts):
try:
return self.get_eod_prices(symbol, from_date, to_date, use_cache)
except EODHDError as exc:
if exc.status_code is not None and 400 <= exc.status_code < 500:
raise # 4xx are not retryable
last_exc = exc
logger.warning("EODHD transient error, attempt %d/%d: %s", attempt + 1, max_attempts, exc)
time.sleep(backoff_seconds * (2 ** attempt))
raise last_exc # type: ignore[misc]
+574
View File
@@ -0,0 +1,574 @@
"""Phase 7 fundamentals panel — Twin Momentum FIR features only.
Parses EODHD /v1.1/fundamentals/{symbol} JSON into a quarterly DataFrame
and derives the 28 Twin-Momentum FIR features (7 base ratios × 4 MA lags)
that feed the rolling cross-sectional OLS in `src/overlays/twin_momentum.py`.
Removal history
---------------
The Beneish-Nichols O-Score overlay was removed on 2026-05-10 after failing
its backtest gate (G2: -1.0 bps/mo improvement, sub-windows -2.1 / +0.1 / -1.0
across 2018-2026). The Hao-Jang-Lee High Accruals overlay was removed on the
same date after failing G3 in a follow-up diagnostic — the simplified Sloan
DA construction produced -22 bps/mo Q1-Q5 spread universe-wide (wrong sign,
t=-1.11) and no candidate veto rule (4-year flag, top-quintile RAW, top-quintile
WINSORISED, top-decile WINSORISED) cleared the +5 bps/mo gate. The signal is
regime-dependent in 2018-2026 US equity, with 2024-2026 actively destructive
for any DA veto. Phase 7 v1 ships FIR-only.
ACCRUALS_DJ remains as one of the seven base FIR features (per Huang-Zhang-Zhou
2021); the FIR overlay's rolling OLS handles outliers well enough — see Phase 7
G1 PASS at +10.3%/yr. Only the *standalone accruals veto* and its supporting
4-consecutive-year flag were removed.
Data-architecture note
----------------------
EODHD's delisted-company fundamentals coverage begins in 2018; any pre-2018
backtest that conditions on "has fundamentals available" introduces survivorship
bias. Phase 7 therefore uses a 2018-01 to 2026-03 sub-window only.
Point-in-time (PIT) note
-------------------------
EODHD quarterly financials are filed with a reporting date, not the
announcement date. We apply a hard 90-day PIT lag (configurable via
`pit_lag_days`) from quarter_end before the data is considered "known."
This is conservative and matches standard practice in accounting-based
factor literature (Ball-Brown 1968, Nichols-Wahlen-Wieland).
"""
import logging
from typing import Any
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Canonical EODHD path constants
# ---------------------------------------------------------------------------
_BS_Q = "Financials::Balance_Sheet::quarterly"
_IS_Q = "Financials::Income_Statement::quarterly"
_CF_Q = "Financials::Cash_Flow::quarterly"
_FREQ_KEY = {"quarterly": "quarterly", "annual": "yearly"}
def _safe_float(value: Any) -> float:
"""Cast EODHD JSON value to float; return NaN on any conversion failure."""
if value is None:
return float("nan")
try:
return float(value)
except (ValueError, TypeError):
return float("nan")
def _zero_float(value: Any) -> float:
"""Cast to float; return 0.0 on null/conversion failure (AFP default-0 items)."""
if value is None:
return 0.0
try:
return float(value)
except (ValueError, TypeError):
return 0.0
def _navigate(data: dict, *keys: str) -> Any:
"""Navigate a nested dict without raising; returns None on missing key."""
cur: Any = data
for k in keys:
if not isinstance(cur, dict):
return None
cur = cur.get(k)
return cur
# ---------------------------------------------------------------------------
# 1. parse_fundamentals_response
# ---------------------------------------------------------------------------
def parse_fundamentals_response(
data: dict, symbol: str, freq: str = "quarterly"
) -> pd.DataFrame:
"""Parse EODHD /v1.1/fundamentals/{symbol} JSON into a per-period DataFrame.
Each row is one filing period with raw fields extracted directly from the
EODHD response. No derived computations happen here. `freq` selects the
EODHD statement frequency: "quarterly" reads `Financials::*::quarterly`
(default, unchanged), "annual" reads `Financials::*::yearly`. The output
column schema is identical for both; the period-end column stays named
`quarter_end` (it is the period-end date regardless of frequency).
Returns
-------
pd.DataFrame
Columns: ticker, quarter_end (datetime),
total_assets, net_income, revenue, cogs, equity,
lt_debt, operating_income, interest_expense, tax_provision,
pretax_income, depreciation, total_liabilities,
research_development,
receivables, ppe_gross,
retained_earnings, short_term_debt, cash,
-- cash flow statement --
cfo, net_stock_iss_cash, capex,
-- working capital proxies --
current_assets, current_liabilities.
Rows with no quarter_end date are silently dropped.
"""
freq_key = _FREQ_KEY.get(freq)
if freq_key is None:
raise ValueError(f"parse_fundamentals_response: unknown freq {freq!r}")
bs_quarterly: dict = _navigate(data, "Financials", "Balance_Sheet", freq_key) or {}
is_quarterly: dict = _navigate(data, "Financials", "Income_Statement", freq_key) or {}
cf_quarterly: dict = _navigate(data, "Financials", "Cash_Flow", freq_key) or {}
if not bs_quarterly and not is_quarterly:
logger.debug("parse_fundamentals_response: no %s data for %s", freq, symbol)
return _empty_quarterly(symbol)
# Collect all unique date keys across the three statements.
all_dates = sorted(
set(bs_quarterly.keys()) | set(is_quarterly.keys()) | set(cf_quarterly.keys())
)
rows: list[dict] = []
for date_key in all_dates:
bs = bs_quarterly.get(date_key, {}) or {}
is_ = is_quarterly.get(date_key, {}) or {}
cf = cf_quarterly.get(date_key, {}) or {}
# Parse quarter_end from EODHD's date field or use the dict key.
# EODHD embeds a "date" key inside the row dict.
raw_date = bs.get("date") or is_.get("date") or cf.get("date") or date_key
try:
quarter_end = pd.Timestamp(raw_date)
except Exception:
logger.debug("Unparseable date key '%s' for %s — skipping", date_key, symbol)
continue
# Guard against corrupt EODHD dates (e.g. '0130-09-30'): they parse to a
# non-nanosecond Timestamp that survives here but overflows the ns cast in
# downstream pd.to_datetime (lag_to_monthly). Drop anything out of range.
if quarter_end.year < 1900 or quarter_end.year > 2100:
logger.debug("Out-of-range date '%s' for %s — skipping", raw_date, symbol)
continue
rows.append(
{
"ticker": symbol,
"quarter_end": quarter_end,
# Balance sheet
"total_assets": _safe_float(bs.get("totalAssets")),
"equity": _safe_float(bs.get("totalStockholderEquity")),
"lt_debt": _safe_float(bs.get("longTermDebt")),
"total_liabilities": _safe_float(bs.get("totalLiab")),
"receivables": _safe_float(bs.get("netReceivables")),
"ppe_gross": _safe_float(bs.get("propertyPlantEquipment")),
"current_assets": _safe_float(bs.get("totalCurrentAssets")),
"current_liabilities": _safe_float(bs.get("totalCurrentLiabilities")),
# QMJ Safety-pillar additions (Altman-Z RE term, AFP LEV total
# debt, working-capital cash term).
"retained_earnings": _safe_float(bs.get("retainedEarnings")),
"short_term_debt": _safe_float(
bs.get("shortTermDebt")
if bs.get("shortTermDebt") is not None
else bs.get("shortLongTermDebt")
),
"cash": _safe_float(
bs.get("cash")
if bs.get("cash") is not None
else bs.get("cashAndShortTermInvestments")
),
# AFP LEV / TOTD / O-score total-debt: minority interest and
# preferred stock. EODHD null => 0.0 (a firm with neither
# contributes 0 to the total-debt aggregate).
"minority_interest": _zero_float(
bs.get("noncontrollingInterestInConsolidatedEntity")
if bs.get("noncontrollingInterestInConsolidatedEntity") is not None
else bs.get("minorityInterest")
),
"preferred_stock": _zero_float(
bs.get("preferredStockTotalEquity")
if bs.get("preferredStockTotalEquity") is not None
else bs.get("preferredStockRedeemable")
),
# Income statement
"revenue": _safe_float(is_.get("totalRevenue")),
"cogs": _safe_float(is_.get("costOfRevenue")),
"net_income": _safe_float(is_.get("netIncome")),
"operating_income": _safe_float(is_.get("operatingIncome") or is_.get("ebit")),
"interest_expense": _safe_float(is_.get("interestExpense")),
# Pretax income = income before tax. EODHD's field is
# `incomeBeforeTax`; `totalOtherIncomeExpenseNet` is the
# non-operating other-income line (NOT pretax income) and is
# only a last-resort fallback. (Prior code had these reversed
# AND relied on `nan or x`, which never falls back because NaN
# is truthy — a real bug fixed 2026-06-05.)
"pretax_income": _safe_float(
is_.get("incomeBeforeTax")
if is_.get("incomeBeforeTax") is not None
else is_.get("totalOtherIncomeExpenseNet")
),
"tax_provision": _safe_float(is_.get("incomeTaxExpense")),
"depreciation": _safe_float(
is_.get("depreciationAndAmortization") or is_.get("depreciation")
),
"research_development": _safe_float(is_.get("researchDevelopment")),
# Cash flow statement.
# EODHD's CF schema does NOT expose `issuanceOfStock`,
# `repurchaseOfStock`, or `acquisitionsNet` — those keys are
# absent from every quarterly row. The combined field
# `salePurchaseOfStock` IS present in 100% of rows and is
# already the net value (positive = net issuance, negative =
# net buyback). We extract it directly as `net_stock_iss_cash`.
"cfo": _safe_float(cf.get("totalCashFromOperatingActivities")),
"net_stock_iss_cash": _safe_float(cf.get("salePurchaseOfStock")),
"capex": _safe_float(cf.get("capitalExpenditures")),
# Depreciation also in CF (often different sign convention)
"depreciation_cf": _safe_float(cf.get("depreciation")),
}
)
if not rows:
return _empty_quarterly(symbol)
df = pd.DataFrame(rows)
df = df.dropna(subset=["quarter_end"])
df = df.sort_values("quarter_end").reset_index(drop=True)
# Use the better depreciation estimate: prefer CF statement (typically positive)
# over IS (typically shown as absolute). Take whichever is finite.
dep_cf_valid = df["depreciation_cf"].notna() & (df["depreciation_cf"].abs() > 0)
df.loc[dep_cf_valid, "depreciation"] = df.loc[dep_cf_valid, "depreciation_cf"].abs()
df = df.drop(columns=["depreciation_cf"])
logger.debug(
"parse_fundamentals_response: %s → %d quarterly rows (%s to %s)",
symbol,
len(df),
df["quarter_end"].min().date() if len(df) else "n/a",
df["quarter_end"].max().date() if len(df) else "n/a",
)
return df
def _empty_quarterly(symbol: str) -> pd.DataFrame:
cols = [
"ticker",
"quarter_end",
"total_assets",
"equity",
"lt_debt",
"total_liabilities",
"receivables",
"ppe_gross",
"current_assets",
"current_liabilities",
"retained_earnings",
"short_term_debt",
"cash",
"minority_interest",
"preferred_stock",
"revenue",
"cogs",
"net_income",
"operating_income",
"interest_expense",
"pretax_income",
"tax_provision",
"depreciation",
"research_development",
"cfo",
"net_stock_iss_cash",
"capex",
]
return pd.DataFrame(columns=cols)
def extract_pit_shares(data: dict) -> pd.Series:
"""Read data["outstandingShares"]["quarterly"] into a date-indexed shares series.
Each EODHD row has 'date' (e.g. '2026-Q1'), 'dateFormatted' (calendar date,
e.g. '2026-03-31'), 'sharesMln', and an integer 'shares'. We index on the
calendar date (dateFormatted) and return the integer share count, used for
market-cap derivation (ME = close × PIT shares).
Returns an empty float Series (datetime index) when the field is absent.
"""
quarterly = _navigate(data, "outstandingShares", "quarterly") or {}
if not quarterly:
return pd.Series(dtype=float, index=pd.DatetimeIndex([], name="date"))
dates: list[pd.Timestamp] = []
shares: list[float] = []
for row in quarterly.values():
if not isinstance(row, dict):
continue
raw_date = row.get("dateFormatted") or row.get("date")
try:
d = pd.Timestamp(raw_date)
except Exception:
continue
dates.append(d)
shares.append(_safe_float(row.get("shares")))
if not dates:
return pd.Series(dtype=float, index=pd.DatetimeIndex([], name="date"))
s = pd.Series(shares, index=pd.DatetimeIndex(dates, name="date"))
s = s[~s.index.duplicated(keep="last")].sort_index()
return s
# ---------------------------------------------------------------------------
# 2. compute_twin_momentum_features
# ---------------------------------------------------------------------------
def compute_twin_momentum_features(quarterly: pd.DataFrame) -> pd.DataFrame:
"""Add 7 Twin-Momentum fundamentals + 4 MA lags (1q/2q/4q/8q) = 28 columns.
The 7 base features (per Huang-Zhang-Zhou 2021, ssrn-2894068):
ROA = net_income / total_assets
ROE = net_income / equity
ROIC = NOPAT / (equity + lt_debt)
NOPAT = operating_income × (1 − effective_tax_rate)
effective_tax_rate = tax_provision / pretax_income
fallback: EBIT × (1 − 0.21)
GP_TO_ASSETS = (revenue − cogs) / total_assets
ACCRUALS_DJ = (ΔWorking Capital − depreciation) / avg_total_assets
working_capital = current_assets − current_liabilities
ASSET_GROWTH = Δtotal_assets / lagged_total_assets
NET_STOCK_ISS = net_stock_iss_cash / lagged_total_assets
(where net_stock_iss_cash = EODHD's
`salePurchaseOfStock` — already the net of
issuance minus buyback. Positive = net dilution;
negative = net buyback. mcap unavailable.)
The 4 moving-average lags (1q, 2q, 4q, 8q) expand each feature into 4
trailing-average variants, giving 28 regressors. Lags are computed
per ticker; NaN propagates if the window is insufficient.
Parameters
----------
quarterly : pd.DataFrame
Output of parse_fundamentals_response; sorted by quarter_end.
Returns
-------
pd.DataFrame
Input DataFrame plus 7 base feature columns and 28 lagged variants
(named e.g. ROA_lag1q, ROA_lag2q, ROA_lag4q, ROA_lag8q, ...).
All computations are ticker-local; no cross-sectional operations.
"""
if quarterly.empty:
return quarterly.copy()
df = quarterly.copy().sort_values(["ticker", "quarter_end"]).reset_index(drop=True)
_BASE_FEATURES = [
"ROA",
"ROE",
"ROIC",
"GP_TO_ASSETS",
"ACCRUALS_DJ",
"ASSET_GROWTH",
"NET_STOCK_ISS",
]
_LAG_WINDOWS = [1, 2, 4, 8]
# --- Helper: effective tax rate per row ---
pretax = df["pretax_income"].to_numpy(dtype=float)
tax = df["tax_provision"].to_numpy(dtype=float)
with np.errstate(invalid="ignore", divide="ignore"):
effective_tax = np.where(
(pretax != 0) & np.isfinite(pretax) & np.isfinite(tax),
tax / pretax,
float("nan"),
)
# Clip to sensible range (0–50%); extreme values indicate special items.
effective_tax = np.clip(effective_tax, 0.0, 0.50)
fallback_tax = np.where(np.isnan(effective_tax), 0.21, effective_tax)
# --- ROA ---
df["ROA"] = _safe_ratio(df["net_income"].to_numpy(float), df["total_assets"].to_numpy(float))
# --- ROE ---
df["ROE"] = _safe_ratio(df["net_income"].to_numpy(float), df["equity"].to_numpy(float))
# --- ROIC ---
nopat = df["operating_income"].to_numpy(dtype=float) * (1.0 - fallback_tax)
invested_capital = df["equity"].to_numpy(float) + df["lt_debt"].to_numpy(float)
df["ROIC"] = _safe_ratio(nopat, invested_capital)
# --- GP_TO_ASSETS ---
gross_profit = df["revenue"].to_numpy(float) - df["cogs"].to_numpy(float)
df["GP_TO_ASSETS"] = _safe_ratio(gross_profit, df["total_assets"].to_numpy(float))
# --- ACCRUALS_DJ, ASSET_GROWTH, NET_STOCK_ISS ---
# Computed per-ticker via explicit iteration to avoid pandas groupby.apply
# DataFrame transposition bug in pandas 1.x/2.x when a single group returns
# a Series with integer index (it gets treated as a column vector).
accruals_out = np.full(len(df), float("nan"))
ag_out = np.full(len(df), float("nan"))
nsi_out = np.full(len(df), float("nan"))
for _ticker, grp in df.groupby("ticker"):
idx = grp.index.to_numpy()
wc = grp["current_assets"].to_numpy(float) - grp["current_liabilities"].to_numpy(float)
dep = grp["depreciation"].to_numpy(float)
ta = grp["total_assets"].to_numpy(float)
net_iss_cash = grp["net_stock_iss_cash"].to_numpy(float)
ta_lag = np.empty_like(ta)
ta_lag[0] = float("nan")
ta_lag[1:] = ta[:-1]
# ACCRUALS_DJ = (ΔWC − Dep) / avg_total_assets
delta_wc = np.empty_like(wc)
delta_wc[0] = float("nan")
delta_wc[1:] = np.diff(wc)
avg_ta = (ta + ta_lag) / 2.0
with np.errstate(invalid="ignore", divide="ignore"):
da = (delta_wc - dep) / avg_ta
accruals_out[idx] = da
# ASSET_GROWTH = Δtotal_assets / lagged_total_assets
with np.errstate(invalid="ignore", divide="ignore"):
ag = (ta - ta_lag) / ta_lag
ag_out[idx] = ag
# NET_STOCK_ISS = net_stock_iss_cash / lagged_total_assets
# EODHD's `salePurchaseOfStock` is already the net (positive =
# net issuance, negative = net buyback) — same sign convention.
with np.errstate(invalid="ignore", divide="ignore"):
nsi = net_iss_cash / ta_lag
nsi_out[idx] = nsi
df["ACCRUALS_DJ"] = accruals_out
df["ASSET_GROWTH"] = ag_out
df["NET_STOCK_ISS"] = nsi_out
# --- Moving-average lags per ticker ---
def _rolling_mean(series: pd.Series, window: int) -> pd.Series:
return series.rolling(window, min_periods=window).mean()
for feat in _BASE_FEATURES:
for w in _LAG_WINDOWS:
col_name = f"{feat}_lag{w}q"
df[col_name] = df.groupby("ticker")[feat].transform(
lambda s, _w=w: _rolling_mean(s, _w)
)
logger.debug(
"compute_twin_momentum_features: %d rows, %d feature columns",
len(df),
len(
[
c
for c in df.columns
if c in _BASE_FEATURES or any(f"{f}_lag" in c for f in _BASE_FEATURES)
]
),
)
return df
def _safe_ratio(numerator: np.ndarray, denominator: np.ndarray) -> np.ndarray:
"""Element-wise division; returns NaN where denominator is zero or non-finite."""
with np.errstate(invalid="ignore", divide="ignore"):
result = numerator / denominator
result[~np.isfinite(denominator) | (denominator == 0)] = float("nan")
return result
# ---------------------------------------------------------------------------
# 3. lag_to_monthly
# ---------------------------------------------------------------------------
def lag_to_monthly(
quarterly: pd.DataFrame,
monthly_dates: pd.DatetimeIndex,
pit_lag_days: int = 90,
) -> pd.DataFrame:
"""Apply PIT lag and forward-fill quarterly fundamentals to monthly month-ends.
Each quarterly row becomes "known" only after `pit_lag_days` have elapsed
from the quarter_end date. Forward-fill means that the most recent known
quarterly data is carried forward to subsequent months until superseded.
No-leakage guarantee:
A row with quarter_end 2020-03-31 and pit_lag_days=90 becomes known
on 2020-06-29. The first monthly date at which it is visible is
2020-06-30 (the June 2020 month-end) — NOT 2020-04-30.
Parameters
----------
quarterly : pd.DataFrame
Per-ticker quarterly DataFrame; must have columns: ticker, quarter_end,
and any number of feature columns.
monthly_dates : pd.DatetimeIndex
Target month-end dates (dtype datetime64). Typically the unique dates
from panel_monthly.parquet.
pit_lag_days : int
PIT lag in calendar days (default 90).
Returns
-------
pd.DataFrame
Columns: date (month-end), ticker, plus all feature columns.
One row per (date, ticker) pair that has at least one non-NaN feature.
"""
if quarterly.empty:
return pd.DataFrame(columns=["date", "ticker"])
quarterly = quarterly.copy()
quarterly["quarter_end"] = pd.to_datetime(quarterly["quarter_end"])
# Compute the first date on which each quarterly row is visible.
quarterly["_known_from"] = quarterly["quarter_end"] + pd.Timedelta(days=pit_lag_days)
monthly_dates = pd.DatetimeIndex(sorted(monthly_dates))
feature_cols = [
c
for c in quarterly.columns
if c not in {"ticker", "quarter_end", "_known_from"} and not c.startswith("_")
]
rows: list[dict] = []
for ticker, grp in quarterly.groupby("ticker"):
grp_sorted = grp.sort_values("_known_from").reset_index(drop=True)
for month_end in monthly_dates:
# Only rows where _known_from <= month_end are visible.
visible = grp_sorted[grp_sorted["_known_from"] <= month_end]
if visible.empty:
continue
# Take the latest visible row (most recent quarter that passed PIT lag).
latest = visible.iloc[-1]
row: dict = {"date": month_end, "ticker": ticker}
for col in feature_cols:
row[col] = latest[col]
rows.append(row)
if not rows:
return pd.DataFrame(columns=["date", "ticker"] + feature_cols)
result = pd.DataFrame(rows)
result["date"] = pd.to_datetime(result["date"])
result = result.sort_values(["date", "ticker"]).reset_index(drop=True)
logger.info(
"lag_to_monthly: %d quarterly rows → %d monthly (date, ticker) pairs (pit_lag=%d days)",
len(quarterly),
len(result),
pit_lag_days,
)
return result
+312
View File
@@ -0,0 +1,312 @@
"""Configurable global-equity universe builder.
The builder combines configured BlackRock holdings sources, resolves their
tickers, applies regional filters, and removes duplicate listings.
No live API calls are made in this module — the fetcher and resolver manage their
own caching. The resolver's exchange-symbol-list lookups always hit disk cache.
"""
import logging
from datetime import date
from pathlib import Path
from typing import Any
import pandas as pd
import yaml
from src.data.blackrock_holdings_fetcher import BlackRockHoldingsFetcher
from src.data.ticker_resolver import TickerResolver
logger = logging.getLogger(__name__)
_OUTPUT_COLUMNS = [
"eodhd_ticker",
"br_ticker",
"name",
"location",
"region_bucket",
"etf_sources",
"weight_pct",
"currency",
"br_exchange",
"resolution_method",
"resolution_confidence",
]
# ---------------------------------------------------------------------------
# Config loader
# ---------------------------------------------------------------------------
def _load_config(config_path: Path) -> dict[str, Any]:
with config_path.open("r", encoding="utf-8") as fh:
return yaml.safe_load(fh)
def _configured_universe_etfs(config: dict[str, Any]) -> list[str]:
"""Return the ordered ETF list selected by the universe configuration."""
etfs_cfg = config.get("etfs", {})
if not isinstance(etfs_cfg, dict) or not etfs_cfg:
raise ValueError("The universe configuration must define at least one ETF")
selected = config.get("universe_etfs")
if selected is None:
return list(etfs_cfg)
if not isinstance(selected, list) or not selected:
raise ValueError("universe_etfs must be a non-empty list")
if not all(isinstance(etf, str) and etf.strip() for etf in selected):
raise ValueError("universe_etfs must contain only non-empty ETF names")
if len(selected) != len(set(selected)):
raise ValueError("universe_etfs must not contain duplicate ETF names")
unknown = [etf for etf in selected if etf not in etfs_cfg]
if unknown:
raise ValueError(f"Unknown universe ETF names: {unknown}")
return selected
# ---------------------------------------------------------------------------
# Region bucketing
# ---------------------------------------------------------------------------
def assign_region_bucket(location: str, config: dict[str, Any]) -> str | None:
"""Map a BlackRock 'Location' string to a region bucket via config.
Returns 'US' | 'EU' | 'JP' | 'CA' | None.
None means the location is excluded (e.g. AU, CN, HK, KR, TW, …).
Unknown locations that appear in neither gated, informational, nor excluded
sections also return None — fail-safe rather than accidentally trading
unchecked geographies.
"""
gated: dict[str, Any] = config.get("gated_regions", {})
informational: dict[str, Any] = config.get("informational_regions", {})
excluded: dict[str, Any] = config.get("excluded_regions", {})
for bucket_name, bucket_cfg in gated.items():
if location in bucket_cfg.get("locations", []):
return bucket_name
for bucket_name, bucket_cfg in informational.items():
if location in bucket_cfg.get("locations", []):
return bucket_name
# excluded_regions values may be either a list directly or a dict with a
# 'locations' key — the YAML currently uses flat lists for excluded entries.
for _group, locations in excluded.items():
loc_list: list[str] = locations if isinstance(locations, list) else locations.get("locations", [])
if location in loc_list:
return None
# Not found in any category → excluded (unknown geography, fail-safe).
return None
# ---------------------------------------------------------------------------
# De-dupe across ETF overlap
# ---------------------------------------------------------------------------
def _dedupe_etf_overlap(
df: pd.DataFrame,
etf_priority: list[str] | None = None,
) -> pd.DataFrame:
"""Remove ETF overlap according to the configured source priority."""
df = df.copy()
priority = etf_priority or list(dict.fromkeys(df["etf"].astype(str)))
etf_order = {etf: index for index, etf in enumerate(priority)}
sources_map: dict[str, str] = (
df.groupby("eodhd_ticker")["etf"]
.apply(
lambda source: ",".join(
sorted(
source.unique(),
key=lambda etf: (etf_order.get(etf, len(etf_order)), etf),
)
)
)
.to_dict()
)
source_order = df["etf"].map(lambda etf: etf_order.get(etf, len(etf_order)))
df = df.assign(_sort_key=source_order).sort_values(
["_sort_key", "etf"],
kind="stable",
)
df = df.drop_duplicates(subset="eodhd_ticker", keep="first").drop(columns="_sort_key")
df["etf_sources"] = df["eodhd_ticker"].map(sources_map)
return df.reset_index(drop=True)
# ---------------------------------------------------------------------------
# Summary printer
# ---------------------------------------------------------------------------
def _print_summary(
etf_counts: dict[str, int],
total_raw: int,
n_resolved: int,
n_unresolved: int,
n_in_scope: int,
n_excluded: int,
overlap_absorbed: int,
n_unique: int,
region_counts: dict[str, int],
output_path: Path,
build_date: str,
) -> None:
line = "=" * 80
print(line)
print(f"Global Universe Build — {build_date}")
print(line)
print("Source ETFs:")
for etf, count in etf_counts.items():
print(f" {etf:<6} fetched {count:,} equity rows")
print(f" {'TOTAL':<6} {total_raw:,} rows")
print()
pct = n_resolved / total_raw * 100 if total_raw else 0.0
print("Resolution:")
print(f" resolved: {n_resolved:,} / {total_raw:,} ({pct:.1f}%)")
print(f" unresolved: {n_unresolved:,} (see unresolved_holdings_*.csv)")
print()
print("After region filter (drop AU/CN/HK/KR/TW/IL/SG/NZ):")
print(f" in-scope: {n_in_scope:,}")
print(f" excluded: {n_excluded:,}")
print()
print("After ETF overlap removal:")
print(f" unique tickers: {n_unique:,} (overlap absorbed: {overlap_absorbed:,} names)")
print()
print("Region bucketing:")
for region, count in sorted(region_counts.items()):
label = f"{region} (gated)" if region in ("US", "EU", "JP") else f"{region} (info)"
print(f" {label:<18} {count:,}")
print(f" {'TOTAL':<18} {n_unique:,}")
print()
print(f"Saved: {output_path}")
# ---------------------------------------------------------------------------
# Main build function
# ---------------------------------------------------------------------------
def build_global_universe(
fetcher: BlackRockHoldingsFetcher | None = None,
resolver: TickerResolver | None = None,
config_path: Path | str = "config/blackrock_etfs.yaml",
output_dir: Path | str = "data/universe",
use_cached_fixtures: bool = False,
) -> pd.DataFrame:
"""End-to-end universe build.
Steps:
1. Load the selected ETFs from config
2. Fetch the selected ETFs or load their cached XML files
3. Resolve tickers via TickerResolver
4. Drop unresolved rows (already written to unresolved CSV by resolver)
5. Apply region bucketing; drop excluded regions
6. Remove ETF overlap according to configuration order
7. Save parquet to output_dir/global_msci_world_imi_{YYYYMMDD}.parquet
8. Print clean summary to stdout
"""
config_path = Path(config_path)
output_dir = Path(output_dir)
config = _load_config(config_path)
selected_etfs = _configured_universe_etfs(config)
build_date = date.today().strftime("%Y-%m-%d")
date_str = date.today().strftime("%Y%m%d")
# Step 1: Build fetcher/resolver if not provided.
if fetcher is None:
fetcher = BlackRockHoldingsFetcher(config_path=config_path)
if resolver is None:
from src.data.eodhd_client import EODHDClient
client = EODHDClient()
resolver = TickerResolver(eodhd_client=client)
# Fetch or load cached fixtures.
etf_frames: list[pd.DataFrame] = []
etf_counts: dict[str, int] = {}
for etf in selected_etfs:
if use_cached_fixtures:
raw = fetcher.load_cached(etf)
df_etf = fetcher.parse_holdings(raw, etf)
else:
df_etf = fetcher.fetch_and_parse(etf)
etf_counts[etf] = len(df_etf)
logger.info("ETF %s: %d equity rows", etf, len(df_etf))
etf_frames.append(df_etf)
if not etf_frames:
raise RuntimeError("No ETF frames loaded — check config and cache.")
raw_df = pd.concat(etf_frames, ignore_index=True)
total_raw = len(raw_df)
# Step 2: Resolve tickers (per-ETF unresolved CSVs written by resolver).
resolved_df = resolver.resolve_dataframe(raw_df, write_unresolved=True)
n_resolved = resolved_df["eodhd_ticker"].notna().sum()
n_unresolved = total_raw - n_resolved
# Step 3: Drop unresolved rows.
df = resolved_df[resolved_df["eodhd_ticker"].notna()].copy()
# Step 4: Apply region bucketing; drop excluded.
df["region_bucket"] = df["location"].apply(
lambda loc: assign_region_bucket(str(loc) if pd.notna(loc) else "", config)
)
n_in_scope = df["region_bucket"].notna().sum()
n_excluded = resolved_df["eodhd_ticker"].notna().sum() - n_in_scope
df = df[df["region_bucket"].notna()].copy()
# Step 5: De-dupe.
n_before_dedupe = len(df)
df = _dedupe_etf_overlap(df, etf_priority=selected_etfs)
n_unique = len(df)
overlap_absorbed = n_before_dedupe - n_unique
# Step 6: Finalize columns.
for col in _OUTPUT_COLUMNS:
if col not in df.columns:
df[col] = None
df = df[_OUTPUT_COLUMNS].reset_index(drop=True)
# Step 7: Save parquet.
output_dir.mkdir(parents=True, exist_ok=True)
output_path = output_dir / f"global_msci_world_imi_{date_str}.parquet"
tmp_path = output_path.with_suffix(".tmp")
try:
df.to_parquet(tmp_path, index=False)
tmp_path.replace(output_path)
except OSError as exc:
tmp_path.unlink(missing_ok=True)
raise RuntimeError(f"Failed to write universe parquet: {exc}") from exc
logger.info("Saved universe parquet: %s (%d rows)", output_path, n_unique)
# Step 8: Print summary.
region_counts: dict[str, int] = df["region_bucket"].value_counts().to_dict()
_print_summary(
etf_counts=etf_counts,
total_raw=total_raw,
n_resolved=n_resolved,
n_unresolved=n_unresolved,
n_in_scope=n_in_scope,
n_excluded=n_excluded,
overlap_absorbed=overlap_absorbed,
n_unique=n_unique,
region_counts=region_counts,
output_path=output_path,
build_date=build_date,
)
return df
+298
View File
@@ -0,0 +1,298 @@
"""Hard-excluded tickers — manually verified data-corruption blacklist.
Three exclusion modes:
ALWAYS-EXCLUDED (cutoff = None)
Ticker is removed from the universe at every panel/signal date. Used for
tickers whose entire history is corrupted or oscillating between price
regimes (LAN.US bouncing $1 ↔ $14,000 every few days, etc.).
DATE-BOUNDED (cutoff = pd.Timestamp)
Ticker is kept for rows where panel date <= cutoff and excluded for rows
where date > cutoff. Used for tickers that traded normally then went bad
on a specific date — typically EOD prices freeze or the adjusted-close
series gets retroactively corrupted after delisting (SHS.US traded
normally through 2013-04-12 then prices froze at $58.49 before later
oscillation).
RANGE-BOUNDED (cutoff = list[(start, end)])
Ticker is excluded for rows where any (start <= date <= end). Used for
ticker-reuse cases: original company traded cleanly, ticker was reused
by an unrelated company on a known reuse date, and the gap window holds
garbled/frozen data that must be excluded. Allowing re-entry once the
reused company is itself eligible (e.g. WEBM.US reused 2009-02-24,
LMS.US reused 2014-07-21).
Each entry has been manually verified by inspecting daily_returns.parquet
before adding here. The list is import-only — no automation populates it.
Consumed by src/universe.py at panel-build time, by the short anti-quality
diagnostic harness scripts/exploratory/run_short_anti_quality_dryrun.py at
panel load time (wired 2026-05-29), AND by scripts/data/build_global_daily_returns.py
at global-panel build time (wired 2026-06-06, with bounded_ranges_only=True) —
there the mask is applied per ticker BEFORE ret_d = adjusted_close.pct_change(),
so dropping a ticker-reuse Era-1 leaves the first surviving Era-2 row's return
NaN rather than a phantom cross-era spike. On that LIVE path only finite past-
window ranges apply; the always-excluded / date-bounded / open-ended entries are
SKIPPED because they exclude a symbol forever-forward and would block a FUTURE
reuse of that symbol by a current index member (live cleans bounded historical
windows, never permanently drops a name). The single-name US live script scripts/live/signal_long.py
does NOT import this list — today's IWV cross-section is a fresh EOD snapshot of
currently-listed names, so none of the aged-out delistings here can appear in it
(verified 2026-05-18: zero overlap with IWV holdings). Backtest data-hygiene
cleanup and global-panel ticker-reuse cleanup both route through this list.
Audit history:
2026-05-17: Initial entries LAN, SIE (caught the 2010-08-19 cycle blowup
in the daily-derisk diagnostic). Systematic audit then ran
against the full 2000-2026 daily_returns window using the
combined classifier in scripts/exploratory/_bad_data_combined.py
(round_trips ≥ 20 + rate_extreme ≥ 2% + min(nu, nd) ≥ 50,
split by std(log10 close) into TIER A / TIER B). project owner
approved all 37 candidates for blacklisting.
2026-05-17b: Added date-bounded exclusion mode. SHS.US added with cutoff
2013-04-12 (last legitimate trading day; prices froze post that
date before later corruption).
2026-05-29: Four date-bounded entries added (HCD/CDO/HTV/TCT) following
the R2_ILLIQ_RSI70 and R2_FROG_RSI70 short-side trade audits
(scripts/exploratory/audit_r2_*_rsi70_trades.py + the patch
script). project owner manually verified each cutoff date. Same audit
surfaced that the short-side harness was bypassing this list
entirely — fix wired into scripts/exploratory/
run_short_anti_quality_dryrun.py::_load_all_panels.
2026-05-29b: Added RANGE-BOUNDED mode for ticker-reuse gaps. RX.US
promoted to always-excluded (price anomalies throughout).
MAKO.US (Stryker acquisition 2013-12-16 → unrelated reuse
2013-12-17), WEBM.US (Cisco acquisition 2007 → reuse
2009-02-24), and LMS.US (Lamson Industries → reuse 2014-07-21)
added with explicit (start, end) gap windows so the Era 1 data
stays usable AND the reused-ticker Era 2 can re-enter once it
independently qualifies.
2026-06-06: GMIN.TO added (first non-US entry) as a REVERSED-POLARITY range-
bounded reuse: the dead-shell Era 1 (-> 2024-04-04) is excluded,
the relisted G Mining Ventures Era 2 (2024-04-05 ->) is kept.
Surfaced when the global signal panel ranked GMIN.TO top with
sigma_w_3y_local=10299 (project owner verified). Same change wired this
list into scripts/data/build_global_daily_returns.py so the global
stack honors it; verified zero overlap between the pre-existing
(US) keys and the global panel, so no collateral exclusions.
2026-06-06b: SILA.US (-> 2024-06-12) added after the GMIN.TO discovery prompted
a panel-wide sigma_w_3y_local sweep (threshold > 3.0); project owner verified
live (reliable data only from the 2024-06-13 NYSE listing). The sweep
also flagged DEC.US, BNY.US and EMEIS.PA. CACHE-REFRESH LESSON: a
delete+refetch CURED DEC.US (the 2023-12-05 split is back-adjusted in
the fresh series — clean 2018->now) and BNY.US (a stale muni-CEF
stitch was replaced by Bank of NY Mellon's full 1973-> history), so
NEITHER needs a blacklist entry. Always try a cache refresh BEFORE
blacklisting a suspected stitch — EODHD may have remapped the symbol
since the cache was written. GMIN.TO + SILA.US did NOT refresh clean
(canonical stitch / unreliable pre-listing) so they stay blacklisted.
EMEIS.PA left as-is (real splits; momentum clean; sigma self-penalizes).
"""
from __future__ import annotations
from collections.abc import Mapping
import pandas as pd
# ExclusionSpec = None | pd.Timestamp | list[(start, end)]
# None -> always excluded
# pd.Timestamp -> excluded for rows where date > cutoff (legacy)
# list[(start, end)] -> excluded for rows where any start <= date <= end
ExclusionSpec = pd.Timestamp | list[tuple[pd.Timestamp, pd.Timestamp]] | None
HARD_EXCLUDED_TICKERS: Mapping[str, ExclusionSpec] = {
# ---------------------------------------------------------------
# TIER A — persistent corruption (std_logP ≥ 1.0)
# Price distribution is bimodal/multi-modal across the entire series.
# ---------------------------------------------------------------
"AEZ.US": None,
"ATT.US": None,
"BMW.US": None,
"BYH.US": None,
"CBE.US": None,
"ENA.US": None,
"ENP.US": None,
"EXO.US": None,
"ICT.US": None,
"ISA.US": None,
"KBL.US": None,
"LAN.US": None, # caught 2010-08-19 daily-derisk blowup
"NST.US": None,
"PGS.US": None,
"RX.US": None, # 2026-05-29b: price anomalies throughout (project owner verified)
"SIE.US": None, # caught 2010-08-19 daily-derisk blowup
"SNG.US": None,
"SWD.US": None,
"TRZ.US": None,
"UIC.US": None,
"XBKS.US": None,
# ---------------------------------------------------------------
# TIER B — sporadic corruption embedded in real series (std_logP < 1.0)
# Real tickers with isolated bad-data days that skew daily compounding
# inside a held cycle. project owner flagged for safety.
# ---------------------------------------------------------------
"ATN.US": None,
"CFC.US": None,
"CGE.US": None,
"CGP.US": None,
"CLE.US": None,
"CRG.US": None,
"EDO.US": None,
"HMB.US": None,
"KRI.US": None,
"NFP.US": None,
"NLCS.US": None,
"NLG.US": None,
"NRL.US": None,
"NSE.US": None,
"PVX.US": None,
"SRX.US": None,
"UCM.US": None,
# ---------------------------------------------------------------
# DATE-BOUNDED — real ticker with a specific last-tradeable date
# Use a pd.Timestamp cutoff so the ticker stays eligible up to that
# date and is dropped afterwards.
# ---------------------------------------------------------------
"SHS.US": pd.Timestamp("2013-04-12"), # traded normally → frozen 4/15 → later oscillation
"HCD.US": pd.Timestamp("2009-06-15"), # 2026-05-29 audit (project owner verified)
"CDO.US": pd.Timestamp("2002-04-12"), # 2026-05-29 audit (project owner verified)
"HTV.US": pd.Timestamp("2009-06-04"), # 2026-05-29 audit (project owner verified)
"TCT.US": pd.Timestamp("2006-03-31"), # 2026-05-29 audit (project owner verified)
# ---------------------------------------------------------------
# RANGE-BOUNDED — ticker-reuse gaps
# Era 1 data (before range start) and Era 2 data (after range end)
# are kept; the gap window holds reused-ticker garbled/frozen data.
# ---------------------------------------------------------------
"MAKO.US": [(pd.Timestamp("2013-12-17"), pd.Timestamp.max)],
# Era 1 = MAKO Surgical (Stryker close 2013-12-16). Era 2 ticker reuse
# began 2013-12-17 at $0.15 (unrelated company). Open-ended end —
# tighten to a re-entry date once Era 2 stabilizes and qualifies
# independently (currently still sub-$1M ADV through most of the
# post-2013 series).
"WEBM.US": [(pd.Timestamp("2007-06-01"), pd.Timestamp("2009-02-23"))],
# Era 1 = WebEx Communications (Cisco acquisition closed mid-2007).
# Last in_universe month 2007-05-31. Ticker reused 2009-02-24 per
# project owner verification — gap covers the dormant/garbled window.
"LMS.US": [(pd.Timestamp("2007-11-01"), pd.Timestamp("2014-07-20"))],
# Era 1 = Lamson Industries. Last in_universe month 2007-10-31.
# Ticker reused 2014-07-21 per project owner verification.
"SILA.US": [(pd.Timestamp.min, pd.Timestamp("2024-06-12"))],
# SILA REALTY TRUST listed on NYSE 2024-06-13 (formerly a non-traded REIT).
# Era 1 (-> 2024-06-12) is pre-listing data project owner could not verify live. The
# original cache stitched it as a $0.0001 shell (+52139 ret_d phantom); a cache
# refresh later swapped that for sparse pre-listing marks (adj 6.56..26, a
# x2.86 jump 2024-03-14) — still unreliable, so the boundary stays at project owner's
# verified reliable-data start 2024-06-13. Post-boundary is clean (max |ret_d|
# 0.20). Era 2 holds only ~102 weeks as of 2026-05, so sigma_w_3y is NaN
# (needs 104w) and self-heals ~late June 2026. project owner verified 2026-06-06.
# (Unlike DEC.US/BNY.US, a refresh did NOT clean Era 1 — hence the blacklist.)
"GMIN.TO": [(pd.Timestamp.min, pd.Timestamp("2024-04-04"))],
# REVERSED-POLARITY reuse: the GARBAGE era is FIRST here (unlike WEBM/LMS/MAKO).
# Era 1 (-> 2024-04-04) = a defunct shell pinned at the C$0.0001 min tick for
# 899 trading days (2019-10-30 .. 2024-04-04). Era 2 (2024-04-05 ->) = G MINING
# VENTURES CORP, which relisted on the reused TSX symbol at ~C$2.23. EODHD
# stitched the two, producing a phantom +4,459,900% ret_d on 2024-04-05
# (8.92/0.0002 - 1 = 44599) that blew sigma_w_3y_local to 10299. The three
# auto-detectors all miss it: frozen-run needs byte-identical VOLUME (volume
# churned daily), combined-evidence needs that frozen run, and round-trip needs
# a <=-90% reversal (the jump is a PERMANENT step, not a round trip). Excluding
# Era 1 drops those rows before ret_d is computed, so the boundary return is
# NaN and the kept Era-2 sigma is sane (~0.61). project owner green-lit 2026-06-06.
# ---------------------------------------------------------------
# STRUCTURAL — non-common-stock instruments mislabeled "Common Stock"
# ---------------------------------------------------------------
# 2026-06-05: Surfaced by the QMJ fundamentals pull — these returned
# metadata-only EODHD shells with no equity financials because they are NOT
# common stock: SPAC warrants/units, preferreds, trust certificates, a bond
# (NRUC=Notes), an ETF (WCMI), a when-issued line (XBIT-V). EODHD's Type
# field mislabels them "Common Stock", so the universe Common-Stock filter
# misses them. Always-excluded for EVERY strategy — they are not the
# underlying common equity for a fundamental OR a technical book.
# NOTE: the 45 REAL companies in the same shell set (foreign listings +
# pre-2018 delistings: TFCF/Fox, MER/Merrill, ZMH/Zimmer, KONE, Sberbank,
# ...) are deliberately NOT here — they belong in the price universe and are
# dropped only from the QMJ cross-section by its min-fundamentals-coverage
# gate (project owner 2026-06-05). See project_qmj_diagnostic_track.
# -- warrants / when-issued --
"JIH-WS.US": None, "JOBY-WS.US": None, "KODK-WS.US": None, "KODK-WS-A.US": None,
"LGC-WS.US": None, "LHC-WS.US": None, "MP-WS.US": None, "MSGE-W.US": None,
"MSGS-W.US": None, "NFH-WS.US": None, "NSCO-WS.US": None, "NUVB-WS.US": None,
"OPFI-WS.US": None, "OXY-WT.US": None, "PL-WT.US": None, "PSTH-WS.US": None,
"QS-WS.US": None, "RBAC-WS.US": None, "SEAH-WS.US": None, "SFTW-WS.US": None,
"SOAC-WS.US": None, "TIMB-W.US": None, "TRNE-WS.US": None, "UTZ-WS.US": None,
"UWMC-WS.US": None, "VVNT-WS.US": None, "VYGG-WS.US": None, "WFC-WS.US": None,
"K-W.US": None, "XBIT-V.US": None,
# -- units --
"JIH-U.US": None, "LGC-U.US": None, "PSTH-U.US": None, "SEAH-U.US": None,
"SOAC-U.US": None, "TRNE-U.US": None, "RCF-UN.US": None,
# -- preferreds / trust certificates --
"JPMPRD.US": None, "JXN-P-A.US": None, "NEE-P-T.US": None, "NEEPRR.US": None,
"PMT-P-C.US": None, "SCE-PM.US": None, "SEAL-P-B.US": None, "TEN-P-E.US": None,
"ISF-CL.US": None, "PJS-CL.US": None,
# -- non-equity (bond / ETF / trust) --
"NRUC.US": None, "WCMI.US": None, "THIR.US": None,
}
def apply_hard_exclusion_mask(
panel: pd.DataFrame, *, bounded_ranges_only: bool = False
) -> pd.Series:
"""Boolean mask (True = exclude) for the panel's (ticker, date) rows.
Honors three exclusion modes:
- ALWAYS-EXCLUDED (spec=None) — every row for the ticker
- DATE-BOUNDED (spec=pd.Timestamp) — rows where date > cutoff
- RANGE-BOUNDED (spec=list[(start, end)]) — rows where any range matches
Caller uses `panel = panel[~mask]` or analogous to drop.
The panel must have columns 'ticker' and 'date'.
Parameters
----------
bounded_ranges_only : bool, default False
When True, apply ONLY finite RANGE-BOUNDED specs — those whose every
sub-range has a fixed end (end < pd.Timestamp.max). ALWAYS-EXCLUDED
(None), DATE-BOUNDED (> cutoff), and OPEN-ENDED ranges (end ==
pd.Timestamp.max) are SKIPPED because each excludes a symbol indefinitely
FORWARD, which would wrongly block a future ticker REUSE by an unrelated
company. The live/global path passes True so a manual entry can only ever
clean a finite PAST window of a *current* index member — it can never
permanently exclude a symbol. The backtest leaves this False: there the
always-excludes are correct (survivorship-limited US history with no
"current index" to trust, where reuse is settled in the past).
"""
out = pd.Series(False, index=panel.index)
if "ticker" not in panel.columns or "date" not in panel.columns:
raise ValueError("panel must have 'ticker' and 'date' columns")
dates = pd.to_datetime(panel["date"])
for ticker, spec in HARD_EXCLUDED_TICKERS.items():
ticker_mask = panel["ticker"] == ticker
if spec is None:
if bounded_ranges_only:
continue # forever-all-dates — never permanently exclude on live
out |= ticker_mask
elif isinstance(spec, pd.Timestamp):
if bounded_ranges_only:
continue # date-bounded is open-ended forward — reuse hazard on live
out |= ticker_mask & (dates > spec)
elif isinstance(spec, list):
for start, end in spec:
if bounded_ranges_only and pd.Timestamp(end) >= pd.Timestamp.max:
continue # open-ended range — forever forward — reuse hazard on live
out |= ticker_mask & (dates >= pd.Timestamp(start)) & (dates <= pd.Timestamp(end))
else:
raise TypeError(
f"Unknown HARD_EXCLUDED_TICKERS spec for {ticker}: {type(spec).__name__}"
)
return out
+931
View File
@@ -0,0 +1,931 @@
"""Paper-faithful Asness-Frazzini-Pedersen (AFP) "Quality Minus Junk" score.
Construction reference: `notes/tier-1/asness-frazzini-pedersen.md` §4-§5.
CRITICAL FRAMING — this is an OUT-OF-SAMPLE test (window 2018-2026, after AFP's
2012 sample end). The construction matches the paper EXACTLY; there are no
"improvements" or neutralizations. ROE is computed pure-paper (NI / BE) even
when book equity is negative — the rank-z + 6-measure averaging + buyback-
rewarding Payout pillar structurally outvote the single pathological measure
(see `project_qmj_diagnostic_track.md`). Negative-equity names (MCD/HD/AZO/...)
are handled BY the construction: LEV is debt/assets, Altman-Z uses *market*
equity, Ohlson-O has the OENEG dummy — no bespoke patch.
Quality = z(average of available pillar scores). The shipped live/default
variant adds R&D expense / market equity as a fifth optional pillar.
Core standardisation (AFP §5): for a raw measure x over a cross-section,
z(x) = (rank(x) - mean(rank)) / std(rank) # z-score the RANK, not x
ascending so HIGH = good. Each pillar = re-z-score of the simple average of its
member z-scores. Missing-data rule: average over the AVAILABLE member z-scores
per stock (do NOT zero-fill). Min-coverage gate: a stock needs >= 1 non-missing
member in EACH of the 4 pillars (and >= 10 of the ~16 fundamental measures
overall) to receive a Quality score; below that it gets NaN Quality and drops
out of the QMJ cross-section while staying in the price universe.
FLOW vs STOCK (AFP appendix A1): "unless specified, XpressFeed data items refer
to ANNUAL items." FLOW variables (net_income, revenue, cogs, depreciation,
capex, operating_income, pretax_income) are therefore aggregated to TTM (a
trailing-4-quarter sum, requiring 4 consecutive quarters else NaN). STOCK
variables (total_assets, equity, retained_earnings, total_liabilities,
current/{assets,liabilities}, cash, short_term_debt, lt_debt, minority_interest,
preferred_stock) are used point-in-time (latest quarter). EVOL is the one
exception: it uses QUARTERLY ROE.
Fidelity caveats (flagged for review — see CAVEAT comments inline):
- BAB / IVOL: computed by src/data/qmj_risk.py from daily returns + the market
proxy as the real Frazzini-Pedersen ex-ante beta (rho * sigma_i/sigma_m on
3-day overlapping returns) and the residual-vol IVOL (std of beta-adjusted
residual, skip last day). There is NO panel-column/total-vol fallback for
the Safety members.
- FUTL (Ohlson): AFP FUTL = pretax_income / total_liabilities (PT/LT only).
- CPI: Ohlson-O deflates adjusted assets by a CPI index. The real series
(FRED CPIAUCSL) is loaded from data/raw/macro/cpiaucsl.csv if present;
absent, a constant fallback (=100) is used with a logged warning. The
deflator enters O only through a log term, so a constant is a level shift
that the cross-sectional rank-z absorbs — but it is NOT the faithful series.
"""
from __future__ import annotations
import json
import logging
from dataclasses import dataclass, field
from pathlib import Path
import numpy as np
import pandas as pd
from src.data.fundamentals import (
extract_pit_shares,
lag_to_monthly,
parse_fundamentals_response,
)
logger = logging.getLogger(__name__)
_QUARTERS_PER_YEAR = 4
_GROWTH_LAG_Q = 20 # 5 years
_PIT_LAG_DAYS = 90
_PIT_LAG_DAYS_ANNUAL = 180 # FF 6-month convention for annual accounting
# freq -> periods-per-year (PPY). 4 = quarterly (TTM = 4-period sum, current
# default); 1 = annual (the annual flow IS the TTM, so the "TTM" is identity).
_PPY_BY_FREQ = {"quarterly": 4, "annual": 1}
# Member -> pillar membership. The averaging respects only non-missing members.
_PROFITABILITY = ["gpoa", "roe", "roa", "cfoa", "gmar", "acc"]
_GROWTH = ["g_gpoa", "g_roe", "g_roa", "g_cfoa", "g_gmar", "g_acc"]
_SAFETY = ["bab", "ivol", "lev", "o_score", "z_score", "evol"]
_PAYOUT = ["eiss", "diss", "npop"]
_RD = ["rd_me"]
_ALL_MEASURES = _PROFITABILITY + _GROWTH + _SAFETY + _PAYOUT
# pillar-name -> member list, for the config-driven coverage gate.
_PILLAR_MEMBERS = {
"profitability": _PROFITABILITY,
"growth": _GROWTH,
"safety": _SAFETY,
"payout": _PAYOUT,
"rd": _RD,
}
_STRICT_REQUIRE_PILLARS: tuple[str, ...] = ("profitability", "growth", "safety", "payout")
# LIVE coverage gate (shipped 2026-06-07): Growth is OPTIONAL. A name missing the
# ENTIRE Growth pillar (no 5-year history — typically recent listings or gappy
# fundamentals) is still scored on the other three pillars. This was the original
# design intent; a strict-vs-relaxed US-only A/B (notes/diagnostics/
# qmj_gate_relax_growth_2026-06-07.md) showed relaxed ~0.06 Sortino / 0.9pt CAGR
# BELOW strict on the 2018-26 window with identical MaxDD — shipped on project owner
# green-light over the A/B (coverage/intent call: +71k scores, +15.1% coverage).
# _STRICT_REQUIRE_PILLARS is kept for the strict-gate regression + as the all-4
# reference. The Quality COMPOSITE is unchanged: it still averages all available
# pillars (Growth included when present); only the eligibility gate is relaxed.
_LIVE_REQUIRE_PILLARS: tuple[str, ...] = ("profitability", "safety", "payout")
_MIN_MEASURES_OVERALL = 10 # >= ~10 of the ~16 fundamental measures
# Fama-French financial-sector exclusion (shipped 2026-06-10). Fama-French exclude
# SIC 6000-6999 (financials) from factor portfolios because the accounting-based
# measures are undefined or distorted for banks/insurers/holding companies: there
# is no COGS (gross-profit measures), no current/non-current split (working-capital
# accruals, Altman-Z), and debt/assets leverage + Ohlson-O are meaningless when
# deposits/reserves are not "debt". We follow the convention via the modern GICS
# analogue (GicSector == "Financials"; Real Estate is its own GICS sector and is
# NOT excluded here). Excluded names get NaN quality (the veto NaN-keeps them) and
# are labelled "na_financial" in the live picks. Set False to restore scoring of
# financials (the prior behaviour, where they mostly fell out via the coverage gate).
_EXCLUDE_FINANCIALS = True
_FINANCIAL_GIC_SECTOR = "Financials"
def gic_sector(data: dict) -> str | None:
"""GICS sector tag from an EODHD fundamentals payload (General.GicSector)."""
general = data.get("General") or {}
sector = general.get("GicSector")
return str(sector) if sector else None
def is_financial(data: dict) -> bool:
"""True when the name is a GICS Financials member (Fama-French exclusion)."""
return gic_sector(data) == _FINANCIAL_GIC_SECTOR
def _ppy_for_freq(freq: str) -> int:
ppy = _PPY_BY_FREQ.get(freq)
if ppy is None:
raise ValueError(f"QMJ: unknown freq {freq!r} (expected 'quarterly' or 'annual')")
return ppy
def _coverage_gate(
z: pd.DataFrame,
require_pillars: tuple[str, ...],
min_measures_overall: int,
all_measures: list[str] | None = None,
) -> pd.Series:
"""Paper-faithful coverage gate: required-pillar presence AND a measure floor.
`require_pillars` is the set of pillars that must each have >=1 non-missing
member z-score; an empty set imposes no per-pillar requirement (pure-paper:
average whatever is available). `min_measures_overall` is the overall
non-missing-member floor. The strict default reproduces the historical gate
(all four pillars + 10 measures) byte-for-byte.
"""
measures = all_measures or _ALL_MEASURES
n_measures = z[measures].notna().sum(axis=1)
gate = n_measures >= min_measures_overall
for pillar in require_pillars:
members = _PILLAR_MEMBERS[pillar]
gate = gate & z[members].notna().any(axis=1)
return gate
@dataclass
class QMJConfig:
"""Injectable knobs for QMJ construction.
daily_returns_path / market_proxy_path feed the real Frazzini-Pedersen
beta + residual IVOL (src/data/qmj_risk.py). bab_ivol lets a caller inject a
precomputed [date, ticker, bab, ivol] frame (tests/sanity) to skip the
daily-return scan.
"""
start: str = "2018-01-01"
freq: str = "quarterly" # "quarterly" (PPY=4, default) or "annual" (PPY=1)
pit_lag_days: int = _PIT_LAG_DAYS
daily_returns_path: str = "data/processed/daily_returns.parquet"
market_proxy_path: str = "data/processed/market_proxy_daily.parquet"
cpi_csv: str = "data/raw/macro/cpiaucsl.csv"
min_measures_overall: int = _MIN_MEASURES_OVERALL
# Growth-optional live gate (2026-06-07). Pass _STRICT_REQUIRE_PILLARS to
# restore the all-4 strict gate.
require_pillars: tuple[str, ...] = _LIVE_REQUIRE_PILLARS
universe: list[str] | None = field(default=None) # None => all panel US names
bab_ivol: pd.DataFrame | None = field(default=None)
# Shipped live/default variant: add positive R&D expense / market equity as
# a fifth optional pillar. Set False to reproduce paper-faithful AFP QMJ.
add_rd_pillar: bool = True
# ---------------------------------------------------------------------------
# Rank-z standardisation (AFP §5)
# ---------------------------------------------------------------------------
def rank_z(x: pd.Series) -> pd.Series:
"""z(x) = (rank(x) - mean(rank)) / std(rank), ascending, HIGH = good.
Ranks are average-rank (ties shared). NaN inputs stay NaN and are excluded
from the rank mean/std. A degenerate cross-section (<2 finite obs or zero
rank dispersion) returns all-NaN.
"""
r = x.rank(method="average", na_option="keep")
finite = r.dropna()
if len(finite) < 2:
return pd.Series(np.nan, index=x.index)
mu = finite.mean()
sd = finite.std(ddof=1)
if not np.isfinite(sd) or sd == 0:
return pd.Series(np.nan, index=x.index)
return (r - mu) / sd
def _pillar_score(z_members: pd.DataFrame, members: list[str]) -> pd.Series:
"""Average available member z-scores per row, then re-rank-z the average.
Available-member average: do NOT zero-fill missing members (AFP missing-data
rule). Rows with no available member get NaN, which propagates out of the
re-z step.
"""
present = [m for m in members if m in z_members.columns]
if not present:
return pd.Series(np.nan, index=z_members.index)
avg = z_members[present].mean(axis=1, skipna=True)
return rank_z(avg)
# ---------------------------------------------------------------------------
# CPI loader (Ohlson-O deflator)
# ---------------------------------------------------------------------------
def load_cpi(cpi_csv: str | Path) -> pd.Series:
"""Load a date-indexed CPI series from a CSV (columns: date,value).
Returns a monotone date-indexed float Series. If the file is absent a
constant-100 stub is returned with a warning — the deflator enters Ohlson-O
only inside a log term, so a constant is a level shift the cross-sectional
rank-z absorbs, but it is NOT the faithful FRED CPIAUCSL series.
"""
path = Path(cpi_csv)
if not path.exists():
logger.warning(
"load_cpi: CPI file %s absent — using constant=100 fallback "
"(NON-FAITHFUL; source FRED CPIAUCSL into this path). TODO",
path,
)
idx = pd.date_range("1990-01-01", "2030-01-01", freq="MS")
return pd.Series(100.0, index=idx, name="cpi")
df = pd.read_csv(path)
cols = {c.lower(): c for c in df.columns}
date_col = cols.get("date", df.columns[0])
val_col = cols.get("value", df.columns[-1])
s = pd.Series(
pd.to_numeric(df[val_col], errors="coerce").to_numpy(),
index=pd.to_datetime(df[date_col]),
name="cpi",
)
return s[s.index.notna()].sort_index()
def _cpi_at(cpi: pd.Series, when: pd.Timestamp) -> float:
"""As-of CPI value (last observation <= when); first obs if before start."""
prior = cpi[cpi.index <= when]
if len(prior):
return float(prior.iloc[-1])
return float(cpi.iloc[0]) if len(cpi) else 100.0
# ---------------------------------------------------------------------------
# Per-ticker quarterly measure computation
# ---------------------------------------------------------------------------
def _ttm(values: np.ndarray, periods_per_year: int = _QUARTERS_PER_YEAR) -> np.ndarray:
"""Trailing-1-year SUM (TTM) over `periods_per_year` consecutive periods.
Input is one ticker's per-period series in chronological order. The first
(PPY-1) periods are NaN (insufficient history); a NaN in any component
period propagates to NaN. PPY=1 (annual) is the identity: the annual flow
already IS the trailing-year sum.
"""
s = pd.Series(values)
return s.rolling(periods_per_year, min_periods=periods_per_year).sum().to_numpy()
def _lag(values: np.ndarray, k: int) -> np.ndarray:
"""k-period lag with NaN padding at the head."""
out = np.full(len(values), np.nan)
if len(values) > k:
out[k:] = values[:-k]
return out
def _div(n: np.ndarray, d: np.ndarray) -> np.ndarray:
with np.errstate(invalid="ignore", divide="ignore"):
r = n / d
r[~np.isfinite(d) | (d == 0)] = np.nan
return r
def compute_quarterly_measures(
quarterly: pd.DataFrame, periods_per_year: int = _QUARTERS_PER_YEAR
) -> pd.DataFrame:
"""Compute all per-period, ticker-local QMJ measures (pre cross-section).
`periods_per_year` (PPY) parameterises the accounting frequency: 4 =
quarterly (default, current behaviour), 1 = annual. FLOW inputs (net_income,
revenue, cogs, depreciation, capex, operating_income, pretax_income) are
aggregated to TTM (trailing-PPY-period sum; PPY=1 is the identity); STOCK
inputs are point-in-time. Working capital uses the AFP-refined definition and
ΔWC is the trailing-year (PPY-period) change. Growth uses a 5*PPY-period lag,
NPOP a 5*PPY-period window, DISS a PPY-period lag. EVOL is frequency-aware:
quarterly uses std of quarterly ROE (60q, >=12 obs; else annual ROE 5y),
annual uses std of annual ROE over the last 5 fiscal years (>=5 obs).
Columns are oriented HIGH = good. The cross-sectional / ME-dependent measures
(o_score, z_score) are completed in build_qmj_panel once ME is available.
"""
if quarterly.empty:
return quarterly.copy()
ppy = periods_per_year
growth_lag = 5 * ppy
npop_window = 5 * ppy
df = quarterly.copy().sort_values(["ticker", "quarter_end"]).reset_index(drop=True)
if "research_development" not in df.columns:
df["research_development"] = np.nan
# STOCK (point-in-time) inputs.
ta = df["total_assets"].to_numpy(float)
eq = df["equity"].to_numpy(float)
pref = df["preferred_stock"].to_numpy(float)
minint = df["minority_interest"].to_numpy(float)
lt_debt = df["lt_debt"].to_numpy(float)
st_debt = df["short_term_debt"].to_numpy(float)
ca = df["current_assets"].to_numpy(float)
cl = df["current_liabilities"].to_numpy(float)
cash = df["cash"].to_numpy(float)
# book_equity = shareholders' equity - preferred (PURE PAPER, as-is even <0).
book_equity = eq - pref
df["book_equity"] = book_equity
# TTM FLOW aggregates, computed per ticker (4 consecutive quarters).
ttm_cols = {
"ttm_net_income": "net_income",
"ttm_revenue": "revenue",
"ttm_cogs": "cogs",
"ttm_depreciation": "depreciation",
"ttm_capex": "capex",
"ttm_operating_income": "operating_income",
"ttm_pretax_income": "pretax_income",
"ttm_research_development": "research_development",
}
for out_c in ttm_cols:
df[out_c] = np.nan
# Refined working capital (TXP omitted: not in EODHD) and its ANNUAL change.
# WC = current_assets - current_liabilities - cash + short_term_debt
wc_refined = ca - cl - cash + st_debt
df["_wc_refined"] = wc_refined
df["wc_refined"] = wc_refined # carried through lag_to_monthly for Altman-Z
df["_dwc"] = np.nan # ΔWC = WC_t - WC_{t-4q} (ANNUAL change)
for _t, grp in df.groupby("ticker"):
idx = grp.index.to_numpy()
for out_c, src in ttm_cols.items():
df.loc[idx, out_c] = _ttm(grp[src].to_numpy(float), ppy)
df.loc[idx, "_dwc"] = grp["_wc_refined"].to_numpy(float) - _lag(
grp["_wc_refined"].to_numpy(float), ppy
)
ttm_ni = df["ttm_net_income"].to_numpy(float)
ttm_rev = df["ttm_revenue"].to_numpy(float)
ttm_cogs = df["ttm_cogs"].to_numpy(float)
ttm_dep = df["ttm_depreciation"].to_numpy(float)
ttm_capex = df["ttm_capex"].to_numpy(float)
dwc = df["_dwc"].to_numpy(float)
ttm_gp = ttm_rev - ttm_cogs # TTM gross profit
capex_abs = np.abs(ttm_capex)
cf = ttm_ni + ttm_dep - dwc - capex_abs # CFOA numerator
mwcpd = ttm_dep - dwc # ACC numerator (DP - ΔWC), HIGH = good
df["_gp"] = ttm_gp
df["_cf"] = cf
df["_mwcpd"] = mwcpd
# --- Profitability (TTM flows / point-in-time stocks; HIGH = good) ---
df["gpoa"] = _div(ttm_gp, ta)
df["roe"] = _div(ttm_ni, book_equity) # PURE PAPER even when BE < 0
df["roa"] = _div(ttm_ni, ta)
df["cfoa"] = _div(cf, ta)
df["gmar"] = _div(ttm_gp, ttm_rev)
# ACC = (DP - ΔWC)/AT, HIGH = good (AFP: high accruals quality = good).
df["acc"] = _div(mwcpd, ta)
# --- Growth (5yr = 5*PPY-period prior): Δnumerator / lagged denominator. ---
g_cols = {
"g_gpoa": (ttm_gp, ta),
"g_roe": (ttm_ni, book_equity),
"g_roa": (ttm_ni, ta),
"g_cfoa": (cf, ta),
"g_gmar": (ttm_gp, ttm_rev),
"g_acc": (mwcpd, ta),
}
for name in g_cols:
df[name] = np.nan
for _t, grp in df.groupby("ticker"):
idx = grp.index.to_numpy()
n = len(idx)
if n <= growth_lag:
continue
for name, (num, den) in g_cols.items():
sub_num = num[idx]
sub_den = den[idx]
lagged_num = _lag(sub_num, growth_lag)
lagged_den = _lag(sub_den, growth_lag)
with np.errstate(invalid="ignore", divide="ignore"):
g = (sub_num - lagged_num) / lagged_den
g[~np.isfinite(lagged_den) | (lagged_den == 0)] = np.nan
df.loc[idx, name] = g
# --- Safety: LEV = -(LT + ST + minority + preferred)/AT (HIGH = good). ---
total_debt = lt_debt + st_debt + minint + pref
df["_total_debt"] = total_debt
df["lev"] = -_div(total_debt, ta)
# TOTD for DISS = LT + ST + minority + preferred (same aggregate as LEV num).
df["_totd"] = total_debt
# --- Safety: EVOL (frequency-aware). Quarterly (PPY=4): -std(QUARTERLY ROE,
# trailing 60q, >=12 obs); else -std(ANNUAL ROE over trailing 5 fiscal years,
# >=5 obs). Annual (PPY=1): -std(ANNUAL ROE over the last 5 fiscal-year rows,
# >=5 obs) — the paper's explicit annual branch. Per-period ROE uses
# per-period net income / book_equity (NOT ttm).
df["evol"] = np.nan
q_roe = _div(df["net_income"].to_numpy(float), book_equity)
df["_q_roe"] = q_roe
for _t, grp in df.groupby("ticker"):
idx = grp.index.to_numpy()
roe_q = grp["_q_roe"].to_numpy(float)
out = np.full(len(idx), np.nan)
for i in range(len(idx)):
if ppy == 1:
ann = roe_q[max(0, i - 4) : i + 1]
ann = ann[np.isfinite(ann)]
if len(ann) >= 5:
out[i] = -np.std(ann, ddof=1)
continue
window = roe_q[max(0, i - 59) : i + 1]
window = window[np.isfinite(window)]
if len(window) >= 12:
out[i] = -np.std(window, ddof=1)
else:
ann = roe_q[max(0, i - 19) : i + 1 : ppy]
ann = ann[np.isfinite(ann)]
if len(ann) >= 5:
out[i] = -np.std(ann, ddof=1)
df.loc[idx, "evol"] = out
# --- Payout: EISS computed in build_qmj_panel (PIT shares). DISS / NPOP. ---
# DISS = -1yr % change in TOTD (PPY-period lag).
df["diss"] = np.nan
df["npop"] = np.nan
for _t, grp in df.groupby("ticker"):
idx = grp.index.to_numpy()
totd = grp["_totd"].to_numpy(float)
n = len(idx)
if n > ppy:
lag_totd = _lag(totd, ppy)
with np.errstate(invalid="ignore", divide="ignore"):
pct = (totd - lag_totd) / lag_totd
pct[~np.isfinite(lag_totd) | (lag_totd == 0)] = np.nan
df.loc[idx, "diss"] = -pct
# NPOP = Σ_5y(per-period NI - ΔBE) / Σ_5y(per-period gross profit), the
# 5*PPY-period window.
ni_q = grp["net_income"].to_numpy(float)
gp_q = grp["revenue"].to_numpy(float) - grp["cogs"].to_numpy(float)
be_q = grp["book_equity"].to_numpy(float)
dbe = np.full(n, np.nan)
dbe[1:] = np.diff(be_q)
net_payout = ni_q - dbe
npop = np.full(n, np.nan)
for i in range(n):
lo = i - npop_window + 1
if lo < 0:
continue
np_win = net_payout[lo : i + 1]
gp_win = gp_q[lo : i + 1]
if np.isfinite(np_win).sum() < npop_window // 2:
continue
denom = np.nansum(gp_win)
if denom != 0 and np.isfinite(denom):
npop[i] = np.nansum(np_win) / denom
df.loc[idx, "npop"] = npop
return df
# ---------------------------------------------------------------------------
# Ohlson-O & Altman-Z (need market cap / CPI — computed at monthly cross-section)
# ---------------------------------------------------------------------------
def ohlson_o_score(
total_assets: float,
total_liabilities: float,
short_term_debt: float,
lt_debt: float,
current_assets: float,
current_liabilities: float,
ttm_net_income: float,
ttm_net_income_prior: float,
ttm_pretax_income: float,
book_equity: float,
market_cap: float,
cpi: float,
) -> float:
"""AFP/Ohlson(1980) O-Score. Returns the RAW O (high = high bankruptcy prob).
The Safety member is -O (negated in build_qmj_panel). Coefficients are the
exact Ohlson(1980) values per the AFP appendix.
AFP definitions: ADJASSET = TA + 0.1*(ME - BE); TLTA = DEBT(DLC+DLTT)/ADJASSET
(DEBT, not total liabilities); WCTA = (CA - CL)/ADJASSET (simple WC here);
NITA = TTM NI / TA (NOT /ADJASSET); FUTL = TTM pretax income / total
liabilities (PT/LT only, no depreciation); INTWO = 1 if TTM NI < 0 both years.
"""
if not np.isfinite(total_assets) or total_assets == 0:
return np.nan
ta_adj = total_assets + 0.1 * (market_cap - book_equity)
if not np.isfinite(ta_adj) or ta_adj <= 0 or cpi <= 0:
return np.nan
if not np.isfinite(total_liabilities) or total_liabilities == 0:
return np.nan
if not np.isfinite(current_assets) or current_assets == 0:
return np.nan
debt = short_term_debt + lt_debt
if not np.isfinite(debt):
return np.nan
tlta = debt / ta_adj
wcta = (current_assets - current_liabilities) / ta_adj
clca = current_liabilities / current_assets
oeneg = 1.0 if total_liabilities > total_assets else 0.0
nita = ttm_net_income / total_assets
futl = ttm_pretax_income / total_liabilities
intwo = 1.0 if (ttm_net_income < 0 and ttm_net_income_prior < 0) else 0.0
denom_chin = abs(ttm_net_income) + abs(ttm_net_income_prior)
chin = (ttm_net_income - ttm_net_income_prior) / denom_chin if denom_chin != 0 else 0.0
o = (
-1.32
- 0.407 * np.log(ta_adj / cpi)
+ 6.03 * tlta
- 1.43 * wcta
+ 0.0757 * clca
- 1.72 * oeneg
- 2.37 * nita
- 1.83 * futl
+ 0.285 * intwo
- 0.521 * chin
)
return float(o)
def altman_z_score(
working_capital: float,
retained_earnings: float,
ttm_operating_income: float,
market_cap: float,
ttm_revenue: float,
total_assets: float,
) -> float:
"""AFP form of Altman(1968) Z-Score. HIGH = safe.
Z = (1.2*WC + 1.4*RE + 3.3*EBIT + 0.6*ME + Sales) / TA
WC = refined working capital (CA - CL - cash + ST debt); RE = retained
earnings; EBIT = TTM operating income; ME = market cap; Sales = TTM revenue;
TA = total assets. (Altman-canonical uses simple CA - CL; AFP/this build
pass the refined WC consistent with the profitability section.)
"""
if not np.isfinite(total_assets) or total_assets == 0:
return np.nan
z = (
1.2 * working_capital
+ 1.4 * retained_earnings
+ 3.3 * ttm_operating_income
+ 0.6 * market_cap
+ ttm_revenue
) / total_assets
return float(z)
# ---------------------------------------------------------------------------
# Market-cap derivation (ME = month-end close × PIT shares)
# ---------------------------------------------------------------------------
def derive_market_cap(
pit_shares: pd.Series,
monthly_dates: pd.DatetimeIndex,
close_by_date: pd.Series,
pit_lag_days: int = _PIT_LAG_DAYS,
) -> pd.Series:
"""ME at each monthly date = month-end close × PIT-aligned shares.
Shares are PIT-aligned with the same lag convention as fundamentals: a
shares observation dated quarter_end becomes known after pit_lag_days, then
forward-filled. close_by_date is a date-indexed close series for one ticker.
Returns a date-indexed ME Series over monthly_dates (NaN where unknown).
"""
out = pd.Series(np.nan, index=pd.DatetimeIndex(monthly_dates), name="me")
if pit_shares.empty:
return out
known_from = pit_shares.index + pd.Timedelta(days=pit_lag_days)
sh = pd.Series(pit_shares.to_numpy(), index=known_from).sort_index()
for d in out.index:
visible = sh[sh.index <= d]
if visible.empty:
continue
shares = visible.iloc[-1]
close = close_by_date.get(d, np.nan)
if np.isfinite(close) and np.isfinite(shares):
out.loc[d] = close * shares
return out
# ---------------------------------------------------------------------------
# Assembly
# ---------------------------------------------------------------------------
def _us_universe(panel: pd.DataFrame, cfg: QMJConfig) -> list[str]:
if cfg.universe is not None:
return list(cfg.universe)
tickers = panel.loc[panel["ticker"].str.endswith(".US"), "ticker"].unique()
return sorted(tickers)
def _load_bab_ivol(cfg: QMJConfig, panel: pd.DataFrame) -> pd.DataFrame:
"""Real FP beta -> bab and residual-vol -> ivol per (date, ticker).
If cfg.bab_ivol is supplied it is used directly (tests / sanity injection).
Otherwise daily_returns + market_proxy are read and qmj_risk computes the
members for the panel's (date, ticker) cross-section.
"""
if cfg.bab_ivol is not None:
bi = cfg.bab_ivol.copy()
bi["date"] = pd.to_datetime(bi["date"])
return bi[["date", "ticker", "bab", "ivol"]]
from src.data.qmj_risk import compute_fp_beta_ivol
daily = pd.read_parquet(cfg.daily_returns_path, columns=["date", "ticker", "ret_d"])
daily["date"] = pd.to_datetime(daily["date"])
market = pd.read_parquet(cfg.market_proxy_path)
market["date"] = pd.to_datetime(market["date"])
pairs = panel[["date", "ticker"]].drop_duplicates()
return compute_fp_beta_ivol(daily, market, pairs)
def build_qmj_panel(
panel_path: str = "data/processed/panel_monthly.parquet",
fundamentals_dir: str = "data/raw/eodhd/fundamentals",
out_path: str | None = "data/processed/qmj_monthly.parquet",
cfg: QMJConfig | None = None,
start: str | None = None,
) -> pd.DataFrame:
"""Build the monthly QMJ quality panel and (optionally) persist it.
Output columns: [date, ticker, qmj_profitability, qmj_growth, qmj_safety,
qmj_payout, qmj_rd, qmj_quality, qmj_n_measures] when the R&D pillar is
enabled; otherwise qmj_rd/rd_me are omitted.
"""
cfg = cfg or QMJConfig()
if start is not None:
cfg.start = start
ppy = _ppy_for_freq(cfg.freq)
all_measures = _ALL_MEASURES + (_RD if cfg.add_rd_pillar else [])
panel = pd.read_parquet(panel_path)
panel["date"] = pd.to_datetime(panel["date"])
panel = panel[panel["date"] >= pd.Timestamp(cfg.start)]
universe = _us_universe(panel, cfg)
monthly_dates = pd.DatetimeIndex(sorted(panel["date"].unique()))
cpi = load_cpi(cfg.cpi_csv)
# Real Frazzini-Pedersen beta -> bab and residual-vol -> ivol (no fallback).
bab_ivol = _load_bab_ivol(cfg, panel)
fdir = Path(fundamentals_dir)
# Per-ticker monthly measure frames accumulate here.
monthly_frames: list[pd.DataFrame] = []
for ticker in universe:
fpath = fdir / f"{ticker}.json"
if not fpath.exists():
continue
try:
data = json.loads(fpath.read_text(encoding="utf-8"))
except (ValueError, OSError):
logger.debug("QMJ: unreadable fundamentals for %s", ticker)
continue
# Fama-French convention: financials are excluded from the quality
# cross-section entirely (so they neither receive a score nor distort the
# rank-z of non-financials). They are NaN-kept downstream by the veto.
if _EXCLUDE_FINANCIALS and is_financial(data):
logger.debug("QMJ: %s excluded (GICS Financials)", ticker)
continue
quarterly = parse_fundamentals_response(data, ticker, freq=cfg.freq)
if quarterly.empty:
continue
measures = compute_quarterly_measures(quarterly, periods_per_year=ppy)
pit_shares = extract_pit_shares(data)
tk_panel = panel[panel["ticker"] == ticker]
if tk_panel.empty:
continue
close_by_date = tk_panel.set_index("date")["close"]
me = derive_market_cap(pit_shares, monthly_dates, close_by_date, cfg.pit_lag_days)
# PIT-lag the per-quarter measures + the raw inputs needed for O/Z to
# monthly month-ends via the shared lag_to_monthly helper.
keep = [
"ticker",
"quarter_end",
*_PROFITABILITY,
*_GROWTH,
"lev",
"evol",
"diss",
"npop",
# raw inputs for O / Z scored at the monthly cross-section:
"total_assets",
"total_liabilities",
"short_term_debt",
"lt_debt",
"current_assets",
"current_liabilities",
"wc_refined",
"book_equity",
"retained_earnings",
"ttm_net_income",
"ttm_pretax_income",
"ttm_operating_income",
"ttm_revenue",
"ttm_research_development",
]
keep = [c for c in keep if c in measures.columns]
m_monthly = lag_to_monthly(measures[keep], monthly_dates, pit_lag_days=cfg.pit_lag_days)
if m_monthly.empty:
continue
# EISS = -1yr % change split-adjusted shares (from PIT shares aligned to
# monthly). Use the same PIT-lag forward-fill, then 12-month % change.
sh_monthly = _shares_monthly(pit_shares, monthly_dates, cfg.pit_lag_days)
m_monthly = m_monthly.merge(
sh_monthly.rename("_shares").reset_index().rename(columns={"index": "date"}),
on="date",
how="left",
)
m_monthly["eiss"] = -m_monthly["_shares"].pct_change(12, fill_method=None)
# Attach ME and the real FP bab / ivol (qmj_risk) by (date, ticker).
m_monthly = m_monthly.merge(
me.rename("me").reset_index().rename(columns={"index": "date"}),
on="date",
how="left",
)
if cfg.add_rd_pillar:
with np.errstate(invalid="ignore", divide="ignore"):
rd_me = m_monthly["ttm_research_development"] / m_monthly["me"]
m_monthly["rd_me"] = rd_me.where(
(m_monthly["ttm_research_development"] > 0) & (m_monthly["me"] > 0)
)
tk_bi = bab_ivol[bab_ivol["ticker"] == ticker][["date", "bab", "ivol"]]
m_monthly = m_monthly.merge(tk_bi, on="date", how="left")
# Prior-year TTM net income (for Ohlson INTWO / CHIN). ttm_net_income is
# forward-filled quarterly, so a 12-month shift gives the TTM NI known
# one fiscal year earlier.
m_monthly = m_monthly.sort_values("date")
m_monthly["_ttm_ni_prior"] = m_monthly["ttm_net_income"].shift(12)
monthly_frames.append(m_monthly)
if not monthly_frames:
logger.warning("build_qmj_panel: no tickers produced measures")
cols = [
"date",
"ticker",
"qmj_profitability",
"qmj_growth",
"qmj_safety",
"qmj_payout",
"qmj_quality",
"qmj_n_measures",
]
empty = pd.DataFrame(columns=cols)
if out_path:
empty.to_parquet(out_path)
return empty
panel_m = pd.concat(monthly_frames, ignore_index=True)
# Compute O / Z per (date, ticker) row now that ME + prior-NI are present.
panel_m["o_raw"] = panel_m.apply(_row_ohlson, axis=1, cpi=cpi)
panel_m["o_score"] = -panel_m["o_raw"] # high O = bad → negate
panel_m["z_score"] = panel_m.apply(_row_altman, axis=1)
# Cross-sectional rank-z per date for every measure, then pillars, gate.
out_rows: list[pd.DataFrame] = []
for date, grp in panel_m.groupby("date"):
g = grp.copy()
z = pd.DataFrame(index=g.index)
for m in all_measures:
z[m] = rank_z(g[m]) if m in g.columns else np.nan
prof = _pillar_score(z, _PROFITABILITY)
grow = _pillar_score(z, _GROWTH)
safe = _pillar_score(z, _SAFETY)
pay = _pillar_score(z, _PAYOUT)
rd = _pillar_score(z, _RD) if cfg.add_rd_pillar else None
n_measures = z[all_measures].notna().sum(axis=1)
gate = _coverage_gate(
z, cfg.require_pillars, cfg.min_measures_overall, all_measures=all_measures
)
pillar_cols = [prof, grow, safe, pay]
if rd is not None:
pillar_cols.append(rd)
pillar_avg = pd.concat(pillar_cols, axis=1).mean(axis=1, skipna=True)
quality = rank_z(pillar_avg.where(gate))
out = pd.DataFrame(
{
"date": date,
"ticker": g["ticker"].to_numpy(),
"qmj_profitability": prof.to_numpy(),
"qmj_growth": grow.to_numpy(),
"qmj_safety": safe.to_numpy(),
"qmj_payout": pay.to_numpy(),
"qmj_quality": quality.to_numpy(),
"qmj_n_measures": n_measures.to_numpy(),
}
)
if rd is not None:
out["qmj_rd"] = rd.to_numpy()
out["rd_me"] = g.get("rd_me", pd.Series(np.nan, index=g.index)).to_numpy()
out_rows.append(out)
result = pd.concat(out_rows, ignore_index=True)
result = result.dropna(subset=["qmj_quality"]).reset_index(drop=True)
result = result.sort_values(["date", "ticker"]).reset_index(drop=True)
logger.info(
"build_qmj_panel: %d (date, ticker) quality scores over %d tickers, %s..%s",
len(result),
result["ticker"].nunique(),
result["date"].min().date() if len(result) else "n/a",
result["date"].max().date() if len(result) else "n/a",
)
if out_path:
Path(out_path).parent.mkdir(parents=True, exist_ok=True)
result.to_parquet(out_path)
return result
def _shares_monthly(
pit_shares: pd.Series, monthly_dates: pd.DatetimeIndex, pit_lag_days: int
) -> pd.Series:
out = pd.Series(np.nan, index=pd.DatetimeIndex(monthly_dates))
if pit_shares.empty:
return out
known_from = pit_shares.index + pd.Timedelta(days=pit_lag_days)
sh = pd.Series(pit_shares.to_numpy(), index=known_from).sort_index()
for d in out.index:
visible = sh[sh.index <= d]
if not visible.empty:
out.loc[d] = visible.iloc[-1]
return out
def _row_ohlson(row: pd.Series, cpi: pd.Series) -> float:
try:
ni_prior = row.get("_ttm_ni_prior")
if not np.isfinite(ni_prior):
ni_prior = row.get("ttm_net_income")
return ohlson_o_score(
total_assets=row.get("total_assets", np.nan),
total_liabilities=row.get("total_liabilities", np.nan),
short_term_debt=row.get("short_term_debt", np.nan),
lt_debt=row.get("lt_debt", np.nan),
current_assets=row.get("current_assets", np.nan),
current_liabilities=row.get("current_liabilities", np.nan),
ttm_net_income=row.get("ttm_net_income", np.nan),
ttm_net_income_prior=ni_prior,
ttm_pretax_income=row.get("ttm_pretax_income", np.nan),
book_equity=row.get("book_equity", np.nan),
market_cap=row.get("me", np.nan),
cpi=_cpi_at(cpi, pd.Timestamp(row["date"])),
)
except (ZeroDivisionError, ValueError, TypeError, FloatingPointError):
return np.nan
def _row_altman(row: pd.Series) -> float:
try:
return altman_z_score(
working_capital=row.get("wc_refined", np.nan),
retained_earnings=row.get("retained_earnings", np.nan),
ttm_operating_income=row.get("ttm_operating_income", np.nan),
market_cap=row.get("me", np.nan),
ttm_revenue=row.get("ttm_revenue", np.nan),
total_assets=row.get("total_assets", np.nan),
)
except (ZeroDivisionError, ValueError, TypeError, FloatingPointError):
return np.nan
+154
View File
@@ -0,0 +1,154 @@
"""Frazzini-Pedersen ex-ante beta + residual idiosyncratic volatility for QMJ Safety.
AFP "Quality Minus Junk" appendix defines the two Safety risk members BAB and
IVOL on the Frazzini-Pedersen (2014) ex-ante beta:
sigma_i = std(daily stock return, trailing ~1y = 252 td)
sigma_m = std(daily market return, trailing ~1y = 252 td)
rho = corr( 3-day-SUM stock return , 3-day-SUM market return ),
trailing ~1.5y = 378 td (3-day overlapping returns correct for
nonsynchronous-trading bias in correlations). NOTE: FP/AFP use a
5y horizon; shortened to 1.5y (project owner 2026-06-06) for usable Safety
coverage across the short 2018-2026 test window — a deliberate,
documented deviation from the paper.
beta = rho * (sigma_i / sigma_m)
bab = -beta
residual_t = ret_d_t - beta * ret_mkt_t
sigma_idio = std(residual, trailing ~252 td, SKIPPING the most recent td)
ivol = -sigma_idio
Everything is PIT at each panel month-end: the trailing windows end at (and
include) the month-end's last available trading day, with no extra lag. Stock
and market series are aligned by calendar date (same intersection approach as
scripts/repair_phase8.py::compute_betas_60d).
"""
from __future__ import annotations
import logging
import numpy as np
import pandas as pd
logger = logging.getLogger(__name__)
_VOL_WINDOW = 252 # ~1y trading days for sigma_i / sigma_m / sigma_idio
_CORR_WINDOW = 378 # ~1.5y trading days for the 3-day-sum correlation (FP use 5y)
_CORR_SUM_DAYS = 3 # nonsynchronous-trading correction horizon
_VOL_MIN_OBS = 120 # min finite obs for a 1y std
_CORR_MIN_OBS = 180 # min finite 3-day-sum pairs for the 1.5y correlation (~half window)
def _trailing_std(x: np.ndarray, end: int, window: int, min_obs: int) -> float:
lo = max(0, end - window + 1)
w = x[lo : end + 1]
w = w[np.isfinite(w)]
if len(w) < min_obs:
return np.nan
return float(np.std(w, ddof=1))
def _trailing_corr_3day(y: np.ndarray, x: np.ndarray, end: int, window: int, min_obs: int) -> float:
lo = max(0, end - window + 1)
ys = pd.Series(y[lo : end + 1])
xs = pd.Series(x[lo : end + 1])
# 3-day overlapping SUM of returns (Frazzini-Pedersen nonsynchronous fix).
y3 = ys.rolling(_CORR_SUM_DAYS, min_periods=_CORR_SUM_DAYS).sum()
x3 = xs.rolling(_CORR_SUM_DAYS, min_periods=_CORR_SUM_DAYS).sum()
mask = np.isfinite(y3.to_numpy()) & np.isfinite(x3.to_numpy())
if mask.sum() < min_obs:
return np.nan
yv = y3.to_numpy()[mask]
xv = x3.to_numpy()[mask]
if np.std(yv) == 0 or np.std(xv) == 0:
return np.nan
return float(np.corrcoef(yv, xv)[0, 1])
def compute_fp_beta_ivol(
daily_returns: pd.DataFrame,
market: pd.DataFrame,
panel_pairs: pd.DataFrame,
) -> pd.DataFrame:
"""FP ex-ante beta -> bab and residual-vol -> ivol per (ticker, panel date).
Parameters
----------
daily_returns : columns [date, ticker, ret_d]
market : columns [date, ret_mkt]
panel_pairs : columns [date, ticker] — the month-end cross-section to score.
Returns a DataFrame [date, ticker, bab, ivol]. Rows where the windows are
too short are NaN (and dropped before output is irrelevant — they are kept
with NaN so the caller's left-merge preserves all pairs).
"""
market = market.sort_values("date").reset_index(drop=True)
mkt_dates = market["date"].to_numpy(dtype="datetime64[ns]")
mkt_ret = market["ret_mkt"].to_numpy(dtype=float)
daily_returns = daily_returns.sort_values(["ticker", "date"]).reset_index(drop=True)
by_ticker = daily_returns.groupby("ticker", sort=False)
pairs = panel_pairs[["date", "ticker"]].copy()
pairs["date"] = pd.to_datetime(pairs["date"])
pair_idx_by_ticker = pairs.groupby("ticker", sort=False).indices
bab = np.full(len(pairs), np.nan)
ivol = np.full(len(pairs), np.nan)
n_tickers = len(by_ticker)
n_done = 0
for ticker, grp in by_ticker:
n_done += 1
if n_done % 1000 == 0:
logger.info("FP beta/ivol: ticker %d / %d", n_done, n_tickers)
positions = pair_idx_by_ticker.get(ticker)
if positions is None or len(positions) == 0:
continue
s_dates = grp["date"].to_numpy(dtype="datetime64[ns]")
s_ret = grp["ret_d"].to_numpy(dtype=float)
# Align stock dates to market dates by calendar-date intersection.
mkt_pos = np.searchsorted(mkt_dates, s_dates)
in_range = mkt_pos < len(mkt_dates)
mkt_pos_safe = np.where(in_range, mkt_pos, 0)
match = in_range & (mkt_dates[mkt_pos_safe] == s_dates)
if not match.any():
continue
aligned_dates = s_dates[match]
aligned_y = s_ret[match]
aligned_x = mkt_ret[mkt_pos[match]]
panel_dates = pairs.iloc[positions]["date"].to_numpy(dtype="datetime64[ns]")
end_pos = np.searchsorted(aligned_dates, panel_dates, side="right") - 1
for i, end in enumerate(end_pos):
if end < 0:
continue
sigma_i = _trailing_std(aligned_y, end, _VOL_WINDOW, _VOL_MIN_OBS)
sigma_m = _trailing_std(aligned_x, end, _VOL_WINDOW, _VOL_MIN_OBS)
if not np.isfinite(sigma_i) or not np.isfinite(sigma_m) or sigma_m == 0:
continue
rho = _trailing_corr_3day(aligned_y, aligned_x, end, _CORR_WINDOW, _CORR_MIN_OBS)
if not np.isfinite(rho):
continue
beta = rho * (sigma_i / sigma_m)
bab[positions[i]] = -beta
# Residual idiosyncratic vol: std of (ret - beta*ret_mkt) over the
# trailing 1y window, SKIPPING the most recent trading day (end-1).
if end - 1 < 0:
continue
resid = aligned_y - beta * aligned_x
sigma_idio = _trailing_std(resid, end - 1, _VOL_WINDOW, _VOL_MIN_OBS)
if np.isfinite(sigma_idio):
ivol[positions[i]] = -sigma_idio
pairs["bab"] = bab
pairs["ivol"] = ivol
return pairs[["date", "ticker", "bab", "ivol"]]
+500
View File
@@ -0,0 +1,500 @@
"""BlackRock-to-EODHD ticker resolver — Phase A.2.
Maps each BlackRock holdings row to an EODHD-format ticker ({TICKER}.{EXCHANGE})
using (br_ticker, br_exchange, location) as the resolution key.
Resolution pipeline per row:
1. Cache hit → method='cache', confidence='high'
2. Primary → method='primary', confidence='high' (direct code match)
3. Normalization → method='normalization', confidence='medium' (ticker variants)
4. Fuzzy name → method='fuzzy_name', confidence='low' (difflib name match)
5. Unresolved → eodhd_ticker=None, failure_reason set
"""
import difflib
import logging
from datetime import date, datetime
from pathlib import Path
from typing import Any
import pandas as pd
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Exchange mapping tables
# ---------------------------------------------------------------------------
BR_TO_EODHD_EXCHANGE: dict[str, str] = {
# United States
"NYSE": "US",
"NASDAQ": "US",
"Nyse Mkt Llc": "US",
"Cboe BZX": "US",
# Japan
"Tokyo Stock Exchange": "TSE",
# Canada
"Toronto Stock Exchange": "TO",
"NLB": "NEO", # NEO / Cboe Canada — EODHD has the .NEO exchange listing
# United Kingdom
"London Stock Exchange": "LSE",
# Germany
"Xetra": "XETRA",
"Deutsche Boerse Xetra": "XETRA",
# France / Netherlands / Belgium / Portugal — Euronext family
"Nyse Euronext - Euronext Paris": "PA",
"Euronext Amsterdam": "AS",
"Nyse Euronext - Euronext Brussels": "BR",
"Nyse Euronext - Euronext Lisbon": "LS",
# Switzerland
"SIX Swiss Exchange": "SW",
# Italy
"Borsa Italiana": "MI",
# Spain
"Bolsa De Madrid": "MC",
# Austria
"Wiener Boerse Ag": "VI",
# Ireland
"Irish Stock Exchange - All Market": "IR",
# Nordic disambiguation: rows dispatched by location because the same string
# covers Sweden / Denmark / Finland / Norway listings.
"Nasdaq Omx Nordic": "__BY_LOCATION__",
"AKT": "__BY_LOCATION__",
# Already country-specific Nordic strings:
"Omx Nordic Exchange Copenhagen A/S": "CO",
"Nasdaq Omx Helsinki Ltd.": "HE",
"Oslo Bors Asa": "OL",
# Excluded-region exchanges — mapped so resolution succeeds cleanly; then
# dropped by the orchestrator's region filter. Without these mappings the
# rows clutter the unresolved CSV with false "no_exchange_mapping" hits.
"Asx - All Markets": "AU", # Australia
"Tel Aviv Stock Exchange": "TA", # Israel
"Hong Kong Exchanges And Clearing Ltd": "HK", # Hong Kong
"Singapore Exchange": "SG", # Singapore
"New Zealand Exchange Ltd": "__NO_EODHD__", # NZ — no EODHD coverage; ~13 names, accept residual miss
}
LOCATION_TO_NORDIC_EXCHANGE: dict[str, str] = {
"Sweden": "ST",
"Denmark": "CO",
"Norway": "OL",
"Finland": "HE",
}
_FUZZY_CUTOFF = 0.85
_FUZZY_SECONDARY_MAX = 0.75 # second match must be below this for disambiguation
class TickerResolverError(RuntimeError):
"""Raised on unrecoverable resolver errors (not on simple resolution failures)."""
def __init__(self, reason: str, context: dict[str, Any] | None = None):
self.reason = reason
self.context = context or {}
super().__init__(f"TickerResolver error: {reason} | context={self.context}")
# ---------------------------------------------------------------------------
# Symbol-list cache (per exchange, loaded lazily)
# ---------------------------------------------------------------------------
class _ExchangeIndex:
"""Lazy-loaded per-exchange code set + name list for fuzzy matching."""
def __init__(self, eodhd_client: Any) -> None:
self._client = eodhd_client
self._codes: dict[str, set[str]] = {}
self._names: dict[str, list[tuple[str, str]]] = {} # ex -> [(code, name_lower)]
def codes(self, exchange: str) -> set[str]:
if exchange not in self._codes:
self._load(exchange)
return self._codes[exchange]
def name_list(self, exchange: str) -> list[tuple[str, str]]:
if exchange not in self._names:
self._load(exchange)
return self._names[exchange]
def _load(self, exchange: str) -> None:
df = self._client.get_exchange_symbols(exchange, delisted=False)
if df.empty or "Code" not in df.columns:
logger.warning("Empty or missing Code column for exchange %s", exchange)
self._codes[exchange] = set()
self._names[exchange] = []
return
self._codes[exchange] = set(df["Code"].dropna().astype(str))
name_col = df["Name"] if "Name" in df.columns else pd.Series([""] * len(df))
self._names[exchange] = [
(str(row["Code"]), str(name_col.iloc[i]).lower())
for i, (_, row) in enumerate(df.iterrows())
]
# ---------------------------------------------------------------------------
# Normalization helpers
# ---------------------------------------------------------------------------
def _ticker_variants(br_ticker: str) -> list[str]:
"""Generate candidate normalized tickers to try against the exchange code set."""
variants: list[str] = []
t = br_ticker
# Strip trailing dot (LSE: "RR." -> "RR", "BP." -> "BP")
if t.endswith("."):
variants.append(t[:-1])
# Zero-pad to 4 chars for TSE (spec says length-3 codes; in practice all TSE
# codes in fixtures are already 4 digits, but keep for robustness)
if t.isdigit() and len(t) == 3:
variants.append(t.zfill(4))
# Space -> dash (e.g. "EIT UN" -> "EIT-UN", Nordic "INVE B" -> "INVE-B")
if " " in t:
variants.append(t.replace(" ", "-"))
# Dot -> dash (e.g. "BRK.A" -> "BRK-A", "REI.UN" -> "REI-UN")
if "." in t and not t.endswith("."):
variants.append(t.replace(".", "-"))
# Dash -> dot (reverse)
if "-" in t:
variants.append(t.replace("-", "."))
# Space -> dot
if " " in t:
variants.append(t.replace(" ", "."))
# Strip trailing whitespace
stripped = t.rstrip()
if stripped != t:
variants.append(stripped)
return variants
# ---------------------------------------------------------------------------
# Main resolver class
# ---------------------------------------------------------------------------
class TickerResolver:
def __init__(
self,
eodhd_client: Any,
unresolved_dir: Path | str = "data/universe",
resolution_cache_path: Path | str = "data/universe/br_to_eodhd_map.parquet",
manual_overrides_path: Path | str = "data/universe/manual_overrides.yaml",
) -> None:
self._client = eodhd_client
self._unresolved_dir = Path(unresolved_dir)
self._cache_path = Path(resolution_cache_path)
self._overrides_path = Path(manual_overrides_path)
self._ex_index = _ExchangeIndex(eodhd_client)
self._cache: pd.DataFrame = self._load_resolution_cache()
self._overrides: dict[tuple[str, str], str] = self._load_manual_overrides()
# ------------------------------------------------------------------
# Cache I/O
# ------------------------------------------------------------------
def _load_resolution_cache(self) -> pd.DataFrame:
if self._cache_path.is_file():
df = pd.read_parquet(self._cache_path)
logger.debug("Loaded %d entries from resolution cache %s", len(df), self._cache_path)
return df
return pd.DataFrame(
columns=["br_ticker", "br_exchange", "eodhd_ticker", "resolution_method", "resolved_at"]
)
def _load_manual_overrides(self) -> dict[tuple[str, str], str]:
"""Load manual (br_ticker, br_exchange) → eodhd_ticker overrides from YAML.
Override file format:
overrides:
- br_ticker: BRKB
br_exchange: NYSE
eodhd_ticker: BRK-B.US
notes: "optional human note"
"""
if not self._overrides_path.is_file():
return {}
import yaml
data = yaml.safe_load(self._overrides_path.read_text(encoding="utf-8")) or {}
out: dict[tuple[str, str], str] = {}
for entry in data.get("overrides", []):
br_ticker = entry.get("br_ticker")
br_exchange = entry.get("br_exchange")
eodhd_ticker = entry.get("eodhd_ticker")
if not (br_ticker and br_exchange and eodhd_ticker):
logger.warning("Skipping malformed override entry: %s", entry)
continue
out[(str(br_ticker), str(br_exchange))] = str(eodhd_ticker)
logger.info("Loaded %d manual overrides from %s", len(out), self._overrides_path)
return out
def _persist_cache(self) -> None:
self._cache_path.parent.mkdir(parents=True, exist_ok=True)
tmp = self._cache_path.with_suffix(".tmp")
try:
self._cache.to_parquet(tmp, index=False)
tmp.replace(self._cache_path)
except OSError as exc:
tmp.unlink(missing_ok=True)
raise TickerResolverError(
reason=f"Failed to write resolution cache: {exc}",
context={"path": str(self._cache_path)},
) from exc
def _cache_lookup(self, br_ticker: str, br_exchange: str) -> str | None:
if self._cache.empty:
return None
mask = (self._cache["br_ticker"] == br_ticker) & (
self._cache["br_exchange"] == br_exchange
)
hits = self._cache[mask]
if hits.empty:
return None
return hits.iloc[0]["eodhd_ticker"]
def _cache_append(self, br_ticker: str, br_exchange: str, eodhd_ticker: str, method: str) -> None:
new_row = pd.DataFrame(
[
{
"br_ticker": br_ticker,
"br_exchange": br_exchange,
"eodhd_ticker": eodhd_ticker,
"resolution_method": method,
"resolved_at": datetime.utcnow().isoformat(),
}
]
)
# Append-only: never overwrite an existing resolution.
mask = (self._cache["br_ticker"] == br_ticker) & (
self._cache["br_exchange"] == br_exchange
)
if not self._cache.empty and mask.any():
return
self._cache = pd.concat([self._cache, new_row], ignore_index=True)
# ------------------------------------------------------------------
# Resolution pipeline
# ------------------------------------------------------------------
def _map_exchange(self, br_exchange: str, location: str) -> str | None:
ex = BR_TO_EODHD_EXCHANGE.get(br_exchange)
if ex == "__BY_LOCATION__":
return LOCATION_TO_NORDIC_EXCHANGE.get(location)
return ex
def _try_fuzzy(
self, name: str, eodhd_exchange: str, candidates_tried: list[str]
) -> str | None:
name_lower = name.lower()
name_list = self._ex_index.name_list(eodhd_exchange)
if not name_list:
return None
lowered_names = [n for _, n in name_list]
matches = difflib.get_close_matches(name_lower, lowered_names, n=3, cutoff=_FUZZY_CUTOFF)
if not matches:
return None
# Require unambiguous match: either only one result, or second result score < threshold.
best_name = matches[0]
if len(matches) > 1:
second_score = difflib.SequenceMatcher(None, name_lower, matches[1]).ratio()
if second_score >= _FUZZY_SECONDARY_MAX:
# Too ambiguous — reject.
return None
# Resolve name back to code.
for code, n in name_list:
if n == best_name:
candidate = f"{code}.{eodhd_exchange}"
candidates_tried.append(candidate)
return candidate
return None
def resolve_one(
self,
br_ticker: str,
br_exchange: str,
location: str,
name: str,
) -> dict[str, Any]:
candidates_tried: list[str] = []
# Step 0: Manual override (project owner-approved fixes for tickers the auto-resolver misses)
override_ticker = self._overrides.get((br_ticker, br_exchange))
if override_ticker is not None:
return {
"eodhd_ticker": override_ticker,
"resolution_method": "manual_override",
"resolution_confidence": "high",
"candidates_tried": [override_ticker],
"failure_reason": None,
}
# Step 1: Cache hit
cached_ticker = self._cache_lookup(br_ticker, br_exchange)
if cached_ticker is not None:
return {
"eodhd_ticker": cached_ticker,
"resolution_method": "cache",
"resolution_confidence": "high",
"candidates_tried": candidates_tried,
"failure_reason": None,
}
# Step 2: Map exchange
eodhd_ex = self._map_exchange(br_exchange, location)
if eodhd_ex is None:
return {
"eodhd_ticker": None,
"resolution_method": None,
"resolution_confidence": None,
"candidates_tried": candidates_tried,
"failure_reason": "no_exchange_mapping",
}
if eodhd_ex == "__NO_EODHD__":
# Region has no EODHD exchange coverage (e.g. NZ). Accept the miss
# — these rows are excluded by the orchestrator's region filter anyway.
return {
"eodhd_ticker": None,
"resolution_method": None,
"resolution_confidence": None,
"candidates_tried": candidates_tried,
"failure_reason": "no_eodhd_coverage_for_region",
}
codes = self._ex_index.codes(eodhd_ex)
# Step 3: Primary — direct ticker match
primary_candidate = f"{br_ticker}.{eodhd_ex}"
candidates_tried.append(primary_candidate)
if br_ticker in codes:
self._cache_append(br_ticker, br_exchange, primary_candidate, "primary")
return {
"eodhd_ticker": primary_candidate,
"resolution_method": "primary",
"resolution_confidence": "high",
"candidates_tried": candidates_tried,
"failure_reason": None,
}
# Step 4: Normalization variants
for variant in _ticker_variants(br_ticker):
candidate = f"{variant}.{eodhd_ex}"
candidates_tried.append(candidate)
if variant in codes:
self._cache_append(br_ticker, br_exchange, candidate, "normalization")
return {
"eodhd_ticker": candidate,
"resolution_method": "normalization",
"resolution_confidence": "medium",
"candidates_tried": candidates_tried,
"failure_reason": None,
}
# Step 5: Fuzzy name match
if name:
fuzzy_ticker = self._try_fuzzy(name, eodhd_ex, candidates_tried)
if fuzzy_ticker is not None:
self._cache_append(br_ticker, br_exchange, fuzzy_ticker, "fuzzy_name")
return {
"eodhd_ticker": fuzzy_ticker,
"resolution_method": "fuzzy_name",
"resolution_confidence": "low",
"candidates_tried": candidates_tried,
"failure_reason": None,
}
# Step 6: Unresolved
return {
"eodhd_ticker": None,
"resolution_method": None,
"resolution_confidence": None,
"candidates_tried": candidates_tried,
"failure_reason": f"not_found_in_{eodhd_ex}",
}
# ------------------------------------------------------------------
# DataFrame resolver
# ------------------------------------------------------------------
def resolve_dataframe(
self,
df: pd.DataFrame,
write_unresolved: bool = True,
) -> pd.DataFrame:
"""Resolve every row in a BlackRock holdings DataFrame.
Input columns required: etf, br_ticker, name, location, br_exchange, currency, weight_pct
Output adds: eodhd_ticker, resolution_method, resolution_confidence
Persists the resolution cache (append-only) after the run.
"""
required = {"etf", "br_ticker", "name", "location", "br_exchange"}
missing = required - set(df.columns)
if missing:
raise TickerResolverError(
reason=f"Input DataFrame missing required columns: {missing}",
context={"columns": list(df.columns)},
)
results: list[dict[str, Any]] = []
for _, row in df.iterrows():
res = self.resolve_one(
br_ticker=str(row["br_ticker"]) if pd.notna(row["br_ticker"]) else "",
br_exchange=str(row["br_exchange"]) if pd.notna(row["br_exchange"]) else "",
location=str(row["location"]) if pd.notna(row["location"]) else "",
name=str(row["name"]) if pd.notna(row["name"]) else "",
)
results.append(res)
out = df.copy()
out["eodhd_ticker"] = [r["eodhd_ticker"] for r in results]
out["resolution_method"] = [r["resolution_method"] for r in results]
out["resolution_confidence"] = [r["resolution_confidence"] for r in results]
# Persist cache after full run.
self._persist_cache()
# Log summary.
total = len(out)
resolved_mask = out["eodhd_ticker"].notna()
n_resolved = resolved_mask.sum()
method_counts = out.loc[resolved_mask, "resolution_method"].value_counts()
n_primary = method_counts.get("primary", 0)
n_norm = method_counts.get("normalization", 0)
n_fuzzy = method_counts.get("fuzzy_name", 0)
n_cache = method_counts.get("cache", 0)
n_unresolved = total - n_resolved
etf_name = df["etf"].iloc[0] if "etf" in df.columns and len(df) > 0 else "unknown"
logger.info(
"Resolved %d/%d holdings for %s: %d primary, %d normalization, %d fuzzy_name, "
"%d cache, %d unresolved",
n_resolved, total, etf_name,
n_primary, n_norm, n_fuzzy, n_cache, n_unresolved,
)
# Write unresolved CSV per ETF.
if write_unresolved and n_unresolved > 0:
unresolved_rows = df[~resolved_mask].copy()
unresolved_rows["candidates_tried"] = [
r["candidates_tried"] for r in results if r["eodhd_ticker"] is None
]
unresolved_rows["failure_reason"] = [
r["failure_reason"] for r in results if r["eodhd_ticker"] is None
]
today_str = date.today().strftime("%Y%m%d")
self._unresolved_dir.mkdir(parents=True, exist_ok=True)
unresolved_path = self._unresolved_dir / f"unresolved_holdings_{etf_name}_{today_str}.csv"
unresolved_rows.to_csv(unresolved_path, index=False)
logger.info(
"Wrote %d unresolved holdings to %s", n_unresolved, unresolved_path
)
return out
View File
+116
View File
@@ -0,0 +1,116 @@
"""Frazzini-Pedersen (2014, JFE) ex-ante beta estimator (eqn 14-15).
Implements the exact F&P recipe:
beta_TS = rho_{5y, 3d-overlap} * sigma_{i, 1y, 1d} / sigma_{m, 1y, 1d}
beta = 0.6 * beta_TS + 0.4 * 1.0 (Vasicek shrink, w fixed)
where sigma is the 1-year (252d) std of 1-day log returns and rho is the
5-year (1260d) Pearson correlation of overlapping 3-day log-return sums.
Reference: Frazzini, A., and L. H. Pedersen (2014), "Betting Against Beta,"
Journal of Financial Economics 111, 1-25, eqn 14-15 (p. 17).
ALIGNMENT-THEN-OVERLAP ORDERING (critical): the stock and market simple-return
series are inner-joined on common dates BEFORE the 3-day overlapping sums are
formed. This is the fix for the historical "position-misaligned 3-day buckets"
bug recorded in scripts/repair_phase8.py:5 — if the two series are bucketed
independently before alignment, a single missing day on one side shifts every
subsequent 3-day window relative to the other side and silently corrupts rho.
Aligning first guarantees the 3-day sums cover identical calendar windows on
both legs at every t, so dropped days only shorten the sample rather than
desynchronise it.
"""
from __future__ import annotations
import numpy as np
import pandas as pd
_FP_VOL_WINDOW = 252
_FP_VOL_MIN_OBS = 120
_FP_CORR_WINDOW = 1260
_FP_CORR_MIN_OBS = 750
_FP_OVERLAP = 3
_FP_VASICEK_W = 0.6
_FP_VASICEK_PRIOR = 1.0
def compute_fp_ex_ante_beta(
stock_rets: pd.Series,
market_rets: pd.Series,
as_of: pd.Timestamp,
*,
vol_window: int = _FP_VOL_WINDOW,
vol_min_obs: int = _FP_VOL_MIN_OBS,
corr_window: int = _FP_CORR_WINDOW,
corr_min_obs: int = _FP_CORR_MIN_OBS,
overlap: int = _FP_OVERLAP,
vasicek_w: float = _FP_VASICEK_W,
) -> float:
"""Ex-ante beta per Frazzini-Pedersen 2014 eqn 14-15.
Args:
stock_rets: date-indexed pd.Series of SIMPLE daily returns (ret_d).
market_rets: date-indexed pd.Series of SIMPLE daily market returns.
as_of: only dates <= as_of are used.
vol_window: trailing window (days) for the 1-day-return std.
vol_min_obs: minimum paired observations required in the vol window.
corr_window: trailing window (days) for the overlapping-sum correlation.
corr_min_obs: minimum paired observations required in the corr window.
overlap: overlapping-sum length (days) for the correlation legs.
vasicek_w: weight on the time-series beta in the Vasicek shrink.
Defaults equal the F&P paper constants, so the call signature reproduces the
prior strict-paper behaviour exactly when no kwargs are passed.
Returns NaN if either window lacks the minimum required paired observations,
if the market vol is non-positive, or if rho is undefined.
"""
if stock_rets.empty or market_rets.empty:
return float("nan")
s = stock_rets[stock_rets.index <= as_of]
m = market_rets[market_rets.index <= as_of]
if s.empty or m.empty:
return float("nan")
# Align FIRST: inner-join on common dates, sorted ascending. All subsequent
# vol/overlap math runs on these identically-dated columns.
# log1p(-1) = -inf on a -100% (delisting/wipeout) day; map non-finite to NaN
# so a single wipeout row drops out of the windows instead of poisoning them.
s_log = np.log1p(s.astype(float)).replace([np.inf, -np.inf], np.nan)
m_log = np.log1p(m.astype(float)).replace([np.inf, -np.inf], np.nan)
frame = pd.concat({"s": s_log, "m": m_log}, axis=1, join="inner").sort_index()
if frame.empty:
return float("nan")
# --- 1-year volatility (1-day log returns) ---
vol_block = frame.tail(vol_window)
s_vol = vol_block["s"].dropna()
m_vol = vol_block["m"].dropna()
if len(s_vol) < vol_min_obs or len(m_vol) < vol_min_obs:
return float("nan")
sigma_i = float(s_vol.std(ddof=1))
sigma_m = float(m_vol.std(ddof=1))
if not np.isfinite(sigma_m) or sigma_m <= 0.0:
return float("nan")
if not np.isfinite(sigma_i):
return float("nan")
# --- 5-year correlation (overlapping 3-day log-return sums) ---
corr_block = frame.tail(corr_window)
s3 = corr_block["s"].rolling(window=overlap).sum()
m3 = corr_block["m"].rolling(window=overlap).sum()
paired = pd.concat({"s3": s3, "m3": m3}, axis=1).dropna()
if len(paired) < corr_min_obs:
return float("nan")
rho = float(paired["s3"].corr(paired["m3"]))
if not np.isfinite(rho):
return float("nan")
beta_ts = rho * sigma_i / sigma_m
if not np.isfinite(beta_ts):
return float("nan")
return float(vasicek_w * beta_ts + (1.0 - vasicek_w) * _FP_VASICEK_PRIOR)
+576
View File
@@ -0,0 +1,576 @@
"""Per-ticker signal feature panel for the multi-region momentum stack (Phase C.3a).
Produces a raw feature panel — one row per ticker — suitable as input to the
C.3b scoring layer and C.4 orchestrator. Scoring, gate application, BAB-D10
filtering, TC quartile cuts, and Amihud quintile cuts are NOT applied here.
All features are local-currency basis. The MSCI methodology specifies
local-currency momentum (the project previously normalised to USD; that was
a deviation from spec and bloat on live runs). 2026-05-29 flip: all ranker
inputs switched from USD-converted to trading-currency price series.
Local-basis features emitted (all needed by the tm_beta_mdd ranker + the filter
stack — universe / BAB-D10 / TC / Amihud):
ret_12_2_local, sigma_w_3y_local, bab_beta_local, trend_r2,
trend_beta_local, mdd_12_2_local, illiq_12m_local, close_local, adv_20d_local
trend_beta_local + mdd_12_2_local power tm_beta_mdd (Gkolemis 2024 slope-of-trend
× Choi 2021 MDD penalty). BAB beta uses the ticker's REGIONAL benchmark, not SPY.
"""
import concurrent.futures
import json
import logging
import sys
import threading
from pathlib import Path
from typing import Any
import pandas as pd
# Make project root importable when this module is imported from scripts/.
_PROJECT_ROOT = Path(__file__).parent.parent.parent
if str(_PROJECT_ROOT) not in sys.path:
sys.path.insert(0, str(_PROJECT_ROOT))
# Import validated, gate-independent math primitives.
from src.signals.price_primitives import ( # noqa: E402
_compute_ex_ante_beta_for_ticker,
_compute_illiq_12m_at_t,
_compute_mdd_12_2_at_t,
_compute_primitives_at_t,
_compute_sigma_w_3y_at_t,
_compute_trend_beta_at_t,
_compute_trend_r2_at_t,
)
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Path constants
# ---------------------------------------------------------------------------
_UNIVERSE_DIR = _PROJECT_ROOT / "data" / "universe"
_PROCESSED_DIR = _PROJECT_ROOT / "data" / "processed"
_SYMBOLS_DIR = _PROJECT_ROOT / "data" / "raw" / "eodhd" / "symbols"
_FUNDAMENTALS_DIR = _PROJECT_ROOT / "data" / "raw" / "eodhd" / "fundamentals"
_LOCAL_RETURNS_PATH = _PROCESSED_DIR / "global_daily_returns.parquet"
_BENCHMARKS_PATH = _PROCESSED_DIR / "regional_benchmarks_daily.parquet"
_GATE_STATES_PATH = _PROCESSED_DIR / "regional_gate_states.parquet"
_EXCLUSION_TABLE_PATH = _PROCESSED_DIR / "global_excluded_ticker_dates.parquet"
# Live per-region QMJ accounting frequency (data-quality policy, 2026-06-07).
# EU is scored on ANNUAL statements: EODHD's EU quarterly coverage is gappy
# (semi-annual filers, missing intermediate quarters) which nulls the TTM/5y-growth
# windows and leaves EU quality coverage at ~71.5% vs US 92% / JP 96% / CA 95%.
# Annual EU statements are complete, so EU names recover full pillars and pass the
# coverage gate (growth-optional since 2026-06-07: require Profitability+Safety+
# Payout; Growth skippable). US/CA/JP stay quarterly — complete and fresher, and the
# US-only backtest confirmed quarterly is the better source there (annual was a
# downgrade). The shipped R&D pillar follows the same policy: US/CA/JP use
# positive TTM quarterly R&D / market equity; EU uses annual R&D / market equity
# with the annual PIT lag. QMJ is rank-z'd + vetoed PER REGION, so mixing
# frequencies across regions is internally consistent.
_LIVE_REGION_FREQ: dict[str, str] = {"EU": "annual"}
# ---------------------------------------------------------------------------
# Universe loader
# ---------------------------------------------------------------------------
def _latest_universe_path() -> Path:
"""Return the most recent global_msci_world_imi_*.parquet in data/universe/."""
candidates = sorted(_UNIVERSE_DIR.glob("global_msci_world_imi_*.parquet"))
if not candidates:
raise FileNotFoundError(
f"No global universe parquet found in {_UNIVERSE_DIR}. "
"Run scripts/live/build_global_universe.py first."
)
return candidates[-1]
def _load_universe(universe_path: Path | str | None) -> pd.DataFrame:
path = Path(universe_path) if universe_path is not None else _latest_universe_path()
uni = pd.read_parquet(path)
required = {"eodhd_ticker", "region_bucket", "name", "location", "currency"}
missing = required - set(uni.columns)
if missing:
raise ValueError(f"Universe parquet missing columns: {missing}")
return uni
# ---------------------------------------------------------------------------
# Panel pre-grouping (called once; workers get O(1) slices)
# ---------------------------------------------------------------------------
def _group_by_ticker(df: pd.DataFrame, ticker_col: str = "ticker") -> dict[str, pd.DataFrame]:
"""Split a panel DataFrame into a dict keyed by ticker for fast per-worker access."""
groups: dict[str, pd.DataFrame] = {}
for ticker, grp in df.groupby(ticker_col, sort=False):
groups[str(ticker)] = grp.reset_index(drop=True)
return groups
# ---------------------------------------------------------------------------
# Trading-currency lookup — sourced from EODHD symbol cache
# ---------------------------------------------------------------------------
def _build_trading_ccy_lookup() -> dict[str, str]:
"""Return {eodhd_ticker: trading_currency} from the EODHD exchange symbol cache.
Trading currency is per-security (e.g. ASML.AS → EUR, 7203.TSE → JPY).
The universe parquet's `currency` column is the BlackRock ETF's fund denomination
The source-fund denomination is not the per-ticker local currency, so we do not use it.
Loaded from the EODHD symbol-list JSON files and used only for cash-reporting
fields; factor math stays local-currency.
"""
from src.data import GATED_EXCHANGES # noqa: PLC0415
out: dict[str, str] = {}
for ex in GATED_EXCHANGES:
p = _SYMBOLS_DIR / f"{ex}_active.json"
if not p.is_file():
continue
try:
syms = json.loads(p.read_text(encoding="utf-8"))
except (json.JSONDecodeError, OSError) as exc:
logger.warning("Could not read symbol cache %s: %s", p.name, exc)
continue
for s in syms:
code = s.get("Code")
ccy = s.get("Currency")
if code and ccy:
out[f"{code}.{ex}"] = ccy
return out
# ---------------------------------------------------------------------------
# Gate exposure — asof join per (region, date)
# ---------------------------------------------------------------------------
def _build_gate_lookup(
gate_states: pd.DataFrame,
decision_date: pd.Timestamp,
) -> dict[str, float]:
"""Return {region -> gate_exposure} at or before decision_date via asof lookup.
Uses last-known-VALID exposure semantics: NaN-exposure rows are skipped so
that a stale vol-index cache (e.g., V2TX not yet published for today while
SXXP already has today's close) falls back to yesterday's gate rather than
poisoning the lookup with NaN. This matches the summary printed by
`build_regional_gate_states.py` and the asof semantics of
`vix_asymmetric.exposure_at_date`.
"""
result: dict[str, float] = {}
for region, grp in gate_states.groupby("region"):
grp_sorted = grp.sort_values("date")
before = grp_sorted[
(grp_sorted["date"] <= decision_date) & grp_sorted["gate_exposure"].notna()
]
if before.empty:
result[str(region)] = float("nan")
else:
result[str(region)] = float(before.iloc[-1]["gate_exposure"])
return result
# ---------------------------------------------------------------------------
# Exclusion range check — vectorised once over the exclusion table
# ---------------------------------------------------------------------------
def _build_exclusion_set(
exclusion_table: pd.DataFrame,
decision_date: pd.Timestamp,
) -> set[str]:
"""Return the set of tickers that have at least one exclusion range covering decision_date."""
mask = (exclusion_table["start_date"] <= decision_date) & (
exclusion_table["end_date"] >= decision_date
)
return set(exclusion_table.loc[mask, "ticker"].unique())
# ---------------------------------------------------------------------------
# Per-ticker worker
# ---------------------------------------------------------------------------
def _compute_ticker_row(
ticker: str,
region: str,
name: str,
location: str,
trading_ccy: str,
local_daily: pd.DataFrame,
benchmark_rets: pd.Series,
decision_date: pd.Timestamp,
) -> dict[str, Any] | None:
"""Compute filter + ranker features for one ticker at decision_date.
Emits exactly the inputs the live tm_beta_mdd ranker + the filter stack
(universe, BAB-D10, TC, Amihud) consume — no diagnostic surplus.
Returns None when the local primitive computation fails (insufficient history).
NaN is used for individual features that fail — the row is still emitted.
All momentum features use local-currency price series per MSCI methodology.
"""
nan = float("nan")
local_primitives = _compute_primitives_at_t(local_daily, decision_date)
if local_primitives is None:
ret_12_2_local = nan
sigma_w_3y_local = nan
close_local = nan
adv_20d_local = nan
else:
ret_12_2_local = local_primitives["ret_12_2"]
sigma_w_3y_local = _compute_sigma_w_3y_at_t(local_daily, decision_date)
close_local = local_primitives["close"]
adv_20d_local = local_primitives["adv_20d"]
trend_r2 = _compute_trend_r2_at_t(local_daily, decision_date)
trend_beta_local = _compute_trend_beta_at_t(local_daily, decision_date)
mdd_12_2_local = _compute_mdd_12_2_at_t(local_daily, decision_date)
illiq_12m_local = _compute_illiq_12m_at_t(local_daily, decision_date)
bab_beta_local = _compute_ex_ante_beta_for_ticker(local_daily, benchmark_rets, decision_date)
return {
"ticker": ticker,
"region": region,
"name": name,
"location": location,
"trading_ccy": trading_ccy,
"close_local": close_local,
"adv_20d_local": adv_20d_local,
"ret_12_2_local": ret_12_2_local,
"sigma_w_3y_local": sigma_w_3y_local,
"bab_beta_local": bab_beta_local,
"trend_r2": trend_r2,
"trend_beta_local": trend_beta_local,
"mdd_12_2_local": mdd_12_2_local,
"illiq_12m_local": illiq_12m_local,
}
# ---------------------------------------------------------------------------
# Primary public function
# ---------------------------------------------------------------------------
def build_signal_panel(
decision_date: pd.Timestamp | str,
universe_path: Path | str | None = None,
n_workers: int = 8,
compute_qmj: bool = False,
include_gate: bool = True,
) -> pd.DataFrame:
"""Build the per-ticker signal feature panel at one decision date.
Columns:
[ticker, region, name, location, trading_ccy,
close_local, adv_20d_local, ret_12_2_local, sigma_w_3y_local,
bab_beta_local, trend_r2, trend_beta_local, mdd_12_2_local,
illiq_12m_local, qmj_profitability, qmj_growth, qmj_safety, qmj_payout,
qmj_rd, qmj_quality, qmj_n_measures, gate_exposure, in_exclusion_range,
computed_at]
The QMJ columns (Asness-Frazzini-Pedersen plus shipped R&D pillar:
qmj_profitability / qmj_growth / qmj_safety / qmj_payout / qmj_rd, the
qmj_quality composite, and qmj_n_measures coverage) are attached only when
compute_qmj=True (the active QMJ-veto path), since scoring the full cross-section is the slow step
(~15-25 min); default-BAB runs and tests omit the columns. Per-region rank-z;
NaN where the QMJ gate fails or fundamentals are missing (NaN-kept).
All momentum features are local-currency basis per MSCI methodology.
Scoring, BAB-D10 veto, TC quartile filter, Amihud quintile filter, and
gate application belong in C.3b / C.4 — not here.
Parameters
----------
decision_date : pd.Timestamp | str
AS-OF date for the panel. All features use data strictly <= this date.
universe_path : Path | str | None
Explicit parquet path; defaults to latest data/universe/global_msci_world_imi_*.parquet.
n_workers : int
ThreadPoolExecutor parallelism for per-ticker computation (default 8).
include_gate : bool
Load regional gate states when true. Use unit exposure when false.
"""
if isinstance(decision_date, str):
decision_date = pd.Timestamp(decision_date)
decision_date = decision_date.normalize()
logger.info(
"Building global signal panel at %s with %d workers", decision_date.date(), n_workers
)
# ------------------------------------------------------------------
# Load universe
# ------------------------------------------------------------------
universe = _load_universe(universe_path)
tickers = universe["eodhd_ticker"].tolist()
logger.info("Universe: %d tickers", len(tickers))
# ------------------------------------------------------------------
# Load local returns panel; pre-group by ticker for O(1) per-worker access
# ------------------------------------------------------------------
logger.info("Loading local returns panel…")
local_panel = pd.read_parquet(_LOCAL_RETURNS_PATH)
local_panel["date"] = pd.to_datetime(local_panel["date"])
logger.info("Pre-grouping panel by ticker…")
local_by_ticker = _group_by_ticker(local_panel)
# ------------------------------------------------------------------
# Load regional benchmarks; build per-region return series
# ------------------------------------------------------------------
benchmarks = pd.read_parquet(_BENCHMARKS_PATH)
benchmarks["date"] = pd.to_datetime(benchmarks["date"])
benchmark_rets_by_region: dict[str, pd.Series] = {}
for region, grp in benchmarks.groupby("region"):
grp_sorted = grp.sort_values("date")
s = grp_sorted.set_index("date")["ret_d"].dropna()
# Restrict to trailing ~500 trading days so the regional-benchmark series is
# long enough for the FP w1.5y (378-day) correlation window. Same lookback as
# signal_long._SPY_DAILY_LOOKBACK.
s_before = s[s.index <= decision_date]
benchmark_rets_by_region[str(region)] = s_before.tail(500)
# ------------------------------------------------------------------
# Load gate states + build per-region gate exposure lookup
# ------------------------------------------------------------------
if include_gate:
gate_states = pd.read_parquet(_GATE_STATES_PATH)
gate_states["date"] = pd.to_datetime(gate_states["date"])
gate_by_region = _build_gate_lookup(gate_states, decision_date)
logger.info("Gate exposures at %s: %s", decision_date.date(), gate_by_region)
else:
regions = universe["region_bucket"].dropna().astype(str).unique()
gate_by_region = {region: 1.0 for region in regions}
logger.info("Ungated panel requested; using unit exposure for every region")
# ------------------------------------------------------------------
# Load exclusion table + build set of excluded tickers at decision_date
# ------------------------------------------------------------------
exclusion_table = pd.read_parquet(_EXCLUSION_TABLE_PATH)
exclusion_table["start_date"] = pd.to_datetime(exclusion_table["start_date"])
exclusion_table["end_date"] = pd.to_datetime(exclusion_table["end_date"])
excluded_set = _build_exclusion_set(exclusion_table, decision_date)
logger.info("Tickers in exclusion range at %s: %d", decision_date.date(), len(excluded_set))
# ------------------------------------------------------------------
# Build per-ticker trading_ccy lookup from EODHD symbol cache.
# The universe parquet's `currency` column reflects the BlackRock ETF's
# The source-fund denomination is not the per-ticker local currency.
# The EODHD symbol-list JSON files carry the correct per-ticker `trading_ccy`
# (EUR for ASML.AS, JPY for 7203.TSE, USD for AAPL.US, etc.).
# ------------------------------------------------------------------
trading_ccy_by_ticker: dict[str, str] = _build_trading_ccy_lookup()
if not trading_ccy_by_ticker:
raise RuntimeError(
f"trading_ccy lookup is empty — no symbol-list JSONs found in {_SYMBOLS_DIR}. "
"Run scripts/data/refresh_symbol_cache.py first."
)
# ------------------------------------------------------------------
# Build per-ticker metadata lookup from universe
# ------------------------------------------------------------------
uni_meta: dict[str, dict[str, str]] = {}
for row in universe.itertuples(index=False):
uni_meta[row.eodhd_ticker] = {
"region": row.region_bucket,
"name": row.name,
"location": row.location,
"trading_ccy": trading_ccy_by_ticker.get(row.eodhd_ticker, "USD"),
}
# ------------------------------------------------------------------
# Parallel per-ticker computation
# ------------------------------------------------------------------
total = len(tickers)
all_rows: list[dict[str, Any]] = []
skipped_no_data = 0
skipped_exception = 0
progress_lock = threading.Lock()
completed_count = 0
def _worker(ticker: str) -> dict[str, Any] | None:
meta = uni_meta.get(ticker)
if meta is None:
return None
local_daily = local_by_ticker.get(ticker)
if local_daily is None or local_daily.empty:
return None
local_view = local_daily[["date", "close", "adjusted_close", "volume", "ret_d"]].copy()
region = meta["region"]
bench_rets = benchmark_rets_by_region.get(region, pd.Series(dtype=float))
try:
row = _compute_ticker_row(
ticker=ticker,
region=region,
name=meta["name"],
location=meta["location"],
trading_ccy=meta["trading_ccy"],
local_daily=local_view,
benchmark_rets=bench_rets,
decision_date=decision_date,
)
except Exception as exc:
logger.warning("Exception computing %s: %s — skipping", ticker, exc)
return None
return row
futures_map: dict[concurrent.futures.Future, str] = {}
with concurrent.futures.ThreadPoolExecutor(max_workers=n_workers) as executor:
for ticker in tickers:
fut = executor.submit(_worker, ticker)
futures_map[fut] = ticker
for fut in concurrent.futures.as_completed(futures_map):
with progress_lock:
completed_count += 1
local_count = completed_count
if local_count % 500 == 0:
logger.info("Processed %d / %d tickers…", local_count, total)
row = fut.result()
ticker_key = futures_map[fut]
if row is None:
skipped_no_data += 1
else:
# Attach gate exposure and exclusion flag here — not inside the
# worker — so the worker stays stateless and testable.
row["gate_exposure"] = gate_by_region.get(row["region"], float("nan"))
row["in_exclusion_range"] = ticker_key in excluded_set
row["computed_at"] = decision_date
all_rows.append(row)
logger.info(
"Panel built: %d rows, %d no-data skips, %d exception skips (total universe %d)",
len(all_rows),
skipped_no_data,
skipped_exception,
total,
)
if not all_rows:
return pd.DataFrame(
columns=[
"ticker",
"region",
"name",
"location",
"trading_ccy",
"close_local",
"adv_20d_local",
"ret_12_2_local",
"sigma_w_3y_local",
"bab_beta_local",
"trend_r2",
"trend_beta_local",
"mdd_12_2_local",
"illiq_12m_local",
"qmj_profitability",
"qmj_growth",
"qmj_safety",
"qmj_payout",
"qmj_rd",
"qmj_quality",
"qmj_n_measures",
"qmj_status",
"gate_exposure",
"in_exclusion_range",
"computed_at",
]
)
panel = pd.DataFrame(all_rows)
panel["computed_at"] = pd.to_datetime(panel["computed_at"])
panel = panel.sort_values("ticker").reset_index(drop=True)
# Log region distribution for visibility.
region_counts = panel["region"].value_counts().to_dict()
logger.info("Region distribution: %s", region_counts)
excluded_count = panel["in_exclusion_range"].sum()
logger.info("Tickers flagged in exclusion range: %d", excluded_count)
# ------------------------------------------------------------------
# QMJ quality (Asness-Frazzini-Pedersen) — attached only when it is the active
# veto (compute_qmj=True). Scoring the full ~4k-name cross-section is the slow
# step (~15-25 min), so default-BAB runs and tests skip it. One decision-date
# cross-section, rank-z'd PER REGION (mirroring the per-region BAB-D10 veto).
# local_by_ticker frames already carry a `ret_d` column (built upstream in
# build_global_daily_returns.py), so they are passed straight through.
# NaN qmj_quality is left in place (the veto NaN-keeps those names).
# ------------------------------------------------------------------
if compute_qmj:
panel = _attach_qmj_quality(
panel,
decision_date=decision_date,
local_by_ticker=local_by_ticker,
benchmark_rets_by_region=benchmark_rets_by_region,
)
return panel
def _attach_qmj_quality(
panel: pd.DataFrame,
decision_date: pd.Timestamp,
local_by_ticker: dict[str, pd.DataFrame],
benchmark_rets_by_region: dict[str, pd.Series],
) -> pd.DataFrame:
"""LEFT-merge the QMJ quality columns onto the assembled panel; log coverage.
Brings in the pillars (profitability/growth/safety/payout/R&D), the
qmj_quality composite (the veto input), and qmj_n_measures (coverage) so the
picks CSV can report the full quality breakdown, not just the composite. The
merge is left so the panel row set is unchanged; names without a QMJ score
get NaN across all QMJ columns.
"""
from src.signals.qmj_live import compute_qmj_quality_live # noqa: PLC0415
close_by_ticker = dict(zip(panel["ticker"], panel["close_local"], strict=False))
qmj = compute_qmj_quality_live(
cross_section=panel[["ticker", "region"]],
decision_date=decision_date,
fundamentals_dir=_FUNDAMENTALS_DIR,
daily_by_ticker=local_by_ticker,
benchmark_by_region=benchmark_rets_by_region,
close_by_ticker=close_by_ticker,
region_freq=_LIVE_REGION_FREQ,
)
qmj_cols = [
"qmj_profitability",
"qmj_growth",
"qmj_safety",
"qmj_payout",
"qmj_rd",
"qmj_quality",
"qmj_n_measures",
"qmj_status",
]
panel = panel.merge(qmj[["ticker", *qmj_cols]], on="ticker", how="left")
for region, grp in panel.groupby("region", sort=False):
n_nonnull = int(grp["qmj_quality"].notna().sum())
logger.info(
"qmj_quality coverage [%s]: %d / %d non-null", region, n_nonnull, len(grp)
)
return panel
+608
View File
@@ -0,0 +1,608 @@
"""Multi-region momentum signal orchestrator (Phase C.3b + C.4).
Consumes the signal panel from global_signal_panel.build_signal_panel and
applies per-region BAB / TC / Amihud filters, computes the tm_beta_mdd score
(Gkolemis 2024 slope-of-trend × Choi 2021 MDD penalty, λ locked at
signal_long._TM_MDD_LAMBDA), then selects picks via prefix-expansion until
US >= quota AND EU >= quota AND JP >= quota.
Gate semantics (continuous, mirrors US live signal_long.py):
gate_exposure is the asymmetric VIX-p95 + Goulding daily scalar already
computed with hybrid-lift applied upstream (see
scripts/data/build_regional_gate_states.py). It is used as a CONTINUOUS
scalar — names are NOT binarized at any threshold.
gate_exposure > 0 → region is risk-on; names enter global ranking.
gate_exposure <= 0 → region is risk-off (RISK_OFF state); names excluded
from selection entirely.
Per-name position weights (mirrors signal_long.py:position_pct_tc_hybrid):
position_pct_tc = 1 / per_region_quota (equal-weight ref)
position_pct_tc_hybrid = position_pct_tc * gate_exposure (gate-scaled)
Note on prefix-expansion: this orchestrator may pick MORE than
per_region_quota names in a given region while extending the list to fill
other regions' quotas. When that happens, a region's total sleeve weight
(sum of position_pct_tc_hybrid across that region) will exceed
gate_exposure × 100%. Weights are emitted as-is; the consumer is expected
to renormalize or cap if a strict sleeve budget is required.
Currency convention:
All tm_beta_mdd inputs are local-currency basis (computed on the trading-
currency price series). No FX conversion in the live pipeline.
sigma_w_3y_local is annualized: raw_weekly_std * sqrt(52).
Local-basis filters: bab_beta_local, trend_r2, illiq_12m_local.
Per-region filter quantile cuts are within-region-cross-section only.
"""
import logging
import warnings
from pathlib import Path
import pandas as pd
from src.signals.global_signal_panel import build_signal_panel
from src.signals.price_primitives import _TM_MDD_LAMBDA
from src.signals.qmj_live import _STATUS_NA_COVERAGE
logger = logging.getLogger(__name__)
# ---------------------------------------------------------------------------
# Constants
# ---------------------------------------------------------------------------
_GATED_REGIONS: frozenset[str] = frozenset({"US", "EU", "JP"})
_CA_REGION: str = "CA"
# Continuous gate semantics: only RISK_OFF (gate_exposure <= 0) excludes a region.
# Partial exposure (e.g. 0.3) is kept and scales position size downstream.
_GATE_OFF_FLOOR: float = 0.0
# QMJ-D10 quality veto factor columns (Asness-Frazzini-Pedersen plus shipped R&D
# pillar) — the live veto since 2026-06-06. The pillars + the qmj_quality
# composite (the veto input) + qmj_n_measures (coverage). Present on the qmj path
# (the live default in signal_long_global.py); the legacy --veto bab diagnostic
# does not score quality.
_QMJ_OUTPUT_COLUMNS: list[str] = [
"qmj_quality",
"qmj_profitability",
"qmj_growth",
"qmj_safety",
"qmj_payout",
"qmj_rd",
"qmj_n_measures",
"qmj_status",
]
_OUTPUT_COLUMNS: list[str] = [
"rank",
"region",
"ticker",
"name",
"location",
"trading_ccy",
"score",
"score_type",
"ret_12_2_local_pct",
"sigma_w_3y_local",
"close_local",
*_QMJ_OUTPUT_COLUMNS,
"trend_r2",
"trend_beta_local",
"mdd_12_2_local",
"illiq_12m_local",
"gate_exposure",
"position_pct_tc",
"position_pct_tc_hybrid",
"traded_flag",
]
_CSV_EXCLUDED_COLUMNS: frozenset[str] = frozenset(
{
"gate_exposure",
"position_pct_tc",
"position_pct_tc_hybrid",
"score_type",
}
)
_CSV_OUTPUT_COLUMNS: list[str] = [
column for column in _OUTPUT_COLUMNS if column not in _CSV_EXCLUDED_COLUMNS
]
# ---------------------------------------------------------------------------
# Per-region filter helpers
# ---------------------------------------------------------------------------
def _apply_bab_d10_per_region(df: pd.DataFrame) -> pd.DataFrame:
"""Drop top decile by bab_beta_local within each region's cross-section.
NaN bab_beta_local rows are kept (absence of data is not evidence of high β).
Quantile breakpoint computed on non-NaN values only.
"""
kept_parts: list[pd.DataFrame] = []
for region, grp in df.groupby("region", sort=False):
has_beta = grp["bab_beta_local"].notna()
if not has_beta.any():
kept_parts.append(grp)
continue
threshold = float(grp.loc[has_beta, "bab_beta_local"].quantile(0.90))
drop_mask = has_beta & (grp["bab_beta_local"] >= threshold)
kept_parts.append(grp.loc[~drop_mask])
n_dropped = int(drop_mask.sum())
logger.debug("BAB-D10 [%s]: dropped %d / %d", region, n_dropped, len(grp))
return pd.concat(kept_parts, ignore_index=True) if kept_parts else df.iloc[0:0].copy()
def _apply_qmj_d10_per_region(df: pd.DataFrame) -> pd.DataFrame:
"""Drop bottom decile by qmj_quality within each region's cross-section.
Asness-Frazzini-Pedersen QMJ veto — the bottom-quality analogue of the
BAB-D10 high-β veto, and an EXACT structural mirror of
_apply_bab_d10_per_region (per-region breakpoint, NaN-keep).
NaN qmj_quality rows are kept (absence of quality data is not evidence of
junk). Quantile breakpoint computed on non-NaN values only.
"""
kept_parts: list[pd.DataFrame] = []
for region, grp in df.groupby("region", sort=False):
has_q = grp["qmj_quality"].notna()
if not has_q.any():
kept_parts.append(grp)
continue
threshold = float(grp.loc[has_q, "qmj_quality"].quantile(0.10))
drop_mask = has_q & (grp["qmj_quality"] <= threshold)
kept_parts.append(grp.loc[~drop_mask])
n_dropped = int(drop_mask.sum())
logger.debug("QMJ-D10 [%s]: dropped %d / %d", region, n_dropped, len(grp))
return pd.concat(kept_parts, ignore_index=True) if kept_parts else df.iloc[0:0].copy()
def _apply_tc_top_quartile_per_region(df: pd.DataFrame) -> pd.DataFrame:
"""Keep only top-quartile trend_r2 names within each region's cross-section.
NaN trend_r2 rows are DROPPED (undefined trend clarity → not trend-following).
"""
kept_parts: list[pd.DataFrame] = []
for region, grp in df.groupby("region", sort=False):
has_r2 = grp["trend_r2"].notna()
valid = grp[has_r2].copy()
if valid.empty:
logger.warning("TC filter [%s]: no valid trend_r2 — region produces 0 rows", region)
continue
with warnings.catch_warnings():
warnings.simplefilter("ignore")
valid["_tc_quartile"] = (
pd.qcut(valid["trend_r2"], q=4, labels=False, duplicates="drop") + 1
)
survivors = valid[valid["_tc_quartile"] == 4].drop(columns=["_tc_quartile"])
n_nan = int((~has_r2).sum())
logger.debug(
"TC top-quartile [%s]: %d -> %d (dropped %d low-R2, %d NaN)",
region,
len(grp),
len(survivors),
len(grp) - len(survivors) - n_nan,
n_nan,
)
kept_parts.append(survivors)
return pd.concat(kept_parts, ignore_index=True) if kept_parts else df.iloc[0:0].copy()
def _apply_amihud_l_top_quintile_per_region(df: pd.DataFrame) -> pd.DataFrame:
"""Drop top quintile by illiq_12m_local within each region's cross-section.
NaN illiq_12m_local rows are KEPT (no data ≠ illiquid).
"""
kept_parts: list[pd.DataFrame] = []
for region, grp in df.groupby("region", sort=False):
has_illiq = grp["illiq_12m_local"].notna()
if not has_illiq.any():
kept_parts.append(grp)
continue
threshold = float(grp.loc[has_illiq, "illiq_12m_local"].quantile(0.80))
drop_mask = has_illiq & (grp["illiq_12m_local"] >= threshold)
kept_parts.append(grp.loc[~drop_mask])
logger.debug(
"Amihud-L [%s]: dropped %d top-quintile-illiq / %d",
region,
int(drop_mask.sum()),
len(grp),
)
return pd.concat(kept_parts, ignore_index=True) if kept_parts else df.iloc[0:0].copy()
# ---------------------------------------------------------------------------
# Score computation
# ---------------------------------------------------------------------------
def _compute_scores(pool: pd.DataFrame) -> pd.DataFrame:
"""Attach tm_beta_mdd_score to the post-filter pool.
Formula: (trend_beta_local + _TM_MDD_LAMBDA · mdd_12_2_local) / sigma_w_3y_local
— Gkolemis 2024 slope-of-trend × Choi 2021 MDD penalty.
λ is locked at the validated optimum (signal_long._TM_MDD_LAMBDA).
Inputs are local-currency basis per MSCI Momentum Index Methodology.
"""
out = pool.copy()
sigma_pos = (out["sigma_w_3y_local"] > 0) & out["sigma_w_3y_local"].notna()
inputs_present = (
sigma_pos
& out["trend_beta_local"].notna()
& out["mdd_12_2_local"].notna()
)
out["tm_beta_mdd_score"] = float("nan")
score_num = out["trend_beta_local"] + _TM_MDD_LAMBDA * out["mdd_12_2_local"]
out.loc[inputs_present, "tm_beta_mdd_score"] = (
score_num.loc[inputs_present] / out.loc[inputs_present, "sigma_w_3y_local"]
)
return out
# ---------------------------------------------------------------------------
# Prefix-expansion selection
# ---------------------------------------------------------------------------
def _prefix_expand(
ranked: pd.DataFrame,
per_region_quota: int,
max_total_picks: int,
gated_off_regions: frozenset[str] | set[str] | None = None,
) -> pd.DataFrame:
"""Walk ranked list; stop when all ACTIVE gated-region quotas are filled.
`gated_off_regions` lists regions whose gate is risk-off this cycle. These
regions are expected to have zero eligible names (their rows were dropped
upstream by the gate_exposure filter); they do NOT trigger the degenerate
killswitch and are NOT required to meet the per-region quota.
Quota check & killswitch operate only on ACTIVE gated regions = _GATED_REGIONS
minus `gated_off_regions`. An active region with zero names is still a
data-degenerate condition (filters wiped out a region that should have been
trading) and raises ValueError.
CA names appear where they rank; no quota minimum for CA (informational).
If max_total_picks is reached before quotas are filled, emit a warning and
return whatever was accumulated (soft cap — don't abort).
Unverified-quality extras (qmj_status == "na_coverage"): a name whose data is
too sparse to form a QMJ score (e.g. a genuine zero-debt firm whose missing
debt line drops it below the measure floor) is INCLUDED where it ranks but
does NOT count toward its region's quota. The region therefore still fills its
quota with `per_region_quota` properly-scored / financial names, and the
flagged name rides along as an ADDITIVE +1 (so it never displaces a vetted
pick). It carries qmj_status="na_coverage" for manual verification — confirm
the blank is benign (e.g. truly no debt) and pull it next cycle if the gap is
bad data masking a junk balance sheet. na_financial names (Fama-French
excluded by design) are NOT flagged; they count toward the quota normally.
"""
gated_off = frozenset(gated_off_regions or [])
active_regions = frozenset(_GATED_REGIONS) - gated_off
if not active_regions:
logger.warning(
"All gated regions (US/EU/JP) are risk-off this cycle. "
"Returning CA-only picks (informational, not traded)."
)
# Fail-loud when an ACTIVE region produced zero names — data-degeneracy, not a regime decision.
for region in active_regions:
region_count = int((ranked["region"] == region).sum())
if region_count == 0:
raise ValueError(
f"Active gated region {region} has zero eligible names after all filters "
f"at this decision date. Aborting to avoid a degenerate list. "
f"(gated_off this cycle: {sorted(gated_off) or 'none'})"
)
counts: dict[str, int] = dict.fromkeys(active_regions, 0)
flagged_extra: dict[str, int] = dict.fromkeys(active_regions, 0)
output_rows: list[pd.Series] = []
for _, row in ranked.iterrows():
output_rows.append(row)
region = str(row["region"])
unverified = str(row.get("qmj_status", "")) == _STATUS_NA_COVERAGE
if region in active_regions:
if unverified:
# Additive +1: included but does not consume a quota slot.
flagged_extra[region] += 1
else:
counts[region] += 1
if len(output_rows) >= max_total_picks:
quotas_filled = all(counts[r] >= per_region_quota for r in active_regions)
if not quotas_filled:
logger.warning(
"Prefix-expansion hit max_total_picks=%d before all quotas filled. "
"Counts: %s (quota=%d). Emitting partial list.",
max_total_picks,
{r: counts.get(r, 0) for r in sorted(active_regions)},
per_region_quota,
)
break
if active_regions and all(counts[r] >= per_region_quota for r in active_regions):
break
total_flagged = sum(flagged_extra.values())
if total_flagged:
logger.warning(
"Prefix-expansion admitted %d unverified-quality (na_coverage) extra(s) "
"beyond quota: %s. These are held + traded but flagged — VERIFY each "
"(confirm a benign data gap, e.g. genuine zero debt) before relying on it.",
total_flagged,
{r: n for r, n in sorted(flagged_extra.items()) if n},
)
return pd.DataFrame(output_rows).reset_index(drop=True)
# ---------------------------------------------------------------------------
# Public API
# ---------------------------------------------------------------------------
def run_multi_region_signal(
decision_date: pd.Timestamp | str,
per_region_quota: int = 25,
output_dir: Path | str = "data/signal",
n_workers: int = 8,
max_total_picks: int = 500,
veto: str = "bab",
apply_gate: bool = True,
) -> pd.DataFrame:
"""End-to-end multi-region signal generation.
Pipeline:
1. Build signal panel via global_signal_panel.build_signal_panel.
2. Drop rows where in_exclusion_range == True.
3. Drop rows where the region's gate_exposure <= 0 (RISK_OFF only).
Partial-exposure regions (e.g. 0.3) remain in the ranking; the gate
scalar is propagated through to position_pct_tc_hybrid for sizing.
4. Per region, apply filters in order: BAB-D10 -> TC top-quartile ->
Amihud L top-quintile. Within-region quantile cuts.
5. Compute tm_beta_mdd_score per surviving row (local-currency basis).
6. Global rank by tm_beta_mdd_score descending.
7. Prefix-expansion selection: walk ranking, stop when US >= quota AND
EU >= quota AND JP >= quota. CA names where they appear, no quota.
Soft cap at max_total_picks with warning; hard error only if any
gated region has zero eligible names.
8. Emit CSV to output_dir/signal_long_global_{YYYYMMDD}.csv.
9. Return picks DataFrame.
Parameters
----------
decision_date : pd.Timestamp | str
As-of date for the signal.
per_region_quota : int
Minimum picks per gated region (US / EU / JP).
output_dir : Path | str
Directory where the output CSV is written.
n_workers : int
Parallelism for the underlying signal panel build.
max_total_picks : int
Soft cap on the prefix-expansion list length (warning logged if hit).
veto : str
Quality/risk veto applied at step 4 (BAB step). "bab" (default) drops the
top decile by bab_beta_local (Frazzini-Pedersen high-β veto) — byte-
identical to the prior behaviour. "qmj" drops the bottom decile by
qmj_quality (Asness-Frazzini-Pedersen junk veto) instead. The remaining
TC / Amihud filters are unaffected by this choice.
apply_gate : bool
Apply regional volatility states when true. Use unit exposure when false.
"""
if isinstance(decision_date, str):
decision_date = pd.Timestamp(decision_date)
decision_date = decision_date.normalize()
date_str = decision_date.strftime("%Y%m%d")
logger.info(
"run_multi_region_signal: date=%s λ=%.3f quota=%d",
decision_date.date(),
_TM_MDD_LAMBDA,
per_region_quota,
)
veto_choice = veto.lower()
if veto_choice not in {"bab", "qmj"}:
raise ValueError(f"Unknown veto {veto!r}; expected 'bab' or 'qmj'.")
# ------------------------------------------------------------------
# Step 1: build raw signal panel (QMJ scored only when it is the active veto)
# ------------------------------------------------------------------
panel = build_signal_panel(
decision_date,
n_workers=n_workers,
compute_qmj=(veto_choice == "qmj"),
include_gate=apply_gate,
)
if panel.empty:
raise RuntimeError(
f"build_signal_panel returned an empty panel at {decision_date.date()}. "
"Check that data/processed/global_daily_returns.parquet is populated."
)
# ------------------------------------------------------------------
# Step 2: drop hygiene exclusions
# ------------------------------------------------------------------
n_pre_excl = len(panel)
panel = panel[~panel["in_exclusion_range"]].copy()
logger.info("Dropped %d excluded tickers; %d remain", n_pre_excl - len(panel), len(panel))
# ------------------------------------------------------------------
# Step 3: drop risk-off regions (gate_exposure <= _GATE_OFF_FLOOR, i.e.
# the asymmetric VIX state machine is in RISK_OFF). Continuous-scaling
# semantics: any region with gate_exposure > 0 stays in the ranking, even
# at partial exposure (e.g. 0.3). The scalar is propagated downstream to
# position_pct_tc_hybrid for per-name sizing — selection does NOT binarize.
#
# NaN gate_exposure for a gated region means the gate lookup found no
# valid exposure value <= decision_date (e.g., vol-index cache never
# populated for that region). This is a data-degenerate condition, NOT a
# regime decision — fail loudly here rather than silently dropping the
# region's rows and tripping the prefix-expansion killswitch downstream.
# ------------------------------------------------------------------
gated_off_regions: set[str] = set()
if apply_gate:
region_max_gate = panel.groupby("region")["gate_exposure"].max().to_dict()
nan_gated_regions = {
region
for region in _GATED_REGIONS
if pd.isna(region_max_gate.get(region, float("nan")))
}
if nan_gated_regions:
raise RuntimeError(
f"Gated region(s) {sorted(nan_gated_regions)} have NaN gate_exposure at "
f"{decision_date.date()} — vol-index cache for this region is missing or "
f"never populated. Check data/processed/regional_gate_states.parquet and "
f"the corresponding vol-index source (VIX / V2TX / Nikkei VI)."
)
gated_off_regions = {
region
for region in _GATED_REGIONS
if region_max_gate.get(region, 0.0) <= _GATE_OFF_FLOOR
}
if gated_off_regions:
logger.info(
"Gated-off regions this cycle (RISK_OFF, excluded from selection): %s",
sorted(gated_off_regions),
)
gate_on = panel["gate_exposure"] > _GATE_OFF_FLOOR
n_gated_off_rows = int((~gate_on).sum())
if n_gated_off_rows:
off_regions = panel.loc[~gate_on, "region"].value_counts().to_dict()
logger.info("Gate RISK_OFF drops %d rows: %s", n_gated_off_rows, off_regions)
panel = panel[gate_on].copy()
if panel.empty:
raise RuntimeError(
f"All regions are RISK_OFF at {decision_date.date()} "
f"(gate_exposure <= {_GATE_OFF_FLOOR} for every ticker). "
"This is unexpected — check gate state computation."
)
else:
panel["gate_exposure"] = 1.0
logger.info("Ungated signal requested; using unit exposure for every region")
# ------------------------------------------------------------------
# Step 4: per-region filters in order — BAB-D10, TC top-quartile, Amihud-L
# ------------------------------------------------------------------
n_pre_veto = len(panel)
if veto_choice == "qmj":
panel = _apply_qmj_d10_per_region(panel)
logger.info("Veto=QMJ-D10 (bottom-quality drop): %d -> %d", n_pre_veto, len(panel))
else:
panel = _apply_bab_d10_per_region(panel)
logger.info("Veto=BAB-D10 (top-β drop): %d -> %d", n_pre_veto, len(panel))
n_pre_tc = len(panel)
panel = _apply_tc_top_quartile_per_region(panel)
logger.info("TC top-quartile: %d -> %d", n_pre_tc, len(panel))
n_pre_illiq = len(panel)
panel = _apply_amihud_l_top_quintile_per_region(panel)
logger.info("Amihud-L top-quintile: %d -> %d", n_pre_illiq, len(panel))
# ------------------------------------------------------------------
# Step 5: compute tm_beta_mdd score
# ------------------------------------------------------------------
pool = _compute_scores(panel)
# ------------------------------------------------------------------
# Step 6: rank globally by tm_beta_mdd_score
# ------------------------------------------------------------------
scorable = pool["tm_beta_mdd_score"].notna()
n_unscorable = int((~scorable).sum())
if n_unscorable:
logger.info(
"tm_beta_mdd (λ=%.3f): dropped %d rows with NaN score; %d remain",
_TM_MDD_LAMBDA,
n_unscorable,
int(scorable.sum()),
)
pool = pool.loc[scorable].sort_values("tm_beta_mdd_score", ascending=False).reset_index(drop=True)
# ------------------------------------------------------------------
# Step 8: prefix-expansion selection
# ------------------------------------------------------------------
picks = _prefix_expand(
pool,
per_region_quota,
max_total_picks,
gated_off_regions=gated_off_regions,
)
# ------------------------------------------------------------------
# Assemble output DataFrame per spec schema
# ------------------------------------------------------------------
out = pd.DataFrame()
out["rank"] = range(1, len(picks) + 1)
out["region"] = picks["region"].values
out["ticker"] = picks["ticker"].values
out["name"] = picks["name"].values
out["location"] = picks["location"].values
out["trading_ccy"] = picks["trading_ccy"].values
out["score"] = picks["tm_beta_mdd_score"].round(6).values
out["score_type"] = "tm_beta_mdd"
out["ret_12_2_local_pct"] = (picks["ret_12_2_local"] * 100).round(4).values
out["sigma_w_3y_local"] = picks["sigma_w_3y_local"].round(6).values
out["close_local"] = picks["close_local"].round(6).values
# QMJ-D10 quality veto factor — the live veto. Present on the qmj path; the
# legacy --veto bab diagnostic does not score quality, so emit NaN there.
for col in (
"qmj_quality",
"qmj_profitability",
"qmj_growth",
"qmj_safety",
"qmj_payout",
"qmj_rd",
):
out[col] = picks[col].round(6).values if col in picks.columns else float("nan")
out["qmj_n_measures"] = (
picks["qmj_n_measures"].values if "qmj_n_measures" in picks.columns else float("nan")
)
# qmj_status (scored / na_coverage / na_financial) — string label so a blank
# quality on the picks CSV is self-explaining (Fama-French financial exclusion).
out["qmj_status"] = (
picks["qmj_status"].values if "qmj_status" in picks.columns else ""
)
out["trend_r2"] = picks["trend_r2"].round(6).values
out["trend_beta_local"] = picks["trend_beta_local"].round(6).values
out["mdd_12_2_local"] = picks["mdd_12_2_local"].round(6).values
# round(12), not round(8): Amihud ILLIQ for liquid names is ~1e-9..1e-11; at
# 8 dp those floor to a misleading 0.0 in the CSV (the Amihud filter itself
# uses the unrounded panel value, so selection is unaffected).
out["illiq_12m_local"] = picks["illiq_12m_local"].round(12).values
out["gate_exposure"] = picks["gate_exposure"].round(6).values
# Per-name position weights — mirror signal_long.py's hybrid sizing.
# position_pct_tc = 1 / per_region_quota (equal-weight reference)
# position_pct_tc_hybrid = position_pct_tc * gate_exposure (gate-scaled)
# CA rows compute these uniformly for schema consistency; traded_flag=False
# tells downstream consumers to ignore CA sizing.
base_weight = 1.0 / float(per_region_quota) if per_region_quota > 0 else 0.0
pos_pct_tc = pd.Series([base_weight] * len(picks), index=picks.index)
pos_pct_hybrid = pos_pct_tc * picks["gate_exposure"].astype(float)
out["position_pct_tc"] = pos_pct_tc.round(6).values
out["position_pct_tc_hybrid"] = pos_pct_hybrid.round(6).values
out["traded_flag"] = picks["region"].isin(_GATED_REGIONS).values
# Ensure exact column order per spec.
out = out[_OUTPUT_COLUMNS].reset_index(drop=True)
# ------------------------------------------------------------------
# Step 9: emit CSV
# ------------------------------------------------------------------
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
csv_path = output_path / f"signal_long_global_{date_str}.csv"
out[_CSV_OUTPUT_COLUMNS].to_csv(csv_path, index=False)
logger.info("CSV saved: %s (%d rows)", csv_path, len(out))
return out
+186
View File
@@ -0,0 +1,186 @@
"""Gate-independent price and risk calculations for live stock selection."""
from __future__ import annotations
import numpy as np
import pandas as pd
from src.signals.ex_ante_beta_fp import compute_fp_ex_ante_beta
_SKIP_TRADING_DAYS = 21
_FORMATION_TRADING_DAYS = 252
_WEEKS_3Y_LIVE = 156
_MIN_WEEKS_FOR_SIGMA = 104
_MDD_MIN_OBS = 150
_FP_CORR_WINDOW = 378
_FP_CORR_MIN_OBS = 120
_TM_MDD_LAMBDA = 0.10
def _compute_primitives_at_t(
daily: pd.DataFrame,
decision_date: pd.Timestamp,
) -> dict[str, float] | None:
"""Compute formation return, prices, and ADV at one decision date."""
sliced = daily[daily["date"] <= decision_date].sort_values("date").reset_index(drop=True)
if len(sliced) < _FORMATION_TRADING_DAYS + 1:
return None
adjusted_close = sliced["adjusted_close"].to_numpy(dtype=float)
raw_close = sliced["close"].to_numpy(dtype=float)
dollar_volume = (sliced["close"] * sliced["volume"]).to_numpy(dtype=float)
adjusted_close_at_t = float(adjusted_close[-1])
adjusted_close_after_skip = float(adjusted_close[-(_SKIP_TRADING_DAYS + 1)])
adjusted_close_at_formation = float(adjusted_close[-(_FORMATION_TRADING_DAYS + 1)])
if adjusted_close_after_skip <= 0 or adjusted_close_at_formation <= 0:
return None
return_12_2 = float(
np.log(adjusted_close_after_skip) - np.log(adjusted_close_at_formation)
)
adv_window = dollar_volume[-20:]
adv_window = adv_window[np.isfinite(adv_window)]
adv_20d = float(np.median(adv_window)) if len(adv_window) >= 10 else float("nan")
return {
"ret_12_2": return_12_2,
"close": float(raw_close[-1]),
"adjusted_close": adjusted_close_at_t,
"adv_20d": adv_20d,
}
def _formation_prices(daily: pd.DataFrame, decision_date: pd.Timestamp) -> np.ndarray | None:
sliced = daily[daily["date"] <= decision_date].sort_values("date").reset_index(drop=True)
if len(sliced) < _FORMATION_TRADING_DAYS + 1:
return None
return (
sliced["adjusted_close"]
.iloc[-(_FORMATION_TRADING_DAYS + 1) : -(_SKIP_TRADING_DAYS)]
.to_numpy(dtype=float)
)
def _compute_trend_r2_at_t(daily: pd.DataFrame, decision_date: pd.Timestamp) -> float:
"""Compute price-trend R-squared over the skip-one formation window."""
formation_prices = _formation_prices(daily, decision_date)
if formation_prices is None:
return float("nan")
prices = formation_prices[np.isfinite(formation_prices)]
observations = prices.size
if observations < 3:
return float("nan")
day_index = np.arange(observations, dtype=float)
day_mean = day_index.mean()
price_mean = prices.mean()
day_sum_squares = np.sum((day_index - day_mean) ** 2)
if day_sum_squares == 0:
return float("nan")
beta = np.sum((day_index - day_mean) * (prices - price_mean)) / day_sum_squares
alpha = price_mean - beta * day_mean
fitted_prices = alpha + beta * day_index
residual_sum_squares = np.sum((prices - fitted_prices) ** 2)
total_sum_squares = np.sum((prices - price_mean) ** 2)
if total_sum_squares == 0:
return float("nan")
return float(max(0.0, min(1.0, 1.0 - residual_sum_squares / total_sum_squares)))
def _compute_trend_beta_at_t(daily: pd.DataFrame, decision_date: pd.Timestamp) -> float:
"""Compute the log-price trend slope over the skip-one formation window."""
formation_prices = _formation_prices(daily, decision_date)
if formation_prices is None:
return float("nan")
prices = formation_prices[np.isfinite(formation_prices) & (formation_prices > 0)]
observations = prices.size
if observations < 3:
return float("nan")
log_prices = np.log(prices)
day_index = np.arange(observations, dtype=float)
day_mean = day_index.mean()
log_price_mean = log_prices.mean()
day_sum_squares = float(np.sum((day_index - day_mean) ** 2))
if day_sum_squares == 0:
return float("nan")
return float(
np.sum((day_index - day_mean) * (log_prices - log_price_mean)) / day_sum_squares
)
def _compute_mdd_12_2_at_t(daily: pd.DataFrame, decision_date: pd.Timestamp) -> float:
"""Compute signed maximum drawdown over the skip-one formation window."""
formation_prices = _formation_prices(daily, decision_date)
if formation_prices is None:
return float("nan")
prices = formation_prices[np.isfinite(formation_prices) & (formation_prices > 0)]
if prices.size < _MDD_MIN_OBS:
return float("nan")
log_prices = np.log(prices)
running_maximum = np.maximum.accumulate(log_prices)
return float((log_prices - running_maximum).min())
def _compute_illiq_12m_at_t(daily: pd.DataFrame, decision_date: pd.Timestamp) -> float:
"""Compute Amihud illiquidity over the skip-one formation window."""
sliced = daily[daily["date"] <= decision_date].sort_values("date").reset_index(drop=True)
if len(sliced) < _FORMATION_TRADING_DAYS + 1:
return float("nan")
window = sliced.iloc[-(_FORMATION_TRADING_DAYS + 1) : -(_SKIP_TRADING_DAYS)]
daily_returns = window["ret_d"].to_numpy(dtype=float)
dollar_volume = (window["close"] * window["volume"]).to_numpy(dtype=float)
valid = np.isfinite(daily_returns) & np.isfinite(dollar_volume) & (dollar_volume > 0)
if not valid.any():
return float("nan")
return float(np.mean(np.abs(daily_returns[valid]) / dollar_volume[valid]))
def _compute_sigma_w_3y_at_t(daily: pd.DataFrame, decision_date: pd.Timestamp) -> float:
"""Compute annualized weekly volatility over the trailing three years."""
if daily.empty:
return float("nan")
sliced = daily[daily["date"] <= decision_date].sort_values("date").reset_index(drop=True)
if sliced.empty:
return float("nan")
weekly_returns = (
sliced.set_index("date")["ret_d"]
.resample("W-FRI")
.apply(lambda values: float((1.0 + values).prod() - 1.0))
)
sigma = (
weekly_returns.rolling(_WEEKS_3Y_LIVE, min_periods=_MIN_WEEKS_FOR_SIGMA)
.std()
.dropna()
* np.sqrt(52)
)
sigma_before = sigma[sigma.index <= decision_date]
if sigma_before.empty:
return float("nan")
return float(sigma_before.iloc[-1])
def _compute_ex_ante_beta_for_ticker(
daily: pd.DataFrame,
benchmark_daily_returns: pd.Series,
decision_date: pd.Timestamp,
) -> float:
"""Compute the Frazzini-Pedersen ex-ante beta for one stock."""
sliced = daily[daily["date"] <= decision_date].sort_values("date").reset_index(drop=True)
if sliced.empty:
return float("nan")
ticker_returns = sliced.set_index("date")["ret_d"].dropna()
return compute_fp_ex_ante_beta(
ticker_returns,
benchmark_daily_returns,
decision_date,
corr_window=_FP_CORR_WINDOW,
corr_min_obs=_FP_CORR_MIN_OBS,
)
+479
View File
@@ -0,0 +1,479 @@
"""Live QMJ quality scorer — single-decision-date, per-region cross-section.
Reproduces the validated `src/data/qmj.py::build_qmj_panel` quality score on ONE
decision-date cross-section, standardised independently PER REGION (mirroring the
live BAB-D10 veto, which is per-region). This feeds the live BAB->QMJ veto swap.
Construction parity with the backtest (NOTHING is re-implemented here):
- per-quarter measures: `compute_quarterly_measures` (qmj.py)
- PIT pick: the single latest quarter whose (quarter_end + pit_lag_days) <=
decision_date — the as-of-date analogue of `lag_to_monthly`'s monthly grid.
- shares / market cap: `extract_pit_shares` (fundamentals.py), PIT-lagged the
same way `derive_market_cap` aligns shares (known_from = quarter_end + lag).
- Ohlson-O / Altman-Z: `ohlson_o_score` / `altman_z_score` (qmj.py) + the same
constant-CPI level shift the backtest uses (rank-z absorbs it).
- BAB / IVOL: `compute_fp_beta_ivol` (qmj_risk.py) — the un-shrunk FP beta the
backtest residual IVOL was built on (the live Vasicek-shrunk bab is affine in
beta so rank-z(bab) is identical, but IVOL residuals need this beta to match).
- rank-z / pillar / gate: `rank_z`, `_pillar_score`, `_ALL_MEASURES`,
`QMJConfig.min_measures_overall` (qmj.py).
Gate-failing rows are kept with NaN qmj_quality (the veto NaN-keeps them).
"""
from __future__ import annotations
import json
import logging
from pathlib import Path
import numpy as np
import pandas as pd
from src.data.fundamentals import (
extract_pit_shares,
parse_fundamentals_response,
)
from src.data.qmj import (
_ALL_MEASURES,
_EXCLUDE_FINANCIALS,
_GROWTH,
_LIVE_REQUIRE_PILLARS,
_PAYOUT,
_PIT_LAG_DAYS_ANNUAL,
_PROFITABILITY,
_RD,
_SAFETY,
QMJConfig,
_coverage_gate,
_cpi_at,
_pillar_score,
_ppy_for_freq,
altman_z_score,
compute_quarterly_measures,
is_financial,
load_cpi,
ohlson_o_score,
rank_z,
)
from src.data.qmj_risk import compute_fp_beta_ivol
logger = logging.getLogger(__name__)
_OUT_COLUMNS = [
"ticker",
"qmj_profitability",
"qmj_growth",
"qmj_safety",
"qmj_payout",
"qmj_rd",
"qmj_quality",
"qmj_n_measures",
"qmj_status",
]
# qmj_status values reported on the live picks so a blank quality is self-explaining:
# "scored" — received a finite qmj_quality (entered the cross-section)
# "na_coverage" — entered scoring but failed the coverage gate (too few measures)
# "na_financial" — excluded by the Fama-French financial-sector convention
_STATUS_SCORED = "scored"
_STATUS_NA_COVERAGE = "na_coverage"
_STATUS_NA_FINANCIAL = "na_financial"
# Raw-input columns carried from the PIT quarter row into Ohlson-O / Altman-Z.
_OZ_INPUTS = [
"total_assets",
"total_liabilities",
"short_term_debt",
"lt_debt",
"current_assets",
"current_liabilities",
"wc_refined",
"book_equity",
"retained_earnings",
"ttm_net_income",
"ttm_pretax_income",
"ttm_operating_income",
"ttm_revenue",
]
def _pit_pick(measures: pd.DataFrame, as_of: pd.Timestamp, pit_lag_days: int) -> pd.Series | None:
"""Latest quarter row known by `as_of` (quarter_end + pit_lag_days <= as_of).
The as-of-date analogue of lag_to_monthly's "latest visible row" pick.
"""
if measures.empty:
return None
known_from = measures["quarter_end"] + pd.Timedelta(days=pit_lag_days)
visible = measures[known_from <= as_of]
if visible.empty:
return None
return visible.sort_values("quarter_end").iloc[-1]
def _shares_asof(pit_shares: pd.Series, as_of: pd.Timestamp, pit_lag_days: int) -> float:
"""Latest PIT-visible share count at `as_of` (known_from = quarter_end + lag).
Mirrors derive_market_cap / _shares_monthly: a shares observation dated
quarter_end becomes known after pit_lag_days, then forward-filled.
"""
if pit_shares.empty:
return np.nan
known_from = pit_shares.index + pd.Timedelta(days=pit_lag_days)
sh = pd.Series(pit_shares.to_numpy(), index=known_from).sort_index()
visible = sh[sh.index <= as_of]
if visible.empty:
return np.nan
return float(visible.iloc[-1])
def _load_fundamentals(fundamentals_dir: Path, ticker: str) -> dict | None:
"""Read and JSON-parse a ticker's fundamentals payload; None if absent/bad."""
fpath = fundamentals_dir / f"{ticker}.json"
if not fpath.exists():
return None
try:
return json.loads(fpath.read_text(encoding="utf-8"))
except (ValueError, OSError):
logger.debug("qmj_live: unreadable fundamentals for %s", ticker)
return None
def _ticker_measures_row(
ticker: str,
fundamentals_dir: Path,
decision_date: pd.Timestamp,
close: float,
cpi: pd.Series,
pit_lag_days: int,
freq: str = "quarterly",
periods_per_year: int = 4,
data: dict | None = None,
) -> dict[str, float] | None:
"""Compute the fundamentals-derived measures for one ticker at decision_date.
Returns a dict of {measure -> value} for the profitability/growth/payout +
lev/evol/o_score/z_score Safety members (bab/ivol attached later). None when
no fundamentals / no PIT-visible quarter. `data` may be a preloaded payload
(avoids re-reading the JSON when the caller already opened it, e.g. for the
financial-sector check); when None it is loaded from `fundamentals_dir`.
"""
if data is None:
data = _load_fundamentals(fundamentals_dir, ticker)
if data is None:
return None
quarterly = parse_fundamentals_response(data, ticker, freq=freq)
if quarterly.empty:
return None
measures = compute_quarterly_measures(quarterly, periods_per_year=periods_per_year)
row = _pit_pick(measures, decision_date, pit_lag_days)
if row is None:
return None
# Prior-year TTM net income: the TTM NI known ~12 months earlier. The backtest
# forward-fills ttm_net_income monthly then shifts 12 months; the as-of pick at
# (decision_date - ~1yr) reproduces that latest-visible quarter.
prior_row = _pit_pick(measures, decision_date - pd.Timedelta(days=365), pit_lag_days)
ttm_ni_prior = (
float(prior_row.get("ttm_net_income", np.nan))
if prior_row is not None
else np.nan
)
if not np.isfinite(ttm_ni_prior):
ttm_ni_prior = float(row.get("ttm_net_income", np.nan))
pit_shares = extract_pit_shares(data)
shares_now = _shares_asof(pit_shares, decision_date, pit_lag_days)
shares_prior = _shares_asof(
pit_shares, decision_date - pd.DateOffset(years=1), pit_lag_days
)
market_cap = close * shares_now if np.isfinite(shares_now) else np.nan
eiss = np.nan
if np.isfinite(shares_now) and np.isfinite(shares_prior) and shares_prior != 0:
eiss = -(shares_now / shares_prior - 1.0)
o_raw = ohlson_o_score(
total_assets=row.get("total_assets", np.nan),
total_liabilities=row.get("total_liabilities", np.nan),
short_term_debt=row.get("short_term_debt", np.nan),
lt_debt=row.get("lt_debt", np.nan),
current_assets=row.get("current_assets", np.nan),
current_liabilities=row.get("current_liabilities", np.nan),
ttm_net_income=row.get("ttm_net_income", np.nan),
ttm_net_income_prior=ttm_ni_prior,
ttm_pretax_income=row.get("ttm_pretax_income", np.nan),
book_equity=row.get("book_equity", np.nan),
market_cap=market_cap,
cpi=_cpi_at(cpi, decision_date),
)
o_score = -o_raw if np.isfinite(o_raw) else np.nan
z_score = altman_z_score(
working_capital=row.get("wc_refined", np.nan),
retained_earnings=row.get("retained_earnings", np.nan),
ttm_operating_income=row.get("ttm_operating_income", np.nan),
market_cap=market_cap,
ttm_revenue=row.get("ttm_revenue", np.nan),
total_assets=row.get("total_assets", np.nan),
)
out: dict[str, float] = {"ticker": ticker}
for m in (*_PROFITABILITY, *_GROWTH):
out[m] = float(row.get(m, np.nan))
out["lev"] = float(row.get("lev", np.nan))
out["evol"] = float(row.get("evol", np.nan))
out["diss"] = float(row.get("diss", np.nan))
out["npop"] = float(row.get("npop", np.nan))
out["o_score"] = float(o_score)
out["z_score"] = float(z_score)
ttm_rd = float(row.get("ttm_research_development", np.nan))
if np.isfinite(ttm_rd) and ttm_rd > 0 and np.isfinite(market_cap) and market_cap > 0:
out["rd_me"] = ttm_rd / market_cap
else:
out["rd_me"] = np.nan
out["eiss"] = float(eiss)
return out
def _region_bab_ivol(
tickers: list[str],
decision_date: pd.Timestamp,
daily_by_ticker: dict[str, pd.DataFrame],
benchmark_rets: pd.Series,
) -> dict[str, tuple[float, float]]:
"""Run compute_fp_beta_ivol ONCE for a region; return {ticker -> (bab, ivol)}.
Builds the (date, ticker, ret_d) daily frame, the (date, ret_mkt) market frame,
and panel_pairs = [(decision_date, ticker)] for the region — the exact inputs
qmj_risk consumed in the backtest, so bab/ivol match.
"""
if benchmark_rets is None or len(benchmark_rets) == 0:
return {}
frames: list[pd.DataFrame] = []
for tk in tickers:
d = daily_by_ticker.get(tk)
if d is None or d.empty:
continue
sub = d[["date", "ret_d"]].copy()
sub["ticker"] = tk
frames.append(sub)
if not frames:
return {}
daily = pd.concat(frames, ignore_index=True)
daily["date"] = pd.to_datetime(daily["date"])
market = benchmark_rets.rename("ret_mkt").reset_index()
market.columns = ["date", "ret_mkt"]
market["date"] = pd.to_datetime(market["date"])
pairs = pd.DataFrame({"date": decision_date, "ticker": tickers})
res = compute_fp_beta_ivol(daily, market, pairs)
return {
str(r.ticker): (float(r.bab), float(r.ivol)) for r in res.itertuples(index=False)
}
def _score_region(
rows: pd.DataFrame,
min_measures_overall: int,
require_pillars: tuple[str, ...] = _LIVE_REQUIRE_PILLARS,
add_rd_pillar: bool = True,
) -> pd.DataFrame:
"""rank-z each measure, build pillars + coverage gate, emit output rows.
Reproduces build_qmj_panel's per-date cross-section block exactly, but on a
single region's rows. Gate-failing rows keep NaN qmj_quality.
"""
g = rows.reset_index(drop=True)
all_measures = _ALL_MEASURES + (_RD if add_rd_pillar else [])
z = pd.DataFrame(index=g.index)
for m in all_measures:
z[m] = rank_z(g[m]) if m in g.columns else np.nan
prof = _pillar_score(z, _PROFITABILITY)
grow = _pillar_score(z, _GROWTH)
safe = _pillar_score(z, _SAFETY)
pay = _pillar_score(z, _PAYOUT)
rd = _pillar_score(z, _RD) if add_rd_pillar else pd.Series(np.nan, index=g.index)
n_measures = z[all_measures].notna().sum(axis=1)
gate = _coverage_gate(
z, require_pillars, min_measures_overall, all_measures=all_measures
)
pillar_cols = [prof, grow, safe, pay]
if add_rd_pillar:
pillar_cols.append(rd)
pillar_avg = pd.concat(pillar_cols, axis=1).mean(axis=1, skipna=True)
quality = rank_z(pillar_avg.where(gate))
status = np.where(
np.isfinite(quality.to_numpy()), _STATUS_SCORED, _STATUS_NA_COVERAGE
)
return pd.DataFrame(
{
"ticker": g["ticker"].to_numpy(),
"qmj_profitability": prof.to_numpy(),
"qmj_growth": grow.to_numpy(),
"qmj_safety": safe.to_numpy(),
"qmj_payout": pay.to_numpy(),
"qmj_rd": rd.to_numpy(),
"qmj_quality": quality.to_numpy(),
"qmj_n_measures": n_measures.to_numpy(),
"qmj_status": status,
}
)
def _na_financial_frame(tickers: list[str]) -> pd.DataFrame:
"""Build NaN-quality rows for Fama-French-excluded financials, labelled.
All factor/quality columns are NaN (the veto NaN-keeps them); qmj_status is
"na_financial" so the picks CSV explains the blank rather than leaving it bare.
"""
out = pd.DataFrame({"ticker": tickers})
for col in _OUT_COLUMNS:
if col == "ticker":
continue
out[col] = _STATUS_NA_FINANCIAL if col == "qmj_status" else np.nan
return out[_OUT_COLUMNS]
def compute_qmj_quality_live(
cross_section: pd.DataFrame,
decision_date: pd.Timestamp,
fundamentals_dir: str | Path,
daily_by_ticker: dict[str, pd.DataFrame],
benchmark_by_region: dict[str, pd.Series],
close_by_ticker: dict[str, float],
pit_lag_days: int = 90,
cfg: QMJConfig | None = None,
freq: str | None = None,
require_pillars: tuple[str, ...] | None = None,
min_measures_overall: int | None = None,
add_rd_pillar: bool | None = None,
region_freq: dict[str, str] | None = None,
) -> pd.DataFrame:
"""Live QMJ quality on one decision-date cross-section, rank-z'd PER REGION.
Parameters
----------
cross_section : DataFrame[ticker, region] — names to score at decision_date.
decision_date : pd.Timestamp.
fundamentals_dir : path to data/raw/eodhd/fundamentals/{ticker}.json.
daily_by_ticker : {ticker -> DataFrame[date, ret_d]} for FP beta/IVOL.
benchmark_by_region : {region -> pd.Series} of date-indexed daily benchmark returns.
close_by_ticker : {ticker -> float} close at decision_date (for market cap).
pit_lag_days : PIT lag in calendar days (default 90, matching the backtest's
quarterly default). Pass 180 (or set cfg) for the annual FF convention.
freq / require_pillars / min_measures_overall : opt-in overrides for the
QMJ construction. When None they fall back to `cfg`, whose default is the
live growth-optional quarterly gate (require Profitability+Safety+Payout;
Growth skippable — shipped 2026-06-07). To stay a faithful single-cross-
section reproduction of build_qmj_panel, pass the SAME values both places.
add_rd_pillar : include R&D expense / market equity as the fifth QMJ pillar.
Defaults to cfg.add_rd_pillar. For quarterly regions this uses positive
TTM R&D; for annual regions it uses the annual reported R&D flow.
region_freq : optional {region -> "quarterly"|"annual"} map. A region listed
here is scored at that frequency (annual ⇒ PIT lag 180d, the FF
convention); regions absent from the map use `freq`/`cfg.freq`. This is
the live per-region data-quality policy (EU→annual since its quarterly
EODHD coverage is gappy; US/CA/JP stay quarterly — complete and fresher).
Because QMJ is rank-z'd and vetoed PER REGION, differing the frequency
across regions introduces no cross-region inconsistency.
Returns columns [ticker, qmj_profitability, qmj_growth, qmj_safety,
qmj_payout, qmj_rd, qmj_quality, qmj_n_measures]. Each region is standardised
independently. Gate-failing rows are kept with NaN qmj_quality.
"""
decision_date = pd.Timestamp(decision_date).normalize()
cfg = cfg or QMJConfig()
resolved_freq = freq if freq is not None else cfg.freq
resolved_require = require_pillars if require_pillars is not None else cfg.require_pillars
resolved_min = (
min_measures_overall if min_measures_overall is not None else cfg.min_measures_overall
)
resolved_add_rd = cfg.add_rd_pillar if add_rd_pillar is None else add_rd_pillar
fdir = Path(fundamentals_dir)
cpi = load_cpi(cfg.cpi_csv)
region_freq = region_freq or {}
cs = cross_section[["ticker", "region"]].drop_duplicates().reset_index(drop=True)
out_frames: list[pd.DataFrame] = []
for region, grp in cs.groupby("region", sort=False):
region_tickers = grp["ticker"].astype(str).tolist()
# Per-region frequency: a region in region_freq overrides the default;
# annual regions use the 180d FF PIT lag, quarterly the passed pit_lag_days.
region_freq_val = region_freq.get(str(region), resolved_freq)
region_ppy = _ppy_for_freq(region_freq_val)
region_lag = _PIT_LAG_DAYS_ANNUAL if region_freq_val == "annual" else pit_lag_days
rows: list[dict[str, float]] = []
financial_tickers: list[str] = []
for tk in region_tickers:
close = close_by_ticker.get(tk, np.nan)
if not np.isfinite(close):
continue
data = _load_fundamentals(fdir, tk)
if data is None:
continue
# Fama-French convention: financials are excluded from the scored
# cross-section (so they neither receive a score nor distort the
# rank-z of non-financials) and labelled "na_financial".
if _EXCLUDE_FINANCIALS and is_financial(data):
financial_tickers.append(tk)
continue
mrow = _ticker_measures_row(
ticker=tk,
fundamentals_dir=fdir,
decision_date=decision_date,
close=float(close),
cpi=cpi,
pit_lag_days=region_lag,
freq=region_freq_val,
periods_per_year=region_ppy,
data=data,
)
if mrow is not None:
rows.append(mrow)
if financial_tickers:
out_frames.append(_na_financial_frame(financial_tickers))
if not rows:
continue
bab_ivol = _region_bab_ivol(
tickers=[r["ticker"] for r in rows],
decision_date=decision_date,
daily_by_ticker=daily_by_ticker,
benchmark_rets=benchmark_by_region.get(str(region)),
)
for r in rows:
bab, ivol = bab_ivol.get(r["ticker"], (np.nan, np.nan))
r["bab"] = bab
r["ivol"] = ivol
region_df = pd.DataFrame(rows)
out_frames.append(
_score_region(
region_df,
resolved_min,
resolved_require,
add_rd_pillar=resolved_add_rd,
)
)
if not out_frames:
return pd.DataFrame(columns=_OUT_COLUMNS)
result = pd.concat(out_frames, ignore_index=True)
return result[_OUT_COLUMNS].reset_index(drop=True)