Datasets:
Update the security master
Browse files- LICENSE +201 -0
- NOTICE +14 -0
- PIPELINE.md +131 -0
- README.md +191 -0
- data/cusip_map/part-00000.parquet +3 -0
- data/identifiers/part-00000.parquet +3 -0
- data/issuers/part-00000.parquet +3 -0
- data/observations/part-00000.parquet +3 -0
- data/observations/part-00001.parquet +3 -0
- data/observations/part-00002.parquet +3 -0
- data/pit/part-00000.parquet +3 -0
- data/pit/security_master.delta/_delta_log/00000000000000000000.json +4 -0
- data/pit/security_master.delta/part-00000-84bed2a2-6ab3-4b85-bb3d-e89904eeb1d4-c000.snappy.parquet +3 -0
- jobs/run.py +107 -0
- manifest.json +155 -0
- pyproject.toml +47 -0
- recipe/__init__.py +3 -0
- recipe/build.py +111 -0
- recipe/cli.py +77 -0
- recipe/config.py +57 -0
- recipe/hf_jobs.py +228 -0
- recipe/intervals.py +275 -0
- recipe/manifest.py +119 -0
- recipe/publish.py +135 -0
- recipe/quality.py +189 -0
- recipe/schema.py +128 -0
- recipe/sec_client.py +309 -0
- recipe/sources.py +224 -0
- recipe/store.py +120 -0
- recipe/symbols.py +144 -0
- tests/conftest.py +57 -0
- tests/test_docs_and_jobs.py +58 -0
- tests/test_intervals.py +89 -0
- tests/test_symbols.py +50 -0
LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright 2026 ZipLime
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
NOTICE
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ZipLime US Security Master
|
| 2 |
+
Copyright 2026 ZipLime
|
| 3 |
+
|
| 4 |
+
Source data: US Securities and Exchange Commission — EDGAR filings, the company
|
| 5 |
+
tickers file, and the fails-to-deliver records. US Government works in the
|
| 6 |
+
public domain.
|
| 7 |
+
|
| 8 |
+
Assembled from the ZipLime insider-trading and company-fundamentals datasets,
|
| 9 |
+
which are themselves derived from EDGAR.
|
| 10 |
+
|
| 11 |
+
This dataset adds normalization, dated intervals, the CUSIP bridge and
|
| 12 |
+
verification. Those additions are licensed under Apache-2.0 (see LICENSE).
|
| 13 |
+
|
| 14 |
+
The SEC does not endorse, certify or verify this dataset.
|
PIPELINE.md
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# How this dataset is built
|
| 2 |
+
|
| 3 |
+
Every step is in [`recipe/`](recipe/), published at the same revision as the
|
| 4 |
+
data. This document records what the steps do and what went wrong on the way.
|
| 5 |
+
|
| 6 |
+
## The idea
|
| 7 |
+
|
| 8 |
+
A security master is usually bought. The free alternatives are snapshots —
|
| 9 |
+
`company_tickers.json` states today's CIK-to-ticker map and carries no past, so
|
| 10 |
+
a company that changed symbol is listed under the new one for its entire life,
|
| 11 |
+
and every backtest built on it silently reads one company's prices against
|
| 12 |
+
another's fundamentals.
|
| 13 |
+
|
| 14 |
+
The history exists, though, scattered across filings nobody reads for this
|
| 15 |
+
purpose. Four million Form 4 submissions each print the issuer's trading symbol
|
| 16 |
+
on a known date. Every XBRL filing header carries the company's name, its former
|
| 17 |
+
name and the date it changed. Settlement records tie a CUSIP to a ticker twice
|
| 18 |
+
a month since 2004. Collected with their dates, those are a security master.
|
| 19 |
+
|
| 20 |
+
So this dataset has almost no source of its own. It is assembled from the
|
| 21 |
+
sibling datasets and from three SEC files, and it publishes the evidence
|
| 22 |
+
alongside the conclusions.
|
| 23 |
+
|
| 24 |
+
## The ticker box
|
| 25 |
+
|
| 26 |
+
[`symbols.py`](recipe/symbols.py) exists because 2.3% of Form 4 filings do not
|
| 27 |
+
put a ticker in the ticker box. They put an exchange prefix (`NYSE: KRC`),
|
| 28 |
+
parentheses (`(SIRI)`), two share classes at once (`ISCA, ISCB`, `JWA/JWB`,
|
| 29 |
+
`CRDA CRDB`), a symbol spelled with spaces (`N O G`), a venue note
|
| 30 |
+
(`NWIN(OB)`), a CIK, or a word meaning absence (`NONE`, `N/A`). Read literally
|
| 31 |
+
they become 3 428 tickers that never traded, and Hubbell, Wiley and
|
| 32 |
+
Brown-Forman lose their real symbols.
|
| 33 |
+
|
| 34 |
+
The parser reaches 98.97% of four million filings; the remainder is genuine
|
| 35 |
+
absence. Two cases in it are worth keeping in mind, because both were bugs
|
| 36 |
+
first:
|
| 37 |
+
|
| 38 |
+
* `NYSE/TRN` splits into two chunks and the first is a venue, not a
|
| 39 |
+
four-letter ticker — but `CBOE` alone is Cboe Global Markets, whose ticker is
|
| 40 |
+
its own name. A venue name is discarded only when some other chunk parsed.
|
| 41 |
+
* `NWIN(OB)` lost its symbol because brackets were stripped before the trailing
|
| 42 |
+
note was read, turning it into `NWIN(OB` and matching nothing.
|
| 43 |
+
|
| 44 |
+
## Observations, then spans
|
| 45 |
+
|
| 46 |
+
Everything collected is a dated statement: *this filer stated this identifier
|
| 47 |
+
on this day*. Ten million of them. The spans in `identifiers` are a groupby over
|
| 48 |
+
that, and nothing more — first observation, last observation, how many, from
|
| 49 |
+
which sources.
|
| 50 |
+
|
| 51 |
+
The restraint is deliberate. It would be easy to emit `valid_to` as the day
|
| 52 |
+
before the next ticker appeared, which reads better and claims something the
|
| 53 |
+
evidence does not support: nobody publishes the day a ticker changed hands, and
|
| 54 |
+
a filing gap is a filing gap, not a delisting. `observations` ships so that
|
| 55 |
+
anyone who wants stronger intervals can derive them from the same evidence.
|
| 56 |
+
|
| 57 |
+
## What "current" means
|
| 58 |
+
|
| 59 |
+
The first definition was "the newest value this filer stated". It made a
|
| 60 |
+
company that stopped filing in 2014 permanently current under its 2014 ticker,
|
| 61 |
+
and when another company later took that ticker over, both were current at
|
| 62 |
+
once — 1 218 tickers, 6% of the live universe, each pointing at two companies.
|
| 63 |
+
|
| 64 |
+
Now `is_current` also requires the filer to still be filing, and 53 remain.
|
| 65 |
+
Those are genuine: dual filers and reorganisations mid-transfer.
|
| 66 |
+
`is_latest_for_filer` keeps the old meaning, because "what did this company last
|
| 67 |
+
call itself" is a real question about dormant companies, and keying issuer
|
| 68 |
+
attributes on `is_current` would leave every dormant filer nameless.
|
| 69 |
+
|
| 70 |
+
## The CUSIP bridge
|
| 71 |
+
|
| 72 |
+
13F and N-PORT name a holding by CUSIP; everything else names a company by CIK.
|
| 73 |
+
The composition is: settlement records give CUSIP to ticker on a date, filings
|
| 74 |
+
give ticker to filer over a span, and the join is on the ticker with the dates
|
| 75 |
+
required to overlap. Overlap is what separates a confident match from a
|
| 76 |
+
plausible one, and it matters precisely for the reused tickers this dataset
|
| 77 |
+
exists to disentangle.
|
| 78 |
+
|
| 79 |
+
Two things were learned by measuring rather than assuming.
|
| 80 |
+
|
| 81 |
+
**The count is the wrong measure.** By raw CUSIP count the bridge looked 37%
|
| 82 |
+
complete, which reads like a failure. Against actual 13F holdings the same
|
| 83 |
+
bridge covers 82.8% of holding rows and 87.9% of position value. Two thirds of
|
| 84 |
+
the CUSIPs ever traded are one-off warrants, foreign lines and delisted shells
|
| 85 |
+
that no strategy touches. The build now gates on match rate weighted by
|
| 86 |
+
settlement traffic, excluding funds.
|
| 87 |
+
|
| 88 |
+
**Exchange-traded funds can never resolve, and that is correct.** `IVV`, `IWM`,
|
| 89 |
+
`SPY` settle like shares and file nothing a CIK could attach to. Counting them
|
| 90 |
+
as misses is what made the bridge look broken. They carry `looks_like_fund` and
|
| 91 |
+
sit outside the gated denominator.
|
| 92 |
+
|
| 93 |
+
**The first six characters are the issuer.** A CUSIP's prefix identifies the
|
| 94 |
+
company, the suffix the instrument, so a class B share or a preferred of a
|
| 95 |
+
company whose common stock already resolved belongs to the same filer. Saying
|
| 96 |
+
so is a fact about how CUSIPs are assigned, not a guess — but the instrument
|
| 97 |
+
itself was never matched, only its issuer, so it carries its own method and a
|
| 98 |
+
middle confidence. It lifted coverage from 37% to 69% of pairs.
|
| 99 |
+
|
| 100 |
+
## Verification
|
| 101 |
+
|
| 102 |
+
[`quality.py`](recipe/quality.py) gates publication. The check that earns its
|
| 103 |
+
place is ambiguity: a ticker current for two filers means somebody's history
|
| 104 |
+
has been attached to the wrong company, and nothing else in the pipeline would
|
| 105 |
+
notice. It caught the `is_current` definition above.
|
| 106 |
+
|
| 107 |
+
The other floors — ticker coverage among active filers, weighted CUSIP match,
|
| 108 |
+
issuer count — are set below measured values so a regression fails and noise
|
| 109 |
+
does not. All of them were set *after* measuring; the first attempt used
|
| 110 |
+
guessed thresholds, and both guesses were wrong in opposite directions.
|
| 111 |
+
|
| 112 |
+
## Schedule
|
| 113 |
+
|
| 114 |
+
A Hugging Face Job runs [`jobs/run.py`](jobs/run.py) weekly on Monday at 07:40
|
| 115 |
+
UTC, after the sibling datasets have refreshed: restore, lint, test, rebuild,
|
| 116 |
+
verify, publish. Weekly rather than daily because the inputs are weekly at
|
| 117 |
+
best — settlement files land twice a month and the sibling datasets are the
|
| 118 |
+
things that move.
|
| 119 |
+
|
| 120 |
+
## What is not done
|
| 121 |
+
|
| 122 |
+
* **No history before Form 4.** Ticker evidence effectively starts in 2006.
|
| 123 |
+
EDGAR does not carry what a company traded as in 1998, so neither does this.
|
| 124 |
+
* **No exchange history worth the name.** Filers rarely name the venue and SEC's
|
| 125 |
+
current map covers only live listings, so 8 210 spans is all the evidence
|
| 126 |
+
there is.
|
| 127 |
+
* **No ISIN, no LEI, no FIGI.** 13F carries a FIGI column and N-PORT carries
|
| 128 |
+
ISIN; neither is ingested yet. The schema has room for them.
|
| 129 |
+
* **No fuzzy name matching.** A CUSIP could often be attached to a filer by
|
| 130 |
+
comparing issuer names, and a name match that is wrong is indistinguishable
|
| 131 |
+
from one that is right. Unmatched is more useful than plausibly wrong.
|
README.md
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
pretty_name: US Security Master — dated identifiers for SEC filers
|
| 6 |
+
size_categories:
|
| 7 |
+
- 1M<n<10M
|
| 8 |
+
task_categories:
|
| 9 |
+
- tabular-classification
|
| 10 |
+
tags:
|
| 11 |
+
- finance
|
| 12 |
+
- sec
|
| 13 |
+
- edgar
|
| 14 |
+
- security-master
|
| 15 |
+
- cusip
|
| 16 |
+
- ticker
|
| 17 |
+
- point-in-time
|
| 18 |
+
- survivorship-bias
|
| 19 |
+
- ziplime
|
| 20 |
+
configs:
|
| 21 |
+
- config_name: issuers
|
| 22 |
+
data_files:
|
| 23 |
+
- split: train
|
| 24 |
+
path: "data/issuers/*.parquet"
|
| 25 |
+
- config_name: identifiers
|
| 26 |
+
data_files:
|
| 27 |
+
- split: train
|
| 28 |
+
path: "data/identifiers/*.parquet"
|
| 29 |
+
- config_name: cusip_map
|
| 30 |
+
data_files:
|
| 31 |
+
- split: train
|
| 32 |
+
path: "data/cusip_map/*.parquet"
|
| 33 |
+
- config_name: observations
|
| 34 |
+
data_files:
|
| 35 |
+
- split: train
|
| 36 |
+
path: "data/observations/*.parquet"
|
| 37 |
+
- config_name: pit
|
| 38 |
+
data_files:
|
| 39 |
+
- split: train
|
| 40 |
+
path: "data/pit/*.parquet"
|
| 41 |
+
---
|
| 42 |
+
|
| 43 |
+
# US Security Master
|
| 44 |
+
|
| 45 |
+
Which company a ticker belonged to, on a date. Which filer a CUSIP points at.
|
| 46 |
+
What a company used to be called.
|
| 47 |
+
|
| 48 |
+
**23 529 filers · 143 932 identifier spans · 10 056 033 dated observations ·
|
| 49 |
+
74 392 CUSIPs · 1960 to 2026**
|
| 50 |
+
|
| 51 |
+
This is the glue for the rest of the family. Every other ZipLime dataset keys
|
| 52 |
+
on the SEC's CIK, which never changes — and every price series, broker feed and
|
| 53 |
+
research note keys on a ticker, which changes all the time. Joining the two
|
| 54 |
+
with today's mapping is the quiet way to put the wrong company's history into a
|
| 55 |
+
backtest.
|
| 56 |
+
|
| 57 |
+
The pipeline lives in [`recipe/`](recipe/) at the same revision as the data.
|
| 58 |
+
See [PIPELINE.md](PIPELINE.md) for the method and its limits.
|
| 59 |
+
|
| 60 |
+
## The problem this exists for
|
| 61 |
+
|
| 62 |
+
| | |
|
| 63 |
+
|---|---|
|
| 64 |
+
| Filers that changed ticker | **6 392** of 23 529 |
|
| 65 |
+
| Filers that changed name | **11 435** |
|
| 66 |
+
| Tickers held by more than one company over time | **2 215** of 26 844 |
|
| 67 |
+
|
| 68 |
+
A ticker is not an identity. `PLUM` can be one company until 2014 and another
|
| 69 |
+
from 2019, and a strategy that resolves it by today's map reads the second
|
| 70 |
+
company's fundamentals against the first company's prices for the earlier
|
| 71 |
+
years. This dataset says which was which, and when.
|
| 72 |
+
|
| 73 |
+
```python
|
| 74 |
+
import polars as pl
|
| 75 |
+
|
| 76 |
+
spans = pl.read_parquet("data/identifiers/*.parquet")
|
| 77 |
+
|
| 78 |
+
def cik_for(ticker: str, on: str) -> str | None:
|
| 79 |
+
hit = spans.filter(
|
| 80 |
+
(pl.col("kind") == "ticker")
|
| 81 |
+
& (pl.col("value") == ticker)
|
| 82 |
+
& (pl.col("valid_from") <= pl.lit(on).str.to_date())
|
| 83 |
+
& (pl.col("valid_to") >= pl.lit(on).str.to_date())
|
| 84 |
+
).sort("observations", descending=True)
|
| 85 |
+
return hit["cik"][0] if hit.height else None
|
| 86 |
+
|
| 87 |
+
cik_for("FB", "2015-06-30") # Meta, under its old symbol
|
| 88 |
+
cik_for("META", "2015-06-30") # None — the symbol did not exist yet
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
## What a span means, and what it does not
|
| 92 |
+
|
| 93 |
+
`valid_from` and `valid_to` are the **first and last filing that stated the
|
| 94 |
+
identifier**, not registry dates. Nobody publishes the day a ticker changed
|
| 95 |
+
hands. A gap inside a span means nobody filed, not that the identifier lapsed,
|
| 96 |
+
and `observations` says how much evidence stands behind it.
|
| 97 |
+
|
| 98 |
+
Two flags answer two different questions:
|
| 99 |
+
|
| 100 |
+
* `is_latest_for_filer` — the newest value this company gave. Use it to ask
|
| 101 |
+
*what did this company last call itself*, including companies that stopped
|
| 102 |
+
filing in 2011.
|
| 103 |
+
* `is_current` — that, **and** the company still files. Use it to ask *who owns
|
| 104 |
+
this ticker now*. Defining current without the second condition left 1 218
|
| 105 |
+
tickers current for two companies at once; with it, 53 remain, and those are
|
| 106 |
+
genuine dual filers.
|
| 107 |
+
|
| 108 |
+
## The CUSIP bridge
|
| 109 |
+
|
| 110 |
+
13F and N-PORT identify a holding by CUSIP. Everything else identifies a
|
| 111 |
+
company by CIK. No free source maps between them, so this one is built:
|
| 112 |
+
settlement records tie a CUSIP to a ticker on a date, filings tie a ticker to a
|
| 113 |
+
filer over a span, and the two compose.
|
| 114 |
+
|
| 115 |
+
| Match | Rows | Meaning |
|
| 116 |
+
|---|---|---|
|
| 117 |
+
| `ticker_and_dates` | 22 921 | the ticker matched and the dates overlap — **high** |
|
| 118 |
+
| `cusip6_inherited` | 23 519 | another security of the same issuer resolved — **medium** |
|
| 119 |
+
| `ticker_only` | 4 747 | the ticker matched, the dates do not overlap — **low** |
|
| 120 |
+
| `unmatched` | 23 205 | no filer found — **none** |
|
| 121 |
+
|
| 122 |
+
**68.8% of CUSIP-ticker pairs resolve to a filer; 78.8% weighted by how often
|
| 123 |
+
the CUSIP appears in settlement records.** Measured against real 13F holdings,
|
| 124 |
+
the matched set covers **82.8% of holding rows and 87.9% of position value.**
|
| 125 |
+
|
| 126 |
+
Counting raw CUSIPs understates it badly, and the reason is worth knowing:
|
| 127 |
+
10 536 of these are exchange-traded funds. An ETF settles like a share and
|
| 128 |
+
files nothing a CIK could attach to — `IVV`, `IWM`, `SPY` will never resolve to
|
| 129 |
+
an operating company, because they are not one. They carry
|
| 130 |
+
`looks_like_fund = true` and are excluded from the coverage the build gates on.
|
| 131 |
+
|
| 132 |
+
```python
|
| 133 |
+
bridge = pl.read_parquet("data/cusip_map/*.parquet")
|
| 134 |
+
holdings = holdings.join(
|
| 135 |
+
bridge.filter(pl.col("match_confidence").is_in(["high", "medium"]))
|
| 136 |
+
.select("cusip", "cik"),
|
| 137 |
+
on="cusip", how="left",
|
| 138 |
+
) # now 13F joins to fundamentals and insider trades on `cik`
|
| 139 |
+
```
|
| 140 |
+
|
| 141 |
+
## Configs
|
| 142 |
+
|
| 143 |
+
| Config | Rows | What one row is |
|
| 144 |
+
|---|---|---|
|
| 145 |
+
| `issuers` | 23 529 | one filer: current name, ticker, industry, and how long it has filed |
|
| 146 |
+
| `identifiers` | 143 932 | one identifier and the span of filings that stated it |
|
| 147 |
+
| `cusip_map` | 74 392 | one CUSIP, the ticker it settles under, the filer behind it |
|
| 148 |
+
| `observations` | 10 056 033 | one dated statement — the evidence the spans are built from |
|
| 149 |
+
| `pit` | 143 932 | one point-in-time identifier event, plus a Delta table for ziplime |
|
| 150 |
+
|
| 151 |
+
`observations` is published so that anyone who disagrees with how the spans
|
| 152 |
+
were derived can derive their own. It is the only honest way to ship a
|
| 153 |
+
judgement.
|
| 154 |
+
|
| 155 |
+
## Where the evidence comes from
|
| 156 |
+
|
| 157 |
+
| Source | Observations | What it gives |
|
| 158 |
+
|---|---|---|
|
| 159 |
+
| Form 4 filings, via [ZipLime/insider-trading](https://huggingface.co/datasets/ZipLime/insider-trading) | 8 123 634 | the ticker a company printed on a filing, on that day — the only free source of ticker **history** |
|
| 160 |
+
| XBRL filings, via [ZipLime/company-fundamentals](https://huggingface.co/datasets/ZipLime/company-fundamentals) | 1 901 363 | names, former names with change dates, industry, incorporation, fiscal year end |
|
| 161 |
+
| SEC `company_tickers_exchange.json` | 31 036 | today's listings, including companies that never filed a Form 4 |
|
| 162 |
+
| SEC fails-to-deliver records, 409 archives | 23.4M records | CUSIP to ticker, twice a month since 2004 |
|
| 163 |
+
|
| 164 |
+
`company_tickers.json` alone is what most projects use, and it is a snapshot:
|
| 165 |
+
it states today and carries no past, so a company that changed symbol appears
|
| 166 |
+
under the new one for its entire life. The history here comes from four million
|
| 167 |
+
filings that each stated a symbol on a known date.
|
| 168 |
+
|
| 169 |
+
## Coverage and honest gaps
|
| 170 |
+
|
| 171 |
+
* **81% of filers have a ticker; 93% of *active* filers do.** The rest are
|
| 172 |
+
funds, trusts and private filers that never printed one.
|
| 173 |
+
* **Exchange is sparse** — 8 210 spans. Filers rarely name the venue, and SEC's
|
| 174 |
+
current map only covers live listings.
|
| 175 |
+
* **Coverage starts in 1960** only because a filing header stated a name change
|
| 176 |
+
from then. Ticker evidence effectively begins in 2006 with Form 4, and
|
| 177 |
+
identifiers before that are not in EDGAR to be found.
|
| 178 |
+
* **A span is evidence, not a registry.** See above.
|
| 179 |
+
* **Fund CUSIPs do not resolve, by construction.** See above.
|
| 180 |
+
* **53 tickers are current for two filers.** Dual filers and reorganisations
|
| 181 |
+
mid-transfer; the raw observations let you decide.
|
| 182 |
+
|
| 183 |
+
## Provenance and updates
|
| 184 |
+
|
| 185 |
+
Sources: SEC EDGAR (Form 4 and XBRL filings, both via sibling ZipLime
|
| 186 |
+
datasets), `company_tickers_exchange.json`, and the fails-to-deliver
|
| 187 |
+
files — all US Government works in the public domain.
|
| 188 |
+
|
| 189 |
+
Rebuilt weekly, Monday 07:40 UTC, by a Hugging Face Job
|
| 190 |
+
([`jobs/run.py`](jobs/run.py)) that lints, tests, rebuilds, verifies and only
|
| 191 |
+
then publishes.
|
data/cusip_map/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:95487d6e87e1011036a6460a202f7c079181b2a9d767a58e0882cd992d719f98
|
| 3 |
+
size 1831699
|
data/identifiers/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aeb152b19dd13941741665b3ca78f72a311d11ea143f38f2ba6db403d15df29a
|
| 3 |
+
size 1744428
|
data/issuers/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9dcfd2a8ad81fe183786fa06a8b6f85f7d259e436c23068145c9e621e4678439
|
| 3 |
+
size 689716
|
data/observations/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eeda9a1363b432a8d465feef471042daca92e94e42d2eb48887a4f574adaee6b
|
| 3 |
+
size 29395692
|
data/observations/part-00001.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4b465a9ab6ba2add257bd56e5232539e5c5c1f43af40a7d27f4dfb437ee66d42
|
| 3 |
+
size 29983873
|
data/observations/part-00002.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a816fed7eaf40d6f30ebeb375d02702d07a5da392417e0cd6369d24ea7648d26
|
| 3 |
+
size 458388
|
data/pit/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ba2b689a141309a0b6810081db7e27d54841a89755b888485d3113ff6e99388b
|
| 3 |
+
size 3593459
|
data/pit/security_master.delta/_delta_log/00000000000000000000.json
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{"commitInfo":{"timestamp":1788775777234,"operation":"WRITE","operationParameters":{"mode":"Overwrite"},"engineInfo":"delta-rs:py-1.6.2","operationMetrics":{"execution_time_ms":186,"num_added_files":1,"num_added_rows":143932,"num_partitions":0,"num_removed_files":0},"clientVersion":"delta-rs.py-1.6.2"}}
|
| 2 |
+
{"protocol":{"minReaderVersion":1,"minWriterVersion":2}}
|
| 3 |
+
{"metaData":{"id":"5d33a43b-fb97-493d-bc98-f8852636a368","name":null,"description":null,"format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"pit_event_id\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"entity_id\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"event_date\",\"type\":\"date\",\"nullable\":true,\"metadata\":{}},{\"name\":\"knowledge_date\",\"type\":\"timestamp\",\"nullable\":true,\"metadata\":{}},{\"name\":\"knowledge_estimated\",\"type\":\"boolean\",\"nullable\":true,\"metadata\":{}},{\"name\":\"kind\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"value\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"valid_to\",\"type\":\"date\",\"nullable\":true,\"metadata\":{}},{\"name\":\"observations\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"sources\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"is_current\",\"type\":\"boolean\",\"nullable\":true,\"metadata\":{}},{\"name\":\"ingested_at\",\"type\":\"timestamp\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":[],"createdTime":1788775777052,"configuration":{}}}
|
| 4 |
+
{"add":{"path":"part-00000-84bed2a2-6ab3-4b85-bb3d-e89904eeb1d4-c000.snappy.parquet","partitionValues":{},"size":5114932,"modificationTime":1788775777232,"dataChange":true,"stats":"{\"numRecords\":143932,\"minValues\":{\"sources\":\"company_tickers\",\"is_current\":false,\"event_date\":\"1960-02-01\",\"value\":\"'MKTG, INC.'\",\"knowledge_date\":\"1960-02-01T23:59:59Z\",\"observations\":1,\"knowledge_estimated\":true,\"ingested_at\":\"2026-09-07T10:09:36.452570Z\",\"kind\":\"exchange\",\"pit_event_id\":\"0000000017|name|DEFINED ASSET FUNDS MUNICIPAL INVT TR FD MON PYM\",\"entity_id\":\"0000000017\",\"valid_to\":\"1960-02-01\"},\"maxValues\":{\"kind\":\"ticker\",\"is_current\":true,\"event_date\":\"2026-09-07\",\"pit_event_id\":\"0002151905|ticker|LABI|2026-09-07\",\"ingested_at\":\"2026-09-07T10:09:36.452570Z\",\"knowledge_estimated\":true,\"knowledge_date\":\"2026-09-07T23:59:59Z\",\"value\":\"zulily, inc.\",\"entity_id\":\"0002151905\",\"valid_to\":\"2026-09-07\",\"observations\":12865,\"sources\":\"xbrl\"},\"nullCount\":{\"entity_id\":0,\"value\":0,\"valid_to\":0,\"is_current\":0,\"ingested_at\":0,\"kind\":0,\"knowledge_date\":0,\"event_date\":0,\"sources\":0,\"knowledge_estimated\":0,\"observations\":0,\"pit_event_id\":0}}","tags":null,"baseRowId":null,"defaultRowCommitVersion":null,"clusteringProvider":null}}
|
data/pit/security_master.delta/part-00000-84bed2a2-6ab3-4b85-bb3d-e89904eeb1d4-c000.snappy.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3da537415f40d6883b947e6374a260303fa922d2be2c8075e2cf5a5d972e3db5
|
| 3 |
+
size 5114932
|
jobs/run.py
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# /// script
|
| 2 |
+
# requires-python = ">=3.11"
|
| 3 |
+
# dependencies = [
|
| 4 |
+
# "httpx>=0.27,<1",
|
| 5 |
+
# "polars>=1.24,<2",
|
| 6 |
+
# "pyarrow>=18,<21",
|
| 7 |
+
# "deltalake>=0.22,<2",
|
| 8 |
+
# "huggingface-hub>=1.19,<2",
|
| 9 |
+
# "pytest>=8,<9",
|
| 10 |
+
# "pytest-asyncio>=0.24,<1",
|
| 11 |
+
# "ruff>=0.11,<1",
|
| 12 |
+
# "pyyaml>=6,<7",
|
| 13 |
+
# ]
|
| 14 |
+
# ///
|
| 15 |
+
"""Hugging Face Jobs entry point for the ZipLime security-master dataset.
|
| 16 |
+
|
| 17 |
+
restore repository -> lint -> tests -> build -> verify -> publish
|
| 18 |
+
|
| 19 |
+
The build reads two sibling datasets from the Hub. That is the point of this
|
| 20 |
+
one: it is glue, and what it says has to be derivable from what the others
|
| 21 |
+
published, not from a working copy that only exists on somebody's laptop.
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
|
| 26 |
+
import argparse
|
| 27 |
+
import os
|
| 28 |
+
import subprocess
|
| 29 |
+
import sys
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
DEFAULT_REPO = "ZipLime/security-master"
|
| 33 |
+
DEFAULT_WORKSPACE = "/tmp/security-master"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def log(message: str) -> None:
|
| 37 |
+
print(f"[security-master] {message}", flush=True)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def restore_repository(repo_id: str, token: str | None, workspace: Path) -> Path:
|
| 41 |
+
from huggingface_hub import snapshot_download
|
| 42 |
+
from huggingface_hub.errors import RepositoryNotFoundError
|
| 43 |
+
|
| 44 |
+
workspace.mkdir(parents=True, exist_ok=True)
|
| 45 |
+
try:
|
| 46 |
+
snapshot_download(
|
| 47 |
+
repo_id=repo_id, repo_type="dataset", token=token, local_dir=str(workspace),
|
| 48 |
+
# Only the recipe and tests are needed: every table is rebuilt from
|
| 49 |
+
# the sources each run, so restoring the data would download tens of
|
| 50 |
+
# megabytes to overwrite them.
|
| 51 |
+
allow_patterns=["recipe/**", "tests/**", "jobs/**", "*.md", "*.json", "*.toml"],
|
| 52 |
+
)
|
| 53 |
+
log(f"restored {repo_id} into {workspace}")
|
| 54 |
+
except RepositoryNotFoundError:
|
| 55 |
+
log(f"{repo_id} does not exist yet; treating this as the first publication")
|
| 56 |
+
if not (workspace / "recipe" / "cli.py").is_file():
|
| 57 |
+
raise SystemExit(f"{workspace} has no recipe; publish it before scheduling a Job")
|
| 58 |
+
return workspace
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def run(command: list[str], *, cwd: Path, env: dict[str, str]) -> int:
|
| 62 |
+
log(f"running: {' '.join(command)}")
|
| 63 |
+
return subprocess.run(command, cwd=cwd, env=env, check=False).returncode
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def main(argv: list[str] | None = None) -> int:
|
| 67 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 68 |
+
parser.add_argument("--mode", choices=["update", "build"], default="update")
|
| 69 |
+
parser.add_argument("--ftd-limit", default=None)
|
| 70 |
+
parser.add_argument("--workspace", default=os.environ.get("JOB_WORKSPACE", DEFAULT_WORKSPACE))
|
| 71 |
+
parser.add_argument("--skip-gates", action="store_true")
|
| 72 |
+
args = parser.parse_args(argv)
|
| 73 |
+
|
| 74 |
+
token = os.environ.get("HF_TOKEN")
|
| 75 |
+
if not token:
|
| 76 |
+
raise SystemExit("the HF_TOKEN secret is required")
|
| 77 |
+
if not os.environ.get("SEC_USER_AGENT"):
|
| 78 |
+
raise SystemExit("the SEC_USER_AGENT secret is required")
|
| 79 |
+
repo_id = os.environ.get("HF_DATASET_REPO", DEFAULT_REPO)
|
| 80 |
+
|
| 81 |
+
workspace = restore_repository(repo_id, token, Path(args.workspace))
|
| 82 |
+
env = {**os.environ, "PYTHONPATH": str(workspace), "DATA_DIR": "data"}
|
| 83 |
+
|
| 84 |
+
if not args.skip_gates:
|
| 85 |
+
for name, command in (("lint", ["ruff", "check", "."]), ("tests", ["pytest", "-q"])):
|
| 86 |
+
code = run(command, cwd=workspace, env=env)
|
| 87 |
+
if code != 0:
|
| 88 |
+
log(f"{name} failed; nothing was fetched and nothing was published")
|
| 89 |
+
return code
|
| 90 |
+
|
| 91 |
+
build = [sys.executable, "-m", "recipe.cli", "build"]
|
| 92 |
+
if args.ftd_limit:
|
| 93 |
+
build += ["--ftd-limit", str(args.ftd_limit)]
|
| 94 |
+
code = run(build, cwd=workspace, env=env)
|
| 95 |
+
if code != 0:
|
| 96 |
+
log("build or verification failed; nothing published")
|
| 97 |
+
return code
|
| 98 |
+
if args.mode == "build":
|
| 99 |
+
return 0
|
| 100 |
+
return run(
|
| 101 |
+
[sys.executable, "-m", "recipe.cli", "publish", "--repo", repo_id],
|
| 102 |
+
cwd=workspace, env=env,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
|
| 106 |
+
if __name__ == "__main__":
|
| 107 |
+
raise SystemExit(main())
|
manifest.json
ADDED
|
@@ -0,0 +1,155 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"bundle_storage_class": "ziplime.data.services.file_system_delta_lake_bundle_storage.FileSystemDeltaLakeBundleStorage",
|
| 3 |
+
"bundle_storage_data": {
|
| 4 |
+
"table_uri": "data/pit/security_master.delta"
|
| 5 |
+
},
|
| 6 |
+
"config_rows": {
|
| 7 |
+
"cusip_map": 74392,
|
| 8 |
+
"identifiers": 143932,
|
| 9 |
+
"issuers": 23529,
|
| 10 |
+
"observations": 10056033,
|
| 11 |
+
"pit": 143932
|
| 12 |
+
},
|
| 13 |
+
"config_schemas": {
|
| 14 |
+
"cusip_map": {
|
| 15 |
+
"cik": "String",
|
| 16 |
+
"cusip": "String",
|
| 17 |
+
"cusip6": "String",
|
| 18 |
+
"first_seen": "Date",
|
| 19 |
+
"inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 20 |
+
"issuer_name": "String",
|
| 21 |
+
"last_seen": "Date",
|
| 22 |
+
"looks_like_fund": "Boolean",
|
| 23 |
+
"match_confidence": "String",
|
| 24 |
+
"match_method": "String",
|
| 25 |
+
"observations": "Int32",
|
| 26 |
+
"ticker": "String"
|
| 27 |
+
},
|
| 28 |
+
"identifiers": {
|
| 29 |
+
"cik": "String",
|
| 30 |
+
"inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 31 |
+
"is_current": "Boolean",
|
| 32 |
+
"is_latest_for_filer": "Boolean",
|
| 33 |
+
"kind": "String",
|
| 34 |
+
"observations": "Int32",
|
| 35 |
+
"rank_within_kind": "Int32",
|
| 36 |
+
"sources": "String",
|
| 37 |
+
"valid_from": "Date",
|
| 38 |
+
"valid_to": "Date",
|
| 39 |
+
"value": "String"
|
| 40 |
+
},
|
| 41 |
+
"issuers": {
|
| 42 |
+
"all_tickers": "String",
|
| 43 |
+
"cik": "String",
|
| 44 |
+
"exchange": "String",
|
| 45 |
+
"filings_observed": "Int32",
|
| 46 |
+
"first_seen": "Date",
|
| 47 |
+
"fiscal_year_end": "String",
|
| 48 |
+
"inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 49 |
+
"is_active": "Boolean",
|
| 50 |
+
"last_seen": "Date",
|
| 51 |
+
"name": "String",
|
| 52 |
+
"name_changes": "Int32",
|
| 53 |
+
"primary_ticker": "String",
|
| 54 |
+
"sic": "String",
|
| 55 |
+
"state_incorporated": "String",
|
| 56 |
+
"ticker_changes": "Int32"
|
| 57 |
+
},
|
| 58 |
+
"observations": {
|
| 59 |
+
"cik": "String",
|
| 60 |
+
"inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 61 |
+
"kind": "String",
|
| 62 |
+
"observed_on": "Date",
|
| 63 |
+
"source": "String",
|
| 64 |
+
"source_ref": "String",
|
| 65 |
+
"value": "String"
|
| 66 |
+
},
|
| 67 |
+
"pit": {
|
| 68 |
+
"entity_id": "String",
|
| 69 |
+
"event_date": "Date",
|
| 70 |
+
"ingested_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 71 |
+
"is_current": "Boolean",
|
| 72 |
+
"kind": "String",
|
| 73 |
+
"knowledge_date": "Datetime(time_unit='us', time_zone='UTC')",
|
| 74 |
+
"knowledge_estimated": "Boolean",
|
| 75 |
+
"observations": "Int32",
|
| 76 |
+
"pit_event_id": "String",
|
| 77 |
+
"sources": "String",
|
| 78 |
+
"valid_to": "Date",
|
| 79 |
+
"value": "String"
|
| 80 |
+
}
|
| 81 |
+
},
|
| 82 |
+
"configs": {
|
| 83 |
+
"cusip_map": {
|
| 84 |
+
"grain": "one CUSIP, the ticker it settles under and the filer behind it",
|
| 85 |
+
"path": "data/cusip_map/**/*.parquet"
|
| 86 |
+
},
|
| 87 |
+
"identifiers": {
|
| 88 |
+
"grain": "one identifier and the span of filings that stated it",
|
| 89 |
+
"path": "data/identifiers/**/*.parquet"
|
| 90 |
+
},
|
| 91 |
+
"issuers": {
|
| 92 |
+
"grain": "one SEC filer, with what it is called now and how long it has filed",
|
| 93 |
+
"path": "data/issuers/**/*.parquet"
|
| 94 |
+
},
|
| 95 |
+
"observations": {
|
| 96 |
+
"grain": "one dated statement that an identifier belonged to a filer",
|
| 97 |
+
"path": "data/observations/**/*.parquet"
|
| 98 |
+
},
|
| 99 |
+
"pit": {
|
| 100 |
+
"delta_path": "data/pit/security_master.delta",
|
| 101 |
+
"grain": "one point-in-time identifier knowledge event",
|
| 102 |
+
"path": "data/pit/**/*.parquet"
|
| 103 |
+
}
|
| 104 |
+
},
|
| 105 |
+
"coverage": {
|
| 106 |
+
"max_observation": "2026-09-07",
|
| 107 |
+
"min_observation": "1960-02-01"
|
| 108 |
+
},
|
| 109 |
+
"data_type": "PIT_DATA",
|
| 110 |
+
"dataset": "security-master",
|
| 111 |
+
"entity_domain": "us_equities",
|
| 112 |
+
"entity_id": "issuer_cik",
|
| 113 |
+
"event_date": "valid_from",
|
| 114 |
+
"event_date_type": "date",
|
| 115 |
+
"frequency_seconds": null,
|
| 116 |
+
"generated_at": "2026-09-07T10:19:29.410389+00:00",
|
| 117 |
+
"identifier_kinds": [
|
| 118 |
+
"ticker",
|
| 119 |
+
"name",
|
| 120 |
+
"former_name",
|
| 121 |
+
"exchange",
|
| 122 |
+
"sic",
|
| 123 |
+
"cusip",
|
| 124 |
+
"figi"
|
| 125 |
+
],
|
| 126 |
+
"knowledge_date": "observed_on",
|
| 127 |
+
"knowledge_date_policy": {
|
| 128 |
+
"never_before_event_date": true,
|
| 129 |
+
"precision": "day; the underlying filings carry a time but settlement records do not, and mixing precisions would imply certainty the coarser source lacks",
|
| 130 |
+
"primary": "end of the day an identifier was first observed in a filing"
|
| 131 |
+
},
|
| 132 |
+
"knowledge_date_type": "timestamp[us, tz=UTC]",
|
| 133 |
+
"name": "security_master",
|
| 134 |
+
"pit": {
|
| 135 |
+
"append_only": false,
|
| 136 |
+
"knowledge_lag_model": "filing_date_end_of_day",
|
| 137 |
+
"restatement_policy": "spans are rebuilt from the full observation history on every run; the observations config is the evidence layer"
|
| 138 |
+
},
|
| 139 |
+
"pretty_name": "ZipLime US Security Master (PIT)",
|
| 140 |
+
"quality_ok": true,
|
| 141 |
+
"rows": 143932,
|
| 142 |
+
"source": {
|
| 143 |
+
"build_version": "1.0.0",
|
| 144 |
+
"coverage_note": "Ticker evidence effectively begins in 2006 with Form 4; earlier dates come from name-change fields in filing headers.",
|
| 145 |
+
"coverage_start": "1960-02-01",
|
| 146 |
+
"license": "US Government work — public domain",
|
| 147 |
+
"origin": "SEC EDGAR Form 4 and XBRL filings (via ZipLime/insider-trading and ZipLime/company-fundamentals), company_tickers_exchange.json, and SEC fails-to-deliver records",
|
| 148 |
+
"package_version": "1.0.0",
|
| 149 |
+
"recipe": "recipe/",
|
| 150 |
+
"recipe_hash": "sha256:3ba230dcb310ad04a7466a2976f2db1a7a346e451df0078feae0f0108a1edb41",
|
| 151 |
+
"schedule": "40 7 * * 1"
|
| 152 |
+
},
|
| 153 |
+
"trading_calendar_name": null,
|
| 154 |
+
"version": "1.0.0"
|
| 155 |
+
}
|
pyproject.toml
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=75", "wheel"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "ziplime-security-master"
|
| 7 |
+
version = "1.0.0"
|
| 8 |
+
description = "Point-in-time US security master: dated tickers, names and the CUSIP bridge"
|
| 9 |
+
readme = "README.md"
|
| 10 |
+
requires-python = ">=3.11"
|
| 11 |
+
license = {text = "Apache-2.0"}
|
| 12 |
+
authors = [{name = "ZipLime"}]
|
| 13 |
+
dependencies = [
|
| 14 |
+
"httpx>=0.27,<1",
|
| 15 |
+
"polars>=1.24,<2",
|
| 16 |
+
"pyarrow>=18,<21",
|
| 17 |
+
"deltalake>=0.22,<2",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
[project.optional-dependencies]
|
| 21 |
+
dev = [
|
| 22 |
+
"pytest>=8,<9",
|
| 23 |
+
"pytest-asyncio>=0.24,<1",
|
| 24 |
+
"ruff>=0.11,<1",
|
| 25 |
+
"pyyaml>=6,<7",
|
| 26 |
+
]
|
| 27 |
+
publish = ["huggingface-hub>=1.19,<2"]
|
| 28 |
+
|
| 29 |
+
[project.scripts]
|
| 30 |
+
ziplime-security-master = "recipe.cli:main"
|
| 31 |
+
|
| 32 |
+
[tool.setuptools.packages.find]
|
| 33 |
+
include = ["recipe*"]
|
| 34 |
+
|
| 35 |
+
[tool.pytest.ini_options]
|
| 36 |
+
addopts = "-ra"
|
| 37 |
+
testpaths = ["tests"]
|
| 38 |
+
asyncio_mode = "auto"
|
| 39 |
+
|
| 40 |
+
[tool.ruff]
|
| 41 |
+
target-version = "py311"
|
| 42 |
+
line-length = 100
|
| 43 |
+
extend-exclude = ["data", ".cache"]
|
| 44 |
+
|
| 45 |
+
[tool.ruff.lint]
|
| 46 |
+
select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
|
| 47 |
+
ignore = ["E501"]
|
recipe/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""US security master: dated identifiers for SEC filers, and the CUSIP bridge."""
|
| 2 |
+
|
| 3 |
+
__version__ = "1.0.0"
|
recipe/build.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Collect observations, derive the tables, write them out."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
import shutil
|
| 7 |
+
from datetime import UTC, datetime
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import polars as pl
|
| 11 |
+
|
| 12 |
+
from .config import Settings
|
| 13 |
+
from .intervals import build_cusip_map, build_identifiers, build_issuers, build_pit
|
| 14 |
+
from .schema import CONFIG_SCHEMAS, align
|
| 15 |
+
from .sources import (
|
| 16 |
+
from_company_tickers,
|
| 17 |
+
from_fundamental_filings,
|
| 18 |
+
from_ownership_filings,
|
| 19 |
+
ftd_archives,
|
| 20 |
+
parse_ftd,
|
| 21 |
+
)
|
| 22 |
+
from .store import atomic_write_parquet
|
| 23 |
+
|
| 24 |
+
LOGGER = logging.getLogger(__name__)
|
| 25 |
+
|
| 26 |
+
PIT_DELTA_NAME = "security_master.delta"
|
| 27 |
+
# Rows per output file. The tables are small next to the datasets they glue
|
| 28 |
+
# together, so one file per table is right until observations outgrow memory.
|
| 29 |
+
MAX_ROWS_PER_FILE = 5_000_000
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _write(data_dir: Path, table: str, frame: pl.DataFrame) -> int:
|
| 33 |
+
root = Path(data_dir) / table
|
| 34 |
+
if root.exists():
|
| 35 |
+
shutil.rmtree(root)
|
| 36 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
frame = align(frame, CONFIG_SCHEMAS[table])
|
| 38 |
+
if frame.is_empty():
|
| 39 |
+
atomic_write_parquet(frame, root / "part-00000.parquet")
|
| 40 |
+
return 0
|
| 41 |
+
for index, start in enumerate(range(0, frame.height, MAX_ROWS_PER_FILE)):
|
| 42 |
+
atomic_write_parquet(
|
| 43 |
+
frame.slice(start, MAX_ROWS_PER_FILE), root / f"part-{index:05d}.parquet"
|
| 44 |
+
)
|
| 45 |
+
return frame.height
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
async def collect_ftd(client, *, limit: int | None = None) -> pl.DataFrame:
|
| 49 |
+
"""Every settlement record SEC currently publishes, as CUSIP-ticker pairs."""
|
| 50 |
+
urls = await ftd_archives(client)
|
| 51 |
+
if limit:
|
| 52 |
+
urls = urls[-limit:]
|
| 53 |
+
LOGGER.info("fails-to-deliver archives: %d", len(urls))
|
| 54 |
+
rows: list[dict] = []
|
| 55 |
+
for index, url in enumerate(urls, 1):
|
| 56 |
+
try:
|
| 57 |
+
payload = await client.get_bytes(url, timeout=180.0)
|
| 58 |
+
except Exception as exc: # a withdrawn file is not a reason to stop
|
| 59 |
+
LOGGER.warning("skipping %s (%s)", url.rsplit("/", 1)[-1], type(exc).__name__)
|
| 60 |
+
continue
|
| 61 |
+
rows.extend(parse_ftd(payload, source_ref=url.rsplit("/", 1)[-1]))
|
| 62 |
+
if index % 40 == 0:
|
| 63 |
+
LOGGER.info(" %d/%d archives, %d records", index, len(urls), len(rows))
|
| 64 |
+
if not rows:
|
| 65 |
+
return pl.DataFrame(schema={"cusip": pl.String, "ticker": pl.String,
|
| 66 |
+
"issuer_name": pl.String, "observed_on": pl.Date,
|
| 67 |
+
"source_ref": pl.String})
|
| 68 |
+
return pl.DataFrame(rows, strict=False)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
async def run_build(
|
| 72 |
+
*, settings: Settings, token: str | None = None, ftd_limit: int | None = None
|
| 73 |
+
) -> dict[str, int]:
|
| 74 |
+
from .sec_client import SECClient
|
| 75 |
+
|
| 76 |
+
data_dir = Path(settings.data_dir)
|
| 77 |
+
observations = [
|
| 78 |
+
from_ownership_filings(settings, token=token),
|
| 79 |
+
from_fundamental_filings(settings, token=token),
|
| 80 |
+
]
|
| 81 |
+
|
| 82 |
+
async with SECClient(
|
| 83 |
+
user_agent=settings.sec_user_agent,
|
| 84 |
+
cache_dir=settings.cache_dir,
|
| 85 |
+
requests_per_second=settings.requests_per_second,
|
| 86 |
+
) as client:
|
| 87 |
+
observations.append(await from_company_tickers(client))
|
| 88 |
+
ftd = await collect_ftd(client, limit=ftd_limit)
|
| 89 |
+
|
| 90 |
+
frame = pl.concat(observations, how="vertical_relaxed")
|
| 91 |
+
LOGGER.info("observations: %d from %d sources", frame.height, frame["source"].n_unique())
|
| 92 |
+
|
| 93 |
+
identifiers = build_identifiers(frame)
|
| 94 |
+
issuers = build_issuers(identifiers, frame)
|
| 95 |
+
cusip_map = build_cusip_map(ftd, identifiers)
|
| 96 |
+
pit = build_pit(identifiers)
|
| 97 |
+
|
| 98 |
+
counts = {
|
| 99 |
+
"observations": _write(data_dir, "observations", frame),
|
| 100 |
+
"identifiers": _write(data_dir, "identifiers", identifiers),
|
| 101 |
+
"issuers": _write(data_dir, "issuers", issuers),
|
| 102 |
+
"cusip_map": _write(data_dir, "cusip_map", cusip_map),
|
| 103 |
+
"pit": _write(data_dir, "pit", pit),
|
| 104 |
+
}
|
| 105 |
+
delta = data_dir / "pit" / PIT_DELTA_NAME
|
| 106 |
+
if delta.exists():
|
| 107 |
+
shutil.rmtree(delta)
|
| 108 |
+
if not pit.is_empty():
|
| 109 |
+
align(pit, CONFIG_SCHEMAS["pit"]).write_delta(str(delta), mode="overwrite")
|
| 110 |
+
LOGGER.info("built %s at %s", counts, datetime.now(UTC).isoformat(timespec="seconds"))
|
| 111 |
+
return counts
|
recipe/cli.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Command line for the security master recipe."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import asyncio
|
| 7 |
+
import json
|
| 8 |
+
import logging
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
from .build import run_build
|
| 12 |
+
from .config import Settings
|
| 13 |
+
from .manifest import build_manifest
|
| 14 |
+
from .quality import validate
|
| 15 |
+
from .store import config_row_counts
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def main(argv: list[str] | None = None) -> int:
|
| 19 |
+
parser = argparse.ArgumentParser(prog="security-master", description=__doc__)
|
| 20 |
+
sub = parser.add_subparsers(dest="command", required=True)
|
| 21 |
+
|
| 22 |
+
build = sub.add_parser("build", help="collect observations and write every table")
|
| 23 |
+
build.add_argument("--ftd-limit", type=int, default=None,
|
| 24 |
+
help="use only the newest N fails-to-deliver archives")
|
| 25 |
+
|
| 26 |
+
verify = sub.add_parser("verify", help="run the quality gate and write the manifest")
|
| 27 |
+
verify.add_argument("--strict", action="store_true")
|
| 28 |
+
|
| 29 |
+
publish = sub.add_parser("publish", help="mirror the built tree to Hugging Face")
|
| 30 |
+
publish.add_argument("--repo", default=None)
|
| 31 |
+
|
| 32 |
+
args = parser.parse_args(argv)
|
| 33 |
+
logging.basicConfig(
|
| 34 |
+
level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s | %(message)s"
|
| 35 |
+
)
|
| 36 |
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
| 37 |
+
settings = Settings.from_env()
|
| 38 |
+
|
| 39 |
+
data_dir = Path(settings.data_dir)
|
| 40 |
+
|
| 41 |
+
if args.command == "build":
|
| 42 |
+
counts = asyncio.run(run_build(settings=settings, ftd_limit=args.ftd_limit))
|
| 43 |
+
report = validate(data_dir)
|
| 44 |
+
report.write(data_dir.parent / "quality_report.json")
|
| 45 |
+
build_manifest(data_dir=data_dir, row_counts=counts, quality_ok=report.ok)
|
| 46 |
+
print(json.dumps({"rows": counts, "quality_ok": report.ok,
|
| 47 |
+
"errors": report.errors, "warnings": report.warnings}, indent=2))
|
| 48 |
+
return 0 if report.ok else 1
|
| 49 |
+
|
| 50 |
+
if args.command == "verify":
|
| 51 |
+
report = validate(data_dir)
|
| 52 |
+
report.write(data_dir.parent / "quality_report.json")
|
| 53 |
+
build_manifest(
|
| 54 |
+
data_dir=data_dir, row_counts=config_row_counts(data_dir), quality_ok=report.ok
|
| 55 |
+
)
|
| 56 |
+
print(json.dumps(report.as_dict(), indent=2, default=str))
|
| 57 |
+
return 0 if report.ok else 1
|
| 58 |
+
|
| 59 |
+
if args.command == "publish":
|
| 60 |
+
from .publish import hf_token, publish_to_hf
|
| 61 |
+
|
| 62 |
+
report = validate(data_dir)
|
| 63 |
+
if not report.ok:
|
| 64 |
+
print(json.dumps({"quality_ok": False, "errors": report.errors}, indent=2))
|
| 65 |
+
return 1
|
| 66 |
+
commit = publish_to_hf(
|
| 67 |
+
project_root=data_dir.resolve().parent,
|
| 68 |
+
repo_id=args.repo or settings.hf_repo,
|
| 69 |
+
token=hf_token(),
|
| 70 |
+
)
|
| 71 |
+
print(json.dumps({"commit": commit}, indent=2))
|
| 72 |
+
return 0
|
| 73 |
+
return 1
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
raise SystemExit(main())
|
recipe/config.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Runtime configuration with SEC-safe defaults."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import os
|
| 6 |
+
from dataclasses import dataclass
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
|
| 9 |
+
DEFAULT_SEC_USER_AGENT = "ZipLime security-master/1.0 algo@limex.com"
|
| 10 |
+
DEFAULT_HF_REPO = "ZipLime/security-master"
|
| 11 |
+
|
| 12 |
+
# The sibling datasets this one is assembled from. It is glue: it has almost no
|
| 13 |
+
# source of its own, and every identifier in it was stated in a filing that one
|
| 14 |
+
# of these already parsed and published.
|
| 15 |
+
SOURCE_REPOS = {
|
| 16 |
+
"insider": "ZipLime/insider-trading",
|
| 17 |
+
"fundamentals": "ZipLime/company-fundamentals",
|
| 18 |
+
"institutional": "ZipLime/institutional-portfolio-13f",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
# Where a local checkout of a sibling lives, for iterating without downloading
|
| 22 |
+
# gigabytes. `SECURITY_MASTER_SIBLINGS=/path/to/hf` makes the build read
|
| 23 |
+
# `/path/to/hf/Insider_trading/data` instead of the Hub.
|
| 24 |
+
SIBLING_DIRS = {
|
| 25 |
+
"insider": "Insider_trading",
|
| 26 |
+
"fundamentals": "Company_fundamentals",
|
| 27 |
+
"institutional": "Institutional_portfolio_13f",
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@dataclass(frozen=True, slots=True)
|
| 32 |
+
class Settings:
|
| 33 |
+
data_dir: Path = Path("data")
|
| 34 |
+
cache_dir: Path = Path(".cache/sec")
|
| 35 |
+
sec_user_agent: str = DEFAULT_SEC_USER_AGENT
|
| 36 |
+
requests_per_second: float = 4.0
|
| 37 |
+
hf_repo: str = DEFAULT_HF_REPO
|
| 38 |
+
siblings_dir: Path | None = None
|
| 39 |
+
|
| 40 |
+
@classmethod
|
| 41 |
+
def from_env(cls, **overrides) -> Settings:
|
| 42 |
+
siblings = os.environ.get("SECURITY_MASTER_SIBLINGS")
|
| 43 |
+
return cls(
|
| 44 |
+
data_dir=Path(overrides.get("data_dir") or os.environ.get("DATA_DIR", "data")),
|
| 45 |
+
cache_dir=Path(overrides.get("cache_dir") or os.environ.get("SEC_CACHE_DIR", ".cache/sec")),
|
| 46 |
+
sec_user_agent=os.environ.get("SEC_USER_AGENT", DEFAULT_SEC_USER_AGENT),
|
| 47 |
+
requests_per_second=float(os.environ.get("SEC_REQUESTS_PER_SECOND", "4")),
|
| 48 |
+
hf_repo=overrides.get("hf_repo") or os.environ.get("HF_DATASET_REPO", DEFAULT_HF_REPO),
|
| 49 |
+
siblings_dir=Path(siblings) if siblings else None,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def validate_sec_user_agent(value: str) -> str:
|
| 54 |
+
cleaned = (value or "").strip()
|
| 55 |
+
if "@" not in cleaned or len(cleaned) < 12:
|
| 56 |
+
raise ValueError(f"SEC requires a User-Agent with a contact address, got {value!r}")
|
| 57 |
+
return cleaned
|
recipe/hf_jobs.py
ADDED
|
@@ -0,0 +1,228 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Declarative management of the Hugging Face Jobs that run this recipe.
|
| 2 |
+
|
| 3 |
+
Scheduling lives on Hugging Face rather than in an external CI system: the data,
|
| 4 |
+
the recipe revision, and the compute that produces them stay in one place, and a
|
| 5 |
+
job is not bound by an external runner's disk or wall-clock limits.
|
| 6 |
+
|
| 7 |
+
The scheduled job executes a UV script published in this same dataset
|
| 8 |
+
repository, so the code that produced a revision is always recoverable from the
|
| 9 |
+
revision itself.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
from dataclasses import dataclass
|
| 15 |
+
from typing import Any
|
| 16 |
+
|
| 17 |
+
from .config import DEFAULT_HF_REPO, validate_sec_user_agent
|
| 18 |
+
|
| 19 |
+
# The work is downloading the sibling datasets and four hundred settlement
|
| 20 |
+
# archives, then a few minutes of grouping. Memory is modest; bandwidth is not.
|
| 21 |
+
UPDATE_FLAVOR = "cpu-upgrade"
|
| 22 |
+
BACKFILL_FLAVOR = "cpu-upgrade"
|
| 23 |
+
UPDATE_TIMEOUT = "3h"
|
| 24 |
+
BACKFILL_TIMEOUT = "4h"
|
| 25 |
+
# Monday 07:40 UTC, half an hour after the fundamentals rebuild: this dataset
|
| 26 |
+
# reads that one's output, and reading yesterday's revision would publish a
|
| 27 |
+
# security master that lags its own sources by a week.
|
| 28 |
+
DEFAULT_SCHEDULE = "40 7 * * 1"
|
| 29 |
+
# One self-contained UV script serves both modes: a Job downloads a single file.
|
| 30 |
+
JOB_SCRIPT = "jobs/run.py"
|
| 31 |
+
UPDATE_JOB_NAME = "security-master-update"
|
| 32 |
+
BACKFILL_JOB_NAME = "security-master-rebuild"
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def script_url(
|
| 36 |
+
*, repo_id: str = DEFAULT_HF_REPO, script: str = JOB_SCRIPT, revision: str = "main"
|
| 37 |
+
) -> str:
|
| 38 |
+
return f"https://huggingface.co/datasets/{repo_id}/resolve/{revision}/{script}"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
@dataclass(frozen=True, slots=True)
|
| 42 |
+
class JobSpec:
|
| 43 |
+
"""Everything needed to launch or schedule one run, minus the credentials."""
|
| 44 |
+
|
| 45 |
+
script: str
|
| 46 |
+
script_url: str
|
| 47 |
+
flavor: str
|
| 48 |
+
timeout: str
|
| 49 |
+
script_args: tuple[str, ...]
|
| 50 |
+
env: dict[str, str]
|
| 51 |
+
name: str
|
| 52 |
+
|
| 53 |
+
def as_kwargs(self, *, secrets: dict[str, str]) -> dict[str, Any]:
|
| 54 |
+
"""Build the huggingface_hub call arguments.
|
| 55 |
+
|
| 56 |
+
The Jobs API takes no ``name`` parameter; a job's display name is the
|
| 57 |
+
``name`` label. Credentials go through ``secrets`` so they are encrypted
|
| 58 |
+
server side instead of travelling as plain environment variables.
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
return {
|
| 62 |
+
"script": self.script_url,
|
| 63 |
+
"script_args": list(self.script_args),
|
| 64 |
+
"flavor": self.flavor,
|
| 65 |
+
"timeout": self.timeout,
|
| 66 |
+
"env": dict(self.env),
|
| 67 |
+
"secrets": secrets,
|
| 68 |
+
"labels": {"name": self.name, "project": "insider-trading"},
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def update_spec(
|
| 73 |
+
*,
|
| 74 |
+
repo_id: str = DEFAULT_HF_REPO,
|
| 75 |
+
revision: str = "main",
|
| 76 |
+
flavor: str = UPDATE_FLAVOR,
|
| 77 |
+
timeout: str = UPDATE_TIMEOUT,
|
| 78 |
+
) -> JobSpec:
|
| 79 |
+
return JobSpec(
|
| 80 |
+
script=JOB_SCRIPT,
|
| 81 |
+
script_url=script_url(repo_id=repo_id, revision=revision),
|
| 82 |
+
flavor=flavor,
|
| 83 |
+
timeout=timeout,
|
| 84 |
+
script_args=("--mode", "update"),
|
| 85 |
+
env={"HF_DATASET_REPO": repo_id},
|
| 86 |
+
name=UPDATE_JOB_NAME,
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def backfill_spec(
|
| 91 |
+
*,
|
| 92 |
+
repo_id: str = DEFAULT_HF_REPO,
|
| 93 |
+
revision: str = "main",
|
| 94 |
+
start: str | None = None,
|
| 95 |
+
end: str | None = None,
|
| 96 |
+
flavor: str = BACKFILL_FLAVOR,
|
| 97 |
+
timeout: str = BACKFILL_TIMEOUT,
|
| 98 |
+
) -> JobSpec:
|
| 99 |
+
args = ["--mode", "build"]
|
| 100 |
+
_ = (start, end)
|
| 101 |
+
return JobSpec(
|
| 102 |
+
script=JOB_SCRIPT,
|
| 103 |
+
script_url=script_url(repo_id=repo_id, revision=revision),
|
| 104 |
+
flavor=flavor,
|
| 105 |
+
timeout=timeout,
|
| 106 |
+
script_args=tuple(args),
|
| 107 |
+
env={"HF_DATASET_REPO": repo_id},
|
| 108 |
+
name=BACKFILL_JOB_NAME,
|
| 109 |
+
)
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def job_secrets(*, hf_token: str, sec_user_agent: str) -> dict[str, str]:
|
| 113 |
+
"""Validate credentials locally so a misconfigured job fails before it costs money."""
|
| 114 |
+
|
| 115 |
+
if not hf_token.strip():
|
| 116 |
+
raise ValueError("HF_TOKEN is required to create or run a Hugging Face Job")
|
| 117 |
+
return {
|
| 118 |
+
"HF_TOKEN": hf_token.strip(),
|
| 119 |
+
"SEC_USER_AGENT": validate_sec_user_agent(sec_user_agent),
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _api(token: str | None) -> Any:
|
| 124 |
+
try:
|
| 125 |
+
from huggingface_hub import HfApi
|
| 126 |
+
except ImportError as error: # pragma: no cover - exercised in the job environment
|
| 127 |
+
raise RuntimeError("install the 'publish' extra to manage Hugging Face Jobs") from error
|
| 128 |
+
return HfApi(token=token)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def _require(api: Any, method: str) -> Any:
|
| 132 |
+
"""Fail with an actionable message when the installed hub predates a Jobs API."""
|
| 133 |
+
|
| 134 |
+
function = getattr(api, method, None)
|
| 135 |
+
if function is None:
|
| 136 |
+
raise RuntimeError(
|
| 137 |
+
f"the installed huggingface_hub has no {method}(); "
|
| 138 |
+
"upgrade with: pip install -U 'huggingface-hub>=1.19'"
|
| 139 |
+
)
|
| 140 |
+
return function
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def create_schedule(
|
| 144 |
+
spec: JobSpec,
|
| 145 |
+
*,
|
| 146 |
+
schedule: str = DEFAULT_SCHEDULE,
|
| 147 |
+
secrets: dict[str, str],
|
| 148 |
+
namespace: str | None = None,
|
| 149 |
+
token: str | None = None,
|
| 150 |
+
) -> Any:
|
| 151 |
+
api = _api(token)
|
| 152 |
+
return _require(api, "create_scheduled_uv_job")(
|
| 153 |
+
schedule=schedule,
|
| 154 |
+
namespace=namespace,
|
| 155 |
+
**spec.as_kwargs(secrets=secrets),
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def run_once(
|
| 160 |
+
spec: JobSpec,
|
| 161 |
+
*,
|
| 162 |
+
secrets: dict[str, str],
|
| 163 |
+
namespace: str | None = None,
|
| 164 |
+
token: str | None = None,
|
| 165 |
+
) -> Any:
|
| 166 |
+
api = _api(token)
|
| 167 |
+
return _require(api, "run_uv_job")(namespace=namespace, **spec.as_kwargs(secrets=secrets))
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def list_schedules(*, namespace: str | None = None, token: str | None = None) -> list[Any]:
|
| 171 |
+
api = _api(token)
|
| 172 |
+
return list(_require(api, "list_scheduled_jobs")(namespace=namespace))
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def inspect_schedule(
|
| 176 |
+
scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
|
| 177 |
+
) -> Any:
|
| 178 |
+
api = _api(token)
|
| 179 |
+
return _require(api, "inspect_scheduled_job")(
|
| 180 |
+
scheduled_job_id=scheduled_job_id, namespace=namespace
|
| 181 |
+
)
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
def delete_schedule(
|
| 185 |
+
scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
|
| 186 |
+
) -> None:
|
| 187 |
+
api = _api(token)
|
| 188 |
+
_require(api, "delete_scheduled_job")(scheduled_job_id=scheduled_job_id, namespace=namespace)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
def suspend_schedule(
|
| 192 |
+
scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
|
| 193 |
+
) -> Any:
|
| 194 |
+
api = _api(token)
|
| 195 |
+
return _require(api, "suspend_scheduled_job")(
|
| 196 |
+
scheduled_job_id=scheduled_job_id, namespace=namespace
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def resume_schedule(
|
| 201 |
+
scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
|
| 202 |
+
) -> Any:
|
| 203 |
+
api = _api(token)
|
| 204 |
+
return _require(api, "resume_scheduled_job")(
|
| 205 |
+
scheduled_job_id=scheduled_job_id, namespace=namespace
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
__all__ = [
|
| 210 |
+
"BACKFILL_FLAVOR",
|
| 211 |
+
"BACKFILL_TIMEOUT",
|
| 212 |
+
"DEFAULT_SCHEDULE",
|
| 213 |
+
"JOB_SCRIPT",
|
| 214 |
+
"UPDATE_FLAVOR",
|
| 215 |
+
"UPDATE_TIMEOUT",
|
| 216 |
+
"JobSpec",
|
| 217 |
+
"backfill_spec",
|
| 218 |
+
"create_schedule",
|
| 219 |
+
"delete_schedule",
|
| 220 |
+
"inspect_schedule",
|
| 221 |
+
"job_secrets",
|
| 222 |
+
"list_schedules",
|
| 223 |
+
"resume_schedule",
|
| 224 |
+
"run_once",
|
| 225 |
+
"script_url",
|
| 226 |
+
"suspend_schedule",
|
| 227 |
+
"update_spec",
|
| 228 |
+
]
|
recipe/intervals.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Turn dated observations into the published tables.
|
| 2 |
+
|
| 3 |
+
The model is deliberately modest. An interval here says "filings stated this
|
| 4 |
+
identifier for this filer between these two dates", not "this identifier was
|
| 5 |
+
legally valid over this span". Nobody publishes the day a ticker changed hands,
|
| 6 |
+
so a stronger claim would be invented. A gap means nobody filed; `observations`
|
| 7 |
+
says how much evidence stands behind the span.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import logging
|
| 13 |
+
import re
|
| 14 |
+
from datetime import UTC, datetime, time, timedelta
|
| 15 |
+
|
| 16 |
+
import polars as pl
|
| 17 |
+
|
| 18 |
+
from .schema import (
|
| 19 |
+
CUSIP_MAP_SCHEMA,
|
| 20 |
+
IDENTIFIER_SCHEMA,
|
| 21 |
+
ISSUER_SCHEMA,
|
| 22 |
+
PIT_SCHEMA,
|
| 23 |
+
align,
|
| 24 |
+
empty_frame,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
LOGGER = logging.getLogger(__name__)
|
| 28 |
+
|
| 29 |
+
# A filer that has not been seen for this long is treated as no longer filing.
|
| 30 |
+
# Two years, not one: an annual filer that slips a quarter is still alive, and
|
| 31 |
+
# calling it dead would reintroduce exactly the survivorship bias this dataset
|
| 32 |
+
# exists to remove.
|
| 33 |
+
DORMANT_AFTER_DAYS = 730
|
| 34 |
+
|
| 35 |
+
# How far a settlement record may sit outside an observed ticker span and still
|
| 36 |
+
# be matched to it. Fails-to-deliver records are dated by settlement, filings by
|
| 37 |
+
# filing; neither brackets the other.
|
| 38 |
+
CUSIP_MATCH_SLACK_DAYS = 200
|
| 39 |
+
|
| 40 |
+
# An exchange-traded fund settles like a share and files nothing a security
|
| 41 |
+
# master can key on: no Form 4, no financial statements under its ticker. It
|
| 42 |
+
# will never resolve to an operating company's CIK, and counting those failures
|
| 43 |
+
# as misses made the bridge look 13% complete when it covers 88% of the money.
|
| 44 |
+
FUND_NAME = re.compile(
|
| 45 |
+
r"\b(ETF|ETN|FUND|FUNDS|TRUST|TR|INDEX|IDX|PORTFOLIO|ISHARES|SPDR|VANGUARD|"
|
| 46 |
+
r"POWERSHARES|PROSHARES|WISDOMTREE|SELECT SECTOR|UNIT SER|DEP RCPT)\b",
|
| 47 |
+
re.I,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def build_identifiers(observations: pl.DataFrame) -> pl.DataFrame:
|
| 52 |
+
"""One row per (filer, kind, value) with the span it was stated over."""
|
| 53 |
+
if observations.is_empty():
|
| 54 |
+
return empty_frame(IDENTIFIER_SCHEMA)
|
| 55 |
+
|
| 56 |
+
grouped = (
|
| 57 |
+
observations.group_by(["cik", "kind", "value"])
|
| 58 |
+
.agg(
|
| 59 |
+
pl.col("observed_on").min().alias("valid_from"),
|
| 60 |
+
pl.col("observed_on").max().alias("valid_to"),
|
| 61 |
+
pl.len().cast(pl.Int32).alias("observations"),
|
| 62 |
+
pl.col("source").unique().sort().str.join("|").alias("sources"),
|
| 63 |
+
)
|
| 64 |
+
)
|
| 65 |
+
# "Current" has to mean current *now*, not merely last-stated. Defining it
|
| 66 |
+
# as "the newest value this filer gave" made a company that stopped filing
|
| 67 |
+
# in 2014 permanently current under its 2014 ticker -- and when another
|
| 68 |
+
# company later took that ticker over, both looked current at once. Six
|
| 69 |
+
# percent of live tickers were ambiguous that way.
|
| 70 |
+
latest = grouped.group_by(["cik", "kind"]).agg(
|
| 71 |
+
pl.col("valid_to").max().alias("kind_latest")
|
| 72 |
+
)
|
| 73 |
+
horizon = observations["observed_on"].max()
|
| 74 |
+
active = (
|
| 75 |
+
observations.group_by("cik")
|
| 76 |
+
.agg(pl.col("observed_on").max().alias("filer_last_seen"))
|
| 77 |
+
.with_columns(
|
| 78 |
+
(pl.col("filer_last_seen") >= horizon - timedelta(days=DORMANT_AFTER_DAYS))
|
| 79 |
+
.alias("filer_active")
|
| 80 |
+
)
|
| 81 |
+
.select("cik", "filer_active")
|
| 82 |
+
)
|
| 83 |
+
grouped = (
|
| 84 |
+
grouped.join(latest, on=["cik", "kind"], how="left")
|
| 85 |
+
.join(active, on="cik", how="left")
|
| 86 |
+
.with_columns(
|
| 87 |
+
(
|
| 88 |
+
(pl.col("valid_to") == pl.col("kind_latest"))
|
| 89 |
+
& pl.col("filer_active").fill_null(False)
|
| 90 |
+
).alias("is_current"),
|
| 91 |
+
(pl.col("valid_to") == pl.col("kind_latest")).alias("is_latest_for_filer"),
|
| 92 |
+
)
|
| 93 |
+
)
|
| 94 |
+
grouped = grouped.with_columns(
|
| 95 |
+
pl.struct("observations", "valid_to")
|
| 96 |
+
.rank("ordinal", descending=True)
|
| 97 |
+
.over(["cik", "kind"])
|
| 98 |
+
.cast(pl.Int32)
|
| 99 |
+
.alias("rank_within_kind"),
|
| 100 |
+
pl.lit(datetime.now(UTC)).alias("inserted_at"),
|
| 101 |
+
)
|
| 102 |
+
return align(grouped, IDENTIFIER_SCHEMA).sort(["cik", "kind", "rank_within_kind"])
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
def _current_value(identifiers: pl.DataFrame, kind: str, column: str) -> pl.DataFrame:
|
| 106 |
+
"""The filer's own newest value, active or not.
|
| 107 |
+
|
| 108 |
+
An issuer row describes a company, including one that stopped filing in
|
| 109 |
+
2011; keying this on `is_current` would leave every dormant filer nameless.
|
| 110 |
+
"""
|
| 111 |
+
return (
|
| 112 |
+
identifiers.filter((pl.col("kind") == kind) & pl.col("is_latest_for_filer"))
|
| 113 |
+
.sort(["cik", "rank_within_kind"])
|
| 114 |
+
.group_by("cik", maintain_order=True)
|
| 115 |
+
.agg(pl.col("value").first().alias(column))
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def build_issuers(identifiers: pl.DataFrame, observations: pl.DataFrame) -> pl.DataFrame:
|
| 120 |
+
"""One row per filer: what it is called now, and how long it has been filing."""
|
| 121 |
+
if identifiers.is_empty():
|
| 122 |
+
return empty_frame(ISSUER_SCHEMA)
|
| 123 |
+
|
| 124 |
+
span = observations.group_by("cik").agg(
|
| 125 |
+
pl.col("observed_on").min().alias("first_seen"),
|
| 126 |
+
pl.col("observed_on").max().alias("last_seen"),
|
| 127 |
+
pl.col("source_ref").n_unique().cast(pl.Int32).alias("filings_observed"),
|
| 128 |
+
)
|
| 129 |
+
frame = span
|
| 130 |
+
for kind, column in (
|
| 131 |
+
("name", "name"), ("ticker", "primary_ticker"), ("exchange", "exchange"),
|
| 132 |
+
("sic", "sic"), ("fiscal_year_end", "fiscal_year_end"),
|
| 133 |
+
("state_incorporated", "state_incorporated"),
|
| 134 |
+
):
|
| 135 |
+
frame = frame.join(_current_value(identifiers, kind, column), on="cik", how="left")
|
| 136 |
+
|
| 137 |
+
tickers = (
|
| 138 |
+
identifiers.filter((pl.col("kind") == "ticker") & pl.col("is_latest_for_filer"))
|
| 139 |
+
.sort(["cik", "rank_within_kind"])
|
| 140 |
+
.group_by("cik", maintain_order=True)
|
| 141 |
+
.agg(pl.col("value").str.join(",").alias("all_tickers"))
|
| 142 |
+
)
|
| 143 |
+
# The pivot names its columns after the kinds, so it produces a column
|
| 144 |
+
# called `name` that collides with the company name already on the frame.
|
| 145 |
+
# Renaming after the join hit the wrong one and blanked every issuer's name.
|
| 146 |
+
changes = (
|
| 147 |
+
identifiers.filter(pl.col("kind").is_in(["ticker", "name"]))
|
| 148 |
+
.group_by(["cik", "kind"])
|
| 149 |
+
.agg(pl.len().alias("n"))
|
| 150 |
+
.pivot(on="kind", index="cik", values="n", aggregate_function="first")
|
| 151 |
+
.rename(lambda column: column if column == "cik" else f"{column}_changes")
|
| 152 |
+
)
|
| 153 |
+
frame = frame.join(tickers, on="cik", how="left").join(changes, on="cik", how="left")
|
| 154 |
+
|
| 155 |
+
horizon = observations["observed_on"].max()
|
| 156 |
+
frame = frame.with_columns(
|
| 157 |
+
(pl.col("last_seen") >= horizon - timedelta(days=DORMANT_AFTER_DAYS)).alias("is_active"),
|
| 158 |
+
pl.lit(datetime.now(UTC)).alias("inserted_at"),
|
| 159 |
+
)
|
| 160 |
+
return align(frame, ISSUER_SCHEMA).sort("cik")
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def build_cusip_map(ftd: pl.DataFrame, identifiers: pl.DataFrame) -> pl.DataFrame:
|
| 164 |
+
"""CUSIP to CIK, by way of the ticker both of them name.
|
| 165 |
+
|
| 166 |
+
13F and N-PORT identify a holding by CUSIP; every other dataset in this
|
| 167 |
+
family identifies a company by CIK, and no free source maps between them.
|
| 168 |
+
Settlement records tie a CUSIP to a ticker on a date, filings tie a ticker
|
| 169 |
+
to a filer over a span, and the two compose -- provided the dates overlap,
|
| 170 |
+
which is what separates a confident match from a plausible one.
|
| 171 |
+
"""
|
| 172 |
+
if ftd.is_empty():
|
| 173 |
+
return empty_frame(CUSIP_MAP_SCHEMA)
|
| 174 |
+
|
| 175 |
+
pairs = ftd.group_by(["cusip", "ticker"]).agg(
|
| 176 |
+
pl.col("issuer_name").mode().first().alias("issuer_name"),
|
| 177 |
+
pl.col("observed_on").min().alias("first_seen"),
|
| 178 |
+
pl.col("observed_on").max().alias("last_seen"),
|
| 179 |
+
pl.len().cast(pl.Int32).alias("observations"),
|
| 180 |
+
)
|
| 181 |
+
spans = (
|
| 182 |
+
identifiers.filter(pl.col("kind") == "ticker")
|
| 183 |
+
.select("cik", pl.col("value").alias("ticker"), "valid_from", "valid_to", "observations")
|
| 184 |
+
.rename({"observations": "ticker_observations"})
|
| 185 |
+
)
|
| 186 |
+
joined = pairs.join(spans, on="ticker", how="left")
|
| 187 |
+
|
| 188 |
+
slack = timedelta(days=CUSIP_MATCH_SLACK_DAYS)
|
| 189 |
+
overlaps = (pl.col("first_seen") <= pl.col("valid_to") + slack) & (
|
| 190 |
+
pl.col("last_seen") >= pl.col("valid_from") - slack
|
| 191 |
+
)
|
| 192 |
+
joined = joined.with_columns(
|
| 193 |
+
pl.when(pl.col("cik").is_null())
|
| 194 |
+
.then(pl.lit("unmatched"))
|
| 195 |
+
.when(overlaps)
|
| 196 |
+
.then(pl.lit("ticker_and_dates"))
|
| 197 |
+
.otherwise(pl.lit("ticker_only"))
|
| 198 |
+
.alias("match_method")
|
| 199 |
+
)
|
| 200 |
+
# One ticker can belong to several filers over time -- that is the whole
|
| 201 |
+
# point of this dataset -- so the date-overlapping candidate wins, and the
|
| 202 |
+
# best-evidenced one breaks a remaining tie.
|
| 203 |
+
ranked = joined.sort(
|
| 204 |
+
["cusip", "ticker",
|
| 205 |
+
pl.col("match_method").replace_strict(
|
| 206 |
+
{"ticker_and_dates": 0, "ticker_only": 1, "unmatched": 2}, default=3
|
| 207 |
+
),
|
| 208 |
+
pl.col("ticker_observations").fill_null(0)],
|
| 209 |
+
descending=[False, False, False, True],
|
| 210 |
+
).group_by(["cusip", "ticker"], maintain_order=True).first()
|
| 211 |
+
|
| 212 |
+
ranked = ranked.with_columns(pl.col("cusip").str.slice(0, 6).alias("cusip6"))
|
| 213 |
+
|
| 214 |
+
# The first six characters of a CUSIP identify the issuer; the rest identify
|
| 215 |
+
# the instrument. So a class B share, a preferred and a warrant of a company
|
| 216 |
+
# whose common stock already resolved belong to the same filer, and saying
|
| 217 |
+
# so is a fact about how CUSIPs are assigned rather than a guess. It carries
|
| 218 |
+
# its own method and a middle confidence, because the *instrument* was never
|
| 219 |
+
# matched -- only its issuer.
|
| 220 |
+
issuer_level = (
|
| 221 |
+
ranked.filter(pl.col("cik").is_not_null())
|
| 222 |
+
.group_by("cusip6")
|
| 223 |
+
.agg(pl.col("cik").mode().first().alias("issuer_cik"))
|
| 224 |
+
)
|
| 225 |
+
ranked = ranked.join(issuer_level, on="cusip6", how="left").with_columns(
|
| 226 |
+
pl.when(pl.col("cik").is_null() & pl.col("issuer_cik").is_not_null())
|
| 227 |
+
.then(pl.lit("cusip6_inherited"))
|
| 228 |
+
.otherwise(pl.col("match_method"))
|
| 229 |
+
.alias("match_method"),
|
| 230 |
+
pl.coalesce([pl.col("cik"), pl.col("issuer_cik")]).alias("cik"),
|
| 231 |
+
)
|
| 232 |
+
|
| 233 |
+
ranked = ranked.with_columns(
|
| 234 |
+
pl.col("issuer_name").fill_null("").str.contains(FUND_NAME.pattern).alias("looks_like_fund"),
|
| 235 |
+
pl.when(pl.col("match_method") == "ticker_and_dates")
|
| 236 |
+
.then(pl.lit("high"))
|
| 237 |
+
.when(pl.col("match_method") == "cusip6_inherited")
|
| 238 |
+
.then(pl.lit("medium"))
|
| 239 |
+
.when(pl.col("match_method") == "ticker_only")
|
| 240 |
+
.then(pl.lit("low"))
|
| 241 |
+
.otherwise(pl.lit("none"))
|
| 242 |
+
.alias("match_confidence"),
|
| 243 |
+
pl.lit(datetime.now(UTC)).alias("inserted_at"),
|
| 244 |
+
)
|
| 245 |
+
return align(ranked, CUSIP_MAP_SCHEMA).sort(["cusip", "ticker"])
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def build_pit(identifiers: pl.DataFrame, *, run_at: datetime | None = None) -> pl.DataFrame:
|
| 249 |
+
"""Identifier spans in point-in-time form.
|
| 250 |
+
|
| 251 |
+
`knowledge_date` is the end of the day an identifier was first observed.
|
| 252 |
+
The underlying filings carry an acceptance time to the second, but a
|
| 253 |
+
settlement record carries only a date, and mixing the two precisions would
|
| 254 |
+
imply a certainty the coarser source does not have. End of day errs late,
|
| 255 |
+
which delays a fact rather than leaking it.
|
| 256 |
+
"""
|
| 257 |
+
if identifiers.is_empty():
|
| 258 |
+
return empty_frame(PIT_SCHEMA)
|
| 259 |
+
now = run_at or datetime.now(UTC)
|
| 260 |
+
frame = identifiers.with_columns(
|
| 261 |
+
pl.concat_str(
|
| 262 |
+
[pl.col("cik"), pl.col("kind"), pl.col("value"),
|
| 263 |
+
pl.col("valid_from").cast(pl.String)], separator="|"
|
| 264 |
+
).alias("pit_event_id"),
|
| 265 |
+
pl.col("cik").alias("entity_id"),
|
| 266 |
+
pl.col("valid_from").alias("event_date"),
|
| 267 |
+
pl.col("valid_from")
|
| 268 |
+
.cast(pl.Datetime("us"))
|
| 269 |
+
.dt.combine(time(23, 59, 59))
|
| 270 |
+
.dt.replace_time_zone("UTC")
|
| 271 |
+
.alias("knowledge_date"),
|
| 272 |
+
pl.lit(True).alias("knowledge_estimated"),
|
| 273 |
+
pl.lit(now).alias("ingested_at"),
|
| 274 |
+
)
|
| 275 |
+
return align(frame, PIT_SCHEMA).sort(["entity_id", "kind", "event_date"])
|
recipe/manifest.py
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The bundle descriptor, rebuilt from what is actually on disk."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import hashlib
|
| 6 |
+
import json
|
| 7 |
+
import os
|
| 8 |
+
import tempfile
|
| 9 |
+
from datetime import UTC, datetime
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
from typing import Any
|
| 12 |
+
|
| 13 |
+
import polars as pl
|
| 14 |
+
|
| 15 |
+
from . import __version__
|
| 16 |
+
from .build import PIT_DELTA_NAME
|
| 17 |
+
from .schema import BUILD_VERSION, CONFIG_SCHEMAS, IDENTIFIER_KINDS
|
| 18 |
+
from .store import read_table
|
| 19 |
+
|
| 20 |
+
RECIPE_ROOT = Path(__file__).resolve().parent.parent
|
| 21 |
+
|
| 22 |
+
CONFIG_DESCRIPTIONS: dict[str, dict[str, str]] = {
|
| 23 |
+
"issuers": {
|
| 24 |
+
"path": "data/issuers/**/*.parquet",
|
| 25 |
+
"grain": "one SEC filer, with what it is called now and how long it has filed",
|
| 26 |
+
},
|
| 27 |
+
"identifiers": {
|
| 28 |
+
"path": "data/identifiers/**/*.parquet",
|
| 29 |
+
"grain": "one identifier and the span of filings that stated it",
|
| 30 |
+
},
|
| 31 |
+
"observations": {
|
| 32 |
+
"path": "data/observations/**/*.parquet",
|
| 33 |
+
"grain": "one dated statement that an identifier belonged to a filer",
|
| 34 |
+
},
|
| 35 |
+
"cusip_map": {
|
| 36 |
+
"path": "data/cusip_map/**/*.parquet",
|
| 37 |
+
"grain": "one CUSIP, the ticker it settles under and the filer behind it",
|
| 38 |
+
},
|
| 39 |
+
"pit": {
|
| 40 |
+
"path": "data/pit/**/*.parquet",
|
| 41 |
+
"delta_path": f"data/pit/{PIT_DELTA_NAME}",
|
| 42 |
+
"grain": "one point-in-time identifier knowledge event",
|
| 43 |
+
},
|
| 44 |
+
}
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def recipe_hash(project_root: Path | None = None) -> str:
|
| 48 |
+
"""Hash of the code that produced a build.
|
| 49 |
+
|
| 50 |
+
The root defaults to the installed recipe rather than being derived from
|
| 51 |
+
`data_dir`: a run writing elsewhere would otherwise hash an empty file set,
|
| 52 |
+
which reads as a valid hash and proves nothing.
|
| 53 |
+
"""
|
| 54 |
+
root = (project_root or RECIPE_ROOT).resolve()
|
| 55 |
+
digest = hashlib.sha256()
|
| 56 |
+
files = sorted(
|
| 57 |
+
{
|
| 58 |
+
path
|
| 59 |
+
for pattern in ("recipe/**/*.py", "jobs/**/*.py", "tests/**/*.py", "pyproject.toml")
|
| 60 |
+
for path in root.glob(pattern)
|
| 61 |
+
if path.is_file()
|
| 62 |
+
}
|
| 63 |
+
)
|
| 64 |
+
if not files:
|
| 65 |
+
raise FileNotFoundError(f"no recipe sources under {root}")
|
| 66 |
+
for path in files:
|
| 67 |
+
digest.update(str(path.relative_to(root)).encode())
|
| 68 |
+
digest.update(b"\0")
|
| 69 |
+
digest.update(path.read_bytes())
|
| 70 |
+
digest.update(b"\0")
|
| 71 |
+
return f"sha256:{digest.hexdigest()}"
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _coverage(data_dir: Path) -> dict[str, str | None]:
|
| 75 |
+
bounds = read_table(data_dir, "observations").select(
|
| 76 |
+
pl.col("observed_on").min().alias("min_observation"),
|
| 77 |
+
pl.col("observed_on").max().alias("max_observation"),
|
| 78 |
+
).collect()
|
| 79 |
+
if bounds.is_empty():
|
| 80 |
+
return {}
|
| 81 |
+
row = bounds.row(0, named=True)
|
| 82 |
+
return {k: (v.isoformat() if v is not None else None) for k, v in row.items()}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def build_manifest(*, data_dir: Path, row_counts: dict[str, int], quality_ok: bool) -> dict[str, Any]:
|
| 86 |
+
data_dir = Path(data_dir)
|
| 87 |
+
project_root = data_dir.resolve().parent
|
| 88 |
+
path = project_root / "manifest.json"
|
| 89 |
+
manifest: dict[str, Any] = json.loads(path.read_text()) if path.exists() else {}
|
| 90 |
+
|
| 91 |
+
manifest["generated_at"] = datetime.now(UTC).isoformat()
|
| 92 |
+
manifest["rows"] = row_counts.get("pit", 0)
|
| 93 |
+
manifest["config_rows"] = row_counts
|
| 94 |
+
manifest["configs"] = CONFIG_DESCRIPTIONS
|
| 95 |
+
manifest["coverage"] = _coverage(data_dir)
|
| 96 |
+
manifest["quality_ok"] = quality_ok
|
| 97 |
+
manifest["identifier_kinds"] = list(IDENTIFIER_KINDS)
|
| 98 |
+
manifest["config_schemas"] = {
|
| 99 |
+
name: {column: str(dtype) for column, dtype in schema.items()}
|
| 100 |
+
for name, schema in CONFIG_SCHEMAS.items()
|
| 101 |
+
}
|
| 102 |
+
source = dict(manifest.get("source") or {})
|
| 103 |
+
source["recipe_hash"] = recipe_hash()
|
| 104 |
+
source["build_version"] = BUILD_VERSION
|
| 105 |
+
source["package_version"] = __version__
|
| 106 |
+
manifest["source"] = source
|
| 107 |
+
|
| 108 |
+
descriptor, temporary = tempfile.mkstemp(prefix=".manifest-", suffix=".json", dir=project_root)
|
| 109 |
+
try:
|
| 110 |
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
| 111 |
+
json.dump(manifest, handle, indent=2, sort_keys=True, ensure_ascii=False)
|
| 112 |
+
handle.write("\n")
|
| 113 |
+
handle.flush()
|
| 114 |
+
os.fsync(handle.fileno())
|
| 115 |
+
os.replace(temporary, path)
|
| 116 |
+
finally:
|
| 117 |
+
if os.path.exists(temporary):
|
| 118 |
+
os.unlink(temporary)
|
| 119 |
+
return manifest
|
recipe/publish.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Bootstrap and atomic same-revision publication through Hugging Face Hub."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
import os
|
| 7 |
+
import shutil
|
| 8 |
+
import tempfile
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
logger = logging.getLogger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def bootstrap_from_hf(
|
| 15 |
+
*, data_dir: Path, repo_id: str, token: str | None = None
|
| 16 |
+
) -> bool:
|
| 17 |
+
"""Hydrate prior append-only state on an ephemeral scheduled runner."""
|
| 18 |
+
|
| 19 |
+
if any((data_dir / "filings").glob("**/*.parquet")):
|
| 20 |
+
return False
|
| 21 |
+
try:
|
| 22 |
+
from huggingface_hub import snapshot_download
|
| 23 |
+
from huggingface_hub.errors import HfHubHTTPError, RepositoryNotFoundError
|
| 24 |
+
except ImportError as error: # pragma: no cover - exercised in publish environment
|
| 25 |
+
raise RuntimeError("install the 'publish' extra to bootstrap from Hugging Face") from error
|
| 26 |
+
|
| 27 |
+
temporary = Path(tempfile.mkdtemp(prefix="insider-hf-bootstrap-"))
|
| 28 |
+
try:
|
| 29 |
+
try:
|
| 30 |
+
snapshot_download(
|
| 31 |
+
repo_id=repo_id,
|
| 32 |
+
repo_type="dataset",
|
| 33 |
+
token=token,
|
| 34 |
+
allow_patterns=["data/**"],
|
| 35 |
+
local_dir=temporary,
|
| 36 |
+
)
|
| 37 |
+
except RepositoryNotFoundError:
|
| 38 |
+
return False # first publication
|
| 39 |
+
except HfHubHTTPError as error:
|
| 40 |
+
if getattr(error.response, "status_code", None) == 404:
|
| 41 |
+
return False
|
| 42 |
+
raise
|
| 43 |
+
downloaded = temporary / "data"
|
| 44 |
+
if not downloaded.exists():
|
| 45 |
+
return False
|
| 46 |
+
data_dir.mkdir(parents=True, exist_ok=True)
|
| 47 |
+
for source in downloaded.glob("**/*"):
|
| 48 |
+
if not source.is_file():
|
| 49 |
+
continue
|
| 50 |
+
target = data_dir / source.relative_to(downloaded)
|
| 51 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 52 |
+
if not target.exists():
|
| 53 |
+
shutil.copy2(source, target)
|
| 54 |
+
return True
|
| 55 |
+
finally:
|
| 56 |
+
shutil.rmtree(temporary, ignore_errors=True)
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def publish_to_hf(
|
| 60 |
+
*, project_root: Path, repo_id: str, token: str | None = None
|
| 61 |
+
) -> str:
|
| 62 |
+
try:
|
| 63 |
+
from huggingface_hub import HfApi
|
| 64 |
+
except ImportError as error: # pragma: no cover - exercised in publish environment
|
| 65 |
+
raise RuntimeError("install the 'publish' extra to publish to Hugging Face") from error
|
| 66 |
+
|
| 67 |
+
api = HfApi(token=token)
|
| 68 |
+
api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True)
|
| 69 |
+
local = {
|
| 70 |
+
str(path.relative_to(project_root))
|
| 71 |
+
for path in project_root.glob("data/**/*.parquet")
|
| 72 |
+
}
|
| 73 |
+
commit = api.upload_folder(
|
| 74 |
+
repo_id=repo_id,
|
| 75 |
+
repo_type="dataset",
|
| 76 |
+
folder_path=project_root,
|
| 77 |
+
# Without this, an upload only ever adds. Partition file names are
|
| 78 |
+
# derived from their contents, so a rebuild writes different names and
|
| 79 |
+
# the previous build's files stay behind -- every row then appears
|
| 80 |
+
# twice, and years dropped from the rebuild come back from the dead.
|
| 81 |
+
# The published tree has to be what is on disk, not the union of every
|
| 82 |
+
# build that ever ran.
|
| 83 |
+
delete_patterns=["data/**"],
|
| 84 |
+
allow_patterns=[
|
| 85 |
+
"data/**",
|
| 86 |
+
"recipe/**",
|
| 87 |
+
"tests/**",
|
| 88 |
+
"jobs/**",
|
| 89 |
+
"README.md",
|
| 90 |
+
"PIPELINE.md",
|
| 91 |
+
"manifest.json",
|
| 92 |
+
"pyproject.toml",
|
| 93 |
+
"LICENSE",
|
| 94 |
+
"NOTICE",
|
| 95 |
+
],
|
| 96 |
+
# The append lock is local coordination state, not published data.
|
| 97 |
+
ignore_patterns=["**/__pycache__/**", "**/*.pyc", "**/.append.lock"],
|
| 98 |
+
commit_message="Update the security master",
|
| 99 |
+
)
|
| 100 |
+
# A mirror that quietly failed to mirror is the failure this guards. Names
|
| 101 |
+
# are enough: a partition file's name is derived from its contents, so a
|
| 102 |
+
# set difference catches both a leftover from a previous build and a file
|
| 103 |
+
# that never arrived -- without downloading anything.
|
| 104 |
+
published = {
|
| 105 |
+
sibling.rfilename
|
| 106 |
+
for sibling in api.dataset_info(repo_id).siblings
|
| 107 |
+
if sibling.rfilename.startswith("data/") and sibling.rfilename.endswith(".parquet")
|
| 108 |
+
}
|
| 109 |
+
stale, missing = published - local, local - published
|
| 110 |
+
if stale or missing:
|
| 111 |
+
raise RuntimeError(
|
| 112 |
+
f"published tree does not match the local one: {len(stale)} stale file(s) "
|
| 113 |
+
f"left behind, {len(missing)} missing. Examples: "
|
| 114 |
+
f"stale={sorted(stale)[:3]} missing={sorted(missing)[:3]}"
|
| 115 |
+
)
|
| 116 |
+
logger.info("published tree mirrors %d local data files", len(local))
|
| 117 |
+
return str(commit.oid)
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def hf_token() -> str | None:
|
| 121 |
+
"""The token to act with: the environment first, then a stored login.
|
| 122 |
+
|
| 123 |
+
A scheduled job receives HF_TOKEN as a secret; a person running the same
|
| 124 |
+
command locally has usually run `hf auth login` instead, and should not
|
| 125 |
+
have to export the token again to use it.
|
| 126 |
+
"""
|
| 127 |
+
|
| 128 |
+
token = os.environ.get("HF_TOKEN")
|
| 129 |
+
if token:
|
| 130 |
+
return token
|
| 131 |
+
try:
|
| 132 |
+
from huggingface_hub import get_token
|
| 133 |
+
except ImportError: # pragma: no cover - exercised in the publish environment
|
| 134 |
+
return None
|
| 135 |
+
return get_token()
|
recipe/quality.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Checks that decide whether a build may be published.
|
| 2 |
+
|
| 3 |
+
A security master fails quietly. A wrong ticker does not raise; it silently
|
| 4 |
+
sends a backtest to another company's price series, and the result looks
|
| 5 |
+
plausible. So the checks here are about identity: that a ticker current for one
|
| 6 |
+
filer is not simultaneously current for another, that intervals are ordered,
|
| 7 |
+
that the CUSIP bridge resolves the names everyone actually looks up.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import json
|
| 13 |
+
from dataclasses import dataclass, field
|
| 14 |
+
from datetime import UTC, datetime
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
from typing import Any
|
| 17 |
+
|
| 18 |
+
import polars as pl
|
| 19 |
+
|
| 20 |
+
from .store import read_table
|
| 21 |
+
|
| 22 |
+
# Floors measured on the corpus, set below what it gives so a regression fails
|
| 23 |
+
# and noise does not.
|
| 24 |
+
MIN_TICKER_COVERAGE = 0.70
|
| 25 |
+
# Weighted by how often a CUSIP appears in settlement records, and counting
|
| 26 |
+
# only instruments that could resolve. A plain count of matched CUSIPs is the
|
| 27 |
+
# wrong measure: two thirds of the CUSIPs ever traded are one-off warrants,
|
| 28 |
+
# foreign lines and delisted shells, and exchange-traded funds -- which settle
|
| 29 |
+
# like shares and file nothing -- can never resolve at all. By count the bridge
|
| 30 |
+
# looks 37% complete; it covers 88% of the position value actually held in 13F.
|
| 31 |
+
MIN_CUSIP_WEIGHTED_MATCH = 0.60
|
| 32 |
+
MIN_ISSUERS = 15_000
|
| 33 |
+
# A ticker genuinely belongs to two filers at once only in odd cases -- a
|
| 34 |
+
# reorganisation mid-transfer, a dual filer. Above this share it means the
|
| 35 |
+
# ticker history is being stitched to the wrong companies.
|
| 36 |
+
MAX_AMBIGUOUS_CURRENT_TICKERS = 0.02
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
@dataclass
|
| 40 |
+
class QualityReport:
|
| 41 |
+
errors: list[str] = field(default_factory=list)
|
| 42 |
+
warnings: list[str] = field(default_factory=list)
|
| 43 |
+
metrics: dict[str, Any] = field(default_factory=dict)
|
| 44 |
+
|
| 45 |
+
def error(self, message: str) -> None:
|
| 46 |
+
self.errors.append(message)
|
| 47 |
+
|
| 48 |
+
def warn(self, message: str) -> None:
|
| 49 |
+
self.warnings.append(message)
|
| 50 |
+
|
| 51 |
+
def metric(self, name: str, value: Any) -> None:
|
| 52 |
+
self.metrics[name] = value
|
| 53 |
+
|
| 54 |
+
@property
|
| 55 |
+
def ok(self) -> bool:
|
| 56 |
+
return not self.errors
|
| 57 |
+
|
| 58 |
+
def as_dict(self) -> dict[str, Any]:
|
| 59 |
+
return {
|
| 60 |
+
"ok": self.ok,
|
| 61 |
+
"generated_at": datetime.now(UTC).isoformat(),
|
| 62 |
+
"errors": self.errors,
|
| 63 |
+
"warnings": self.warnings,
|
| 64 |
+
"metrics": self.metrics,
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
def write(self, path: Path) -> None:
|
| 68 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 69 |
+
path.write_text(json.dumps(self.as_dict(), indent=2, default=str), encoding="utf-8")
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def validate(data_dir: Path) -> QualityReport:
|
| 73 |
+
report = QualityReport()
|
| 74 |
+
data_dir = Path(data_dir)
|
| 75 |
+
|
| 76 |
+
observations = read_table(data_dir, "observations").collect()
|
| 77 |
+
identifiers = read_table(data_dir, "identifiers").collect()
|
| 78 |
+
issuers = read_table(data_dir, "issuers").collect()
|
| 79 |
+
cusip_map = read_table(data_dir, "cusip_map").collect()
|
| 80 |
+
pit = read_table(data_dir, "pit").collect()
|
| 81 |
+
|
| 82 |
+
for name, frame in (
|
| 83 |
+
("observations", observations), ("identifiers", identifiers),
|
| 84 |
+
("issuers", issuers), ("cusip_map", cusip_map), ("pit", pit),
|
| 85 |
+
):
|
| 86 |
+
report.metric(f"rows_{name}", frame.height)
|
| 87 |
+
if issuers.is_empty():
|
| 88 |
+
report.error("issuers table is empty")
|
| 89 |
+
return report
|
| 90 |
+
if issuers.height < MIN_ISSUERS:
|
| 91 |
+
report.error(f"only {issuers.height} issuers, below the {MIN_ISSUERS} floor")
|
| 92 |
+
|
| 93 |
+
for column in ("cik", "kind", "value", "observed_on", "source"):
|
| 94 |
+
nulls = observations[column].null_count()
|
| 95 |
+
if nulls:
|
| 96 |
+
report.error(f"observations.{column}: {nulls} nulls")
|
| 97 |
+
|
| 98 |
+
reversed_spans = identifiers.filter(pl.col("valid_to") < pl.col("valid_from")).height
|
| 99 |
+
if reversed_spans:
|
| 100 |
+
report.error(f"identifiers: {reversed_spans} spans end before they start")
|
| 101 |
+
|
| 102 |
+
duplicates = identifiers.height - identifiers.select("cik", "kind", "value").unique().height
|
| 103 |
+
if duplicates:
|
| 104 |
+
report.error(f"identifiers: {duplicates} duplicate (cik, kind, value) rows")
|
| 105 |
+
|
| 106 |
+
if issuers["cik"].n_unique() != issuers.height:
|
| 107 |
+
report.error("issuers: duplicate CIKs")
|
| 108 |
+
|
| 109 |
+
with_ticker = issuers.filter(pl.col("primary_ticker").is_not_null()).height
|
| 110 |
+
coverage = with_ticker / issuers.height
|
| 111 |
+
report.metric("issuers_with_ticker", round(coverage, 4))
|
| 112 |
+
active = issuers.filter(pl.col("is_active"))
|
| 113 |
+
report.metric("issuers_active", active.height)
|
| 114 |
+
if not active.is_empty():
|
| 115 |
+
active_coverage = active.filter(pl.col("primary_ticker").is_not_null()).height / active.height
|
| 116 |
+
report.metric("active_issuers_with_ticker", round(active_coverage, 4))
|
| 117 |
+
if active_coverage < MIN_TICKER_COVERAGE:
|
| 118 |
+
report.error(
|
| 119 |
+
f"only {active_coverage:.1%} of active issuers have a ticker, "
|
| 120 |
+
f"below the {MIN_TICKER_COVERAGE:.0%} floor"
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# The check that matters most: a ticker current for two filers at once means
|
| 124 |
+
# somebody's history has been attached to the wrong company.
|
| 125 |
+
current = identifiers.filter((pl.col("kind") == "ticker") & pl.col("is_current"))
|
| 126 |
+
if not current.is_empty():
|
| 127 |
+
ambiguous = (
|
| 128 |
+
current.group_by("value").agg(pl.col("cik").n_unique().alias("filers"))
|
| 129 |
+
.filter(pl.col("filers") > 1)
|
| 130 |
+
)
|
| 131 |
+
share = ambiguous.height / current["value"].n_unique()
|
| 132 |
+
report.metric("ambiguous_current_tickers", ambiguous.height)
|
| 133 |
+
report.metric("ambiguous_current_ticker_share", round(share, 4))
|
| 134 |
+
if share > MAX_AMBIGUOUS_CURRENT_TICKERS:
|
| 135 |
+
report.error(
|
| 136 |
+
f"{ambiguous.height} tickers are current for more than one filer "
|
| 137 |
+
f"({share:.1%}) — histories are being stitched to the wrong companies"
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if not cusip_map.is_empty():
|
| 141 |
+
matched = cusip_map.filter(pl.col("cik").is_not_null()).height
|
| 142 |
+
report.metric("cusip_rows", cusip_map.height)
|
| 143 |
+
report.metric("cusip_matched_share", round(matched / cusip_map.height, 4))
|
| 144 |
+
resolvable = cusip_map.filter(~pl.col("looks_like_fund").fill_null(False))
|
| 145 |
+
weight = resolvable["observations"].sum() or 1
|
| 146 |
+
rate = resolvable.filter(pl.col("cik").is_not_null())["observations"].sum() / weight
|
| 147 |
+
report.metric("cusip_weighted_match", round(rate, 4))
|
| 148 |
+
report.metric("cusip_fund_rows", cusip_map.height - resolvable.height)
|
| 149 |
+
report.metric(
|
| 150 |
+
"cusip_by_confidence",
|
| 151 |
+
{
|
| 152 |
+
row["match_confidence"]: row["n"]
|
| 153 |
+
for row in cusip_map.group_by("match_confidence")
|
| 154 |
+
.agg(pl.len().alias("n")).iter_rows(named=True)
|
| 155 |
+
},
|
| 156 |
+
)
|
| 157 |
+
if rate < MIN_CUSIP_WEIGHTED_MATCH:
|
| 158 |
+
report.error(
|
| 159 |
+
f"only {rate:.1%} of non-fund CUSIP traffic resolved to a filer, "
|
| 160 |
+
f"below the {MIN_CUSIP_WEIGHTED_MATCH:.0%} floor"
|
| 161 |
+
)
|
| 162 |
+
if cusip_map.select("cusip", "ticker").unique().height != cusip_map.height:
|
| 163 |
+
report.error("cusip_map: duplicate (cusip, ticker) rows")
|
| 164 |
+
|
| 165 |
+
if not pit.is_empty():
|
| 166 |
+
if pit.height != identifiers.height:
|
| 167 |
+
report.error(
|
| 168 |
+
f"pit has {pit.height} events for {identifiers.height} identifier spans"
|
| 169 |
+
)
|
| 170 |
+
for column in ("entity_id", "event_date", "knowledge_date"):
|
| 171 |
+
if pit[column].null_count():
|
| 172 |
+
report.error(f"pit.{column}: {pit[column].null_count()} nulls")
|
| 173 |
+
|
| 174 |
+
bounds = observations.select(
|
| 175 |
+
pl.col("observed_on").min().alias("first"), pl.col("observed_on").max().alias("last")
|
| 176 |
+
).row(0)
|
| 177 |
+
report.metric("coverage_first_observation", str(bounds[0]))
|
| 178 |
+
report.metric("coverage_last_observation", str(bounds[1]))
|
| 179 |
+
report.metric(
|
| 180 |
+
"observations_by_source",
|
| 181 |
+
{
|
| 182 |
+
row["source"]: row["n"]
|
| 183 |
+
for row in observations.group_by("source").agg(pl.len().alias("n")).iter_rows(named=True)
|
| 184 |
+
},
|
| 185 |
+
)
|
| 186 |
+
return report
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
__all__ = ["QualityReport", "validate"]
|
recipe/schema.py
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Canonical Polars schemas for every published config."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from collections.abc import Mapping
|
| 6 |
+
|
| 7 |
+
import polars as pl
|
| 8 |
+
|
| 9 |
+
UTC_DATETIME = pl.Datetime(time_unit="us", time_zone="UTC")
|
| 10 |
+
|
| 11 |
+
BUILD_VERSION = "1.0.0"
|
| 12 |
+
|
| 13 |
+
# What kinds of identifier this master carries. `former_name` is separate from
|
| 14 |
+
# `name` because a former name is stated *as* former -- the filing says when it
|
| 15 |
+
# stopped being used, which a run of name observations cannot tell you.
|
| 16 |
+
IDENTIFIER_KINDS = ("ticker", "name", "former_name", "exchange", "sic", "cusip", "figi")
|
| 17 |
+
|
| 18 |
+
# One dated statement that an identifier belonged to a filer. This is the
|
| 19 |
+
# evidence layer: intervals are derived from it, and anyone who disagrees with
|
| 20 |
+
# how they were derived can derive their own.
|
| 21 |
+
OBSERVATION_SCHEMA: dict[str, pl.DataType] = {
|
| 22 |
+
"cik": pl.String,
|
| 23 |
+
"kind": pl.String,
|
| 24 |
+
"value": pl.String,
|
| 25 |
+
"observed_on": pl.Date,
|
| 26 |
+
"source": pl.String,
|
| 27 |
+
"source_ref": pl.String,
|
| 28 |
+
"inserted_at": UTC_DATETIME,
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
# One identifier and the span over which filings actually stated it.
|
| 32 |
+
#
|
| 33 |
+
# `valid_from`/`valid_to` are first and last *observation*, not registry dates:
|
| 34 |
+
# nobody publishes the day a ticker changed hands. A gap means nobody filed,
|
| 35 |
+
# not that the identifier lapsed, and `observations` says how much evidence
|
| 36 |
+
# stands behind the span.
|
| 37 |
+
IDENTIFIER_SCHEMA: dict[str, pl.DataType] = {
|
| 38 |
+
"cik": pl.String,
|
| 39 |
+
"kind": pl.String,
|
| 40 |
+
"value": pl.String,
|
| 41 |
+
"valid_from": pl.Date,
|
| 42 |
+
"valid_to": pl.Date,
|
| 43 |
+
"observations": pl.Int32,
|
| 44 |
+
"sources": pl.String,
|
| 45 |
+
# `is_current` means live now: the newest value this filer stated *and* the
|
| 46 |
+
# filer still files. `is_latest_for_filer` drops the second condition, which
|
| 47 |
+
# is what you want when asking "what did this company last call itself".
|
| 48 |
+
"is_current": pl.Boolean,
|
| 49 |
+
"is_latest_for_filer": pl.Boolean,
|
| 50 |
+
"rank_within_kind": pl.Int32,
|
| 51 |
+
"inserted_at": UTC_DATETIME,
|
| 52 |
+
}
|
| 53 |
+
|
| 54 |
+
ISSUER_SCHEMA: dict[str, pl.DataType] = {
|
| 55 |
+
"cik": pl.String,
|
| 56 |
+
"name": pl.String,
|
| 57 |
+
"primary_ticker": pl.String,
|
| 58 |
+
"all_tickers": pl.String,
|
| 59 |
+
"exchange": pl.String,
|
| 60 |
+
"sic": pl.String,
|
| 61 |
+
"fiscal_year_end": pl.String,
|
| 62 |
+
"state_incorporated": pl.String,
|
| 63 |
+
"first_seen": pl.Date,
|
| 64 |
+
"last_seen": pl.Date,
|
| 65 |
+
"is_active": pl.Boolean,
|
| 66 |
+
"ticker_changes": pl.Int32,
|
| 67 |
+
"name_changes": pl.Int32,
|
| 68 |
+
"filings_observed": pl.Int32,
|
| 69 |
+
"inserted_at": UTC_DATETIME,
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
# The bridge. 13F and N-PORT name a holding by CUSIP; every other dataset in
|
| 73 |
+
# this family names a company by CIK. Nobody publishes a free map between them.
|
| 74 |
+
CUSIP_MAP_SCHEMA: dict[str, pl.DataType] = {
|
| 75 |
+
"cusip": pl.String,
|
| 76 |
+
"cusip6": pl.String,
|
| 77 |
+
"ticker": pl.String,
|
| 78 |
+
"cik": pl.String,
|
| 79 |
+
"issuer_name": pl.String,
|
| 80 |
+
"first_seen": pl.Date,
|
| 81 |
+
"last_seen": pl.Date,
|
| 82 |
+
"observations": pl.Int32,
|
| 83 |
+
"match_method": pl.String,
|
| 84 |
+
"match_confidence": pl.String,
|
| 85 |
+
# True for an ETF or fund share, which settles like a stock and files
|
| 86 |
+
# nothing a CIK could be attached to. Not a failed match: a different kind
|
| 87 |
+
# of instrument.
|
| 88 |
+
"looks_like_fund": pl.Boolean,
|
| 89 |
+
"inserted_at": UTC_DATETIME,
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
PIT_SCHEMA: dict[str, pl.DataType] = {
|
| 93 |
+
"pit_event_id": pl.String,
|
| 94 |
+
"entity_id": pl.String,
|
| 95 |
+
"event_date": pl.Date,
|
| 96 |
+
"knowledge_date": UTC_DATETIME,
|
| 97 |
+
"knowledge_estimated": pl.Boolean,
|
| 98 |
+
"kind": pl.String,
|
| 99 |
+
"value": pl.String,
|
| 100 |
+
"valid_to": pl.Date,
|
| 101 |
+
"observations": pl.Int32,
|
| 102 |
+
"sources": pl.String,
|
| 103 |
+
"is_current": pl.Boolean,
|
| 104 |
+
"ingested_at": UTC_DATETIME,
|
| 105 |
+
}
|
| 106 |
+
|
| 107 |
+
CONFIG_SCHEMAS: dict[str, dict[str, pl.DataType]] = {
|
| 108 |
+
"observations": OBSERVATION_SCHEMA,
|
| 109 |
+
"identifiers": IDENTIFIER_SCHEMA,
|
| 110 |
+
"issuers": ISSUER_SCHEMA,
|
| 111 |
+
"cusip_map": CUSIP_MAP_SCHEMA,
|
| 112 |
+
"pit": PIT_SCHEMA,
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def empty_frame(schema: Mapping[str, pl.DataType]) -> pl.DataFrame:
|
| 117 |
+
return pl.DataFrame(schema=dict(schema))
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def align(frame: pl.DataFrame, schema: Mapping[str, pl.DataType]) -> pl.DataFrame:
|
| 121 |
+
missing = [
|
| 122 |
+
pl.lit(None, dtype=dtype).alias(name)
|
| 123 |
+
for name, dtype in schema.items()
|
| 124 |
+
if name not in frame.columns
|
| 125 |
+
]
|
| 126 |
+
if missing:
|
| 127 |
+
frame = frame.with_columns(missing)
|
| 128 |
+
return frame.select([pl.col(n).cast(d, strict=False) for n, d in schema.items()])
|
recipe/sec_client.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Async SEC client with declared identity, throttling, retries, and cache."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import asyncio
|
| 6 |
+
import gzip
|
| 7 |
+
import hashlib
|
| 8 |
+
import json
|
| 9 |
+
import os
|
| 10 |
+
import random
|
| 11 |
+
import tempfile
|
| 12 |
+
import time
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Any
|
| 15 |
+
from urllib.parse import urlparse
|
| 16 |
+
|
| 17 |
+
import httpx
|
| 18 |
+
|
| 19 |
+
from .config import DEFAULT_SEC_USER_AGENT, validate_sec_user_agent
|
| 20 |
+
|
| 21 |
+
_ALLOWED_HOSTS = frozenset({"sec.gov", "www.sec.gov", "data.sec.gov"})
|
| 22 |
+
_RETRYABLE_STATUS = frozenset({408, 425, 429, 500, 502, 503, 504})
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class SECObjectMissing(Exception):
|
| 26 |
+
"""The requested EDGAR object does not exist.
|
| 27 |
+
|
| 28 |
+
EDGAR serves its archive from an object store that answers a missing key
|
| 29 |
+
with ``403 AccessDenied`` rather than ``404``. Weekends, holidays, and the
|
| 30 |
+
current day before the feed is published all look like this, so a caller
|
| 31 |
+
that treated only 404 as "not there" would fail on an ordinary run.
|
| 32 |
+
"""
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class SECAccessBlocked(Exception):
|
| 36 |
+
"""SEC refused the request itself, not a specific object.
|
| 37 |
+
|
| 38 |
+
This is a Fair Access block: an undeclared automated tool or an exceeded
|
| 39 |
+
request rate. It must never be mistaken for a per-filing error. Recording a
|
| 40 |
+
blocked run as thousands of parse failures would write those failures into
|
| 41 |
+
append-only history, where they cannot be corrected.
|
| 42 |
+
"""
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _classify_forbidden(response: httpx.Response) -> Exception:
|
| 46 |
+
"""Tell a missing archive object apart from a Fair Access block.
|
| 47 |
+
|
| 48 |
+
The archive backend stamps ``x-amz-request-id`` and returns an XML
|
| 49 |
+
``AccessDenied`` body; a block is served by the edge as HTML.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
if "x-amz-request-id" in response.headers and b"AccessDenied" in response.content[:4096]:
|
| 53 |
+
return SECObjectMissing(f"EDGAR has no object at {response.request.url}")
|
| 54 |
+
return SECAccessBlocked(
|
| 55 |
+
"SEC refused the request (Fair Access). Check the declared User-Agent and "
|
| 56 |
+
f"request rate before retrying: {response.request.url}"
|
| 57 |
+
)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class SECClient:
|
| 61 |
+
"""Fair-Access-aware HTTP client.
|
| 62 |
+
|
| 63 |
+
The shared monotonic limiter spaces request starts. The default six requests
|
| 64 |
+
per second stays comfortably below SEC's published ten-request threshold.
|
| 65 |
+
"""
|
| 66 |
+
|
| 67 |
+
def __init__(
|
| 68 |
+
self,
|
| 69 |
+
*,
|
| 70 |
+
user_agent: str = DEFAULT_SEC_USER_AGENT,
|
| 71 |
+
cache_dir: str | Path = ".cache/sec",
|
| 72 |
+
requests_per_second: float = 6.0,
|
| 73 |
+
max_attempts: int = 5,
|
| 74 |
+
timeout: float = 45.0,
|
| 75 |
+
transport: httpx.AsyncBaseTransport | None = None,
|
| 76 |
+
) -> None:
|
| 77 |
+
if not 0 < requests_per_second < 10:
|
| 78 |
+
raise ValueError("requests_per_second must be greater than zero and below 10")
|
| 79 |
+
self.user_agent = validate_sec_user_agent(user_agent)
|
| 80 |
+
self.cache_dir = Path(cache_dir)
|
| 81 |
+
self.cache_dir.mkdir(parents=True, exist_ok=True)
|
| 82 |
+
self.requests_per_second = requests_per_second
|
| 83 |
+
self.max_attempts = max_attempts
|
| 84 |
+
self._spacing = 1.0 / requests_per_second
|
| 85 |
+
self._limiter_lock = asyncio.Lock()
|
| 86 |
+
self._next_request_at = 0.0
|
| 87 |
+
self._timeout = timeout
|
| 88 |
+
self._client = httpx.AsyncClient(
|
| 89 |
+
headers={
|
| 90 |
+
"User-Agent": self.user_agent,
|
| 91 |
+
"Accept-Encoding": "gzip, deflate",
|
| 92 |
+
"Accept": "*/*",
|
| 93 |
+
},
|
| 94 |
+
timeout=timeout,
|
| 95 |
+
follow_redirects=True,
|
| 96 |
+
transport=transport,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
async def __aenter__(self) -> SECClient:
|
| 100 |
+
return self
|
| 101 |
+
|
| 102 |
+
async def __aexit__(self, *_: object) -> None:
|
| 103 |
+
await self.aclose()
|
| 104 |
+
|
| 105 |
+
async def aclose(self) -> None:
|
| 106 |
+
await self._client.aclose()
|
| 107 |
+
|
| 108 |
+
@staticmethod
|
| 109 |
+
def _validate_url(url: str) -> None:
|
| 110 |
+
parsed = urlparse(url)
|
| 111 |
+
if parsed.scheme != "https" or (parsed.hostname or "").lower() not in _ALLOWED_HOSTS:
|
| 112 |
+
raise ValueError(f"SECClient refuses non-SEC URL: {url!r}")
|
| 113 |
+
|
| 114 |
+
def _cache_path(self, url: str) -> Path:
|
| 115 |
+
digest = hashlib.sha256(url.encode("utf-8")).hexdigest()
|
| 116 |
+
suffix = Path(urlparse(url).path).suffix[:10] or ".bin"
|
| 117 |
+
return self.cache_dir / digest[:2] / f"{digest}{suffix}"
|
| 118 |
+
|
| 119 |
+
async def _throttle(self) -> None:
|
| 120 |
+
async with self._limiter_lock:
|
| 121 |
+
now = time.monotonic()
|
| 122 |
+
delay = max(0.0, self._next_request_at - now)
|
| 123 |
+
if delay:
|
| 124 |
+
await asyncio.sleep(delay)
|
| 125 |
+
self._next_request_at = time.monotonic() + self._spacing
|
| 126 |
+
|
| 127 |
+
@staticmethod
|
| 128 |
+
def _fresh(path: Path, max_age_seconds: float | None) -> bool:
|
| 129 |
+
if not path.is_file():
|
| 130 |
+
return False
|
| 131 |
+
if max_age_seconds is None:
|
| 132 |
+
return True
|
| 133 |
+
return time.time() - path.stat().st_mtime <= max_age_seconds
|
| 134 |
+
|
| 135 |
+
@staticmethod
|
| 136 |
+
def _decode_cached(payload: bytes) -> bytes:
|
| 137 |
+
"""Read a cache entry written either compressed or plain."""
|
| 138 |
+
|
| 139 |
+
if payload[:2] == b"\x1f\x8b":
|
| 140 |
+
return gzip.decompress(payload)
|
| 141 |
+
return payload
|
| 142 |
+
|
| 143 |
+
@staticmethod
|
| 144 |
+
def _atomic_write(path: Path, payload: bytes) -> None:
|
| 145 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 146 |
+
descriptor, temporary = tempfile.mkstemp(prefix=".download-", dir=path.parent)
|
| 147 |
+
try:
|
| 148 |
+
with os.fdopen(descriptor, "wb") as handle:
|
| 149 |
+
# SEC source documents are XML and compress about sevenfold. A
|
| 150 |
+
# full historical cache is the difference between ~10 GB and
|
| 151 |
+
# ~1.5 GB, which is what makes keeping it affordable — and a
|
| 152 |
+
# kept cache turns a future parser fix into a re-parse instead
|
| 153 |
+
# of a multi-day re-download.
|
| 154 |
+
handle.write(gzip.compress(payload, compresslevel=6, mtime=0))
|
| 155 |
+
handle.flush()
|
| 156 |
+
os.fsync(handle.fileno())
|
| 157 |
+
os.replace(temporary, path)
|
| 158 |
+
finally:
|
| 159 |
+
if os.path.exists(temporary):
|
| 160 |
+
os.unlink(temporary)
|
| 161 |
+
|
| 162 |
+
async def get_bytes(
|
| 163 |
+
self,
|
| 164 |
+
url: str,
|
| 165 |
+
*,
|
| 166 |
+
use_cache: bool = True,
|
| 167 |
+
max_age_seconds: float | None = None,
|
| 168 |
+
first_bytes: int | None = None,
|
| 169 |
+
timeout: float | None = None,
|
| 170 |
+
) -> bytes:
|
| 171 |
+
"""Fetch a URL, optionally only its opening bytes.
|
| 172 |
+
|
| 173 |
+
``first_bytes`` issues a ranged request. Reading an acceptance
|
| 174 |
+
timestamp needs a couple of kilobytes out of a submission that may be
|
| 175 |
+
hundreds; the request still counts against the rate limit, but the
|
| 176 |
+
transfer does not. A ranged response is never cached, since it is a
|
| 177 |
+
fragment rather than the document.
|
| 178 |
+
|
| 179 |
+
``timeout`` overrides the client default for one call. The default suits
|
| 180 |
+
an 8 KB filing; a daily feed archive is hundreds of megabytes and needs
|
| 181 |
+
minutes, and timing it out mid-transfer silently drops a whole day.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
self._validate_url(url)
|
| 185 |
+
cache_path = self._cache_path(url)
|
| 186 |
+
if first_bytes is not None:
|
| 187 |
+
use_cache = False
|
| 188 |
+
elif use_cache and self._fresh(cache_path, max_age_seconds):
|
| 189 |
+
return self._decode_cached(cache_path.read_bytes())
|
| 190 |
+
|
| 191 |
+
last_error: Exception | None = None
|
| 192 |
+
for attempt in range(1, self.max_attempts + 1):
|
| 193 |
+
await self._throttle()
|
| 194 |
+
try:
|
| 195 |
+
headers = (
|
| 196 |
+
{"Range": f"bytes=0-{first_bytes - 1}"} if first_bytes else None
|
| 197 |
+
)
|
| 198 |
+
response = await self._client.get(
|
| 199 |
+
url, headers=headers, timeout=timeout or self._timeout
|
| 200 |
+
)
|
| 201 |
+
# A block and a missing object are both terminal, but they mean
|
| 202 |
+
# opposite things to the caller, so neither is retried here.
|
| 203 |
+
if response.status_code == 403:
|
| 204 |
+
raise _classify_forbidden(response)
|
| 205 |
+
if response.status_code == 404:
|
| 206 |
+
raise SECObjectMissing(f"EDGAR has no object at {url}")
|
| 207 |
+
if response.status_code not in _RETRYABLE_STATUS:
|
| 208 |
+
if first_bytes is None or response.status_code != 206:
|
| 209 |
+
response.raise_for_status()
|
| 210 |
+
payload = response.content
|
| 211 |
+
if use_cache:
|
| 212 |
+
self._atomic_write(cache_path, payload)
|
| 213 |
+
return payload
|
| 214 |
+
retry_after = response.headers.get("Retry-After")
|
| 215 |
+
delay = float(retry_after) if retry_after and retry_after.isdigit() else 0.0
|
| 216 |
+
last_error = httpx.HTTPStatusError(
|
| 217 |
+
f"retryable SEC response {response.status_code}",
|
| 218 |
+
request=response.request,
|
| 219 |
+
response=response,
|
| 220 |
+
)
|
| 221 |
+
except (httpx.TransportError, httpx.TimeoutException) as error:
|
| 222 |
+
# Includes RemoteProtocolError: EDGAR sometimes closes a large
|
| 223 |
+
# transfer early. Retrying is the right response; the backoff
|
| 224 |
+
# below spaces the attempts.
|
| 225 |
+
last_error = error
|
| 226 |
+
delay = 0.0
|
| 227 |
+
|
| 228 |
+
if attempt < self.max_attempts:
|
| 229 |
+
exponential = min(30.0, 0.75 * (2 ** (attempt - 1)))
|
| 230 |
+
await asyncio.sleep(max(delay, exponential + random.uniform(0, 0.25)))
|
| 231 |
+
|
| 232 |
+
assert last_error is not None
|
| 233 |
+
raise last_error
|
| 234 |
+
|
| 235 |
+
async def get_resumable(
|
| 236 |
+
self,
|
| 237 |
+
url: str,
|
| 238 |
+
*,
|
| 239 |
+
timeout: float,
|
| 240 |
+
max_resumes: int = 40,
|
| 241 |
+
) -> bytes:
|
| 242 |
+
"""Download a large object, resuming from where a break left off.
|
| 243 |
+
|
| 244 |
+
EDGAR closes long transfers early often enough that restarting from
|
| 245 |
+
zero is futile: a 450 MB archive that fails at 80% would re-download
|
| 246 |
+
the whole thing, fail again, and eventually cost the day. A ranged
|
| 247 |
+
continuation keeps the bytes already received and asks only for the
|
| 248 |
+
remainder.
|
| 249 |
+
|
| 250 |
+
The resume budget is generous because each attempt makes progress: a
|
| 251 |
+
break costs only the bytes not yet received. Archives reach 1.4 GB by
|
| 252 |
+
the 2020s and can break repeatedly within one transfer, and a budget of
|
| 253 |
+
eight was already losing whole weekdays at 540 MB.
|
| 254 |
+
"""
|
| 255 |
+
|
| 256 |
+
self._validate_url(url)
|
| 257 |
+
buffer = bytearray()
|
| 258 |
+
resumes = 0
|
| 259 |
+
stalls = 0
|
| 260 |
+
max_stalls = 5
|
| 261 |
+
progress_mark = 0
|
| 262 |
+
while True:
|
| 263 |
+
headers = {"Range": f"bytes={len(buffer)}-"} if buffer else None
|
| 264 |
+
await self._throttle()
|
| 265 |
+
try:
|
| 266 |
+
async with self._client.stream(
|
| 267 |
+
"GET", url, headers=headers, timeout=timeout
|
| 268 |
+
) as response:
|
| 269 |
+
if response.status_code == 403:
|
| 270 |
+
await response.aread()
|
| 271 |
+
raise _classify_forbidden(response)
|
| 272 |
+
if response.status_code == 404:
|
| 273 |
+
raise SECObjectMissing(f"EDGAR has no object at {url}")
|
| 274 |
+
if response.status_code in _RETRYABLE_STATUS:
|
| 275 |
+
# The plain path retries these; the resumable one must
|
| 276 |
+
# too, or a transient 503 becomes a lost day.
|
| 277 |
+
await response.aread()
|
| 278 |
+
resumes += 1
|
| 279 |
+
if resumes > max_resumes:
|
| 280 |
+
response.raise_for_status()
|
| 281 |
+
await asyncio.sleep(min(30.0, 2.0 * resumes))
|
| 282 |
+
continue
|
| 283 |
+
if response.status_code not in (200, 206):
|
| 284 |
+
await response.aread()
|
| 285 |
+
response.raise_for_status()
|
| 286 |
+
async for chunk in response.aiter_bytes():
|
| 287 |
+
buffer.extend(chunk)
|
| 288 |
+
return bytes(buffer)
|
| 289 |
+
except (httpx.TransportError, httpx.TimeoutException):
|
| 290 |
+
# A break that still delivered bytes is progress, not a failed
|
| 291 |
+
# attempt: only stalls count against the budget, so a large
|
| 292 |
+
# archive breaking many times still completes.
|
| 293 |
+
if len(buffer) > progress_mark:
|
| 294 |
+
progress_mark = len(buffer)
|
| 295 |
+
stalls = 0
|
| 296 |
+
else:
|
| 297 |
+
stalls += 1
|
| 298 |
+
resumes += 1
|
| 299 |
+
if stalls > max_stalls or resumes > max_resumes:
|
| 300 |
+
raise
|
| 301 |
+
await asyncio.sleep(min(30.0, 2.0 * stalls + 1.0))
|
| 302 |
+
|
| 303 |
+
async def get_text(self, url: str, **kwargs: Any) -> str:
|
| 304 |
+
payload = await self.get_bytes(url, **kwargs)
|
| 305 |
+
return payload.decode("utf-8", errors="replace")
|
| 306 |
+
|
| 307 |
+
async def get_json(self, url: str, **kwargs: Any) -> Any:
|
| 308 |
+
return json.loads(await self.get_text(url, **kwargs))
|
| 309 |
+
|
recipe/sources.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Where the identifier observations come from.
|
| 2 |
+
|
| 3 |
+
This dataset has almost no source of its own. Every ticker in it was printed on
|
| 4 |
+
a Form 4 by the company it belongs to; every former name came from a filing
|
| 5 |
+
header; every CUSIP-to-ticker pair came from a settlement record. The job here
|
| 6 |
+
is to collect those statements with their dates and keep the evidence.
|
| 7 |
+
|
| 8 |
+
Reading a sibling dataset locally is supported so a build can be iterated
|
| 9 |
+
without moving gigabytes, but the scheduled job reads the published revisions:
|
| 10 |
+
what this dataset says has to be derivable from what the others published.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import io
|
| 16 |
+
import logging
|
| 17 |
+
import re
|
| 18 |
+
import zipfile
|
| 19 |
+
from collections.abc import Iterator
|
| 20 |
+
from datetime import UTC, date, datetime
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import polars as pl
|
| 24 |
+
|
| 25 |
+
from .config import SIBLING_DIRS, SOURCE_REPOS, Settings
|
| 26 |
+
from .schema import OBSERVATION_SCHEMA, align, empty_frame
|
| 27 |
+
from .symbols import parse_symbols
|
| 28 |
+
|
| 29 |
+
LOGGER = logging.getLogger(__name__)
|
| 30 |
+
|
| 31 |
+
COMPANY_TICKERS_URL = "https://www.sec.gov/files/company_tickers_exchange.json"
|
| 32 |
+
FTD_INDEX_URL = "https://www.sec.gov/data/foiadocsfailsdatahtm"
|
| 33 |
+
FTD_LINK = re.compile(r'href="(/files/[^"]*cnsfails(\d{6})[ab]\.zip)"')
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _observations(rows: list[dict]) -> pl.DataFrame:
|
| 37 |
+
if not rows:
|
| 38 |
+
return empty_frame(OBSERVATION_SCHEMA)
|
| 39 |
+
frame = pl.DataFrame(rows, strict=False).with_columns(
|
| 40 |
+
pl.lit(datetime.now(UTC)).alias("inserted_at")
|
| 41 |
+
)
|
| 42 |
+
return align(frame, OBSERVATION_SCHEMA)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def sibling_path(settings: Settings, name: str) -> Path | None:
|
| 46 |
+
if settings.siblings_dir is None:
|
| 47 |
+
return None
|
| 48 |
+
path = settings.siblings_dir / SIBLING_DIRS[name] / "data"
|
| 49 |
+
return path if path.is_dir() else None
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _download_sibling(name: str, patterns: list[str], token: str | None) -> Path:
|
| 53 |
+
from huggingface_hub import snapshot_download
|
| 54 |
+
|
| 55 |
+
LOGGER.info("downloading %s from %s", patterns, SOURCE_REPOS[name])
|
| 56 |
+
return Path(
|
| 57 |
+
snapshot_download(
|
| 58 |
+
repo_id=SOURCE_REPOS[name],
|
| 59 |
+
repo_type="dataset",
|
| 60 |
+
allow_patterns=patterns,
|
| 61 |
+
token=token,
|
| 62 |
+
)
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def sibling_frame(
|
| 67 |
+
settings: Settings, name: str, config: str, columns: list[str], *, token: str | None = None
|
| 68 |
+
) -> pl.LazyFrame:
|
| 69 |
+
"""One config of a sibling dataset, local if available, else from the Hub."""
|
| 70 |
+
local = sibling_path(settings, name)
|
| 71 |
+
if local is not None:
|
| 72 |
+
files = sorted(
|
| 73 |
+
path
|
| 74 |
+
for path in (local / config).rglob("*.parquet")
|
| 75 |
+
if not any(part.endswith(".delta") for part in path.parts)
|
| 76 |
+
)
|
| 77 |
+
if files:
|
| 78 |
+
return pl.scan_parquet(files).select(columns)
|
| 79 |
+
root = _download_sibling(name, [f"data/{config}/**"], token)
|
| 80 |
+
files = sorted(
|
| 81 |
+
path
|
| 82 |
+
for path in (root / "data" / config).rglob("*.parquet")
|
| 83 |
+
if not any(part.endswith(".delta") for part in path.parts)
|
| 84 |
+
)
|
| 85 |
+
if not files:
|
| 86 |
+
raise FileNotFoundError(f"{SOURCE_REPOS[name]} has no {config} parquet")
|
| 87 |
+
return pl.scan_parquet(files).select(columns)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def from_ownership_filings(settings: Settings, *, token: str | None = None) -> pl.DataFrame:
|
| 91 |
+
"""Tickers and issuer names as Form 4 filers printed them.
|
| 92 |
+
|
| 93 |
+
Four million filings, each stating the symbol on the day it was filed. This
|
| 94 |
+
is the only free source of ticker *history*: `company_tickers.json` states
|
| 95 |
+
today's map and carries no past, so a company that changed symbol is listed
|
| 96 |
+
under the new one for its whole life.
|
| 97 |
+
"""
|
| 98 |
+
frame = sibling_frame(
|
| 99 |
+
settings, "insider", "filings",
|
| 100 |
+
["issuer_cik", "issuer_name", "issuer_trading_symbol_raw", "filing_date",
|
| 101 |
+
"accession_number"],
|
| 102 |
+
token=token,
|
| 103 |
+
).collect()
|
| 104 |
+
LOGGER.info("ownership filings: %d", frame.height)
|
| 105 |
+
|
| 106 |
+
rows: list[dict] = []
|
| 107 |
+
for cik, name, raw, filed, accession in frame.iter_rows():
|
| 108 |
+
if filed is None or not cik:
|
| 109 |
+
continue
|
| 110 |
+
for symbol in parse_symbols(raw):
|
| 111 |
+
rows.append({
|
| 112 |
+
"cik": cik, "kind": "ticker", "value": symbol.ticker,
|
| 113 |
+
"observed_on": filed, "source": "form4", "source_ref": accession,
|
| 114 |
+
})
|
| 115 |
+
if symbol.exchange:
|
| 116 |
+
rows.append({
|
| 117 |
+
"cik": cik, "kind": "exchange", "value": symbol.exchange,
|
| 118 |
+
"observed_on": filed, "source": "form4", "source_ref": accession,
|
| 119 |
+
})
|
| 120 |
+
if name:
|
| 121 |
+
rows.append({
|
| 122 |
+
"cik": cik, "kind": "name", "value": name.strip(),
|
| 123 |
+
"observed_on": filed, "source": "form4", "source_ref": accession,
|
| 124 |
+
})
|
| 125 |
+
return _observations(rows)
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def from_fundamental_filings(settings: Settings, *, token: str | None = None) -> pl.DataFrame:
|
| 129 |
+
"""Names, former names, industry and incorporation, dated by filing.
|
| 130 |
+
|
| 131 |
+
`former_name` is the one identifier here that carries its own end date: the
|
| 132 |
+
filing states the name it used to have and when it changed, which no run of
|
| 133 |
+
observations could reconstruct.
|
| 134 |
+
"""
|
| 135 |
+
frame = sibling_frame(
|
| 136 |
+
settings, "fundamentals", "filings",
|
| 137 |
+
["cik", "company_name", "former_name", "former_name_changed", "sic",
|
| 138 |
+
"fiscal_year_end", "state_incorporated", "filed_date", "accession_number"],
|
| 139 |
+
token=token,
|
| 140 |
+
).collect()
|
| 141 |
+
LOGGER.info("fundamental filings: %d", frame.height)
|
| 142 |
+
|
| 143 |
+
rows: list[dict] = []
|
| 144 |
+
for cik, name, former, changed, sic, fye, state, filed, accession in frame.iter_rows():
|
| 145 |
+
if filed is None or not cik:
|
| 146 |
+
continue
|
| 147 |
+
base = {"cik": cik, "observed_on": filed, "source": "xbrl", "source_ref": accession}
|
| 148 |
+
if name:
|
| 149 |
+
rows.append({**base, "kind": "name", "value": name.strip()})
|
| 150 |
+
if former:
|
| 151 |
+
rows.append({
|
| 152 |
+
**base, "kind": "former_name", "value": former.strip(),
|
| 153 |
+
"observed_on": changed or filed,
|
| 154 |
+
})
|
| 155 |
+
if sic:
|
| 156 |
+
rows.append({**base, "kind": "sic", "value": sic})
|
| 157 |
+
if fye:
|
| 158 |
+
rows.append({**base, "kind": "fiscal_year_end", "value": fye})
|
| 159 |
+
if state:
|
| 160 |
+
rows.append({**base, "kind": "state_incorporated", "value": state})
|
| 161 |
+
return _observations(rows)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
async def from_company_tickers(client, *, today: date | None = None) -> pl.DataFrame:
|
| 165 |
+
"""SEC's current CIK-to-ticker map, with the exchange.
|
| 166 |
+
|
| 167 |
+
It states today and only today, which is exactly why it cannot be the whole
|
| 168 |
+
dataset -- but it is authoritative for what is listed right now, and it
|
| 169 |
+
covers companies that never filed a Form 4.
|
| 170 |
+
"""
|
| 171 |
+
payload = await client.get_json(COMPANY_TICKERS_URL, max_age_seconds=24 * 3600)
|
| 172 |
+
fields = payload.get("fields") if isinstance(payload, dict) else None
|
| 173 |
+
records = payload.get("data") if isinstance(payload, dict) else payload
|
| 174 |
+
observed = today or date.today()
|
| 175 |
+
rows: list[dict] = []
|
| 176 |
+
for record in records or []:
|
| 177 |
+
item = dict(zip(fields, record, strict=False)) if fields else record
|
| 178 |
+
cik = str(item.get("cik") or item.get("cik_str") or "").strip()
|
| 179 |
+
if not cik.isdigit():
|
| 180 |
+
continue
|
| 181 |
+
cik = cik.zfill(10)
|
| 182 |
+
base = {"cik": cik, "observed_on": observed, "source": "company_tickers",
|
| 183 |
+
"source_ref": "company_tickers_exchange.json"}
|
| 184 |
+
ticker = (item.get("ticker") or "").strip().upper()
|
| 185 |
+
if ticker:
|
| 186 |
+
rows.append({**base, "kind": "ticker", "value": ticker})
|
| 187 |
+
exchange = (item.get("exchange") or "").strip().upper()
|
| 188 |
+
if exchange:
|
| 189 |
+
rows.append({**base, "kind": "exchange", "value": exchange})
|
| 190 |
+
name = (item.get("name") or item.get("title") or "").strip()
|
| 191 |
+
if name:
|
| 192 |
+
rows.append({**base, "kind": "name", "value": name})
|
| 193 |
+
LOGGER.info("company_tickers: %d observations", len(rows))
|
| 194 |
+
return _observations(rows)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
async def ftd_archives(client) -> list[str]:
|
| 198 |
+
"""Every fails-to-deliver file SEC currently links to."""
|
| 199 |
+
html = await client.get_text(FTD_INDEX_URL, max_age_seconds=24 * 3600)
|
| 200 |
+
links = {f"https://www.sec.gov{path}": month for path, month in FTD_LINK.findall(html)}
|
| 201 |
+
return sorted(links)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def parse_ftd(payload: bytes, *, source_ref: str) -> Iterator[dict]:
|
| 205 |
+
"""CUSIP, symbol and issuer name as the clearing record states them.
|
| 206 |
+
|
| 207 |
+
Settlement records are a strange place to find a security master, and they
|
| 208 |
+
are the best free one: `SETTLEMENT DATE|CUSIP|SYMBOL|QUANTITY|DESCRIPTION|
|
| 209 |
+
PRICE`, twice a month since 2004, twelve thousand securities a file. No
|
| 210 |
+
other free source ties a CUSIP to a ticker on a date.
|
| 211 |
+
"""
|
| 212 |
+
with zipfile.ZipFile(io.BytesIO(payload)) as archive:
|
| 213 |
+
name = archive.namelist()[0]
|
| 214 |
+
text = archive.read(name).decode("latin-1")
|
| 215 |
+
for line in text.splitlines()[1:]:
|
| 216 |
+
parts = line.split("|")
|
| 217 |
+
if len(parts) < 5:
|
| 218 |
+
continue
|
| 219 |
+
settled, cusip, symbol, _quantity, description = (part.strip() for part in parts[:5])
|
| 220 |
+
if len(settled) != 8 or not settled.isdigit() or not cusip or not symbol:
|
| 221 |
+
continue
|
| 222 |
+
observed = date(int(settled[:4]), int(settled[4:6]), int(settled[6:]))
|
| 223 |
+
yield {"cusip": cusip.upper(), "ticker": symbol.upper(),
|
| 224 |
+
"issuer_name": description, "observed_on": observed, "source_ref": source_ref}
|
recipe/store.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Write and read the published tables.
|
| 2 |
+
|
| 3 |
+
Storage is deliberately simpler here than in the sibling datasets. There, rows
|
| 4 |
+
arrive one filing at a time from a feed and an append-only store with a primary
|
| 5 |
+
key is the only way to tell a new row from one already held. Here the unit of
|
| 6 |
+
arrival is a whole quarterly archive, and every accession appears in exactly
|
| 7 |
+
one archive -- verified across four quarters, zero overlap. So a quarter is
|
| 8 |
+
written as one partition that a rebuild reproduces byte for byte, no key column
|
| 9 |
+
is needed, and re-ingesting a quarter is idempotent by construction rather than
|
| 10 |
+
by comparison.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import shutil
|
| 17 |
+
import tempfile
|
| 18 |
+
from collections.abc import Mapping
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
|
| 21 |
+
import polars as pl
|
| 22 |
+
|
| 23 |
+
from .schema import CONFIG_SCHEMAS, align
|
| 24 |
+
|
| 25 |
+
PARTITION = "kind"
|
| 26 |
+
# Facts of one quarter run to about forty megabytes of parquet; splitting that
|
| 27 |
+
# into several files would only multiply metadata. One file per quarter also
|
| 28 |
+
# makes the partition trivially replaceable.
|
| 29 |
+
PART_NAME = "part-00000.parquet"
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def partition_dir(data_dir: Path, table: str, quarter: str) -> Path:
|
| 33 |
+
return Path(data_dir) / table / f"{PARTITION}={quarter}"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def atomic_write_parquet(frame: pl.DataFrame, target: Path) -> None:
|
| 37 |
+
"""Write through a temporary file in the same directory, then rename.
|
| 38 |
+
|
| 39 |
+
A partly written parquet is indistinguishable from a valid one until it is
|
| 40 |
+
read, and a build interrupted mid-write would leave the dataset in a state
|
| 41 |
+
that only fails later, in a consumer's process.
|
| 42 |
+
"""
|
| 43 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 44 |
+
descriptor, temporary = tempfile.mkstemp(
|
| 45 |
+
prefix=".part-", suffix=".parquet", dir=target.parent
|
| 46 |
+
)
|
| 47 |
+
os.close(descriptor)
|
| 48 |
+
try:
|
| 49 |
+
frame.write_parquet(temporary, compression="zstd", statistics=True)
|
| 50 |
+
os.replace(temporary, target)
|
| 51 |
+
finally:
|
| 52 |
+
if os.path.exists(temporary):
|
| 53 |
+
os.unlink(temporary)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def write_quarter(
|
| 57 |
+
data_dir: Path, table: str, quarter: str, frame: pl.DataFrame
|
| 58 |
+
) -> tuple[Path, int]:
|
| 59 |
+
"""Replace one quarter's partition of one table."""
|
| 60 |
+
schema = CONFIG_SCHEMAS[table]
|
| 61 |
+
directory = partition_dir(data_dir, table, quarter)
|
| 62 |
+
if directory.exists():
|
| 63 |
+
shutil.rmtree(directory)
|
| 64 |
+
target = directory / PART_NAME
|
| 65 |
+
atomic_write_parquet(align(frame, schema), target)
|
| 66 |
+
return target, frame.height
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def ingested_quarters(data_dir: Path, table: str = "facts") -> set[str]:
|
| 70 |
+
"""Quarters already on disk, read from the partition names themselves.
|
| 71 |
+
|
| 72 |
+
A separate ledger file would be a second source of truth about what was
|
| 73 |
+
built, and the two would disagree the first time a run was interrupted.
|
| 74 |
+
"""
|
| 75 |
+
root = Path(data_dir) / table
|
| 76 |
+
if not root.is_dir():
|
| 77 |
+
return set()
|
| 78 |
+
return {
|
| 79 |
+
path.name.split("=", 1)[1]
|
| 80 |
+
for path in root.iterdir()
|
| 81 |
+
if path.is_dir() and path.name.startswith(f"{PARTITION}=") and any(path.iterdir())
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def read_table(
|
| 86 |
+
data_dir: Path, table: str, *, quarters: set[str] | None = None
|
| 87 |
+
) -> pl.LazyFrame:
|
| 88 |
+
"""Lazy scan of a table, optionally restricted to some quarters."""
|
| 89 |
+
root = Path(data_dir) / table
|
| 90 |
+
if not root.is_dir():
|
| 91 |
+
return pl.LazyFrame(schema=dict(CONFIG_SCHEMAS[table]))
|
| 92 |
+
# The Delta table lives inside the pit directory and is made of parquet
|
| 93 |
+
# files holding the very same rows. Globbing them alongside the partitions
|
| 94 |
+
# returns every point-in-time event twice, which reads as a broken
|
| 95 |
+
# projection rather than as a directory-listing mistake.
|
| 96 |
+
files = sorted(
|
| 97 |
+
path
|
| 98 |
+
for path in root.rglob("*.parquet")
|
| 99 |
+
if not any(part.endswith(".delta") or part == "_delta_log" for part in path.parts)
|
| 100 |
+
and (quarters is None or path.parent.name.split("=", 1)[-1] in quarters)
|
| 101 |
+
)
|
| 102 |
+
if not files:
|
| 103 |
+
return pl.LazyFrame(schema=dict(CONFIG_SCHEMAS[table]))
|
| 104 |
+
return pl.scan_parquet(files)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def table_rows(data_dir: Path, table: str) -> int:
|
| 108 |
+
return int(read_table(data_dir, table).select(pl.len()).collect().item())
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def write_singleton(data_dir: Path, table: str, frame: pl.DataFrame) -> Path:
|
| 112 |
+
"""A table small enough to live in one file, such as the archive ledger."""
|
| 113 |
+
target = Path(data_dir) / table / PART_NAME
|
| 114 |
+
atomic_write_parquet(align(frame, CONFIG_SCHEMAS[table]), target)
|
| 115 |
+
return target
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def config_row_counts(data_dir: Path, tables: Mapping[str, object] | None = None) -> dict[str, int]:
|
| 119 |
+
names = list(tables or CONFIG_SCHEMAS)
|
| 120 |
+
return {name: table_rows(data_dir, name) for name in names}
|
recipe/symbols.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Turn what a filing wrote in the ticker box into tickers.
|
| 2 |
+
|
| 3 |
+
Four million Form 4 filings state a trading symbol, and 2.3% of them state
|
| 4 |
+
something else: an exchange prefix (`NYSE: KRC`), parentheses (`(SIRI)`), two
|
| 5 |
+
share classes at once (`ISCA, ISCB`, `JWA/JWB`, `BFA, BFB`), or a word meaning
|
| 6 |
+
absence (`NONE`, `N/A`). Read literally, those become 3 428 tickers that never
|
| 7 |
+
traded, and the companies behind them - Hubbell, Brown-Forman, Wiley - lose
|
| 8 |
+
their real symbols.
|
| 9 |
+
|
| 10 |
+
The parser returns every symbol it finds, because a company with two share
|
| 11 |
+
classes genuinely has two, and the exchange when the filer volunteered one.
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import re
|
| 17 |
+
from dataclasses import dataclass
|
| 18 |
+
|
| 19 |
+
# A symbol as the exchanges write them: up to five letters, optionally a class
|
| 20 |
+
# suffix after a dot or dash. Deliberately not looser -- a pattern that accepts
|
| 21 |
+
# anything short and upper-case swallows "NONE", "OTC" and "N A".
|
| 22 |
+
SYMBOL = re.compile(r"^[A-Z]{1,5}(?:[.\-][A-Z]{1,2})?$")
|
| 23 |
+
|
| 24 |
+
# Words filers write to mean "no symbol". Matched whole, after stripping.
|
| 25 |
+
ABSENT = frozenset({
|
| 26 |
+
"NONE", "N/A", "NA", "N A", "N.A.", "NOTAPPLICABLE", "NOT APPLICABLE",
|
| 27 |
+
"NOTLISTED", "NOT LISTED", "NOTRADING", "NO TRADING SYMBOL", "NO SYMBOL",
|
| 28 |
+
"PRIVATE", "UNLISTED", "--", "-", ".", "*", "TBD", "PENDING", "XXX",
|
| 29 |
+
})
|
| 30 |
+
|
| 31 |
+
# Exchange names filers put in front of the symbol. The value is the canonical
|
| 32 |
+
# code kept alongside the ticker: the prefix is noise for identification and
|
| 33 |
+
# evidence for listing.
|
| 34 |
+
EXCHANGE_PREFIX = {
|
| 35 |
+
"NYSE": "NYSE", "NEW YORK STOCK EXCHANGE": "NYSE", "NYSE MKT": "NYSEAMERICAN",
|
| 36 |
+
"NYSE AMERICAN": "NYSEAMERICAN", "NYSE ARCA": "NYSEARCA", "ARCA": "NYSEARCA",
|
| 37 |
+
"AMEX": "NYSEAMERICAN", "AMERICAN STOCK EXCHANGE": "NYSEAMERICAN",
|
| 38 |
+
"NASDAQ": "NASDAQ", "NASD": "NASDAQ", "NASDAQ GS": "NASDAQ",
|
| 39 |
+
"NASDAQ GM": "NASDAQ", "NASDAQ CM": "NASDAQ", "NASDAQ GLOBAL SELECT": "NASDAQ",
|
| 40 |
+
"OTC": "OTC", "OTCBB": "OTC", "OTC BB": "OTC", "OTC MARKETS": "OTC",
|
| 41 |
+
"PINK": "OTC", "PINK SHEETS": "OTC", "CBOE": "CBOE", "BATS": "CBOE",
|
| 42 |
+
"TSX": "TSX", "TSXV": "TSXV", "LSE": "LSE",
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
_SPLIT = re.compile(r"[,;/&]| and | or ", re.I)
|
| 46 |
+
# Decoration around a symbol. A character-set strip is easy to mistype -- this
|
| 47 |
+
# one carried a duplicated bracket for a while -- and says less about intent.
|
| 48 |
+
_TRIM = re.compile(r"^[\s()\[\]{}\"']+|[\s()\[\]{}\"']+$")
|
| 49 |
+
# A trailing venue note: NWIN(OB), ACME (Pink Sheets).
|
| 50 |
+
_TRAILING_NOTE = re.compile(r"\s*\(([^)]{1,20})\)\s*$")
|
| 51 |
+
_PREFIX = re.compile(r"^\s*([A-Za-z .]{2,28}?)\s*[:\-]\s*(.+)$")
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@dataclass(frozen=True, slots=True)
|
| 55 |
+
class Symbol:
|
| 56 |
+
ticker: str
|
| 57 |
+
exchange: str | None = None
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _clean(chunk: str) -> tuple[str, str | None]:
|
| 61 |
+
"""Strip decoration from one chunk and pull out an exchange if it is there."""
|
| 62 |
+
# The trailing note is read before brackets are stripped: stripping first
|
| 63 |
+
# turns "NWIN(OB)" into "NWIN(OB", which matches nothing.
|
| 64 |
+
text = re.sub(r"\s+", " ", chunk.strip())
|
| 65 |
+
exchange: str | None = None
|
| 66 |
+
note = _TRAILING_NOTE.search(text)
|
| 67 |
+
if note and SYMBOL.match(_TRIM.sub("", text[: note.start()]).upper()):
|
| 68 |
+
exchange = EXCHANGE_PREFIX.get(note.group(1).strip().upper())
|
| 69 |
+
text = text[: note.start()].strip()
|
| 70 |
+
text = _TRIM.sub("", text)
|
| 71 |
+
# "N O G" is one symbol written with spaces, not three symbols.
|
| 72 |
+
letters = text.split(" ")
|
| 73 |
+
if len(letters) > 1 and all(len(part) == 1 and part.isalpha() for part in letters):
|
| 74 |
+
text = "".join(letters)
|
| 75 |
+
match = _PREFIX.match(text)
|
| 76 |
+
if match:
|
| 77 |
+
candidate = match.group(1).strip().upper().rstrip(".")
|
| 78 |
+
if candidate in EXCHANGE_PREFIX:
|
| 79 |
+
exchange = EXCHANGE_PREFIX[candidate]
|
| 80 |
+
text = match.group(2).strip()
|
| 81 |
+
elif SYMBOL.match(candidate) and not SYMBOL.match(match.group(2).strip().upper()):
|
| 82 |
+
# "KRC - New York Stock Exchange": the symbol is on the left, and
|
| 83 |
+
# the exchange is still worth keeping.
|
| 84 |
+
exchange = EXCHANGE_PREFIX.get(match.group(2).strip().upper().rstrip("."))
|
| 85 |
+
text = candidate
|
| 86 |
+
return _TRIM.sub("", text), exchange
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def parse_symbols(raw: str | None) -> list[Symbol]:
|
| 90 |
+
"""Every symbol stated in one ticker field, in the order written."""
|
| 91 |
+
if raw is None:
|
| 92 |
+
return []
|
| 93 |
+
text = re.sub(r"\s+", " ", raw).strip()
|
| 94 |
+
if not text or text.upper() in ABSENT:
|
| 95 |
+
return []
|
| 96 |
+
|
| 97 |
+
outer_exchange: str | None = None
|
| 98 |
+
stripped, exchange = _clean(text)
|
| 99 |
+
if exchange:
|
| 100 |
+
outer_exchange, text = exchange, stripped
|
| 101 |
+
|
| 102 |
+
# Split on separators first, then on plain spaces -- "CRDA CRDB" is two
|
| 103 |
+
# share classes. A single chunk that already parses is left alone, so a
|
| 104 |
+
# symbol containing a space is not shredded.
|
| 105 |
+
chunks = _SPLIT.split(text)
|
| 106 |
+
if len(chunks) == 1 and " " in text and not SYMBOL.match(_clean(text)[0].upper()):
|
| 107 |
+
chunks = text.split(" ")
|
| 108 |
+
|
| 109 |
+
found: list[Symbol] = []
|
| 110 |
+
seen: set[str] = set()
|
| 111 |
+
exchange_only: list[str] = []
|
| 112 |
+
for chunk in chunks:
|
| 113 |
+
candidate, chunk_exchange = _clean(chunk)
|
| 114 |
+
upper = candidate.upper()
|
| 115 |
+
# "NYSE/TRN" splits into two chunks and the first is an exchange, not a
|
| 116 |
+
# four-letter ticker. But "CBOE" alone is Cboe Global Markets, whose
|
| 117 |
+
# ticker is its own name -- so a venue name is only discarded when some
|
| 118 |
+
# other chunk turned out to be a symbol.
|
| 119 |
+
if upper in EXCHANGE_PREFIX:
|
| 120 |
+
exchange_only.append(upper)
|
| 121 |
+
continue
|
| 122 |
+
if not upper or upper in ABSENT or not SYMBOL.match(upper):
|
| 123 |
+
continue
|
| 124 |
+
if upper in seen:
|
| 125 |
+
continue
|
| 126 |
+
seen.add(upper)
|
| 127 |
+
found.append(Symbol(ticker=upper, exchange=chunk_exchange or outer_exchange))
|
| 128 |
+
|
| 129 |
+
if not found and exchange_only:
|
| 130 |
+
return [
|
| 131 |
+
Symbol(ticker=name, exchange=None)
|
| 132 |
+
for name in exchange_only
|
| 133 |
+
if SYMBOL.match(name)
|
| 134 |
+
]
|
| 135 |
+
if found and exchange_only:
|
| 136 |
+
venue = EXCHANGE_PREFIX[exchange_only[0]]
|
| 137 |
+
found = [Symbol(s.ticker, s.exchange or venue) for s in found]
|
| 138 |
+
return found
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def primary_symbol(raw: str | None) -> str | None:
|
| 142 |
+
"""The first symbol, which is the one a filer writes for the main class."""
|
| 143 |
+
symbols = parse_symbols(raw)
|
| 144 |
+
return symbols[0].ticker if symbols else None
|
tests/conftest.py
ADDED
|
@@ -0,0 +1,57 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import sys
|
| 4 |
+
from datetime import UTC, date, datetime
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
import polars as pl
|
| 8 |
+
import pytest
|
| 9 |
+
|
| 10 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 11 |
+
if str(ROOT) not in sys.path:
|
| 12 |
+
sys.path.insert(0, str(ROOT))
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def observation(cik, kind, value, day, source="form4", ref="acc-1"):
|
| 16 |
+
return {"cik": cik, "kind": kind, "value": value, "observed_on": day,
|
| 17 |
+
"source": source, "source_ref": ref, "inserted_at": datetime.now(UTC)}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@pytest.fixture
|
| 21 |
+
def observations() -> pl.DataFrame:
|
| 22 |
+
"""A filer that renamed itself and changed ticker, plus a later reuser.
|
| 23 |
+
|
| 24 |
+
`PLUM` moves from one company to another, which is the case a security
|
| 25 |
+
master exists to get right: a backtest that resolves it by today's mapping
|
| 26 |
+
reads the wrong company's history for the earlier years.
|
| 27 |
+
"""
|
| 28 |
+
rows = [
|
| 29 |
+
observation("0000000001", "ticker", "OLDT", date(2012, 3, 1), ref="a1"),
|
| 30 |
+
observation("0000000001", "ticker", "OLDT", date(2015, 3, 1), ref="a2"),
|
| 31 |
+
observation("0000000001", "ticker", "NEWT", date(2016, 3, 1), ref="a3"),
|
| 32 |
+
observation("0000000001", "ticker", "NEWT", date(2024, 3, 1), ref="a4"),
|
| 33 |
+
observation("0000000001", "name", "Old Name Inc", date(2012, 3, 1), ref="a1"),
|
| 34 |
+
observation("0000000001", "name", "New Name Inc", date(2024, 3, 1), ref="a4"),
|
| 35 |
+
observation("0000000001", "sic", "3571", date(2024, 3, 1), source="xbrl", ref="a4"),
|
| 36 |
+
# PLUM belonged to filer 2 until 2014 and to filer 3 from 2019.
|
| 37 |
+
observation("0000000002", "ticker", "PLUM", date(2010, 5, 1), ref="b1"),
|
| 38 |
+
observation("0000000002", "ticker", "PLUM", date(2014, 5, 1), ref="b2"),
|
| 39 |
+
observation("0000000003", "ticker", "PLUM", date(2019, 5, 1), ref="c1"),
|
| 40 |
+
observation("0000000003", "ticker", "PLUM", date(2024, 5, 1), ref="c2"),
|
| 41 |
+
]
|
| 42 |
+
return pl.DataFrame(rows, strict=False)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@pytest.fixture
|
| 46 |
+
def ftd() -> pl.DataFrame:
|
| 47 |
+
return pl.DataFrame(
|
| 48 |
+
[
|
| 49 |
+
{"cusip": "111111111", "ticker": "PLUM", "issuer_name": "PLUM CORP",
|
| 50 |
+
"observed_on": date(2012, 6, 1), "source_ref": "f1"},
|
| 51 |
+
{"cusip": "222222222", "ticker": "PLUM", "issuer_name": "PLUM HOLDINGS",
|
| 52 |
+
"observed_on": date(2022, 6, 1), "source_ref": "f2"},
|
| 53 |
+
{"cusip": "333333333", "ticker": "GHOST", "issuer_name": "GHOST INC",
|
| 54 |
+
"observed_on": date(2020, 6, 1), "source_ref": "f3"},
|
| 55 |
+
],
|
| 56 |
+
strict=False,
|
| 57 |
+
)
|
tests/test_docs_and_jobs.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The published documents and the job must describe what is actually built."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import re
|
| 7 |
+
import tomllib
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
|
| 10 |
+
import yaml
|
| 11 |
+
|
| 12 |
+
from recipe.hf_jobs import DEFAULT_SCHEDULE, JOB_SCRIPT
|
| 13 |
+
from recipe.schema import CONFIG_SCHEMAS
|
| 14 |
+
|
| 15 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _frontmatter() -> dict:
|
| 19 |
+
text = (ROOT / "README.md").read_text(encoding="utf-8")
|
| 20 |
+
assert text.startswith("---\n")
|
| 21 |
+
return yaml.safe_load(text.split("---\n", 2)[1])
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def test_readme_declares_every_config():
|
| 25 |
+
assert {entry["config_name"] for entry in _frontmatter()["configs"]} == set(CONFIG_SCHEMAS)
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def test_readme_has_no_unfilled_placeholders():
|
| 29 |
+
assert not re.findall(r"\{\{[A-Z_]+\}\}", (ROOT / "README.md").read_text(encoding="utf-8"))
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def test_job_script_declares_every_runtime_dependency():
|
| 33 |
+
"""A Job installs from the script header alone; a gap fails only in the cloud."""
|
| 34 |
+
project = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))["project"]
|
| 35 |
+
required = {re.split(r"[<>=]", n, maxsplit=1)[0].strip().lower() for n in project["dependencies"]}
|
| 36 |
+
for group in ("dev", "publish"):
|
| 37 |
+
required |= {
|
| 38 |
+
re.split(r"[<>=]", n, maxsplit=1)[0].strip().lower()
|
| 39 |
+
for n in project.get("optional-dependencies", {}).get(group, [])
|
| 40 |
+
}
|
| 41 |
+
header = (ROOT / JOB_SCRIPT).read_text(encoding="utf-8").split("# ///")[1]
|
| 42 |
+
declared = {m.group(1).lower() for m in re.finditer(r'"\s*([A-Za-z0-9_.-]+)\s*[<>=]', header)}
|
| 43 |
+
assert required <= declared
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def test_manifest_matches_the_recipe():
|
| 47 |
+
from recipe.build import PIT_DELTA_NAME
|
| 48 |
+
|
| 49 |
+
manifest = json.loads((ROOT / "manifest.json").read_text(encoding="utf-8"))
|
| 50 |
+
assert manifest["bundle_storage_data"]["table_uri"].endswith(PIT_DELTA_NAME)
|
| 51 |
+
assert manifest["source"]["schedule"] == DEFAULT_SCHEDULE
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def test_schedule_runs_after_the_dataset_it_reads():
|
| 55 |
+
"""This dataset is assembled from company-fundamentals; reading yesterday's
|
| 56 |
+
revision would publish a master that lags its own sources by a week."""
|
| 57 |
+
hour, minute = int(DEFAULT_SCHEDULE.split()[1]), int(DEFAULT_SCHEDULE.split()[0])
|
| 58 |
+
assert (hour, minute) > (7, 10), DEFAULT_SCHEDULE
|
tests/test_intervals.py
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Observations into spans, filers, and the CUSIP bridge."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from datetime import date
|
| 6 |
+
|
| 7 |
+
import polars as pl
|
| 8 |
+
|
| 9 |
+
from recipe.intervals import build_cusip_map, build_identifiers, build_issuers, build_pit
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_a_ticker_change_becomes_two_spans(observations):
|
| 13 |
+
spans = build_identifiers(observations)
|
| 14 |
+
ticker = spans.filter(
|
| 15 |
+
(pl.col("cik") == "0000000001") & (pl.col("kind") == "ticker")
|
| 16 |
+
).sort("valid_from")
|
| 17 |
+
assert ticker["value"].to_list() == ["OLDT", "NEWT"]
|
| 18 |
+
assert ticker["valid_from"].to_list() == [date(2012, 3, 1), date(2016, 3, 1)]
|
| 19 |
+
assert ticker["valid_to"].to_list() == [date(2015, 3, 1), date(2024, 3, 1)]
|
| 20 |
+
assert ticker["is_current"].to_list() == [False, True]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def test_a_dormant_filer_holds_no_current_ticker(observations):
|
| 24 |
+
"""A company that stopped filing in 2014 is not currently listed under its
|
| 25 |
+
2014 ticker -- and PLUM belongs to whoever files under it now."""
|
| 26 |
+
spans = build_identifiers(observations)
|
| 27 |
+
plum = spans.filter((pl.col("kind") == "ticker") & (pl.col("value") == "PLUM"))
|
| 28 |
+
current = plum.filter(pl.col("is_current"))
|
| 29 |
+
assert current.height == 1, "one live owner, not two"
|
| 30 |
+
assert current["cik"][0] == "0000000003"
|
| 31 |
+
# The dormant filer keeps its own history, flagged as its latest.
|
| 32 |
+
dormant = plum.filter(pl.col("cik") == "0000000002").row(0, named=True)
|
| 33 |
+
assert dormant["is_current"] is False
|
| 34 |
+
assert dormant["is_latest_for_filer"] is True
|
| 35 |
+
assert dormant["valid_to"] == date(2014, 5, 1)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def test_issuer_keeps_its_name(observations):
|
| 39 |
+
"""Regression: the changes pivot produced a column called `name` too, and
|
| 40 |
+
renaming after the join blanked every issuer's name."""
|
| 41 |
+
spans = build_identifiers(observations)
|
| 42 |
+
issuers = build_issuers(spans, observations)
|
| 43 |
+
row = issuers.filter(pl.col("cik") == "0000000001").row(0, named=True)
|
| 44 |
+
assert row["name"] == "New Name Inc"
|
| 45 |
+
assert row["primary_ticker"] == "NEWT"
|
| 46 |
+
assert row["name_changes"] == 2
|
| 47 |
+
assert row["ticker_changes"] == 2
|
| 48 |
+
assert row["sic"] == "3571"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_dormant_filers_are_marked_inactive(observations):
|
| 52 |
+
spans = build_identifiers(observations)
|
| 53 |
+
issuers = build_issuers(spans, observations)
|
| 54 |
+
assert issuers.filter(pl.col("cik") == "0000000002")["is_active"][0] is False
|
| 55 |
+
assert issuers.filter(pl.col("cik") == "0000000001")["is_active"][0] is True
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def test_a_reused_ticker_resolves_by_date(observations, ftd):
|
| 59 |
+
"""The point of the bridge: PLUM is two companies, and the CUSIP knows when."""
|
| 60 |
+
spans = build_identifiers(observations)
|
| 61 |
+
bridge = build_cusip_map(ftd, spans)
|
| 62 |
+
early = bridge.filter(pl.col("cusip") == "111111111").row(0, named=True)
|
| 63 |
+
late = bridge.filter(pl.col("cusip") == "222222222").row(0, named=True)
|
| 64 |
+
assert early["cik"] == "0000000002" and early["match_confidence"] == "high"
|
| 65 |
+
assert late["cik"] == "0000000003" and late["match_confidence"] == "high"
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def test_a_cusip_with_no_filer_is_kept_and_labelled(observations, ftd):
|
| 69 |
+
spans = build_identifiers(observations)
|
| 70 |
+
bridge = build_cusip_map(ftd, spans)
|
| 71 |
+
ghost = bridge.filter(pl.col("cusip") == "333333333").row(0, named=True)
|
| 72 |
+
assert ghost["cik"] is None
|
| 73 |
+
assert ghost["match_method"] == "unmatched" and ghost["match_confidence"] == "none"
|
| 74 |
+
assert ghost["ticker"] == "GHOST", "the ticker is still usable without a filer"
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_cusip6_is_the_issuer_prefix(observations, ftd):
|
| 78 |
+
bridge = build_cusip_map(ftd, build_identifiers(observations))
|
| 79 |
+
assert bridge.filter(pl.col("cusip") == "111111111")["cusip6"][0] == "111111"
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def test_pit_dates_every_span_and_never_leaks(observations):
|
| 83 |
+
spans = build_identifiers(observations)
|
| 84 |
+
pit = build_pit(spans)
|
| 85 |
+
assert pit.height == spans.height
|
| 86 |
+
assert pit["entity_id"].null_count() == 0
|
| 87 |
+
# Knowledge is the end of the day observed, so it never precedes the event.
|
| 88 |
+
assert (pit["knowledge_date"].dt.date() >= pit["event_date"]).all()
|
| 89 |
+
assert pit["knowledge_estimated"].all()
|
tests/test_symbols.py
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The ticker box, and everything filers put in it that is not a ticker."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from recipe.symbols import parse_symbols, primary_symbol
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@pytest.mark.parametrize(
|
| 11 |
+
("raw", "expected"),
|
| 12 |
+
[
|
| 13 |
+
("AAPL", [("AAPL", None)]),
|
| 14 |
+
("brk.b", [("BRK.B", None)]),
|
| 15 |
+
# Two share classes in one box: Hubbell, Wiley, Brown-Forman all do this.
|
| 16 |
+
("ISCA, ISCB", [("ISCA", None), ("ISCB", None)]),
|
| 17 |
+
("JWA/JWB", [("JWA", None), ("JWB", None)]),
|
| 18 |
+
("CRDA CRDB", [("CRDA", None), ("CRDB", None)]),
|
| 19 |
+
# An exchange prefix is evidence of listing, not part of the symbol.
|
| 20 |
+
("NYSE: KRC", [("KRC", "NYSE")]),
|
| 21 |
+
("(NYSE:FBC)", [("FBC", "NYSE")]),
|
| 22 |
+
("NYSE/TRN", [("TRN", "NYSE")]),
|
| 23 |
+
("KRC - New York Stock Exchange", [("KRC", "NYSE")]),
|
| 24 |
+
("ACME (Pink Sheets)", [("ACME", "OTC")]),
|
| 25 |
+
("NWIN(OB)", [("NWIN", None)]),
|
| 26 |
+
("(SIRI)", [("SIRI", None)]),
|
| 27 |
+
("N O G", [("NOG", None)]),
|
| 28 |
+
# Cboe Global Markets trades as CBOE: a venue name can be a real ticker,
|
| 29 |
+
# so it is only discarded when something else in the field parsed.
|
| 30 |
+
("CBOE", [("CBOE", None)]),
|
| 31 |
+
("NONE", []),
|
| 32 |
+
("N/A", []),
|
| 33 |
+
("none", []),
|
| 34 |
+
("", []),
|
| 35 |
+
(None, []),
|
| 36 |
+
# A CIK typed into the ticker box.
|
| 37 |
+
("1314152", []),
|
| 38 |
+
],
|
| 39 |
+
)
|
| 40 |
+
def test_parses(raw, expected):
|
| 41 |
+
assert [(s.ticker, s.exchange) for s in parse_symbols(raw)] == expected
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_primary_symbol_takes_the_first_class():
|
| 45 |
+
assert primary_symbol("ISCA, ISCB") == "ISCA"
|
| 46 |
+
assert primary_symbol("NONE") is None
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_duplicates_within_one_field_collapse():
|
| 50 |
+
assert [s.ticker for s in parse_symbols("AAPL, AAPL")] == ["AAPL"]
|