Datasets:
Update the industry classification
Browse files- LICENSE +201 -0
- NOTICE +25 -0
- PIPELINE.md +207 -0
- README.md +229 -0
- data/by_ticker/part-00000.parquet +3 -0
- data/classification/part-00000.parquet +3 -0
- data/naics_map/part-00000.parquet +3 -0
- data/observations/part-00000.parquet +3 -0
- data/sic_codes/part-00000.parquet +3 -0
- data/spans/part-00000.parquet +3 -0
- data/taxonomy/part-00000.parquet +3 -0
- jobs/run.py +107 -0
- manifest.json +554 -0
- pyproject.toml +51 -0
- recipe/__init__.py +3 -0
- recipe/build.py +484 -0
- recipe/cli.py +81 -0
- recipe/config.py +57 -0
- recipe/hf_jobs.py +229 -0
- recipe/manifest.py +137 -0
- recipe/naics.py +61 -0
- recipe/publish.py +135 -0
- recipe/quality.py +300 -0
- recipe/schema.py +195 -0
- recipe/sec_client.py +309 -0
- recipe/sic.py +140 -0
- recipe/sources.py +540 -0
- recipe/store.py +55 -0
- recipe/taxonomy.py +437 -0
- tests/conftest.py +75 -0
- tests/test_build.py +154 -0
- tests/test_docs_and_jobs.py +87 -0
- tests/test_sources.py +216 -0
- tests/test_taxonomy.py +106 -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,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ZipLime US Industry Classification
|
| 2 |
+
Copyright 2026 ZipLime
|
| 3 |
+
|
| 4 |
+
Source data:
|
| 5 |
+
|
| 6 |
+
* US Securities and Exchange Commission — the Standard Industrial
|
| 7 |
+
Classification code assigned to each EDGAR filer, read from filing headers
|
| 8 |
+
and from EDGAR's submissions archive, and the SEC's published list of the
|
| 9 |
+
codes it assigns. US Government works in the public domain.
|
| 10 |
+
* US Census Bureau — the 1987 SIC to 1997 NAICS concordance, and the 1987 SIC
|
| 11 |
+
hierarchy it states. US Government works in the public domain.
|
| 12 |
+
|
| 13 |
+
Assembled from the ZipLime company-fundamentals and security-master datasets,
|
| 14 |
+
which are themselves derived from EDGAR.
|
| 15 |
+
|
| 16 |
+
The sector and industry taxonomy in recipe/taxonomy.py is original work by
|
| 17 |
+
ZipLime, licensed under Apache-2.0 with the rest of the recipe (see LICENSE).
|
| 18 |
+
|
| 19 |
+
This dataset is NOT GICS and NOT ICB. It does not reproduce, approximate or
|
| 20 |
+
substitute for either. GICS is a product of MSCI and S&P Dow Jones Indices;
|
| 21 |
+
ICB is a product of FTSE Russell. Neither is used here, and no classification
|
| 22 |
+
licensed from either was consulted in building this one.
|
| 23 |
+
|
| 24 |
+
Neither the SEC nor the Census Bureau endorses, certifies or verifies this
|
| 25 |
+
dataset.
|
PIPELINE.md
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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, which judgements were made, and
|
| 5 |
+
what went wrong on the way.
|
| 6 |
+
|
| 7 |
+
## The idea
|
| 8 |
+
|
| 9 |
+
Sector classification is a licensed product. GICS belongs to MSCI and S&P Dow
|
| 10 |
+
Jones Indices, ICB to FTSE Russell, and neither can be redistributed — so a
|
| 11 |
+
free dataset that wants to say what business a company is in has to build the
|
| 12 |
+
answer from something else.
|
| 13 |
+
|
| 14 |
+
The something else exists and is public domain: the SEC assigns a Standard
|
| 15 |
+
Industrial Classification code to every filer, prints it in the header of
|
| 16 |
+
every filing, and publishes the list of the 444 codes it uses. What it does
|
| 17 |
+
not provide is a rollup worth using. The SIC divisions put pharmaceuticals,
|
| 18 |
+
semiconductors, oil refining and breweries in one bucket called Manufacturing
|
| 19 |
+
that covers a third of the listed universe.
|
| 20 |
+
|
| 21 |
+
So this dataset is two things: the SEC's codes collected with their dates, and
|
| 22 |
+
a rollup from those codes to sectors, written here and licensed Apache-2.0.
|
| 23 |
+
The first is evidence; the second is an opinion, stated as code in
|
| 24 |
+
[`recipe/taxonomy.py`](recipe/taxonomy.py) so it can be argued with.
|
| 25 |
+
|
| 26 |
+
## Why it is not GICS
|
| 27 |
+
|
| 28 |
+
It would be easy to write eleven sectors with GICS's names and let readers
|
| 29 |
+
assume compatibility. That would be wrong twice: legally, because the GICS
|
| 30 |
+
structure is a licensed product, and factually, because a SIC-derived sector
|
| 31 |
+
disagrees with GICS on real companies.
|
| 32 |
+
|
| 33 |
+
The disagreements are not marginal. Alphabet and Meta are Communication
|
| 34 |
+
Services in GICS; here they are Technology, because EDGAR files them under
|
| 35 |
+
7370 alongside systems integrators and nothing in a filing separates an
|
| 36 |
+
advertising platform from a consultancy. Managed care is Health Care in both,
|
| 37 |
+
but by different routes. Most of all, GICS has no bucket for a blank cheque
|
| 38 |
+
company, and this taxonomy gives it a sector of its own because 2 167 filers
|
| 39 |
+
have been one.
|
| 40 |
+
|
| 41 |
+
Fama and French's industry definitions were considered and left out. They are
|
| 42 |
+
the standard free taxonomy in academic finance and they would have been a
|
| 43 |
+
natural fit — but the files carry a bare copyright notice with no licence
|
| 44 |
+
grant, and the portfolios built from them derive from CRSP. Shipping a
|
| 45 |
+
redistributable dataset meant not shipping them. Anyone who wants them can
|
| 46 |
+
apply them to the `sic` column in a line of code; this dataset simply does not
|
| 47 |
+
carry the table.
|
| 48 |
+
|
| 49 |
+
## Three sources and almost no source of its own
|
| 50 |
+
|
| 51 |
+
Like the security master, this is mostly glue.
|
| 52 |
+
|
| 53 |
+
**The history** comes from `company-fundamentals`, a sibling dataset, whose
|
| 54 |
+
`filings` table carries the SIC printed in the header of every XBRL filing
|
| 55 |
+
since 2009 — 431 290 dated statements over 16 771 filers. This is the only
|
| 56 |
+
free source of SIC *history*. EDGAR's own record of a filer states today's
|
| 57 |
+
code and carries no past, so a dataset built on it alone would say Lucid was
|
| 58 |
+
a car maker in 2020, when it was an empty shell called Churchill Capital IV.
|
| 59 |
+
|
| 60 |
+
Measured on the corpus, **2 281 filers have been reclassified at least once**:
|
| 61 |
+
13.6% of the 16 771 with a filing history, which is the only population where
|
| 62 |
+
a change could be seen at all. That is the number that decides whether the
|
| 63 |
+
dated columns are worth their weight.
|
| 64 |
+
|
| 65 |
+
**The gap** is the 5 863 filers that have had a ticker and never filed XBRL:
|
| 66 |
+
delisted before 2009, funds, foreign issuers on paper. They are covered from
|
| 67 |
+
EDGAR's submissions archive, and what it gives is explicitly undated — the SEC
|
| 68 |
+
states what it has the filer under now, not when that was assigned. Those rows
|
| 69 |
+
carry `is_dated = false` and `date_basis = "undated"`, and the `by_ticker`
|
| 70 |
+
table stretches the code over the ticker's life rather than pretending to a
|
| 71 |
+
date it does not have.
|
| 72 |
+
|
| 73 |
+
Leaving them out was the alternative, and it would have made the universe out
|
| 74 |
+
of survivors. That is the bias the rest of this family exists to avoid.
|
| 75 |
+
|
| 76 |
+
**The reference** is the SEC's SIC code list — scraped, because it is a web
|
| 77 |
+
page and nothing else; there is no CSV, no JSON and no bulk file — and the
|
| 78 |
+
Census Bureau's 1987 SIC to 1997 NAICS concordance, which doubles as the
|
| 79 |
+
source for the 1987 hierarchy's own titles.
|
| 80 |
+
|
| 81 |
+
## What a SIC code is, and what EDGAR's codes are
|
| 82 |
+
|
| 83 |
+
These are two different things, and conflating them loses two fifths of the
|
| 84 |
+
list.
|
| 85 |
+
|
| 86 |
+
The 1987 SIC has 1 005 four-digit industries in 83 major groups. EDGAR assigns
|
| 87 |
+
444 codes, and only 284 of them are 1987 industries. The other 160 are a major
|
| 88 |
+
group or an industry group padded with zeros — `2000` for the whole of food,
|
| 89 |
+
`3570` for computer and office equipment — used when the SEC did not care to
|
| 90 |
+
be more precise.
|
| 91 |
+
|
| 92 |
+
Checked against all 1 005 of them: **no real 1987 code ends in a zero**. So the
|
| 93 |
+
padding is unambiguous and `sic_level` reads it off. Joining EDGAR's codes to
|
| 94 |
+
the NAICS crosswalk as if they were 1987 industries would have silently
|
| 95 |
+
dropped 39% of them; instead a roll-up is expanded to every industry beneath
|
| 96 |
+
it before the crosswalk is consulted.
|
| 97 |
+
|
| 98 |
+
Twelve EDGAR codes are inventions with no 1987 counterpart at all: asset
|
| 99 |
+
backed securities, blank cheques, finance lessors, American Depositary
|
| 100 |
+
Receipts, foreign governments, non-operating establishments and six others.
|
| 101 |
+
Three of them sit arithmetically in major group 88, which is Private
|
| 102 |
+
Households — so `division_of` returns nothing for them rather than calling a
|
| 103 |
+
depositary receipt a household service.
|
| 104 |
+
|
| 105 |
+
## The NAICS bridge is weak, and says so
|
| 106 |
+
|
| 107 |
+
Measured over this corpus: 32.7% of EDGAR's codes resolve to exactly one 1997
|
| 108 |
+
NAICS industry, 71.9% to exactly one NAICS sector, and fourteen codes resolve
|
| 109 |
+
to nothing. The rest are one-to-many, because 1997 split a 1987 industry in two.
|
| 110 |
+
|
| 111 |
+
So `naics_1997` is filled only where the answer is unique, `naics_sector` only
|
| 112 |
+
where the sector is unique, and `naics_candidates` says how many there were.
|
| 113 |
+
Picking one by a tie-break would read as fact and be a coin toss. The full
|
| 114 |
+
crosswalk ships as `naics_map` so anyone who wants to pick differently can.
|
| 115 |
+
|
| 116 |
+
## Spans are runs, not groups
|
| 117 |
+
|
| 118 |
+
A filer's codes are collapsed into runs of consecutive filings that said the
|
| 119 |
+
same thing — not grouped by (filer, code). A company that was a blank cheque,
|
| 120 |
+
became a car maker and was reclassified back has three spans, and a groupby
|
| 121 |
+
would flatten it to two and lose the order the SEC saw it in.
|
| 122 |
+
|
| 123 |
+
`valid_to` is the last filing that stated the code, not the day before the
|
| 124 |
+
next one. Nobody publishes the day a classification changed, and a filing gap
|
| 125 |
+
is a filing gap.
|
| 126 |
+
|
| 127 |
+
## `by_ticker`, and the two ways it can be wrong
|
| 128 |
+
|
| 129 |
+
This is the table most people will use: a symbol, a window, a sector. It is
|
| 130 |
+
the overlap of a ticker span from the security master and a SIC span from
|
| 131 |
+
here, both over the same filer.
|
| 132 |
+
|
| 133 |
+
Two decisions:
|
| 134 |
+
|
| 135 |
+
* **Every ticker gets a row**, including the ones with no code at all, marked
|
| 136 |
+
`unknown` and unclassified. A symbol missing from the table and a symbol the
|
| 137 |
+
SEC never classified look identical to a consumer, and only one of them is a
|
| 138 |
+
bug.
|
| 139 |
+
* **`is_current` marks exactly one row per live ticker** — the filer's symbol
|
| 140 |
+
now, under the newest code it has been seen under. The first version marked
|
| 141 |
+
the ticker span current, which brought a reclassified company back under
|
| 142 |
+
both its old sector and its new one, and `filter(is_current)` returned two
|
| 143 |
+
contradictory rows for the same symbol.
|
| 144 |
+
|
| 145 |
+
## Verification
|
| 146 |
+
|
| 147 |
+
[`quality.py`](recipe/quality.py) gates publication. Two checks earn their
|
| 148 |
+
place, and both are about the shape of the answer rather than its plumbing:
|
| 149 |
+
|
| 150 |
+
* **How much of the live universe is unclassified.** The SEC adds codes —
|
| 151 |
+
asset-backed securities and crypto assets both arrived after the 1987 manual
|
| 152 |
+
— and nothing else would notice that a new one fell into the catch-all.
|
| 153 |
+
* **How much of it sits in the largest sector.** The whole reason this exists
|
| 154 |
+
is that the SIC divisions are unusable, Manufacturing alone being a third of
|
| 155 |
+
the universe. A regression that collapsed the taxonomy back towards its
|
| 156 |
+
input would show up here and nowhere else. Measured largest sector is Health
|
| 157 |
+
Care at 16.5%; the ceiling is 30%.
|
| 158 |
+
|
| 159 |
+
The taxonomy is code, so it is tested like code: every rule has to name an
|
| 160 |
+
industry that exists, every industry a sector that exists, every four-digit
|
| 161 |
+
code has to land somewhere, and no narrow rule may sit after the range that
|
| 162 |
+
contains it — which would make it dead.
|
| 163 |
+
|
| 164 |
+
## What went wrong
|
| 165 |
+
|
| 166 |
+
**The per-filer crawl.** The first implementation asked
|
| 167 |
+
`data.sec.gov/submissions/CIK*.json` once per filer, at six requests a second,
|
| 168 |
+
well under SEC's published limit of ten. It ran at **a fifth of a request per
|
| 169 |
+
second**: SEC answers a few hundred and then throttles, and the client spends
|
| 170 |
+
its life in backoff. Eight hours for six thousand small files, and the process
|
| 171 |
+
burned eight seconds of CPU doing it.
|
| 172 |
+
|
| 173 |
+
SEC publishes a bulk archive of the same directory for exactly this reason. It
|
| 174 |
+
is 1.5 GB and one request, and it arrives in four minutes. The lesson is not
|
| 175 |
+
about rate limits — the rate was within the published limit — but that a
|
| 176 |
+
service offering a bulk file would rather you took it.
|
| 177 |
+
|
| 178 |
+
**The coverage metric that could not fail.** The first version measured ticker
|
| 179 |
+
coverage over the rows in `by_ticker`, which only contained tickers that had
|
| 180 |
+
resolved. It read 100% while a fifth of the universe was missing from the
|
| 181 |
+
table entirely. Making every ticker present, classified or not, turned the
|
| 182 |
+
metric into one that can go down.
|
| 183 |
+
|
| 184 |
+
## Schedule
|
| 185 |
+
|
| 186 |
+
A Hugging Face Job runs [`jobs/run.py`](jobs/run.py) weekly on Monday at 09:40
|
| 187 |
+
UTC: restore, lint, test, rebuild, verify, publish. Two hours after
|
| 188 |
+
`company-fundamentals` (07:10) and `security-master` (07:40), both of which it
|
| 189 |
+
reads — running before them would publish a classification a week behind its
|
| 190 |
+
own sources. Weekly rather than daily because a company's assigned code moves
|
| 191 |
+
on the scale of years.
|
| 192 |
+
|
| 193 |
+
## What is not done
|
| 194 |
+
|
| 195 |
+
* **No GICS, ICB or Fama-French.** Covered above. The `sic` column is there so
|
| 196 |
+
anyone with a licence can bring their own.
|
| 197 |
+
* **No sub-industry below the ~90 industries here.** SIC does not support it:
|
| 198 |
+
two fifths of EDGAR's codes are already roll-ups, so a finer taxonomy would
|
| 199 |
+
be inventing precision the input does not carry.
|
| 200 |
+
* **No revenue-based classification.** The right way to classify a
|
| 201 |
+
conglomerate is by segment revenue, which `company-fundamentals` publishes
|
| 202 |
+
as dimensional facts. Nothing here reads them yet.
|
| 203 |
+
* **No history before 2009 for anything but the ticker window.** XBRL headers
|
| 204 |
+
begin in 2009 Q2. A company's code in 1998 is in the SGML header of its
|
| 205 |
+
filings, four million of them, and that is a separate dataset's worth of
|
| 206 |
+
work.
|
| 207 |
+
* **No foreign classification.** The universe is SEC filers.
|
README.md
ADDED
|
@@ -0,0 +1,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
pretty_name: US Industry Classification — free sectors for SEC filers, with dates
|
| 6 |
+
size_categories:
|
| 7 |
+
- 100K<n<1M
|
| 8 |
+
task_categories:
|
| 9 |
+
- tabular-classification
|
| 10 |
+
tags:
|
| 11 |
+
- finance
|
| 12 |
+
- sector
|
| 13 |
+
- industry
|
| 14 |
+
- classification
|
| 15 |
+
- sic
|
| 16 |
+
- naics
|
| 17 |
+
- sec
|
| 18 |
+
- edgar
|
| 19 |
+
- point-in-time
|
| 20 |
+
- backtesting
|
| 21 |
+
- ziplime
|
| 22 |
+
configs:
|
| 23 |
+
- config_name: classification
|
| 24 |
+
data_files:
|
| 25 |
+
- split: train
|
| 26 |
+
path: "data/classification/*.parquet"
|
| 27 |
+
- config_name: by_ticker
|
| 28 |
+
data_files:
|
| 29 |
+
- split: train
|
| 30 |
+
path: "data/by_ticker/*.parquet"
|
| 31 |
+
- config_name: spans
|
| 32 |
+
data_files:
|
| 33 |
+
- split: train
|
| 34 |
+
path: "data/spans/*.parquet"
|
| 35 |
+
- config_name: observations
|
| 36 |
+
data_files:
|
| 37 |
+
- split: train
|
| 38 |
+
path: "data/observations/*.parquet"
|
| 39 |
+
- config_name: sic_codes
|
| 40 |
+
data_files:
|
| 41 |
+
- split: train
|
| 42 |
+
path: "data/sic_codes/*.parquet"
|
| 43 |
+
- config_name: naics_map
|
| 44 |
+
data_files:
|
| 45 |
+
- split: train
|
| 46 |
+
path: "data/naics_map/*.parquet"
|
| 47 |
+
- config_name: taxonomy
|
| 48 |
+
data_files:
|
| 49 |
+
- split: train
|
| 50 |
+
path: "data/taxonomy/*.parquet"
|
| 51 |
+
---
|
| 52 |
+
|
| 53 |
+
# US Industry Classification
|
| 54 |
+
|
| 55 |
+
What business a listed company is in — and what business it was in then.
|
| 56 |
+
|
| 57 |
+
**22 205 filers · 11 322 live tickers · 23 750 dated classification spans ·
|
| 58 |
+
435 269 statements · 15 sectors, 90 industries · 2009 to 2026**
|
| 59 |
+
|
| 60 |
+
Free to use, free to redistribute. Built entirely from US government works:
|
| 61 |
+
the SIC code the SEC assigns to every filer, and the Census Bureau's bridge to
|
| 62 |
+
NAICS. The rollup from those codes to sectors is ZipLime's own, published
|
| 63 |
+
under Apache-2.0 in [`recipe/taxonomy.py`](recipe/taxonomy.py).
|
| 64 |
+
|
| 65 |
+
The pipeline lives in [`recipe/`](recipe/) at the same revision as the data.
|
| 66 |
+
See [PIPELINE.md](PIPELINE.md) for the method and its limits.
|
| 67 |
+
|
| 68 |
+
## This is not GICS and not ICB
|
| 69 |
+
|
| 70 |
+
It cannot be. GICS belongs to MSCI and S&P Dow Jones Indices, ICB to FTSE
|
| 71 |
+
Russell, and neither can be redistributed — which is the whole reason this
|
| 72 |
+
exists. Nothing licensed from either was used or consulted.
|
| 73 |
+
|
| 74 |
+
So expect disagreements, and know where they are:
|
| 75 |
+
|
| 76 |
+
* **Alphabet and Meta are Technology here, Communication Services in GICS.**
|
| 77 |
+
The SEC files both under 7370, alongside systems integrators, and nothing in
|
| 78 |
+
a filing separates an advertising platform from a consultancy.
|
| 79 |
+
* **Disney is Consumer Cyclical here, Communication Services in GICS.** Its
|
| 80 |
+
assigned code is 7990, amusement and recreation. The code is the SEC's.
|
| 81 |
+
* **Blank cheque companies get a sector of their own.** GICS has no bucket for
|
| 82 |
+
one. 2 167 filers here have been one, and anyone building a universe wants
|
| 83 |
+
to drop them by name rather than find them scattered through Financials.
|
| 84 |
+
|
| 85 |
+
If you have a GICS or ICB licence, the `sic` column is here to join against.
|
| 86 |
+
|
| 87 |
+
## The point: it is dated
|
| 88 |
+
|
| 89 |
+
A company's industry is not a constant. **2 281 filers have been reclassified
|
| 90 |
+
at least once** — most often a blank cheque that became an operating company.
|
| 91 |
+
|
| 92 |
+
```python
|
| 93 |
+
import polars as pl
|
| 94 |
+
|
| 95 |
+
history = pl.read_parquet("data/by_ticker/*.parquet")
|
| 96 |
+
history.filter(pl.col("ticker") == "LCID").select(
|
| 97 |
+
"valid_from", "valid_to", "sic", "sector", "industry"
|
| 98 |
+
)
|
| 99 |
+
# 2021-07-27 … 2026-05-05 | 3711 | Consumer Cyclical | Automobiles
|
| 100 |
+
```
|
| 101 |
+
|
| 102 |
+
Churchill Capital IV was SIC 6770, a blank cheque, until it became Lucid. A
|
| 103 |
+
dataset that states only today's code calls it a car maker in 2020, and a
|
| 104 |
+
sector-neutral backtest then shorts the automotive basket against an empty
|
| 105 |
+
shell.
|
| 106 |
+
|
| 107 |
+
## Getting a sector for a ticker
|
| 108 |
+
|
| 109 |
+
```python
|
| 110 |
+
import polars as pl
|
| 111 |
+
|
| 112 |
+
live = (
|
| 113 |
+
pl.read_parquet("data/by_ticker/*.parquet")
|
| 114 |
+
.filter(pl.col("is_current"))
|
| 115 |
+
.select("ticker", "cik", "sector_code", "sector", "industry", "sic")
|
| 116 |
+
)
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
`is_current` marks exactly one row per live symbol: the filer's ticker now,
|
| 120 |
+
under the newest code it has been seen under. For a date in the past, filter
|
| 121 |
+
on the window instead:
|
| 122 |
+
|
| 123 |
+
```python
|
| 124 |
+
on = pl.date(2015, 6, 30)
|
| 125 |
+
history.filter((pl.col("valid_from") <= on) & (on <= pl.col("valid_to")))
|
| 126 |
+
```
|
| 127 |
+
|
| 128 |
+
Join on `cik` wherever you have it. It is stable, and it is the key the rest
|
| 129 |
+
of this dataset family uses.
|
| 130 |
+
|
| 131 |
+
## Configs
|
| 132 |
+
|
| 133 |
+
| Config | Rows | What one row is |
|
| 134 |
+
|---|---|---|
|
| 135 |
+
| `classification` | 22 205 | one filer: the sector it is in now, fully resolved |
|
| 136 |
+
| `by_ticker` | 30 729 | one ticker over one window, with the sector it was in then |
|
| 137 |
+
| `spans` | 23 750 | one run of filings that all stated the same SIC code |
|
| 138 |
+
| `observations` | 435 269 | one dated statement — the evidence the spans are built from |
|
| 139 |
+
| `sic_codes` | 444 | one EDGAR SIC code: hierarchy, sector, NAICS bridge, usage |
|
| 140 |
+
| `naics_map` | 1 854 | one 1987 SIC to 1997 NAICS pair from the Census concordance |
|
| 141 |
+
| `taxonomy` | 90 | one industry of the taxonomy and the SIC ranges it covers |
|
| 142 |
+
|
| 143 |
+
`observations` is published so that anyone who disagrees with how the spans
|
| 144 |
+
were cut can cut their own. It is the only honest way to ship a judgement.
|
| 145 |
+
|
| 146 |
+
## The taxonomy
|
| 147 |
+
|
| 148 |
+
Fifteen sectors. Thirteen are what you would expect; three exist because the
|
| 149 |
+
SEC's universe is not just operating companies.
|
| 150 |
+
|
| 151 |
+
| Sector | Live filers | Note |
|
| 152 |
+
|---|---|---|
|
| 153 |
+
| Health Care | 1 432 | includes Managed Health Care — Centene, Cigna, Elevance |
|
| 154 |
+
| Industrials | 1 145 | |
|
| 155 |
+
| Technology | 1 057 | includes Internet Software & Services |
|
| 156 |
+
| Financials | 1 045 | |
|
| 157 |
+
| Consumer Cyclical | 770 | |
|
| 158 |
+
| Funds & Trusts | 594 | closed-end funds, ETFs, securitisation vehicles |
|
| 159 |
+
| Materials | 506 | |
|
| 160 |
+
| Shell & Blank Check | 452 | SPACs and non-operating establishments |
|
| 161 |
+
| Unclassified | 403 | almost all depositary receipt programmes |
|
| 162 |
+
| Real Estate | 335 | |
|
| 163 |
+
| Energy | 274 | |
|
| 164 |
+
| Consumer Defensive | 267 | |
|
| 165 |
+
| Telecom & Media | 223 | |
|
| 166 |
+
| Utilities | 180 | |
|
| 167 |
+
| Government | — | foreign sovereigns and public administration |
|
| 168 |
+
|
| 169 |
+
**No sector holds more than 17% of the live universe**, which is the test the
|
| 170 |
+
SIC divisions fail: Division D, Manufacturing, is a third of it on its own.
|
| 171 |
+
|
| 172 |
+
Read the taxonomy without reading Python:
|
| 173 |
+
|
| 174 |
+
```python
|
| 175 |
+
pl.read_parquet("data/taxonomy/*.parquet").select(
|
| 176 |
+
"sector", "industry", "sic_ranges"
|
| 177 |
+
)
|
| 178 |
+
```
|
| 179 |
+
|
| 180 |
+
## Where it comes from
|
| 181 |
+
|
| 182 |
+
| Source | What it gives | Rows |
|
| 183 |
+
|---|---|---|
|
| 184 |
+
| XBRL filing headers, via [ZipLime/company-fundamentals](https://huggingface.co/datasets/ZipLime/company-fundamentals) | the code the SEC had a filer under, on the day it filed — the only free source of SIC **history** | 431 290 |
|
| 185 |
+
| EDGAR's submissions archive | today's code for filers that never filed XBRL: delisted before 2009, funds, foreign issuers on paper | 3 979 |
|
| 186 |
+
| EDGAR's submissions archive, read for forms | what kind of entity a filer with no code is — N-CSR means a registered investment company, F-6 a depositary receipt programme | 1 455 |
|
| 187 |
+
| Ticker windows, via [ZipLime/security-master](https://huggingface.co/datasets/ZipLime/security-master) | which symbol belonged to which filer, when | 29 511 |
|
| 188 |
+
| SEC's published SIC code list | the title of each code and the office that reviews it | 444 |
|
| 189 |
+
| Census Bureau 1987 SIC → 1997 NAICS concordance | the NAICS bridge, and the 1987 hierarchy's own titles | 1 854 |
|
| 190 |
+
|
| 191 |
+
## Coverage and honest gaps
|
| 192 |
+
|
| 193 |
+
* **97.3% of live tickers get an answer.** The remainder are dormant filers
|
| 194 |
+
EDGAR has never classified and whose forms say nothing either.
|
| 195 |
+
* **Nothing before 2009.** XBRL headers begin in 2009 Q2. A company's code in
|
| 196 |
+
1998 is in the SGML header of its filings and is not read here.
|
| 197 |
+
* **`date_basis` tells you what the dates are worth.** `dated` (15 266 rows)
|
| 198 |
+
means a filing stated the code inside that window. `undated` (13 015) means
|
| 199 |
+
a code is known for the filer but nothing dates it to that window, so the
|
| 200 |
+
latest one is applied across it. `unknown` (2 448) means no code at all.
|
| 201 |
+
* **Two fifths of EDGAR's codes are roll-ups.** `2000` means all of food,
|
| 202 |
+
`3570` all of computer and office equipment. `sic_level` says which you
|
| 203 |
+
have: 284 of the 444 are real four-digit industries, 118 are three-digit
|
| 204 |
+
groups, 42 are two-digit major groups.
|
| 205 |
+
* **The NAICS bridge is weak and labelled as such.** Only 32.7% of codes
|
| 206 |
+
resolve to exactly one 1997 NAICS industry and 71.9% to one NAICS sector.
|
| 207 |
+
`naics_1997` and `naics_sector` are filled only where the answer is unique;
|
| 208 |
+
`naics_candidates` says how many there were. The full crosswalk is in
|
| 209 |
+
`naics_map`.
|
| 210 |
+
* **8731 mixes contract research with research-stage biotech.** Charles River
|
| 211 |
+
and Incyte share a code, and nothing in a filing separates them.
|
| 212 |
+
* **52 symbols are current for two filers, 30 of them in different sectors.**
|
| 213 |
+
Genuine ticker transfers and reuse — Barnes Group handed `B` to Barrick.
|
| 214 |
+
Each row is right for its own filer; deciding who owns a symbol today is
|
| 215 |
+
[security-master](https://huggingface.co/datasets/ZipLime/security-master)'s
|
| 216 |
+
job.
|
| 217 |
+
* **The classification is the SEC's opinion, not the company's.** Assigned
|
| 218 |
+
codes go stale; the SEC does not re-review them on a schedule.
|
| 219 |
+
|
| 220 |
+
## Provenance and updates
|
| 221 |
+
|
| 222 |
+
Sources: SEC EDGAR (filing headers via the sibling dataset, and the
|
| 223 |
+
submissions archive), the SEC's SIC code list, and the US Census Bureau's
|
| 224 |
+
SIC-to-NAICS concordance — all US Government works in the public domain. The
|
| 225 |
+
sector taxonomy is ZipLime's own work under Apache-2.0. See [NOTICE](NOTICE).
|
| 226 |
+
|
| 227 |
+
Rebuilt weekly, Monday 09:40 UTC, by a Hugging Face Job
|
| 228 |
+
([`jobs/run.py`](jobs/run.py)) that lints, tests, rebuilds, verifies and only
|
| 229 |
+
then publishes.
|
data/by_ticker/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:831cbc7123530308eb4de065ebdf0c8e2ce18b4ac67be041f51368f71db334aa
|
| 3 |
+
size 727024
|
data/classification/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:724491615796030c045ab30a070eb5dd9519564c17b060d25724fe905ecebe09
|
| 3 |
+
size 830399
|
data/naics_map/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:73683e3d179237e97f3dd0553dac85c261106ab8d5e0e81d020da12ea2851ef0
|
| 3 |
+
size 67201
|
data/observations/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4d08effad90c3f6de818a6c1dda5b9fc96e97eaf2fc0fd57da0eb28425f03706
|
| 3 |
+
size 6255799
|
data/sic_codes/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:950199b74a4376da1f722fb692f9f8254b0562cb9585948df970b9d44cfb8af4
|
| 3 |
+
size 29383
|
data/spans/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b8276701bffbdc4a806a6a719788f2cfcbb28de837d912ffad8fb0cbbe26e0a6
|
| 3 |
+
size 270249
|
data/taxonomy/part-00000.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ace4f48cf120b06ec15cca0987f163f2258e78af624f3c53878b27eff46f730a
|
| 3 |
+
size 6420
|
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 |
+
# "fastexcel>=0.12,<1",
|
| 8 |
+
# "huggingface-hub>=1.19,<2",
|
| 9 |
+
# "pytest>=8,<10",
|
| 10 |
+
# "pytest-asyncio>=0.24,<2",
|
| 11 |
+
# "ruff==0.16.5",
|
| 12 |
+
# "pyyaml>=6,<7",
|
| 13 |
+
# ]
|
| 14 |
+
# ///
|
| 15 |
+
"""Hugging Face Jobs entry point for the ZipLime industry-classification dataset.
|
| 16 |
+
|
| 17 |
+
restore repository -> lint -> tests -> build -> verify -> publish
|
| 18 |
+
|
| 19 |
+
The build reads two sibling datasets from the Hub rather than from a working
|
| 20 |
+
copy. That is the point: what this dataset says about a company has to be
|
| 21 |
+
derivable from what the others published, at a revision anyone can fetch.
|
| 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/industry-classification"
|
| 33 |
+
DEFAULT_WORKSPACE = "/tmp/industry-classification"
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def log(message: str) -> None:
|
| 37 |
+
print(f"[industry-classification] {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("--submission-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.submission_limit:
|
| 93 |
+
build += ["--submission-limit", str(args.submission_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,554 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"config_rows": {
|
| 3 |
+
"by_ticker": 30729,
|
| 4 |
+
"classification": 22205,
|
| 5 |
+
"naics_map": 1854,
|
| 6 |
+
"observations": 435269,
|
| 7 |
+
"sic_codes": 444,
|
| 8 |
+
"spans": 23750,
|
| 9 |
+
"taxonomy": 90
|
| 10 |
+
},
|
| 11 |
+
"config_schemas": {
|
| 12 |
+
"by_ticker": {
|
| 13 |
+
"cik": "String",
|
| 14 |
+
"date_basis": "String",
|
| 15 |
+
"exchange": "String",
|
| 16 |
+
"industry": "String",
|
| 17 |
+
"industry_code": "String",
|
| 18 |
+
"inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 19 |
+
"is_current": "Boolean",
|
| 20 |
+
"name": "String",
|
| 21 |
+
"sector": "String",
|
| 22 |
+
"sector_code": "String",
|
| 23 |
+
"sic": "String",
|
| 24 |
+
"ticker": "String",
|
| 25 |
+
"valid_from": "Date",
|
| 26 |
+
"valid_to": "Date"
|
| 27 |
+
},
|
| 28 |
+
"classification": {
|
| 29 |
+
"all_tickers": "String",
|
| 30 |
+
"cik": "String",
|
| 31 |
+
"division": "String",
|
| 32 |
+
"division_title": "String",
|
| 33 |
+
"exchange": "String",
|
| 34 |
+
"first_seen": "Date",
|
| 35 |
+
"industry": "String",
|
| 36 |
+
"industry_code": "String",
|
| 37 |
+
"industry_group": "String",
|
| 38 |
+
"inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 39 |
+
"is_active": "Boolean",
|
| 40 |
+
"is_dated": "Boolean",
|
| 41 |
+
"major_group": "String",
|
| 42 |
+
"major_group_title": "String",
|
| 43 |
+
"naics_1997": "String",
|
| 44 |
+
"naics_candidates": "Int32",
|
| 45 |
+
"naics_sector": "String",
|
| 46 |
+
"naics_sector_title": "String",
|
| 47 |
+
"naics_title": "String",
|
| 48 |
+
"name": "String",
|
| 49 |
+
"observations": "Int32",
|
| 50 |
+
"primary_ticker": "String",
|
| 51 |
+
"sec_office": "String",
|
| 52 |
+
"sector": "String",
|
| 53 |
+
"sector_code": "String",
|
| 54 |
+
"sic": "String",
|
| 55 |
+
"sic_level": "String",
|
| 56 |
+
"sic_title": "String",
|
| 57 |
+
"source": "String",
|
| 58 |
+
"stated_on": "Date",
|
| 59 |
+
"taxonomy_version": "String"
|
| 60 |
+
},
|
| 61 |
+
"naics_map": {
|
| 62 |
+
"inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 63 |
+
"is_part": "Boolean",
|
| 64 |
+
"naics_1997": "String",
|
| 65 |
+
"naics_sector": "String",
|
| 66 |
+
"naics_sector_title": "String",
|
| 67 |
+
"naics_title": "String",
|
| 68 |
+
"part_description": "String",
|
| 69 |
+
"sic": "String",
|
| 70 |
+
"sic_title": "String"
|
| 71 |
+
},
|
| 72 |
+
"observations": {
|
| 73 |
+
"cik": "String",
|
| 74 |
+
"inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 75 |
+
"is_dated": "Boolean",
|
| 76 |
+
"knowledge_time": "Datetime(time_unit='us', time_zone='UTC')",
|
| 77 |
+
"sic": "String",
|
| 78 |
+
"source": "String",
|
| 79 |
+
"source_ref": "String",
|
| 80 |
+
"stated_on": "Date"
|
| 81 |
+
},
|
| 82 |
+
"sic_codes": {
|
| 83 |
+
"division": "String",
|
| 84 |
+
"division_title": "String",
|
| 85 |
+
"filers": "Int32",
|
| 86 |
+
"filings": "Int32",
|
| 87 |
+
"in_sic_1987": "Boolean",
|
| 88 |
+
"industry": "String",
|
| 89 |
+
"industry_code": "String",
|
| 90 |
+
"industry_group": "String",
|
| 91 |
+
"inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 92 |
+
"major_group": "String",
|
| 93 |
+
"major_group_title": "String",
|
| 94 |
+
"naics_1997": "String",
|
| 95 |
+
"naics_candidates": "Int32",
|
| 96 |
+
"naics_sector": "String",
|
| 97 |
+
"naics_sector_title": "String",
|
| 98 |
+
"naics_title": "String",
|
| 99 |
+
"sec_office": "String",
|
| 100 |
+
"sector": "String",
|
| 101 |
+
"sector_code": "String",
|
| 102 |
+
"sic": "String",
|
| 103 |
+
"sic_level": "String",
|
| 104 |
+
"title": "String"
|
| 105 |
+
},
|
| 106 |
+
"spans": {
|
| 107 |
+
"cik": "String",
|
| 108 |
+
"industry": "String",
|
| 109 |
+
"industry_code": "String",
|
| 110 |
+
"inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 111 |
+
"is_latest": "Boolean",
|
| 112 |
+
"observations": "Int32",
|
| 113 |
+
"rank_for_filer": "Int32",
|
| 114 |
+
"sector": "String",
|
| 115 |
+
"sector_code": "String",
|
| 116 |
+
"sic": "String",
|
| 117 |
+
"sources": "String",
|
| 118 |
+
"valid_from": "Date",
|
| 119 |
+
"valid_to": "Date"
|
| 120 |
+
},
|
| 121 |
+
"taxonomy": {
|
| 122 |
+
"edgar_codes": "Int32",
|
| 123 |
+
"industry": "String",
|
| 124 |
+
"industry_code": "String",
|
| 125 |
+
"inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
|
| 126 |
+
"sector": "String",
|
| 127 |
+
"sector_code": "String",
|
| 128 |
+
"sic_ranges": "String",
|
| 129 |
+
"taxonomy_version": "String"
|
| 130 |
+
}
|
| 131 |
+
},
|
| 132 |
+
"configs": {
|
| 133 |
+
"by_ticker": {
|
| 134 |
+
"grain": "one ticker over one window, with the sector it was in then",
|
| 135 |
+
"path": "data/by_ticker/**/*.parquet"
|
| 136 |
+
},
|
| 137 |
+
"classification": {
|
| 138 |
+
"grain": "one SEC filer, with the sector and industry it is in now",
|
| 139 |
+
"path": "data/classification/**/*.parquet"
|
| 140 |
+
},
|
| 141 |
+
"naics_map": {
|
| 142 |
+
"grain": "one 1987 SIC to 1997 NAICS pair from the Census concordance",
|
| 143 |
+
"path": "data/naics_map/**/*.parquet"
|
| 144 |
+
},
|
| 145 |
+
"observations": {
|
| 146 |
+
"grain": "one dated statement that a filer was assigned a SIC code",
|
| 147 |
+
"path": "data/observations/**/*.parquet"
|
| 148 |
+
},
|
| 149 |
+
"sic_codes": {
|
| 150 |
+
"grain": "one EDGAR SIC code, with its hierarchy, sector and NAICS bridge",
|
| 151 |
+
"path": "data/sic_codes/**/*.parquet"
|
| 152 |
+
},
|
| 153 |
+
"spans": {
|
| 154 |
+
"grain": "one run of filings that all stated the same SIC code",
|
| 155 |
+
"path": "data/spans/**/*.parquet"
|
| 156 |
+
},
|
| 157 |
+
"taxonomy": {
|
| 158 |
+
"grain": "one industry of the ZipLime taxonomy and the SIC ranges it covers",
|
| 159 |
+
"path": "data/taxonomy/**/*.parquet"
|
| 160 |
+
}
|
| 161 |
+
},
|
| 162 |
+
"coverage": {
|
| 163 |
+
"max_statement": "2026-10-13",
|
| 164 |
+
"min_statement": "2009-04-15"
|
| 165 |
+
},
|
| 166 |
+
"generated_at": "2026-10-13T19:43:19.146667+00:00",
|
| 167 |
+
"industries": {
|
| 168 |
+
"CONC_AUTO": {
|
| 169 |
+
"sector": "CONC",
|
| 170 |
+
"title": "Automobiles"
|
| 171 |
+
},
|
| 172 |
+
"CONC_AUTOPART": {
|
| 173 |
+
"sector": "CONC",
|
| 174 |
+
"title": "Automobile Components"
|
| 175 |
+
},
|
| 176 |
+
"CONC_BROADLINE": {
|
| 177 |
+
"sector": "CONC",
|
| 178 |
+
"title": "Broadline Retail"
|
| 179 |
+
},
|
| 180 |
+
"CONC_CONSSVC": {
|
| 181 |
+
"sector": "CONC",
|
| 182 |
+
"title": "Consumer Services"
|
| 183 |
+
},
|
| 184 |
+
"CONC_DURABLES": {
|
| 185 |
+
"sector": "CONC",
|
| 186 |
+
"title": "Household Durables"
|
| 187 |
+
},
|
| 188 |
+
"CONC_ECOMM": {
|
| 189 |
+
"sector": "CONC",
|
| 190 |
+
"title": "Direct & Online Retail"
|
| 191 |
+
},
|
| 192 |
+
"CONC_EDUCATION": {
|
| 193 |
+
"sector": "CONC",
|
| 194 |
+
"title": "Education Services"
|
| 195 |
+
},
|
| 196 |
+
"CONC_HOMEBLD": {
|
| 197 |
+
"sector": "CONC",
|
| 198 |
+
"title": "Homebuilding"
|
| 199 |
+
},
|
| 200 |
+
"CONC_HOTEL": {
|
| 201 |
+
"sector": "CONC",
|
| 202 |
+
"title": "Hotels, Gaming & Leisure Facilities"
|
| 203 |
+
},
|
| 204 |
+
"CONC_LEISURE": {
|
| 205 |
+
"sector": "CONC",
|
| 206 |
+
"title": "Leisure Products"
|
| 207 |
+
},
|
| 208 |
+
"CONC_RESTAURANT": {
|
| 209 |
+
"sector": "CONC",
|
| 210 |
+
"title": "Restaurants"
|
| 211 |
+
},
|
| 212 |
+
"CONC_RETAIL": {
|
| 213 |
+
"sector": "CONC",
|
| 214 |
+
"title": "Specialty Retail"
|
| 215 |
+
},
|
| 216 |
+
"CONC_TEXTILE": {
|
| 217 |
+
"sector": "CONC",
|
| 218 |
+
"title": "Textiles, Apparel & Luxury Goods"
|
| 219 |
+
},
|
| 220 |
+
"COND_AGRI": {
|
| 221 |
+
"sector": "COND",
|
| 222 |
+
"title": "Agricultural Products"
|
| 223 |
+
},
|
| 224 |
+
"COND_BEV": {
|
| 225 |
+
"sector": "COND",
|
| 226 |
+
"title": "Beverages"
|
| 227 |
+
},
|
| 228 |
+
"COND_FOOD": {
|
| 229 |
+
"sector": "COND",
|
| 230 |
+
"title": "Food Products"
|
| 231 |
+
},
|
| 232 |
+
"COND_FOODDIST": {
|
| 233 |
+
"sector": "COND",
|
| 234 |
+
"title": "Food & Beverage Distribution"
|
| 235 |
+
},
|
| 236 |
+
"COND_FOODRETAIL": {
|
| 237 |
+
"sector": "COND",
|
| 238 |
+
"title": "Food & Drug Retail"
|
| 239 |
+
},
|
| 240 |
+
"COND_HOUSEHOLD": {
|
| 241 |
+
"sector": "COND",
|
| 242 |
+
"title": "Household & Personal Products"
|
| 243 |
+
},
|
| 244 |
+
"COND_TOBACCO": {
|
| 245 |
+
"sector": "COND",
|
| 246 |
+
"title": "Tobacco"
|
| 247 |
+
},
|
| 248 |
+
"ENER_COAL": {
|
| 249 |
+
"sector": "ENER",
|
| 250 |
+
"title": "Coal & Consumable Fuels"
|
| 251 |
+
},
|
| 252 |
+
"ENER_EP": {
|
| 253 |
+
"sector": "ENER",
|
| 254 |
+
"title": "Oil & Gas Exploration & Production"
|
| 255 |
+
},
|
| 256 |
+
"ENER_MIDSTREAM": {
|
| 257 |
+
"sector": "ENER",
|
| 258 |
+
"title": "Oil & Gas Storage & Transportation"
|
| 259 |
+
},
|
| 260 |
+
"ENER_REFINE": {
|
| 261 |
+
"sector": "ENER",
|
| 262 |
+
"title": "Oil & Gas Refining & Marketing"
|
| 263 |
+
},
|
| 264 |
+
"ENER_SERVICES": {
|
| 265 |
+
"sector": "ENER",
|
| 266 |
+
"title": "Oil & Gas Equipment & Services"
|
| 267 |
+
},
|
| 268 |
+
"FINS_BANK": {
|
| 269 |
+
"sector": "FINS",
|
| 270 |
+
"title": "Banks"
|
| 271 |
+
},
|
| 272 |
+
"FINS_CAPMKT": {
|
| 273 |
+
"sector": "FINS",
|
| 274 |
+
"title": "Capital Markets"
|
| 275 |
+
},
|
| 276 |
+
"FINS_CONSFIN": {
|
| 277 |
+
"sector": "FINS",
|
| 278 |
+
"title": "Consumer Finance"
|
| 279 |
+
},
|
| 280 |
+
"FINS_DIVFIN": {
|
| 281 |
+
"sector": "FINS",
|
| 282 |
+
"title": "Diversified Financial Services"
|
| 283 |
+
},
|
| 284 |
+
"FINS_INSURANCE": {
|
| 285 |
+
"sector": "FINS",
|
| 286 |
+
"title": "Insurance"
|
| 287 |
+
},
|
| 288 |
+
"FINS_MORTGAGE": {
|
| 289 |
+
"sector": "FINS",
|
| 290 |
+
"title": "Mortgage Finance"
|
| 291 |
+
},
|
| 292 |
+
"FINS_THRIFT": {
|
| 293 |
+
"sector": "FINS",
|
| 294 |
+
"title": "Thrifts & Savings Institutions"
|
| 295 |
+
},
|
| 296 |
+
"FUND_ABS": {
|
| 297 |
+
"sector": "FUND",
|
| 298 |
+
"title": "Asset-Backed Securities"
|
| 299 |
+
},
|
| 300 |
+
"FUND_INVEST": {
|
| 301 |
+
"sector": "FUND",
|
| 302 |
+
"title": "Investment Companies & Funds"
|
| 303 |
+
},
|
| 304 |
+
"FUND_TRUST": {
|
| 305 |
+
"sector": "FUND",
|
| 306 |
+
"title": "Trusts"
|
| 307 |
+
},
|
| 308 |
+
"GOVT_PUBLIC": {
|
| 309 |
+
"sector": "GOVT",
|
| 310 |
+
"title": "Public Administration"
|
| 311 |
+
},
|
| 312 |
+
"GOVT_SOVEREIGN": {
|
| 313 |
+
"sector": "GOVT",
|
| 314 |
+
"title": "Sovereign & Supranational"
|
| 315 |
+
},
|
| 316 |
+
"HLTH_BIOTECH": {
|
| 317 |
+
"sector": "HLTH",
|
| 318 |
+
"title": "Biotechnology"
|
| 319 |
+
},
|
| 320 |
+
"HLTH_DEVICE": {
|
| 321 |
+
"sector": "HLTH",
|
| 322 |
+
"title": "Health Care Equipment & Supplies"
|
| 323 |
+
},
|
| 324 |
+
"HLTH_DIST": {
|
| 325 |
+
"sector": "HLTH",
|
| 326 |
+
"title": "Health Care Distributors"
|
| 327 |
+
},
|
| 328 |
+
"HLTH_MANAGED": {
|
| 329 |
+
"sector": "HLTH",
|
| 330 |
+
"title": "Managed Health Care"
|
| 331 |
+
},
|
| 332 |
+
"HLTH_PHARMA": {
|
| 333 |
+
"sector": "HLTH",
|
| 334 |
+
"title": "Pharmaceuticals"
|
| 335 |
+
},
|
| 336 |
+
"HLTH_PROVIDER": {
|
| 337 |
+
"sector": "HLTH",
|
| 338 |
+
"title": "Health Care Providers & Services"
|
| 339 |
+
},
|
| 340 |
+
"HLTH_TOOLS": {
|
| 341 |
+
"sector": "HLTH",
|
| 342 |
+
"title": "Life Sciences Tools & Diagnostics"
|
| 343 |
+
},
|
| 344 |
+
"INDU_AERO": {
|
| 345 |
+
"sector": "INDU",
|
| 346 |
+
"title": "Aerospace & Defence"
|
| 347 |
+
},
|
| 348 |
+
"INDU_AIRLINE": {
|
| 349 |
+
"sector": "INDU",
|
| 350 |
+
"title": "Passenger Airlines"
|
| 351 |
+
},
|
| 352 |
+
"INDU_BLDGPROD": {
|
| 353 |
+
"sector": "INDU",
|
| 354 |
+
"title": "Building Products"
|
| 355 |
+
},
|
| 356 |
+
"INDU_COMMSVC": {
|
| 357 |
+
"sector": "INDU",
|
| 358 |
+
"title": "Commercial Services & Supplies"
|
| 359 |
+
},
|
| 360 |
+
"INDU_CONSTR": {
|
| 361 |
+
"sector": "INDU",
|
| 362 |
+
"title": "Construction & Engineering"
|
| 363 |
+
},
|
| 364 |
+
"INDU_DISTRIB": {
|
| 365 |
+
"sector": "INDU",
|
| 366 |
+
"title": "Trading Companies & Distributors"
|
| 367 |
+
},
|
| 368 |
+
"INDU_ELECEQ": {
|
| 369 |
+
"sector": "INDU",
|
| 370 |
+
"title": "Electrical Equipment"
|
| 371 |
+
},
|
| 372 |
+
"INDU_GROUND": {
|
| 373 |
+
"sector": "INDU",
|
| 374 |
+
"title": "Ground Transportation"
|
| 375 |
+
},
|
| 376 |
+
"INDU_LOGISTICS": {
|
| 377 |
+
"sector": "INDU",
|
| 378 |
+
"title": "Air Freight & Logistics"
|
| 379 |
+
},
|
| 380 |
+
"INDU_MACH": {
|
| 381 |
+
"sector": "INDU",
|
| 382 |
+
"title": "Machinery"
|
| 383 |
+
},
|
| 384 |
+
"INDU_MARINE": {
|
| 385 |
+
"sector": "INDU",
|
| 386 |
+
"title": "Marine Transportation"
|
| 387 |
+
},
|
| 388 |
+
"INDU_MISC": {
|
| 389 |
+
"sector": "INDU",
|
| 390 |
+
"title": "Diversified Industrial Products"
|
| 391 |
+
},
|
| 392 |
+
"INDU_PROFSVC": {
|
| 393 |
+
"sector": "INDU",
|
| 394 |
+
"title": "Professional Services"
|
| 395 |
+
},
|
| 396 |
+
"INDU_RAIL": {
|
| 397 |
+
"sector": "INDU",
|
| 398 |
+
"title": "Rail Transportation"
|
| 399 |
+
},
|
| 400 |
+
"INDU_WASTE": {
|
| 401 |
+
"sector": "INDU",
|
| 402 |
+
"title": "Waste Management"
|
| 403 |
+
},
|
| 404 |
+
"MATR_AGCHEM": {
|
| 405 |
+
"sector": "MATR",
|
| 406 |
+
"title": "Fertilizers & Agricultural Chemicals"
|
| 407 |
+
},
|
| 408 |
+
"MATR_BLDGMAT": {
|
| 409 |
+
"sector": "MATR",
|
| 410 |
+
"title": "Construction Materials"
|
| 411 |
+
},
|
| 412 |
+
"MATR_CHEM": {
|
| 413 |
+
"sector": "MATR",
|
| 414 |
+
"title": "Chemicals"
|
| 415 |
+
},
|
| 416 |
+
"MATR_CONTAIN": {
|
| 417 |
+
"sector": "MATR",
|
| 418 |
+
"title": "Containers & Packaging"
|
| 419 |
+
},
|
| 420 |
+
"MATR_FOREST": {
|
| 421 |
+
"sector": "MATR",
|
| 422 |
+
"title": "Paper & Forest Products"
|
| 423 |
+
},
|
| 424 |
+
"MATR_METALMIN": {
|
| 425 |
+
"sector": "MATR",
|
| 426 |
+
"title": "Metals & Mining"
|
| 427 |
+
},
|
| 428 |
+
"MATR_NONFERROUS": {
|
| 429 |
+
"sector": "MATR",
|
| 430 |
+
"title": "Aluminium & Nonferrous Metals"
|
| 431 |
+
},
|
| 432 |
+
"MATR_PRECIOUS": {
|
| 433 |
+
"sector": "MATR",
|
| 434 |
+
"title": "Gold & Precious Metals"
|
| 435 |
+
},
|
| 436 |
+
"MATR_RUBBER": {
|
| 437 |
+
"sector": "MATR",
|
| 438 |
+
"title": "Rubber & Plastic Products"
|
| 439 |
+
},
|
| 440 |
+
"MATR_STEEL": {
|
| 441 |
+
"sector": "MATR",
|
| 442 |
+
"title": "Steel"
|
| 443 |
+
},
|
| 444 |
+
"REAL_MGMT": {
|
| 445 |
+
"sector": "REAL",
|
| 446 |
+
"title": "Real Estate Management & Development"
|
| 447 |
+
},
|
| 448 |
+
"REAL_REIT": {
|
| 449 |
+
"sector": "REAL",
|
| 450 |
+
"title": "Real Estate Investment Trusts"
|
| 451 |
+
},
|
| 452 |
+
"SHEL_BLANK": {
|
| 453 |
+
"sector": "SHEL",
|
| 454 |
+
"title": "Blank Check & Shell Companies"
|
| 455 |
+
},
|
| 456 |
+
"SHEL_NONOP": {
|
| 457 |
+
"sector": "SHEL",
|
| 458 |
+
"title": "Non-Operating Establishments"
|
| 459 |
+
},
|
| 460 |
+
"TECH_COMMEQ": {
|
| 461 |
+
"sector": "TECH",
|
| 462 |
+
"title": "Communications Equipment"
|
| 463 |
+
},
|
| 464 |
+
"TECH_ELECTRONIC": {
|
| 465 |
+
"sector": "TECH",
|
| 466 |
+
"title": "Electronic Equipment & Components"
|
| 467 |
+
},
|
| 468 |
+
"TECH_HARDWARE": {
|
| 469 |
+
"sector": "TECH",
|
| 470 |
+
"title": "Technology Hardware & Equipment"
|
| 471 |
+
},
|
| 472 |
+
"TECH_INTERNET": {
|
| 473 |
+
"sector": "TECH",
|
| 474 |
+
"title": "Internet Software & Services"
|
| 475 |
+
},
|
| 476 |
+
"TECH_ITSVC": {
|
| 477 |
+
"sector": "TECH",
|
| 478 |
+
"title": "IT Services"
|
| 479 |
+
},
|
| 480 |
+
"TECH_SEMI": {
|
| 481 |
+
"sector": "TECH",
|
| 482 |
+
"title": "Semiconductors & Semiconductor Equipment"
|
| 483 |
+
},
|
| 484 |
+
"TECH_SOFTWARE": {
|
| 485 |
+
"sector": "TECH",
|
| 486 |
+
"title": "Software"
|
| 487 |
+
},
|
| 488 |
+
"TLCM_ADVERT": {
|
| 489 |
+
"sector": "TLCM",
|
| 490 |
+
"title": "Advertising & Marketing"
|
| 491 |
+
},
|
| 492 |
+
"TLCM_MEDIA": {
|
| 493 |
+
"sector": "TLCM",
|
| 494 |
+
"title": "Media & Entertainment"
|
| 495 |
+
},
|
| 496 |
+
"TLCM_PUBLISH": {
|
| 497 |
+
"sector": "TLCM",
|
| 498 |
+
"title": "Publishing"
|
| 499 |
+
},
|
| 500 |
+
"TLCM_TELECOM": {
|
| 501 |
+
"sector": "TLCM",
|
| 502 |
+
"title": "Telecommunication Services"
|
| 503 |
+
},
|
| 504 |
+
"UNCL_ADR": {
|
| 505 |
+
"sector": "UNCL",
|
| 506 |
+
"title": "Depositary Receipts"
|
| 507 |
+
},
|
| 508 |
+
"UNCL_OTHER": {
|
| 509 |
+
"sector": "UNCL",
|
| 510 |
+
"title": "Unclassified"
|
| 511 |
+
},
|
| 512 |
+
"UTIL_ELEC": {
|
| 513 |
+
"sector": "UTIL",
|
| 514 |
+
"title": "Electric Utilities"
|
| 515 |
+
},
|
| 516 |
+
"UTIL_GAS": {
|
| 517 |
+
"sector": "UTIL",
|
| 518 |
+
"title": "Gas Utilities"
|
| 519 |
+
},
|
| 520 |
+
"UTIL_MULTI": {
|
| 521 |
+
"sector": "UTIL",
|
| 522 |
+
"title": "Multi-Utilities"
|
| 523 |
+
},
|
| 524 |
+
"UTIL_WATER": {
|
| 525 |
+
"sector": "UTIL",
|
| 526 |
+
"title": "Water Utilities"
|
| 527 |
+
}
|
| 528 |
+
},
|
| 529 |
+
"quality_ok": true,
|
| 530 |
+
"rows": 22205,
|
| 531 |
+
"sectors": {
|
| 532 |
+
"CONC": "Consumer Cyclical",
|
| 533 |
+
"COND": "Consumer Defensive",
|
| 534 |
+
"ENER": "Energy",
|
| 535 |
+
"FINS": "Financials",
|
| 536 |
+
"FUND": "Funds & Trusts",
|
| 537 |
+
"GOVT": "Government",
|
| 538 |
+
"HLTH": "Health Care",
|
| 539 |
+
"INDU": "Industrials",
|
| 540 |
+
"MATR": "Materials",
|
| 541 |
+
"REAL": "Real Estate",
|
| 542 |
+
"SHEL": "Shell & Blank Check",
|
| 543 |
+
"TECH": "Technology",
|
| 544 |
+
"TLCM": "Telecom & Media",
|
| 545 |
+
"UNCL": "Unclassified",
|
| 546 |
+
"UTIL": "Utilities"
|
| 547 |
+
},
|
| 548 |
+
"source": {
|
| 549 |
+
"build_version": "1.0.0",
|
| 550 |
+
"package_version": "1.0.0",
|
| 551 |
+
"recipe_hash": "sha256:675e969a373cd6ec1fad32888bf6c51ecc4c536cd8164ec4106c5cec24cd989a",
|
| 552 |
+
"taxonomy_version": "1.0.0"
|
| 553 |
+
}
|
| 554 |
+
}
|
pyproject.toml
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[build-system]
|
| 2 |
+
requires = ["setuptools>=75", "wheel"]
|
| 3 |
+
build-backend = "setuptools.build_meta"
|
| 4 |
+
|
| 5 |
+
[project]
|
| 6 |
+
name = "ziplime-industry-classification"
|
| 7 |
+
version = "1.0.0"
|
| 8 |
+
description = "Free, point-in-time sector and industry classification for US SEC filers"
|
| 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 |
+
# Reads the Census concordance, which is a 2008-vintage .xls that only a
|
| 18 |
+
# BIFF-capable reader opens. polars delegates to it for read_excel.
|
| 19 |
+
"fastexcel>=0.12,<1",
|
| 20 |
+
]
|
| 21 |
+
|
| 22 |
+
[project.optional-dependencies]
|
| 23 |
+
dev = [
|
| 24 |
+
"pytest>=8,<10",
|
| 25 |
+
"pytest-asyncio>=0.24,<2",
|
| 26 |
+
# Pinned exactly, not to a range: ruff gates publication, and a new minor
|
| 27 |
+
# release adding a rule would fail the scheduled job on code that was clean
|
| 28 |
+
# when it was written.
|
| 29 |
+
"ruff==0.16.5",
|
| 30 |
+
]
|
| 31 |
+
publish = ["huggingface-hub>=1.19,<2"]
|
| 32 |
+
|
| 33 |
+
[project.scripts]
|
| 34 |
+
ziplime-industry-classification = "recipe.cli:main"
|
| 35 |
+
|
| 36 |
+
[tool.setuptools.packages.find]
|
| 37 |
+
include = ["recipe*"]
|
| 38 |
+
|
| 39 |
+
[tool.pytest.ini_options]
|
| 40 |
+
addopts = "-ra"
|
| 41 |
+
testpaths = ["tests"]
|
| 42 |
+
asyncio_mode = "auto"
|
| 43 |
+
|
| 44 |
+
[tool.ruff]
|
| 45 |
+
target-version = "py311"
|
| 46 |
+
line-length = 100
|
| 47 |
+
extend-exclude = ["data", ".cache"]
|
| 48 |
+
|
| 49 |
+
[tool.ruff.lint]
|
| 50 |
+
select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
|
| 51 |
+
ignore = ["E501"]
|
recipe/__init__.py
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""US industry classification: what business a listed company is in, on a date."""
|
| 2 |
+
|
| 3 |
+
__version__ = "1.0.0"
|
recipe/build.py
ADDED
|
@@ -0,0 +1,484 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Collect the dated codes, derive the tables, write them out."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import logging
|
| 6 |
+
import shutil
|
| 7 |
+
from collections import defaultdict
|
| 8 |
+
from datetime import UTC, datetime
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import polars as pl
|
| 12 |
+
|
| 13 |
+
from .config import Settings
|
| 14 |
+
from .naics import sector_of
|
| 15 |
+
from .schema import CONFIG_SCHEMAS, align, empty_frame
|
| 16 |
+
from .sic import code_level, division_of, industry_group, major_group, prefix_of
|
| 17 |
+
from .sources import (
|
| 18 |
+
edgar_sic_list,
|
| 19 |
+
fetch_concordance,
|
| 20 |
+
from_fundamental_filings,
|
| 21 |
+
issuers,
|
| 22 |
+
parse_concordance,
|
| 23 |
+
submissions_snapshot,
|
| 24 |
+
ticker_spans,
|
| 25 |
+
)
|
| 26 |
+
from .store import atomic_write_parquet
|
| 27 |
+
from .taxonomy import (
|
| 28 |
+
INDUSTRIES,
|
| 29 |
+
RULES,
|
| 30 |
+
SECTORS,
|
| 31 |
+
TAXONOMY_VERSION,
|
| 32 |
+
UNCLASSIFIED,
|
| 33 |
+
classify,
|
| 34 |
+
classify_entity,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
LOGGER = logging.getLogger(__name__)
|
| 38 |
+
|
| 39 |
+
MAX_ROWS_PER_FILE = 5_000_000
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _write(data_dir: Path, table: str, frame: pl.DataFrame) -> int:
|
| 43 |
+
root = Path(data_dir) / table
|
| 44 |
+
if root.exists():
|
| 45 |
+
shutil.rmtree(root)
|
| 46 |
+
root.mkdir(parents=True, exist_ok=True)
|
| 47 |
+
frame = align(frame, CONFIG_SCHEMAS[table])
|
| 48 |
+
if frame.is_empty():
|
| 49 |
+
atomic_write_parquet(frame, root / "part-00000.parquet")
|
| 50 |
+
return 0
|
| 51 |
+
for index, start in enumerate(range(0, frame.height, MAX_ROWS_PER_FILE)):
|
| 52 |
+
atomic_write_parquet(
|
| 53 |
+
frame.slice(start, MAX_ROWS_PER_FILE), root / f"part-{index:05d}.parquet"
|
| 54 |
+
)
|
| 55 |
+
return frame.height
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
# ------------------------------------------------------------------ spans
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def build_spans(observations: pl.DataFrame) -> pl.DataFrame:
|
| 62 |
+
"""Collapse consecutive statements of the same code into one run.
|
| 63 |
+
|
| 64 |
+
A run, not a groupby on (filer, code): a company that was a blank check,
|
| 65 |
+
became a car maker and was reclassified back has three spans, and
|
| 66 |
+
flattening them to two would erase the order the SEC saw it in.
|
| 67 |
+
"""
|
| 68 |
+
if observations.is_empty():
|
| 69 |
+
return empty_frame(CONFIG_SCHEMAS["spans"])
|
| 70 |
+
|
| 71 |
+
ordered = observations.sort(["cik", "stated_on", "knowledge_time", "source_ref"])
|
| 72 |
+
ordered = ordered.with_columns(
|
| 73 |
+
(
|
| 74 |
+
(pl.col("sic") != pl.col("sic").shift(1).over("cik"))
|
| 75 |
+
| pl.col("cik").ne(pl.col("cik").shift(1)).fill_null(True)
|
| 76 |
+
)
|
| 77 |
+
.fill_null(True)
|
| 78 |
+
.alias("starts_run")
|
| 79 |
+
).with_columns(pl.col("starts_run").cum_sum().alias("run"))
|
| 80 |
+
|
| 81 |
+
spans = (
|
| 82 |
+
ordered.group_by(["cik", "run"])
|
| 83 |
+
.agg(
|
| 84 |
+
pl.col("sic").first().alias("sic"),
|
| 85 |
+
pl.col("stated_on").min().alias("valid_from"),
|
| 86 |
+
pl.col("stated_on").max().alias("valid_to"),
|
| 87 |
+
pl.len().cast(pl.Int32).alias("observations"),
|
| 88 |
+
pl.col("source").unique().sort().alias("source_list"),
|
| 89 |
+
)
|
| 90 |
+
.with_columns(pl.col("source_list").list.join(",").alias("sources"))
|
| 91 |
+
.drop("source_list", "run")
|
| 92 |
+
.sort(["cik", "valid_from", "valid_to"])
|
| 93 |
+
)
|
| 94 |
+
spans = spans.with_columns(
|
| 95 |
+
(pl.len().over("cik") - pl.col("sic").cum_count().over("cik") + 1)
|
| 96 |
+
.cast(pl.Int32)
|
| 97 |
+
.alias("rank_for_filer")
|
| 98 |
+
).with_columns((pl.col("rank_for_filer") == 1).alias("is_latest"))
|
| 99 |
+
|
| 100 |
+
assignments = _assign(spans["sic"])
|
| 101 |
+
now = datetime.now(UTC)
|
| 102 |
+
return spans.with_columns(
|
| 103 |
+
*assignments, pl.lit(now).alias("inserted_at")
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def _assign(codes: pl.Series) -> list[pl.Series]:
|
| 108 |
+
"""Sector and industry columns for a column of SIC codes."""
|
| 109 |
+
cache: dict[str | None, tuple[str, str, str, str]] = {}
|
| 110 |
+
sector_code, sector, industry_code, industry = [], [], [], []
|
| 111 |
+
for code in codes.to_list():
|
| 112 |
+
if code not in cache:
|
| 113 |
+
found = classify(code)
|
| 114 |
+
cache[code] = (found.sector_code, found.sector, found.industry_code, found.industry)
|
| 115 |
+
values = cache[code]
|
| 116 |
+
sector_code.append(values[0])
|
| 117 |
+
sector.append(values[1])
|
| 118 |
+
industry_code.append(values[2])
|
| 119 |
+
industry.append(values[3])
|
| 120 |
+
return [
|
| 121 |
+
pl.Series("sector_code", sector_code, dtype=pl.String),
|
| 122 |
+
pl.Series("sector", sector, dtype=pl.String),
|
| 123 |
+
pl.Series("industry_code", industry_code, dtype=pl.String),
|
| 124 |
+
pl.Series("industry", industry, dtype=pl.String),
|
| 125 |
+
]
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
# -------------------------------------------------------------- reference
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def build_naics_lookup(crosswalk: pl.DataFrame) -> dict[str, dict]:
|
| 132 |
+
"""For every EDGAR code, what the Census crosswalk can say about it.
|
| 133 |
+
|
| 134 |
+
A roll-up stands for all the 1987 industries beneath it, so `2000` is
|
| 135 |
+
resolved by taking every 20xx row in the crosswalk at once. The answer is
|
| 136 |
+
filled in only where it is unique: one NAICS industry for `naics_1997`,
|
| 137 |
+
one NAICS sector for `naics_sector`, and the candidate count either way so
|
| 138 |
+
a reader can see how much was thrown away.
|
| 139 |
+
"""
|
| 140 |
+
by_prefix: dict[str, list[tuple[str, str | None]]] = defaultdict(list)
|
| 141 |
+
for row in crosswalk.iter_rows(named=True):
|
| 142 |
+
sic, naics = row["sic"], row["naics_1997"]
|
| 143 |
+
if not sic or not naics:
|
| 144 |
+
continue
|
| 145 |
+
for width in (2, 3, 4):
|
| 146 |
+
by_prefix[sic[:width]].append((naics, row["naics_title"]))
|
| 147 |
+
return {prefix: _resolve(pairs) for prefix, pairs in by_prefix.items()}
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def _resolve(pairs: list[tuple[str, str | None]]) -> dict:
|
| 151 |
+
codes = {code for code, _ in pairs}
|
| 152 |
+
sectors = {sector_of(code)[0] for code in codes} - {None}
|
| 153 |
+
one_code = next(iter(codes)) if len(codes) == 1 else None
|
| 154 |
+
title = None
|
| 155 |
+
if one_code:
|
| 156 |
+
title = next((name for code, name in pairs if code == one_code), None)
|
| 157 |
+
sector = next(iter(sectors)) if len(sectors) == 1 else None
|
| 158 |
+
return {
|
| 159 |
+
"naics_1997": one_code,
|
| 160 |
+
"naics_title": title,
|
| 161 |
+
"naics_sector": sector,
|
| 162 |
+
"naics_sector_title": sector_of(sector or "")[1] if sector else None,
|
| 163 |
+
"naics_candidates": len(codes),
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def build_sic_codes(
|
| 168 |
+
edgar: pl.DataFrame,
|
| 169 |
+
*,
|
| 170 |
+
naics_lookup: dict[str, dict],
|
| 171 |
+
major_groups: dict[str, str],
|
| 172 |
+
usage: pl.DataFrame,
|
| 173 |
+
) -> pl.DataFrame:
|
| 174 |
+
"""EDGAR's code list with everything derivable from a code hung off it."""
|
| 175 |
+
now = datetime.now(UTC)
|
| 176 |
+
rows: list[dict] = []
|
| 177 |
+
for row in edgar.iter_rows(named=True):
|
| 178 |
+
code = row["sic"]
|
| 179 |
+
found = classify(code)
|
| 180 |
+
division = division_of(code)
|
| 181 |
+
group = major_group(code)
|
| 182 |
+
resolved = naics_lookup.get(prefix_of(code), {})
|
| 183 |
+
rows.append({
|
| 184 |
+
"sic": code,
|
| 185 |
+
"title": row["title"],
|
| 186 |
+
"sec_office": row["sec_office"],
|
| 187 |
+
"sic_level": code_level(code),
|
| 188 |
+
"in_sic_1997_placeholder": None,
|
| 189 |
+
"division": division.letter if division else None,
|
| 190 |
+
"division_title": division.title if division else None,
|
| 191 |
+
"major_group": group,
|
| 192 |
+
"major_group_title": major_groups.get(group),
|
| 193 |
+
"industry_group": industry_group(code),
|
| 194 |
+
"sector_code": found.sector_code,
|
| 195 |
+
"sector": found.sector,
|
| 196 |
+
"industry_code": found.industry_code,
|
| 197 |
+
"industry": found.industry,
|
| 198 |
+
"naics_1997": resolved.get("naics_1997"),
|
| 199 |
+
"naics_title": resolved.get("naics_title"),
|
| 200 |
+
"naics_sector": resolved.get("naics_sector"),
|
| 201 |
+
"naics_sector_title": resolved.get("naics_sector_title"),
|
| 202 |
+
"naics_candidates": resolved.get("naics_candidates", 0),
|
| 203 |
+
"inserted_at": now,
|
| 204 |
+
})
|
| 205 |
+
frame = pl.DataFrame(rows).drop("in_sic_1997_placeholder")
|
| 206 |
+
# A code is a real 1987 industry when the crosswalk knows it by its own
|
| 207 |
+
# four digits, not by the prefix a roll-up was expanded through.
|
| 208 |
+
real = set(naics_lookup) & {code for code in frame["sic"] if len(code) == 4}
|
| 209 |
+
frame = frame.with_columns(
|
| 210 |
+
pl.col("sic")
|
| 211 |
+
.map_elements(lambda code: code in real and code_level(code) == "industry",
|
| 212 |
+
return_dtype=pl.Boolean)
|
| 213 |
+
.alias("in_sic_1987")
|
| 214 |
+
)
|
| 215 |
+
return frame.join(usage, on="sic", how="left").with_columns(
|
| 216 |
+
pl.col("filers").fill_null(0).cast(pl.Int32),
|
| 217 |
+
pl.col("filings").fill_null(0).cast(pl.Int32),
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def build_taxonomy_table() -> pl.DataFrame:
|
| 222 |
+
"""The taxonomy itself, so it can be read without reading Python."""
|
| 223 |
+
ranges: dict[str, list[str]] = defaultdict(list)
|
| 224 |
+
for low, high, industry_code in RULES:
|
| 225 |
+
ranges[industry_code].append(f"{low:04d}" if low == high else f"{low:04d}-{high:04d}")
|
| 226 |
+
now = datetime.now(UTC)
|
| 227 |
+
rows = [
|
| 228 |
+
{
|
| 229 |
+
"sector_code": sector_code,
|
| 230 |
+
"sector": SECTORS[sector_code],
|
| 231 |
+
"industry_code": industry_code,
|
| 232 |
+
"industry": industry,
|
| 233 |
+
"sic_ranges": " ".join(ranges.get(industry_code, [])) or None,
|
| 234 |
+
"taxonomy_version": TAXONOMY_VERSION,
|
| 235 |
+
"inserted_at": now,
|
| 236 |
+
}
|
| 237 |
+
for industry_code, (sector_code, industry) in INDUSTRIES.items()
|
| 238 |
+
]
|
| 239 |
+
order = list(SECTORS)
|
| 240 |
+
return pl.DataFrame(rows).sort(
|
| 241 |
+
pl.col("sector_code").replace_strict(order, range(len(order)), default=len(order)),
|
| 242 |
+
"industry_code",
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
|
| 246 |
+
# --------------------------------------------------------- the two answers
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def entity_fallback(kinds: pl.DataFrame) -> pl.DataFrame:
|
| 250 |
+
"""Entity kinds resolved to sector and industry, for filers with no code."""
|
| 251 |
+
columns = {
|
| 252 |
+
"cik": pl.String, "sector_code": pl.String, "sector": pl.String,
|
| 253 |
+
"industry_code": pl.String, "industry": pl.String,
|
| 254 |
+
}
|
| 255 |
+
if kinds.is_empty():
|
| 256 |
+
return pl.DataFrame(schema=columns)
|
| 257 |
+
rows = []
|
| 258 |
+
for row in kinds.iter_rows(named=True):
|
| 259 |
+
found = classify_entity(row["entity_kind"])
|
| 260 |
+
if found:
|
| 261 |
+
rows.append({
|
| 262 |
+
"cik": row["cik"], "sector_code": found.sector_code, "sector": found.sector,
|
| 263 |
+
"industry_code": found.industry_code, "industry": found.industry,
|
| 264 |
+
})
|
| 265 |
+
return pl.DataFrame(rows, schema=columns) if rows else pl.DataFrame(schema=columns)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def build_classification(
|
| 269 |
+
spans: pl.DataFrame,
|
| 270 |
+
directory: pl.DataFrame,
|
| 271 |
+
reference: pl.DataFrame,
|
| 272 |
+
fallback: pl.DataFrame,
|
| 273 |
+
) -> pl.DataFrame:
|
| 274 |
+
"""One row per filer: the newest code it has been seen under, resolved.
|
| 275 |
+
|
| 276 |
+
Filers with no code at all are still here when EDGAR's forms say what kind
|
| 277 |
+
of entity they are -- with `sic` null and `source` naming the forms, so
|
| 278 |
+
nothing passes a derived label off as an assigned one.
|
| 279 |
+
"""
|
| 280 |
+
if spans.is_empty():
|
| 281 |
+
return empty_frame(CONFIG_SCHEMAS["classification"])
|
| 282 |
+
latest = spans.filter(pl.col("is_latest")).select(
|
| 283 |
+
"cik", "sic", "observations", "sources",
|
| 284 |
+
pl.col("valid_to").alias("stated_on"),
|
| 285 |
+
)
|
| 286 |
+
reference_columns = [
|
| 287 |
+
"sic", "title", "sic_level", "sec_office", "division", "division_title",
|
| 288 |
+
"major_group", "major_group_title", "industry_group", "sector_code", "sector",
|
| 289 |
+
"industry_code", "industry", "naics_1997", "naics_title", "naics_sector",
|
| 290 |
+
"naics_sector_title", "naics_candidates",
|
| 291 |
+
]
|
| 292 |
+
frame = (
|
| 293 |
+
latest.join(directory, on="cik", how="left")
|
| 294 |
+
.join(reference.select(reference_columns), on="sic", how="left")
|
| 295 |
+
.rename({"title": "sic_title", "sources": "source"})
|
| 296 |
+
)
|
| 297 |
+
# A filer whose only code came from the snapshot has no history behind it.
|
| 298 |
+
frame = frame.with_columns(
|
| 299 |
+
(~pl.col("source").str.contains("submissions")).alias("is_dated"),
|
| 300 |
+
)
|
| 301 |
+
extra = fallback.join(frame.select("cik"), on="cik", how="anti")
|
| 302 |
+
if not extra.is_empty():
|
| 303 |
+
extra = extra.join(directory, on="cik", how="left").with_columns(
|
| 304 |
+
pl.lit("edgar_forms").alias("source"),
|
| 305 |
+
pl.lit(False).alias("is_dated"),
|
| 306 |
+
pl.lit(0, dtype=pl.Int32).alias("observations"),
|
| 307 |
+
)
|
| 308 |
+
frame = pl.concat([frame, extra], how="diagonal_relaxed")
|
| 309 |
+
return frame.with_columns(
|
| 310 |
+
pl.lit(TAXONOMY_VERSION).alias("taxonomy_version"),
|
| 311 |
+
pl.lit(datetime.now(UTC)).alias("inserted_at"),
|
| 312 |
+
).sort("cik")
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def build_by_ticker(
|
| 316 |
+
tickers: pl.DataFrame,
|
| 317 |
+
spans: pl.DataFrame,
|
| 318 |
+
directory: pl.DataFrame,
|
| 319 |
+
fallback: pl.DataFrame | None = None,
|
| 320 |
+
) -> pl.DataFrame:
|
| 321 |
+
"""The classification keyed the way a strategy asks for it.
|
| 322 |
+
|
| 323 |
+
A ticker span and a code span are two intervals over the same filer, and
|
| 324 |
+
the useful row is their overlap: `AAPL` was Apple's symbol from here to
|
| 325 |
+
here, and over that window the SEC had Apple under 3571.
|
| 326 |
+
|
| 327 |
+
Where the two never overlap the ticker still gets a row, marked `undated`,
|
| 328 |
+
carrying the filer's latest code across the whole window. That covers the
|
| 329 |
+
delisted-before-2009 case -- Form 4 proves the symbol in 2007 and the only
|
| 330 |
+
code EDGAR holds is today's -- and also the one where both exist but miss
|
| 331 |
+
each other, which happens when a symbol appears in a single late filing.
|
| 332 |
+
Dropping those would quietly shrink the universe to the survivors, which
|
| 333 |
+
is the exact bias the rest of this family exists to avoid.
|
| 334 |
+
|
| 335 |
+
A ticker whose filer has no code at all still gets a row too, marked
|
| 336 |
+
`unknown` and unclassified. A symbol absent from the table and a symbol
|
| 337 |
+
the SEC never classified look identical to a consumer, and only one of
|
| 338 |
+
them is a bug -- so the table carries every ticker and says which it is.
|
| 339 |
+
|
| 340 |
+
`is_current` marks the single row in force today: the filer's symbol now,
|
| 341 |
+
under the newest code it has been seen under. Filtering on it gives one
|
| 342 |
+
row per live ticker, which is the question almost everyone is asking.
|
| 343 |
+
"""
|
| 344 |
+
if tickers.is_empty() or spans.is_empty():
|
| 345 |
+
return empty_frame(CONFIG_SCHEMAS["by_ticker"])
|
| 346 |
+
|
| 347 |
+
labelled = spans.select(
|
| 348 |
+
"cik", "sic", "sector_code", "sector", "industry_code", "industry",
|
| 349 |
+
pl.col("valid_from").alias("span_from"), pl.col("valid_to").alias("span_to"),
|
| 350 |
+
"is_latest",
|
| 351 |
+
)
|
| 352 |
+
joined = tickers.join(labelled, on="cik", how="left")
|
| 353 |
+
overlapping = (
|
| 354 |
+
joined.filter(pl.col("sic").is_not_null())
|
| 355 |
+
.with_columns(
|
| 356 |
+
pl.max_horizontal("valid_from", "span_from").alias("overlap_from"),
|
| 357 |
+
pl.min_horizontal("valid_to", "span_to").alias("overlap_to"),
|
| 358 |
+
)
|
| 359 |
+
.filter(pl.col("overlap_from") <= pl.col("overlap_to"))
|
| 360 |
+
.with_columns(
|
| 361 |
+
pl.col("overlap_from").alias("valid_from"),
|
| 362 |
+
pl.col("overlap_to").alias("valid_to"),
|
| 363 |
+
pl.lit("dated").alias("date_basis"),
|
| 364 |
+
)
|
| 365 |
+
.drop("overlap_from", "overlap_to")
|
| 366 |
+
)
|
| 367 |
+
|
| 368 |
+
key = ["cik", "ticker"]
|
| 369 |
+
resolved = overlapping.select(key).unique()
|
| 370 |
+
remainder = (
|
| 371 |
+
tickers.join(resolved, on=key, how="anti")
|
| 372 |
+
.join(labelled.filter(pl.col("is_latest")).drop("span_from", "span_to"),
|
| 373 |
+
on="cik", how="left")
|
| 374 |
+
.with_columns(
|
| 375 |
+
pl.when(pl.col("sic").is_null())
|
| 376 |
+
.then(pl.lit("unknown"))
|
| 377 |
+
.otherwise(pl.lit("undated"))
|
| 378 |
+
.alias("date_basis"),
|
| 379 |
+
pl.lit(True).alias("is_latest"),
|
| 380 |
+
)
|
| 381 |
+
)
|
| 382 |
+
if fallback is not None and not fallback.is_empty():
|
| 383 |
+
remainder = remainder.join(fallback, on="cik", how="left", suffix="_kind")
|
| 384 |
+
for column in ("sector_code", "sector", "industry_code", "industry"):
|
| 385 |
+
remainder = remainder.with_columns(
|
| 386 |
+
pl.coalesce(pl.col(column), pl.col(f"{column}_kind")).alias(column)
|
| 387 |
+
).drop(f"{column}_kind")
|
| 388 |
+
remainder = remainder.with_columns(
|
| 389 |
+
pl.col("sector_code").fill_null(UNCLASSIFIED.sector_code),
|
| 390 |
+
pl.col("sector").fill_null(UNCLASSIFIED.sector),
|
| 391 |
+
pl.col("industry_code").fill_null(UNCLASSIFIED.industry_code),
|
| 392 |
+
pl.col("industry").fill_null(UNCLASSIFIED.industry),
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
columns = [
|
| 396 |
+
"ticker", "cik", "valid_from", "valid_to", "sic", "sector_code", "sector",
|
| 397 |
+
"industry_code", "industry", "date_basis", "is_current", "is_latest",
|
| 398 |
+
]
|
| 399 |
+
frame = pl.concat(
|
| 400 |
+
[overlapping.select(columns), remainder.select(columns)], how="vertical_relaxed"
|
| 401 |
+
)
|
| 402 |
+
# `is_current` on the way in means "this is the filer's symbol now". On the
|
| 403 |
+
# way out it means "this row is the one in force now", which also requires
|
| 404 |
+
# the code to be the newest one -- otherwise a live ticker whose company
|
| 405 |
+
# was reclassified would come back current under both its old sector and
|
| 406 |
+
# its new one.
|
| 407 |
+
frame = frame.with_columns(
|
| 408 |
+
(pl.col("is_current").fill_null(False) & pl.col("is_latest")).alias("is_current")
|
| 409 |
+
).drop("is_latest")
|
| 410 |
+
return (
|
| 411 |
+
frame.join(directory.select("cik", "name", "exchange"), on="cik", how="left")
|
| 412 |
+
.with_columns(pl.lit(datetime.now(UTC)).alias("inserted_at"))
|
| 413 |
+
.sort(["ticker", "valid_from", "cik"])
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
# ------------------------------------------------------------------ build
|
| 418 |
+
|
| 419 |
+
|
| 420 |
+
async def run_build(
|
| 421 |
+
*, settings: Settings, token: str | None = None, submission_limit: int | None = None
|
| 422 |
+
) -> dict[str, int]:
|
| 423 |
+
from .sec_client import SECClient
|
| 424 |
+
|
| 425 |
+
data_dir = Path(settings.data_dir)
|
| 426 |
+
dated = from_fundamental_filings(settings, token=token)
|
| 427 |
+
tickers = ticker_spans(settings, token=token)
|
| 428 |
+
directory = issuers(settings, token=token)
|
| 429 |
+
|
| 430 |
+
# The filers that have had a ticker but never filed XBRL: delisted before
|
| 431 |
+
# 2009, a fund, a foreign issuer on paper. Their code exists only in
|
| 432 |
+
# EDGAR's own record, and without them the universe is the survivors.
|
| 433 |
+
seen = set(dated["cik"].unique().to_list())
|
| 434 |
+
gap = sorted(set(tickers["cik"].unique().to_list()) - seen)
|
| 435 |
+
LOGGER.info("filers with a ticker and no XBRL filing: %d", len(gap))
|
| 436 |
+
|
| 437 |
+
async with SECClient(
|
| 438 |
+
user_agent=settings.sec_user_agent,
|
| 439 |
+
cache_dir=settings.cache_dir,
|
| 440 |
+
requests_per_second=settings.requests_per_second,
|
| 441 |
+
) as client:
|
| 442 |
+
edgar = await edgar_sic_list(client)
|
| 443 |
+
snapshot, kinds = await submissions_snapshot(client, gap, limit=submission_limit)
|
| 444 |
+
concordance_bytes = await fetch_concordance(settings.cache_dir)
|
| 445 |
+
|
| 446 |
+
crosswalk, major_groups, divisions = parse_concordance(concordance_bytes)
|
| 447 |
+
LOGGER.info("divisions in the concordance: %d", len(divisions))
|
| 448 |
+
|
| 449 |
+
observations = pl.concat([dated, snapshot], how="vertical_relaxed")
|
| 450 |
+
LOGGER.info(
|
| 451 |
+
"observations: %d over %d filers", observations.height, observations["cik"].n_unique()
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
spans = build_spans(observations)
|
| 455 |
+
usage = observations.group_by("sic").agg(
|
| 456 |
+
pl.col("cik").n_unique().cast(pl.Int32).alias("filers"),
|
| 457 |
+
pl.len().cast(pl.Int32).alias("filings"),
|
| 458 |
+
)
|
| 459 |
+
naics_lookup = build_naics_lookup(crosswalk)
|
| 460 |
+
reference = build_sic_codes(
|
| 461 |
+
edgar, naics_lookup=naics_lookup, major_groups=major_groups, usage=usage
|
| 462 |
+
)
|
| 463 |
+
fallback = entity_fallback(kinds)
|
| 464 |
+
LOGGER.info("filers classified from their forms alone: %d", fallback.height)
|
| 465 |
+
classification = build_classification(spans, directory, reference, fallback)
|
| 466 |
+
by_ticker = build_by_ticker(tickers, spans, directory, fallback)
|
| 467 |
+
taxonomy = build_taxonomy_table()
|
| 468 |
+
taxonomy = taxonomy.join(
|
| 469 |
+
reference.group_by("industry_code").agg(pl.len().cast(pl.Int32).alias("edgar_codes")),
|
| 470 |
+
on="industry_code",
|
| 471 |
+
how="left",
|
| 472 |
+
).with_columns(pl.col("edgar_codes").fill_null(0).cast(pl.Int32))
|
| 473 |
+
|
| 474 |
+
counts = {
|
| 475 |
+
"classification": _write(data_dir, "classification", classification),
|
| 476 |
+
"by_ticker": _write(data_dir, "by_ticker", by_ticker),
|
| 477 |
+
"spans": _write(data_dir, "spans", spans),
|
| 478 |
+
"observations": _write(data_dir, "observations", observations),
|
| 479 |
+
"sic_codes": _write(data_dir, "sic_codes", reference),
|
| 480 |
+
"naics_map": _write(data_dir, "naics_map", crosswalk),
|
| 481 |
+
"taxonomy": _write(data_dir, "taxonomy", taxonomy),
|
| 482 |
+
}
|
| 483 |
+
LOGGER.info("built %s at %s", counts, datetime.now(UTC).isoformat(timespec="seconds"))
|
| 484 |
+
return counts
|
recipe/cli.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Command line for the industry classification 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="industry-classification", description=__doc__)
|
| 20 |
+
sub = parser.add_subparsers(dest="command", required=True)
|
| 21 |
+
|
| 22 |
+
build = sub.add_parser("build", help="collect the codes and write every table")
|
| 23 |
+
build.add_argument(
|
| 24 |
+
"--submission-limit",
|
| 25 |
+
type=int,
|
| 26 |
+
default=None,
|
| 27 |
+
help="resolve at most N filers from the submissions archive (for quick runs)",
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
sub.add_parser("verify", help="run the quality gate and write the manifest")
|
| 31 |
+
|
| 32 |
+
publish = sub.add_parser("publish", help="mirror the built tree to Hugging Face")
|
| 33 |
+
publish.add_argument("--repo", default=None)
|
| 34 |
+
|
| 35 |
+
args = parser.parse_args(argv)
|
| 36 |
+
logging.basicConfig(
|
| 37 |
+
level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s | %(message)s"
|
| 38 |
+
)
|
| 39 |
+
logging.getLogger("httpx").setLevel(logging.WARNING)
|
| 40 |
+
settings = Settings.from_env()
|
| 41 |
+
data_dir = Path(settings.data_dir)
|
| 42 |
+
|
| 43 |
+
if args.command == "build":
|
| 44 |
+
counts = asyncio.run(
|
| 45 |
+
run_build(settings=settings, submission_limit=args.submission_limit)
|
| 46 |
+
)
|
| 47 |
+
report = validate(data_dir)
|
| 48 |
+
report.write(data_dir.parent / "quality_report.json")
|
| 49 |
+
build_manifest(data_dir=data_dir, row_counts=counts, quality_ok=report.ok)
|
| 50 |
+
print(json.dumps({"rows": counts, "quality_ok": report.ok,
|
| 51 |
+
"errors": report.errors, "warnings": report.warnings}, indent=2))
|
| 52 |
+
return 0 if report.ok else 1
|
| 53 |
+
|
| 54 |
+
if args.command == "verify":
|
| 55 |
+
report = validate(data_dir)
|
| 56 |
+
report.write(data_dir.parent / "quality_report.json")
|
| 57 |
+
build_manifest(
|
| 58 |
+
data_dir=data_dir, row_counts=config_row_counts(data_dir), quality_ok=report.ok
|
| 59 |
+
)
|
| 60 |
+
print(json.dumps(report.as_dict(), indent=2, default=str))
|
| 61 |
+
return 0 if report.ok else 1
|
| 62 |
+
|
| 63 |
+
if args.command == "publish":
|
| 64 |
+
from .publish import hf_token, publish_to_hf
|
| 65 |
+
|
| 66 |
+
report = validate(data_dir)
|
| 67 |
+
if not report.ok:
|
| 68 |
+
print(json.dumps({"quality_ok": False, "errors": report.errors}, indent=2))
|
| 69 |
+
return 1
|
| 70 |
+
commit = publish_to_hf(
|
| 71 |
+
project_root=data_dir.resolve().parent,
|
| 72 |
+
repo_id=args.repo or settings.hf_repo,
|
| 73 |
+
token=hf_token(),
|
| 74 |
+
)
|
| 75 |
+
print(json.dumps({"commit": commit}, indent=2))
|
| 76 |
+
return 0
|
| 77 |
+
return 1
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
if __name__ == "__main__":
|
| 81 |
+
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 industry-classification/1.0 algo@limex.com"
|
| 10 |
+
DEFAULT_HF_REPO = "ZipLime/industry-classification"
|
| 11 |
+
|
| 12 |
+
# The sibling datasets this one is assembled from. Like the security master,
|
| 13 |
+
# this dataset is mostly glue: the SIC code attached to a filer was stated by
|
| 14 |
+
# the SEC on a filing that `company-fundamentals` already parsed, and the
|
| 15 |
+
# ticker it hangs off was derived by `security-master` from Form 4 headers.
|
| 16 |
+
SOURCE_REPOS = {
|
| 17 |
+
"fundamentals": "ZipLime/company-fundamentals",
|
| 18 |
+
"security_master": "ZipLime/security-master",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
# Where a local checkout of a sibling lives, for iterating without downloading
|
| 22 |
+
# anything. `INDUSTRY_SIBLINGS=/path/to/hf` makes the build read
|
| 23 |
+
# `/path/to/hf/Company_fundamentals/data` instead of the Hub.
|
| 24 |
+
SIBLING_DIRS = {
|
| 25 |
+
"fundamentals": "Company_fundamentals",
|
| 26 |
+
"security_master": "Security_master",
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
@dataclass(frozen=True, slots=True)
|
| 30 |
+
class Settings:
|
| 31 |
+
data_dir: Path = Path("data")
|
| 32 |
+
cache_dir: Path = Path(".cache/sec")
|
| 33 |
+
sec_user_agent: str = DEFAULT_SEC_USER_AGENT
|
| 34 |
+
requests_per_second: float = 4.0
|
| 35 |
+
hf_repo: str = DEFAULT_HF_REPO
|
| 36 |
+
siblings_dir: Path | None = None
|
| 37 |
+
|
| 38 |
+
@classmethod
|
| 39 |
+
def from_env(cls, **overrides) -> Settings:
|
| 40 |
+
siblings = os.environ.get("INDUSTRY_SIBLINGS")
|
| 41 |
+
return cls(
|
| 42 |
+
data_dir=Path(overrides.get("data_dir") or os.environ.get("DATA_DIR", "data")),
|
| 43 |
+
cache_dir=Path(
|
| 44 |
+
overrides.get("cache_dir") or os.environ.get("SEC_CACHE_DIR", ".cache/sec")
|
| 45 |
+
),
|
| 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,229 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 two sibling tables -- twenty megabytes -- and about six
|
| 20 |
+
# thousand small EDGAR lookups for the filers those tables do not cover. The
|
| 21 |
+
# grouping that follows is seconds on half a million rows. Memory is modest
|
| 22 |
+
# and so is bandwidth; the wall clock is the rate limiter, not the CPU.
|
| 23 |
+
# The flavour also lives in the scheduled job on the Hub, which is what
|
| 24 |
+
# actually decides the hardware -- changing it here alone changes nothing.
|
| 25 |
+
UPDATE_FLAVOR = "cpu-basic"
|
| 26 |
+
BACKFILL_FLAVOR = "cpu-basic"
|
| 27 |
+
UPDATE_TIMEOUT = "2h"
|
| 28 |
+
BACKFILL_TIMEOUT = "3h"
|
| 29 |
+
# Monday 09:40 UTC, two hours after company-fundamentals and security-master.
|
| 30 |
+
# This dataset is derived from both, and running before them would publish a
|
| 31 |
+
# classification that lags its own sources by a week. The :40 slot is clear;
|
| 32 |
+
# 08:10, 08:40 and 09:10 belong to other members of the family.
|
| 33 |
+
DEFAULT_SCHEDULE = "40 9 * * 1"
|
| 34 |
+
JOB_SCRIPT = "jobs/run.py"
|
| 35 |
+
UPDATE_JOB_NAME = "industry-classification-update"
|
| 36 |
+
BACKFILL_JOB_NAME = "industry-classification-rebuild"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def script_url(
|
| 40 |
+
*, repo_id: str = DEFAULT_HF_REPO, script: str = JOB_SCRIPT, revision: str = "main"
|
| 41 |
+
) -> str:
|
| 42 |
+
return f"https://huggingface.co/datasets/{repo_id}/resolve/{revision}/{script}"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
@dataclass(frozen=True, slots=True)
|
| 46 |
+
class JobSpec:
|
| 47 |
+
"""Everything needed to launch or schedule one run, minus the credentials."""
|
| 48 |
+
|
| 49 |
+
script: str
|
| 50 |
+
script_url: str
|
| 51 |
+
flavor: str
|
| 52 |
+
timeout: str
|
| 53 |
+
script_args: tuple[str, ...]
|
| 54 |
+
env: dict[str, str]
|
| 55 |
+
name: str
|
| 56 |
+
|
| 57 |
+
def as_kwargs(self, *, secrets: dict[str, str]) -> dict[str, Any]:
|
| 58 |
+
"""Build the huggingface_hub call arguments.
|
| 59 |
+
|
| 60 |
+
The Jobs API takes no ``name`` parameter; a job's display name is the
|
| 61 |
+
``name`` label. Credentials go through ``secrets`` so they are encrypted
|
| 62 |
+
server side instead of travelling as plain environment variables.
|
| 63 |
+
"""
|
| 64 |
+
|
| 65 |
+
return {
|
| 66 |
+
"script": self.script_url,
|
| 67 |
+
"script_args": list(self.script_args),
|
| 68 |
+
"flavor": self.flavor,
|
| 69 |
+
"timeout": self.timeout,
|
| 70 |
+
"env": dict(self.env),
|
| 71 |
+
"secrets": secrets,
|
| 72 |
+
"labels": {"name": self.name, "project": "industry-classification"},
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def update_spec(
|
| 77 |
+
*,
|
| 78 |
+
repo_id: str = DEFAULT_HF_REPO,
|
| 79 |
+
revision: str = "main",
|
| 80 |
+
flavor: str = UPDATE_FLAVOR,
|
| 81 |
+
timeout: str = UPDATE_TIMEOUT,
|
| 82 |
+
) -> JobSpec:
|
| 83 |
+
return JobSpec(
|
| 84 |
+
script=JOB_SCRIPT,
|
| 85 |
+
script_url=script_url(repo_id=repo_id, revision=revision),
|
| 86 |
+
flavor=flavor,
|
| 87 |
+
timeout=timeout,
|
| 88 |
+
script_args=("--mode", "update"),
|
| 89 |
+
env={"HF_DATASET_REPO": repo_id},
|
| 90 |
+
name=UPDATE_JOB_NAME,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def backfill_spec(
|
| 95 |
+
*,
|
| 96 |
+
repo_id: str = DEFAULT_HF_REPO,
|
| 97 |
+
revision: str = "main",
|
| 98 |
+
flavor: str = BACKFILL_FLAVOR,
|
| 99 |
+
timeout: str = BACKFILL_TIMEOUT,
|
| 100 |
+
) -> JobSpec:
|
| 101 |
+
args = ["--mode", "build"]
|
| 102 |
+
return JobSpec(
|
| 103 |
+
script=JOB_SCRIPT,
|
| 104 |
+
script_url=script_url(repo_id=repo_id, revision=revision),
|
| 105 |
+
flavor=flavor,
|
| 106 |
+
timeout=timeout,
|
| 107 |
+
script_args=tuple(args),
|
| 108 |
+
env={"HF_DATASET_REPO": repo_id},
|
| 109 |
+
name=BACKFILL_JOB_NAME,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def job_secrets(*, hf_token: str, sec_user_agent: str) -> dict[str, str]:
|
| 114 |
+
"""Validate credentials locally so a misconfigured job fails before it costs money."""
|
| 115 |
+
|
| 116 |
+
if not hf_token.strip():
|
| 117 |
+
raise ValueError("HF_TOKEN is required to create or run a Hugging Face Job")
|
| 118 |
+
return {
|
| 119 |
+
"HF_TOKEN": hf_token.strip(),
|
| 120 |
+
"SEC_USER_AGENT": validate_sec_user_agent(sec_user_agent),
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _api(token: str | None) -> Any:
|
| 125 |
+
try:
|
| 126 |
+
from huggingface_hub import HfApi
|
| 127 |
+
except ImportError as error: # pragma: no cover - exercised in the job environment
|
| 128 |
+
raise RuntimeError("install the 'publish' extra to manage Hugging Face Jobs") from error
|
| 129 |
+
return HfApi(token=token)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _require(api: Any, method: str) -> Any:
|
| 133 |
+
"""Fail with an actionable message when the installed hub predates a Jobs API."""
|
| 134 |
+
|
| 135 |
+
function = getattr(api, method, None)
|
| 136 |
+
if function is None:
|
| 137 |
+
raise RuntimeError(
|
| 138 |
+
f"the installed huggingface_hub has no {method}(); "
|
| 139 |
+
"upgrade with: pip install -U 'huggingface-hub>=1.19'"
|
| 140 |
+
)
|
| 141 |
+
return function
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def create_schedule(
|
| 145 |
+
spec: JobSpec,
|
| 146 |
+
*,
|
| 147 |
+
schedule: str = DEFAULT_SCHEDULE,
|
| 148 |
+
secrets: dict[str, str],
|
| 149 |
+
namespace: str | None = None,
|
| 150 |
+
token: str | None = None,
|
| 151 |
+
) -> Any:
|
| 152 |
+
api = _api(token)
|
| 153 |
+
return _require(api, "create_scheduled_uv_job")(
|
| 154 |
+
schedule=schedule,
|
| 155 |
+
namespace=namespace,
|
| 156 |
+
**spec.as_kwargs(secrets=secrets),
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def run_once(
|
| 161 |
+
spec: JobSpec,
|
| 162 |
+
*,
|
| 163 |
+
secrets: dict[str, str],
|
| 164 |
+
namespace: str | None = None,
|
| 165 |
+
token: str | None = None,
|
| 166 |
+
) -> Any:
|
| 167 |
+
api = _api(token)
|
| 168 |
+
return _require(api, "run_uv_job")(namespace=namespace, **spec.as_kwargs(secrets=secrets))
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
def list_schedules(*, namespace: str | None = None, token: str | None = None) -> list[Any]:
|
| 172 |
+
api = _api(token)
|
| 173 |
+
return list(_require(api, "list_scheduled_jobs")(namespace=namespace))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def inspect_schedule(
|
| 177 |
+
scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
|
| 178 |
+
) -> Any:
|
| 179 |
+
api = _api(token)
|
| 180 |
+
return _require(api, "inspect_scheduled_job")(
|
| 181 |
+
scheduled_job_id=scheduled_job_id, namespace=namespace
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def delete_schedule(
|
| 186 |
+
scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
|
| 187 |
+
) -> None:
|
| 188 |
+
api = _api(token)
|
| 189 |
+
_require(api, "delete_scheduled_job")(scheduled_job_id=scheduled_job_id, namespace=namespace)
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def suspend_schedule(
|
| 193 |
+
scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
|
| 194 |
+
) -> Any:
|
| 195 |
+
api = _api(token)
|
| 196 |
+
return _require(api, "suspend_scheduled_job")(
|
| 197 |
+
scheduled_job_id=scheduled_job_id, namespace=namespace
|
| 198 |
+
)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
def resume_schedule(
|
| 202 |
+
scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
|
| 203 |
+
) -> Any:
|
| 204 |
+
api = _api(token)
|
| 205 |
+
return _require(api, "resume_scheduled_job")(
|
| 206 |
+
scheduled_job_id=scheduled_job_id, namespace=namespace
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
__all__ = [
|
| 211 |
+
"BACKFILL_FLAVOR",
|
| 212 |
+
"BACKFILL_TIMEOUT",
|
| 213 |
+
"DEFAULT_SCHEDULE",
|
| 214 |
+
"JOB_SCRIPT",
|
| 215 |
+
"UPDATE_FLAVOR",
|
| 216 |
+
"UPDATE_TIMEOUT",
|
| 217 |
+
"JobSpec",
|
| 218 |
+
"backfill_spec",
|
| 219 |
+
"create_schedule",
|
| 220 |
+
"delete_schedule",
|
| 221 |
+
"inspect_schedule",
|
| 222 |
+
"job_secrets",
|
| 223 |
+
"list_schedules",
|
| 224 |
+
"resume_schedule",
|
| 225 |
+
"run_once",
|
| 226 |
+
"script_url",
|
| 227 |
+
"suspend_schedule",
|
| 228 |
+
"update_spec",
|
| 229 |
+
]
|
recipe/manifest.py
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 .schema import BUILD_VERSION, CONFIG_SCHEMAS
|
| 17 |
+
from .store import read_table
|
| 18 |
+
from .taxonomy import INDUSTRIES, SECTORS, TAXONOMY_VERSION
|
| 19 |
+
|
| 20 |
+
RECIPE_ROOT = Path(__file__).resolve().parent.parent
|
| 21 |
+
|
| 22 |
+
CONFIG_DESCRIPTIONS: dict[str, dict[str, str]] = {
|
| 23 |
+
"classification": {
|
| 24 |
+
"path": "data/classification/**/*.parquet",
|
| 25 |
+
"grain": "one SEC filer, with the sector and industry it is in now",
|
| 26 |
+
},
|
| 27 |
+
"by_ticker": {
|
| 28 |
+
"path": "data/by_ticker/**/*.parquet",
|
| 29 |
+
"grain": "one ticker over one window, with the sector it was in then",
|
| 30 |
+
},
|
| 31 |
+
"spans": {
|
| 32 |
+
"path": "data/spans/**/*.parquet",
|
| 33 |
+
"grain": "one run of filings that all stated the same SIC code",
|
| 34 |
+
},
|
| 35 |
+
"observations": {
|
| 36 |
+
"path": "data/observations/**/*.parquet",
|
| 37 |
+
"grain": "one dated statement that a filer was assigned a SIC code",
|
| 38 |
+
},
|
| 39 |
+
"sic_codes": {
|
| 40 |
+
"path": "data/sic_codes/**/*.parquet",
|
| 41 |
+
"grain": "one EDGAR SIC code, with its hierarchy, sector and NAICS bridge",
|
| 42 |
+
},
|
| 43 |
+
"naics_map": {
|
| 44 |
+
"path": "data/naics_map/**/*.parquet",
|
| 45 |
+
"grain": "one 1987 SIC to 1997 NAICS pair from the Census concordance",
|
| 46 |
+
},
|
| 47 |
+
"taxonomy": {
|
| 48 |
+
"path": "data/taxonomy/**/*.parquet",
|
| 49 |
+
"grain": "one industry of the ZipLime taxonomy and the SIC ranges it covers",
|
| 50 |
+
},
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def recipe_hash(project_root: Path | None = None) -> str:
|
| 55 |
+
"""Hash of the code that produced a build.
|
| 56 |
+
|
| 57 |
+
The taxonomy is part of the recipe rather than part of the data, so this
|
| 58 |
+
hash is what tells two revisions of the dataset apart when the sources did
|
| 59 |
+
not move but an industry was reassigned.
|
| 60 |
+
"""
|
| 61 |
+
root = (project_root or RECIPE_ROOT).resolve()
|
| 62 |
+
digest = hashlib.sha256()
|
| 63 |
+
files = sorted(
|
| 64 |
+
{
|
| 65 |
+
path
|
| 66 |
+
for pattern in ("recipe/**/*.py", "jobs/**/*.py", "tests/**/*.py", "pyproject.toml")
|
| 67 |
+
for path in root.glob(pattern)
|
| 68 |
+
if path.is_file()
|
| 69 |
+
}
|
| 70 |
+
)
|
| 71 |
+
if not files:
|
| 72 |
+
raise FileNotFoundError(f"no recipe sources under {root}")
|
| 73 |
+
for path in files:
|
| 74 |
+
digest.update(str(path.relative_to(root)).encode())
|
| 75 |
+
digest.update(b"\0")
|
| 76 |
+
digest.update(path.read_bytes())
|
| 77 |
+
digest.update(b"\0")
|
| 78 |
+
return f"sha256:{digest.hexdigest()}"
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _coverage(data_dir: Path) -> dict[str, str | None]:
|
| 82 |
+
bounds = (
|
| 83 |
+
read_table(data_dir, "observations")
|
| 84 |
+
.select(
|
| 85 |
+
pl.col("stated_on").min().alias("min_statement"),
|
| 86 |
+
pl.col("stated_on").max().alias("max_statement"),
|
| 87 |
+
)
|
| 88 |
+
.collect()
|
| 89 |
+
)
|
| 90 |
+
if bounds.is_empty():
|
| 91 |
+
return {}
|
| 92 |
+
row = bounds.row(0, named=True)
|
| 93 |
+
return {k: (v.isoformat() if v is not None else None) for k, v in row.items()}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def build_manifest(
|
| 97 |
+
*, data_dir: Path, row_counts: dict[str, int], quality_ok: bool
|
| 98 |
+
) -> dict[str, Any]:
|
| 99 |
+
data_dir = Path(data_dir)
|
| 100 |
+
project_root = data_dir.resolve().parent
|
| 101 |
+
path = project_root / "manifest.json"
|
| 102 |
+
manifest: dict[str, Any] = json.loads(path.read_text()) if path.exists() else {}
|
| 103 |
+
|
| 104 |
+
manifest["generated_at"] = datetime.now(UTC).isoformat()
|
| 105 |
+
manifest["rows"] = row_counts.get("classification", 0)
|
| 106 |
+
manifest["config_rows"] = row_counts
|
| 107 |
+
manifest["configs"] = CONFIG_DESCRIPTIONS
|
| 108 |
+
manifest["coverage"] = _coverage(data_dir)
|
| 109 |
+
manifest["quality_ok"] = quality_ok
|
| 110 |
+
manifest["sectors"] = dict(SECTORS)
|
| 111 |
+
manifest["industries"] = {
|
| 112 |
+
code: {"sector": sector, "title": title}
|
| 113 |
+
for code, (sector, title) in INDUSTRIES.items()
|
| 114 |
+
}
|
| 115 |
+
manifest["config_schemas"] = {
|
| 116 |
+
name: {column: str(dtype) for column, dtype in schema.items()}
|
| 117 |
+
for name, schema in CONFIG_SCHEMAS.items()
|
| 118 |
+
}
|
| 119 |
+
source = dict(manifest.get("source") or {})
|
| 120 |
+
source["recipe_hash"] = recipe_hash()
|
| 121 |
+
source["build_version"] = BUILD_VERSION
|
| 122 |
+
source["taxonomy_version"] = TAXONOMY_VERSION
|
| 123 |
+
source["package_version"] = __version__
|
| 124 |
+
manifest["source"] = source
|
| 125 |
+
|
| 126 |
+
descriptor, temporary = tempfile.mkstemp(prefix=".manifest-", suffix=".json", dir=project_root)
|
| 127 |
+
try:
|
| 128 |
+
with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
|
| 129 |
+
json.dump(manifest, handle, indent=2, sort_keys=True, ensure_ascii=False)
|
| 130 |
+
handle.write("\n")
|
| 131 |
+
handle.flush()
|
| 132 |
+
os.fsync(handle.fileno())
|
| 133 |
+
os.replace(temporary, path)
|
| 134 |
+
finally:
|
| 135 |
+
if os.path.exists(temporary):
|
| 136 |
+
os.unlink(temporary)
|
| 137 |
+
return manifest
|
recipe/naics.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The 1997 NAICS sectors, and what the crosswalk to them can and cannot say.
|
| 2 |
+
|
| 3 |
+
The Census Bureau publishes a concordance from 1987 SIC to 1997 NAICS, which
|
| 4 |
+
is the only free, official bridge between the classification the SEC still
|
| 5 |
+
assigns and the one the rest of the US statistical system moved to in 1997.
|
| 6 |
+
|
| 7 |
+
It is a weak bridge and the numbers say so. Measured over the filings in this
|
| 8 |
+
corpus: 36% land on exactly one NAICS industry, 70% on exactly one NAICS
|
| 9 |
+
sector, and 5% on nothing at all. The rest are one-to-many -- a 1987 industry
|
| 10 |
+
that 1997 split in two, marked `pt` for "part" in the source file.
|
| 11 |
+
|
| 12 |
+
So NAICS is published here as a crosswalk, not as an answer. `naics_1997` is
|
| 13 |
+
filled only where a code resolves to exactly one industry, `naics_sector` only
|
| 14 |
+
where it resolves to exactly one sector, and `naics_candidates` says how many
|
| 15 |
+
there were. A single NAICS per company, picked by a tie-break, would read as
|
| 16 |
+
fact and be a coin toss.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
|
| 21 |
+
# 1997 NAICS sectors. Manufacturing, retail and transportation each span
|
| 22 |
+
# several two-digit prefixes, which is why this is a map rather than a slice.
|
| 23 |
+
NAICS_SECTORS: dict[str, str] = {
|
| 24 |
+
"11": "Agriculture, Forestry, Fishing and Hunting",
|
| 25 |
+
"21": "Mining",
|
| 26 |
+
"22": "Utilities",
|
| 27 |
+
"23": "Construction",
|
| 28 |
+
"31": "Manufacturing",
|
| 29 |
+
"32": "Manufacturing",
|
| 30 |
+
"33": "Manufacturing",
|
| 31 |
+
"42": "Wholesale Trade",
|
| 32 |
+
"44": "Retail Trade",
|
| 33 |
+
"45": "Retail Trade",
|
| 34 |
+
"48": "Transportation and Warehousing",
|
| 35 |
+
"49": "Transportation and Warehousing",
|
| 36 |
+
"51": "Information",
|
| 37 |
+
"52": "Finance and Insurance",
|
| 38 |
+
"53": "Real Estate and Rental and Leasing",
|
| 39 |
+
"54": "Professional, Scientific, and Technical Services",
|
| 40 |
+
"55": "Management of Companies and Enterprises",
|
| 41 |
+
"56": "Administrative and Support and Waste Management and Remediation Services",
|
| 42 |
+
"61": "Educational Services",
|
| 43 |
+
"62": "Health Care and Social Assistance",
|
| 44 |
+
"71": "Arts, Entertainment, and Recreation",
|
| 45 |
+
"72": "Accommodation and Food Services",
|
| 46 |
+
"81": "Other Services (except Public Administration)",
|
| 47 |
+
"92": "Public Administration",
|
| 48 |
+
"99": "Unclassified",
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def sector_of(naics: str | None) -> tuple[str | None, str | None]:
|
| 53 |
+
"""The sector a NAICS code belongs to, as (code, title)."""
|
| 54 |
+
if not naics or len(naics) < 2:
|
| 55 |
+
return None, None
|
| 56 |
+
prefix = naics[:2]
|
| 57 |
+
title = NAICS_SECTORS.get(prefix)
|
| 58 |
+
return (prefix, title) if title else (None, None)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
__all__ = ["NAICS_SECTORS", "sector_of"]
|
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 / "classification").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="industry-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 industry classification",
|
| 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,300 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Checks that decide whether a build may be published.
|
| 2 |
+
|
| 3 |
+
A classification dataset fails quietly. Nothing raises when a bank is labelled
|
| 4 |
+
a materials company: the backtest runs, the sector-neutral hedge is placed
|
| 5 |
+
against the wrong basket, and the result looks plausible. So the checks here
|
| 6 |
+
are about the shape of the answer rather than its plumbing.
|
| 7 |
+
|
| 8 |
+
Two of them earn their place:
|
| 9 |
+
|
| 10 |
+
* how much of the live universe is unclassified. The SEC adds codes -- asset
|
| 11 |
+
backed securities and crypto assets both arrived after the 1987 manual --
|
| 12 |
+
and nothing else in the pipeline would notice that a new one fell through
|
| 13 |
+
the taxonomy into the catch-all.
|
| 14 |
+
* how much of it lands in the single largest sector. The reason this dataset
|
| 15 |
+
exists is that the SIC divisions are unusable for investing, Manufacturing
|
| 16 |
+
alone being a third of the listed universe. A regression that collapsed the
|
| 17 |
+
taxonomy back towards its input would show up here and nowhere else.
|
| 18 |
+
|
| 19 |
+
The floors are set below measured values so a regression fails and noise does
|
| 20 |
+
not. All of them were set after measuring.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
from __future__ import annotations
|
| 24 |
+
|
| 25 |
+
import json
|
| 26 |
+
from dataclasses import dataclass, field
|
| 27 |
+
from datetime import UTC, datetime
|
| 28 |
+
from pathlib import Path
|
| 29 |
+
from typing import Any
|
| 30 |
+
|
| 31 |
+
import polars as pl
|
| 32 |
+
|
| 33 |
+
from .store import read_table
|
| 34 |
+
from .taxonomy import INDUSTRIES, RULES, SECTORS
|
| 35 |
+
|
| 36 |
+
MIN_CLASSIFIED_FILERS = 20_000
|
| 37 |
+
MIN_EDGAR_CODES = 400
|
| 38 |
+
# Share of current tickers the dataset says something positive about. A
|
| 39 |
+
# closed-end fund and a depositary receipt programme count: "this is a fund"
|
| 40 |
+
# is an answer, and the point of the measure is to catch symbols the dataset
|
| 41 |
+
# knows nothing whatsoever about.
|
| 42 |
+
MIN_CURRENT_TICKER_COVERAGE = 0.95
|
| 43 |
+
# Share of the live universe the dataset can say nothing at all about --
|
| 44 |
+
# `UNCL_OTHER`, not `UNCL_ADR`, because "this is a depositary receipt
|
| 45 |
+
# programme" is an answer. Measured at zero; the ceiling is for regressions.
|
| 46 |
+
MAX_UNCLASSIFIED = 0.02
|
| 47 |
+
# Symbols current for two filers that disagree about the sector. Measured at
|
| 48 |
+
# 30, and every one checked was real: a ticker genuinely transferred (Barnes
|
| 49 |
+
# Group to Barrick), a symbol reused after a delisting, or a fund whose Form 4
|
| 50 |
+
# ticker box holds a share class. A lot more would mean the security master is
|
| 51 |
+
# stitching histories to the wrong companies, which this would notice first.
|
| 52 |
+
MAX_CONTRADICTORY_TICKERS = 40
|
| 53 |
+
# Share of the live universe in the single largest sector. The SIC division
|
| 54 |
+
# this replaces puts a third of the universe in Manufacturing.
|
| 55 |
+
MAX_LARGEST_SECTOR = 0.30
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass
|
| 59 |
+
class QualityReport:
|
| 60 |
+
errors: list[str] = field(default_factory=list)
|
| 61 |
+
warnings: list[str] = field(default_factory=list)
|
| 62 |
+
metrics: dict[str, Any] = field(default_factory=dict)
|
| 63 |
+
|
| 64 |
+
def error(self, message: str) -> None:
|
| 65 |
+
self.errors.append(message)
|
| 66 |
+
|
| 67 |
+
def warn(self, message: str) -> None:
|
| 68 |
+
self.warnings.append(message)
|
| 69 |
+
|
| 70 |
+
def metric(self, name: str, value: Any) -> None:
|
| 71 |
+
self.metrics[name] = value
|
| 72 |
+
|
| 73 |
+
@property
|
| 74 |
+
def ok(self) -> bool:
|
| 75 |
+
return not self.errors
|
| 76 |
+
|
| 77 |
+
def as_dict(self) -> dict[str, Any]:
|
| 78 |
+
return {
|
| 79 |
+
"ok": self.ok,
|
| 80 |
+
"generated_at": datetime.now(UTC).isoformat(),
|
| 81 |
+
"errors": self.errors,
|
| 82 |
+
"warnings": self.warnings,
|
| 83 |
+
"metrics": self.metrics,
|
| 84 |
+
}
|
| 85 |
+
|
| 86 |
+
def write(self, path: Path) -> None:
|
| 87 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 88 |
+
path.write_text(json.dumps(self.as_dict(), indent=2, default=str), encoding="utf-8")
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def check_taxonomy(report: QualityReport) -> None:
|
| 92 |
+
"""The taxonomy is code, so it is checked like code.
|
| 93 |
+
|
| 94 |
+
Every rule has to name an industry that exists and every industry a sector
|
| 95 |
+
that exists, or the build writes nulls into the column the whole dataset
|
| 96 |
+
is for.
|
| 97 |
+
"""
|
| 98 |
+
unknown_industries = {code for _, _, code in RULES if code not in INDUSTRIES}
|
| 99 |
+
if unknown_industries:
|
| 100 |
+
report.error(f"RULES name industries that do not exist: {sorted(unknown_industries)}")
|
| 101 |
+
unknown_sectors = {
|
| 102 |
+
sector for sector, _ in INDUSTRIES.values() if sector not in SECTORS
|
| 103 |
+
}
|
| 104 |
+
if unknown_sectors:
|
| 105 |
+
report.error(f"INDUSTRIES name sectors that do not exist: {sorted(unknown_sectors)}")
|
| 106 |
+
inverted = [(low, high) for low, high, _ in RULES if low > high]
|
| 107 |
+
if inverted:
|
| 108 |
+
report.error(f"RULES has {len(inverted)} inverted ranges, e.g. {inverted[:3]}")
|
| 109 |
+
report.metric("taxonomy_sectors", len(SECTORS))
|
| 110 |
+
report.metric("taxonomy_industries", len(INDUSTRIES))
|
| 111 |
+
report.metric("taxonomy_rules", len(RULES))
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def validate(data_dir: Path) -> QualityReport:
|
| 115 |
+
report = QualityReport()
|
| 116 |
+
data_dir = Path(data_dir)
|
| 117 |
+
check_taxonomy(report)
|
| 118 |
+
|
| 119 |
+
tables = {
|
| 120 |
+
name: read_table(data_dir, name).collect()
|
| 121 |
+
for name in ("classification", "by_ticker", "spans", "observations", "sic_codes",
|
| 122 |
+
"naics_map", "taxonomy")
|
| 123 |
+
}
|
| 124 |
+
for name, frame in tables.items():
|
| 125 |
+
report.metric(f"rows_{name}", frame.height)
|
| 126 |
+
|
| 127 |
+
classification = tables["classification"]
|
| 128 |
+
if classification.is_empty():
|
| 129 |
+
report.error("classification is empty")
|
| 130 |
+
return report
|
| 131 |
+
if classification.height < MIN_CLASSIFIED_FILERS:
|
| 132 |
+
report.error(
|
| 133 |
+
f"only {classification.height} filers classified, "
|
| 134 |
+
f"below the {MIN_CLASSIFIED_FILERS} floor"
|
| 135 |
+
)
|
| 136 |
+
if classification["cik"].n_unique() != classification.height:
|
| 137 |
+
report.error("classification: duplicate CIKs")
|
| 138 |
+
for column in ("sector_code", "industry_code"):
|
| 139 |
+
nulls = classification[column].null_count()
|
| 140 |
+
if nulls:
|
| 141 |
+
report.error(f"classification.{column}: {nulls} nulls")
|
| 142 |
+
# A null code is legitimate exactly where the sector came from the forms a
|
| 143 |
+
# filer files rather than from a code the SEC assigned. Anywhere else it
|
| 144 |
+
# means a row lost its join.
|
| 145 |
+
assigned = classification.filter(pl.col("source") != "edgar_forms")
|
| 146 |
+
orphans = assigned.filter(pl.col("sic").is_null()).height
|
| 147 |
+
if orphans:
|
| 148 |
+
report.error(f"classification: {orphans} rows have no SIC and no reason to lack one")
|
| 149 |
+
derived = classification.height - assigned.height
|
| 150 |
+
report.metric("classified_from_forms", derived)
|
| 151 |
+
|
| 152 |
+
observations = tables["observations"]
|
| 153 |
+
for column in ("cik", "sic", "stated_on", "source"):
|
| 154 |
+
nulls = observations[column].null_count()
|
| 155 |
+
if nulls:
|
| 156 |
+
report.error(f"observations.{column}: {nulls} nulls")
|
| 157 |
+
report.metric(
|
| 158 |
+
"observations_by_source",
|
| 159 |
+
{
|
| 160 |
+
row["source"]: row["n"]
|
| 161 |
+
for row in observations.group_by("source").agg(pl.len().alias("n")).iter_rows(
|
| 162 |
+
named=True
|
| 163 |
+
)
|
| 164 |
+
},
|
| 165 |
+
)
|
| 166 |
+
bounds = observations.select(
|
| 167 |
+
pl.col("stated_on").min().alias("first"), pl.col("stated_on").max().alias("last")
|
| 168 |
+
).row(0)
|
| 169 |
+
report.metric("coverage_first_statement", str(bounds[0]))
|
| 170 |
+
report.metric("coverage_last_statement", str(bounds[1]))
|
| 171 |
+
|
| 172 |
+
spans = tables["spans"]
|
| 173 |
+
reversed_spans = spans.filter(pl.col("valid_to") < pl.col("valid_from")).height
|
| 174 |
+
if reversed_spans:
|
| 175 |
+
report.error(f"spans: {reversed_spans} spans end before they start")
|
| 176 |
+
changed = spans.group_by("cik").agg(pl.len().alias("n")).filter(pl.col("n") > 1).height
|
| 177 |
+
report.metric("filers_reclassified", changed)
|
| 178 |
+
|
| 179 |
+
reference = tables["sic_codes"]
|
| 180 |
+
if reference.height < MIN_EDGAR_CODES:
|
| 181 |
+
report.error(
|
| 182 |
+
f"only {reference.height} EDGAR codes, below the {MIN_EDGAR_CODES} floor"
|
| 183 |
+
)
|
| 184 |
+
missing_titles = reference.filter(
|
| 185 |
+
pl.col("title").is_null() | (pl.col("title").str.strip_chars() == "")
|
| 186 |
+
).height
|
| 187 |
+
if missing_titles:
|
| 188 |
+
report.error(f"sic_codes: {missing_titles} codes with no title")
|
| 189 |
+
missing_groups = reference.filter(pl.col("major_group_title").is_null()).height
|
| 190 |
+
if missing_groups:
|
| 191 |
+
report.warn(f"sic_codes: {missing_groups} codes with no major group title")
|
| 192 |
+
report.metric(
|
| 193 |
+
"sic_codes_by_level",
|
| 194 |
+
{
|
| 195 |
+
row["sic_level"]: row["n"]
|
| 196 |
+
for row in reference.group_by("sic_level").agg(pl.len().alias("n")).iter_rows(
|
| 197 |
+
named=True
|
| 198 |
+
)
|
| 199 |
+
},
|
| 200 |
+
)
|
| 201 |
+
report.metric(
|
| 202 |
+
"naics_unique_industry",
|
| 203 |
+
round(reference.filter(pl.col("naics_1997").is_not_null()).height / reference.height, 4),
|
| 204 |
+
)
|
| 205 |
+
report.metric(
|
| 206 |
+
"naics_unique_sector",
|
| 207 |
+
round(
|
| 208 |
+
reference.filter(pl.col("naics_sector").is_not_null()).height / reference.height, 4
|
| 209 |
+
),
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
# The live universe: filers that still file and still have a symbol. The
|
| 213 |
+
# shape checks are about this set, not about every shell that ever filed.
|
| 214 |
+
live = classification.filter(
|
| 215 |
+
pl.col("is_active").fill_null(False) & pl.col("primary_ticker").is_not_null()
|
| 216 |
+
)
|
| 217 |
+
report.metric("live_filers", live.height)
|
| 218 |
+
if not live.is_empty():
|
| 219 |
+
shares = (
|
| 220 |
+
live.group_by("sector_code")
|
| 221 |
+
.agg(pl.len().alias("n"))
|
| 222 |
+
.with_columns((pl.col("n") / live.height).alias("share"))
|
| 223 |
+
.sort("share", descending=True)
|
| 224 |
+
)
|
| 225 |
+
report.metric(
|
| 226 |
+
"live_sector_share",
|
| 227 |
+
{row["sector_code"]: round(row["share"], 4) for row in shares.iter_rows(named=True)},
|
| 228 |
+
)
|
| 229 |
+
unclassified = live.filter(pl.col("industry_code") == "UNCL_OTHER").height / live.height
|
| 230 |
+
report.metric("live_unclassified_share", round(unclassified, 4))
|
| 231 |
+
report.metric(
|
| 232 |
+
"live_depositary_receipt_share",
|
| 233 |
+
round(live.filter(pl.col("industry_code") == "UNCL_ADR").height / live.height, 4),
|
| 234 |
+
)
|
| 235 |
+
if unclassified > MAX_UNCLASSIFIED:
|
| 236 |
+
report.error(
|
| 237 |
+
f"{unclassified:.1%} of the live universe is unclassified, above the "
|
| 238 |
+
f"{MAX_UNCLASSIFIED:.0%} ceiling — the SEC has probably added a code"
|
| 239 |
+
)
|
| 240 |
+
largest = shares.row(0, named=True)
|
| 241 |
+
report.metric("largest_live_sector", f"{largest['sector_code']} {largest['share']:.1%}")
|
| 242 |
+
if largest["share"] > MAX_LARGEST_SECTOR:
|
| 243 |
+
report.error(
|
| 244 |
+
f"sector {largest['sector_code']} holds {largest['share']:.1%} of the live "
|
| 245 |
+
f"universe, above the {MAX_LARGEST_SECTOR:.0%} ceiling — the taxonomy has "
|
| 246 |
+
"collapsed towards its input"
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
by_ticker = tables["by_ticker"]
|
| 250 |
+
current = by_ticker.filter(pl.col("is_current").fill_null(False))
|
| 251 |
+
report.metric("current_ticker_rows", current.height)
|
| 252 |
+
if not current.is_empty():
|
| 253 |
+
symbols = current["ticker"].n_unique()
|
| 254 |
+
named = current.filter(pl.col("industry_code") != "UNCL_OTHER")["ticker"].n_unique()
|
| 255 |
+
coverage = named / symbols
|
| 256 |
+
report.metric("current_tickers", symbols)
|
| 257 |
+
report.metric("current_ticker_coverage", round(coverage, 4))
|
| 258 |
+
if coverage < MIN_CURRENT_TICKER_COVERAGE:
|
| 259 |
+
report.error(
|
| 260 |
+
f"only {coverage:.1%} of current tickers resolve to a sector, below the "
|
| 261 |
+
f"{MIN_CURRENT_TICKER_COVERAGE:.0%} floor"
|
| 262 |
+
)
|
| 263 |
+
# A symbol current for two filers is the security master's known
|
| 264 |
+
# ambiguity, inherited here. It only hurts if the two disagree about
|
| 265 |
+
# what business the company is in.
|
| 266 |
+
shared = (
|
| 267 |
+
current.group_by("ticker")
|
| 268 |
+
.agg(pl.col("cik").n_unique().alias("filers"),
|
| 269 |
+
pl.col("sector_code").n_unique().alias("sectors"))
|
| 270 |
+
.filter(pl.col("filers") > 1)
|
| 271 |
+
)
|
| 272 |
+
report.metric("ambiguous_current_tickers", shared.height)
|
| 273 |
+
contradictory = shared.filter(pl.col("sectors") > 1).height
|
| 274 |
+
report.metric("contradictory_current_tickers", contradictory)
|
| 275 |
+
if contradictory > MAX_CONTRADICTORY_TICKERS:
|
| 276 |
+
report.warn(
|
| 277 |
+
f"{contradictory} symbols are current for two filers that disagree "
|
| 278 |
+
"about the sector"
|
| 279 |
+
)
|
| 280 |
+
report.metric(
|
| 281 |
+
"current_tickers_by_industry_group",
|
| 282 |
+
{
|
| 283 |
+
row["industry_code"]: row["n"]
|
| 284 |
+
for row in current.filter(pl.col("sector_code").is_in(["UNCL", "FUND"]))
|
| 285 |
+
.group_by("industry_code").agg(pl.len().alias("n")).iter_rows(named=True)
|
| 286 |
+
},
|
| 287 |
+
)
|
| 288 |
+
report.metric(
|
| 289 |
+
"by_ticker_date_basis",
|
| 290 |
+
{
|
| 291 |
+
row["date_basis"]: row["n"]
|
| 292 |
+
for row in by_ticker.group_by("date_basis").agg(pl.len().alias("n")).iter_rows(
|
| 293 |
+
named=True
|
| 294 |
+
)
|
| 295 |
+
},
|
| 296 |
+
)
|
| 297 |
+
return report
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
__all__ = ["QualityReport", "check_taxonomy", "validate"]
|
recipe/schema.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# One dated statement that the SEC had a filer under a given code. This is the
|
| 14 |
+
# evidence layer; everything else is a groupby over it, and anyone who
|
| 15 |
+
# disagrees with how the spans were cut can cut their own.
|
| 16 |
+
OBSERVATION_SCHEMA: dict[str, pl.DataType] = {
|
| 17 |
+
"cik": pl.String,
|
| 18 |
+
"sic": pl.String,
|
| 19 |
+
"stated_on": pl.Date,
|
| 20 |
+
"knowledge_time": UTC_DATETIME,
|
| 21 |
+
# "xbrl" for a code read off a filing header, "submissions" for one read
|
| 22 |
+
# off EDGAR's current record of the filer. The second carries no history:
|
| 23 |
+
# it is what the SEC says today, dated the day the build ran.
|
| 24 |
+
"source": pl.String,
|
| 25 |
+
"source_ref": pl.String,
|
| 26 |
+
"is_dated": pl.Boolean,
|
| 27 |
+
"inserted_at": UTC_DATETIME,
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
# A run of consecutive filings that all stated the same code.
|
| 31 |
+
#
|
| 32 |
+
# `valid_to` is the last filing that stated it, not the day it stopped being
|
| 33 |
+
# true. A company that files nothing for two years has a two-year gap in its
|
| 34 |
+
# evidence, and pretending the span runs to the next filing would invent a
|
| 35 |
+
# fact nobody published.
|
| 36 |
+
SPAN_SCHEMA: dict[str, pl.DataType] = {
|
| 37 |
+
"cik": pl.String,
|
| 38 |
+
"sic": pl.String,
|
| 39 |
+
"valid_from": pl.Date,
|
| 40 |
+
"valid_to": pl.Date,
|
| 41 |
+
"observations": pl.Int32,
|
| 42 |
+
"sources": pl.String,
|
| 43 |
+
"is_latest": pl.Boolean,
|
| 44 |
+
"rank_for_filer": pl.Int32,
|
| 45 |
+
"sector_code": pl.String,
|
| 46 |
+
"sector": pl.String,
|
| 47 |
+
"industry_code": pl.String,
|
| 48 |
+
"industry": pl.String,
|
| 49 |
+
"inserted_at": UTC_DATETIME,
|
| 50 |
+
}
|
| 51 |
+
|
| 52 |
+
# What a filer is classified as now: the newest code it has been seen under,
|
| 53 |
+
# resolved all the way down the taxonomy and joined to its tickers.
|
| 54 |
+
CLASSIFICATION_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 |
+
"is_active": pl.Boolean,
|
| 61 |
+
"sic": pl.String,
|
| 62 |
+
"sic_title": pl.String,
|
| 63 |
+
# "industry" for a real 1987 four-digit code, "industry_group" or
|
| 64 |
+
# "major_group" for one the SEC padded with zeros because it did not care
|
| 65 |
+
# to be more precise.
|
| 66 |
+
"sic_level": pl.String,
|
| 67 |
+
"sec_office": pl.String,
|
| 68 |
+
"division": pl.String,
|
| 69 |
+
"division_title": pl.String,
|
| 70 |
+
"major_group": pl.String,
|
| 71 |
+
"major_group_title": pl.String,
|
| 72 |
+
"industry_group": pl.String,
|
| 73 |
+
"sector_code": pl.String,
|
| 74 |
+
"sector": pl.String,
|
| 75 |
+
"industry_code": pl.String,
|
| 76 |
+
"industry": pl.String,
|
| 77 |
+
"naics_1997": pl.String,
|
| 78 |
+
"naics_title": pl.String,
|
| 79 |
+
"naics_sector": pl.String,
|
| 80 |
+
"naics_sector_title": pl.String,
|
| 81 |
+
"naics_candidates": pl.Int32,
|
| 82 |
+
"stated_on": pl.Date,
|
| 83 |
+
"observations": pl.Int32,
|
| 84 |
+
"source": pl.String,
|
| 85 |
+
"is_dated": pl.Boolean,
|
| 86 |
+
"first_seen": pl.Date,
|
| 87 |
+
"taxonomy_version": pl.String,
|
| 88 |
+
"inserted_at": UTC_DATETIME,
|
| 89 |
+
}
|
| 90 |
+
|
| 91 |
+
# The same answer keyed the way a strategy asks the question: by the symbol it
|
| 92 |
+
# trades, over the window the symbol belonged to that company.
|
| 93 |
+
TICKER_SCHEMA: dict[str, pl.DataType] = {
|
| 94 |
+
"ticker": pl.String,
|
| 95 |
+
"cik": pl.String,
|
| 96 |
+
"name": pl.String,
|
| 97 |
+
"exchange": pl.String,
|
| 98 |
+
"valid_from": pl.Date,
|
| 99 |
+
"valid_to": pl.Date,
|
| 100 |
+
"sic": pl.String,
|
| 101 |
+
"sector_code": pl.String,
|
| 102 |
+
"sector": pl.String,
|
| 103 |
+
"industry_code": pl.String,
|
| 104 |
+
"industry": pl.String,
|
| 105 |
+
# How much the dates are worth:
|
| 106 |
+
# "dated" - the window is the overlap of a ticker span and a code span,
|
| 107 |
+
# both backed by filings. The code was in force then.
|
| 108 |
+
# "undated" - a code is known for the filer, but nothing dates it to this
|
| 109 |
+
# window: either it came from today's snapshot, or the spans
|
| 110 |
+
# simply do not overlap. The filer's latest code is applied
|
| 111 |
+
# across the whole window.
|
| 112 |
+
# "unknown" - no code at all; the sector, if any, came from the forms the
|
| 113 |
+
# filer files.
|
| 114 |
+
"date_basis": pl.String,
|
| 115 |
+
"is_current": pl.Boolean,
|
| 116 |
+
"inserted_at": UTC_DATETIME,
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
# EDGAR's own list of the codes it assigns, with everything derivable from a
|
| 120 |
+
# code hung off it. 444 rows, and the join target for the three tables above.
|
| 121 |
+
SIC_CODE_SCHEMA: dict[str, pl.DataType] = {
|
| 122 |
+
"sic": pl.String,
|
| 123 |
+
"title": pl.String,
|
| 124 |
+
"sec_office": pl.String,
|
| 125 |
+
"sic_level": pl.String,
|
| 126 |
+
"in_sic_1987": pl.Boolean,
|
| 127 |
+
"division": pl.String,
|
| 128 |
+
"division_title": pl.String,
|
| 129 |
+
"major_group": pl.String,
|
| 130 |
+
"major_group_title": pl.String,
|
| 131 |
+
"industry_group": pl.String,
|
| 132 |
+
"sector_code": pl.String,
|
| 133 |
+
"sector": pl.String,
|
| 134 |
+
"industry_code": pl.String,
|
| 135 |
+
"industry": pl.String,
|
| 136 |
+
"naics_1997": pl.String,
|
| 137 |
+
"naics_title": pl.String,
|
| 138 |
+
"naics_sector": pl.String,
|
| 139 |
+
"naics_sector_title": pl.String,
|
| 140 |
+
"naics_candidates": pl.Int32,
|
| 141 |
+
"filers": pl.Int32,
|
| 142 |
+
"filings": pl.Int32,
|
| 143 |
+
"inserted_at": UTC_DATETIME,
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
# The Census crosswalk as published: one row per (SIC, NAICS) pair, with the
|
| 147 |
+
# part description where one 1987 industry was split across several 1997 ones.
|
| 148 |
+
NAICS_MAP_SCHEMA: dict[str, pl.DataType] = {
|
| 149 |
+
"sic": pl.String,
|
| 150 |
+
"sic_title": pl.String,
|
| 151 |
+
"is_part": pl.Boolean,
|
| 152 |
+
"part_description": pl.String,
|
| 153 |
+
"naics_1997": pl.String,
|
| 154 |
+
"naics_title": pl.String,
|
| 155 |
+
"naics_sector": pl.String,
|
| 156 |
+
"naics_sector_title": pl.String,
|
| 157 |
+
"inserted_at": UTC_DATETIME,
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
# The taxonomy itself, so it can be read without reading Python.
|
| 161 |
+
TAXONOMY_SCHEMA: dict[str, pl.DataType] = {
|
| 162 |
+
"sector_code": pl.String,
|
| 163 |
+
"sector": pl.String,
|
| 164 |
+
"industry_code": pl.String,
|
| 165 |
+
"industry": pl.String,
|
| 166 |
+
"sic_ranges": pl.String,
|
| 167 |
+
"edgar_codes": pl.Int32,
|
| 168 |
+
"taxonomy_version": pl.String,
|
| 169 |
+
"inserted_at": UTC_DATETIME,
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
CONFIG_SCHEMAS: dict[str, dict[str, pl.DataType]] = {
|
| 173 |
+
"classification": CLASSIFICATION_SCHEMA,
|
| 174 |
+
"by_ticker": TICKER_SCHEMA,
|
| 175 |
+
"spans": SPAN_SCHEMA,
|
| 176 |
+
"observations": OBSERVATION_SCHEMA,
|
| 177 |
+
"sic_codes": SIC_CODE_SCHEMA,
|
| 178 |
+
"naics_map": NAICS_MAP_SCHEMA,
|
| 179 |
+
"taxonomy": TAXONOMY_SCHEMA,
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
def empty_frame(schema: Mapping[str, pl.DataType]) -> pl.DataFrame:
|
| 184 |
+
return pl.DataFrame(schema=dict(schema))
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def align(frame: pl.DataFrame, schema: Mapping[str, pl.DataType]) -> pl.DataFrame:
|
| 188 |
+
missing = [
|
| 189 |
+
pl.lit(None, dtype=dtype).alias(name)
|
| 190 |
+
for name, dtype in schema.items()
|
| 191 |
+
if name not in frame.columns
|
| 192 |
+
]
|
| 193 |
+
if missing:
|
| 194 |
+
frame = frame.with_columns(missing)
|
| 195 |
+
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/sic.py
ADDED
|
@@ -0,0 +1,140 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The shape of a SIC code, and what the SEC does to it.
|
| 2 |
+
|
| 3 |
+
Two different things are called "SIC". The 1987 Standard Industrial
|
| 4 |
+
Classification is a census taxonomy with 1 005 four-digit industries in 83
|
| 5 |
+
major groups and 11 divisions. EDGAR's is a list of 444 codes the SEC assigns
|
| 6 |
+
to filers, and only 284 of them are 1987 industries: the other 160 are the
|
| 7 |
+
major group or the industry group padded with zeros, used when the SEC does
|
| 8 |
+
not care to be more precise than "food" or "computer and office equipment".
|
| 9 |
+
|
| 10 |
+
No real 1987 code ends in a zero -- checked against all 1 005 of them -- so
|
| 11 |
+
the padding is unambiguous and `code_level` can read it off. That matters for
|
| 12 |
+
the NAICS crosswalk, which is keyed on real four-digit industries and would
|
| 13 |
+
silently drop two fifths of EDGAR's codes if they were joined as if they were
|
| 14 |
+
the same thing.
|
| 15 |
+
"""
|
| 16 |
+
|
| 17 |
+
from __future__ import annotations
|
| 18 |
+
|
| 19 |
+
from dataclasses import dataclass
|
| 20 |
+
|
| 21 |
+
# 1987 SIC Manual (Office of Management and Budget), divisions A-K as ranges of
|
| 22 |
+
# major group. Published structure of a US government classification; the
|
| 23 |
+
# ranges are asserted here and checked in the tests against the division
|
| 24 |
+
# headers in the Census concordance file, which is the same structure stated
|
| 25 |
+
# by the agency that maintains it.
|
| 26 |
+
DIVISIONS: tuple[tuple[str, int, int, str], ...] = (
|
| 27 |
+
("A", 1, 9, "Agriculture, Forestry and Fishing"),
|
| 28 |
+
("B", 10, 14, "Mining"),
|
| 29 |
+
("C", 15, 17, "Construction"),
|
| 30 |
+
("D", 20, 39, "Manufacturing"),
|
| 31 |
+
("E", 40, 49, "Transportation, Communications, Electric, Gas and Sanitary Services"),
|
| 32 |
+
("F", 50, 51, "Wholesale Trade"),
|
| 33 |
+
("G", 52, 59, "Retail Trade"),
|
| 34 |
+
("H", 60, 67, "Finance, Insurance and Real Estate"),
|
| 35 |
+
("I", 70, 89, "Services"),
|
| 36 |
+
("J", 91, 97, "Public Administration"),
|
| 37 |
+
("K", 99, 99, "Nonclassifiable Establishments"),
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
# The two major groups the Census concordance never prints a header row for:
|
| 41 |
+
# it jumps from the division heading straight to 4011, and from the last
|
| 42 |
+
# division heading straight to 9999. Titles are the 1987 manual's own.
|
| 43 |
+
MAJOR_GROUP_FALLBACKS = {
|
| 44 |
+
"40": "Railroad Transportation",
|
| 45 |
+
"99": "Nonclassifiable Establishments",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
# EDGAR codes whose major group says nothing about the business. 88 is
|
| 49 |
+
# "Private Households" in the 1987 manual; the SEC reuses the range for two
|
| 50 |
+
# registrant types that are not industries at all.
|
| 51 |
+
EDGAR_ONLY_CODES = {
|
| 52 |
+
"8880": "American Depositary Receipts",
|
| 53 |
+
"8888": "Foreign Governments",
|
| 54 |
+
"9995": "Non-Operating Establishments",
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@dataclass(frozen=True, slots=True)
|
| 59 |
+
class Division:
|
| 60 |
+
letter: str
|
| 61 |
+
title: str
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def normalize(code: str | int | None) -> str | None:
|
| 65 |
+
"""A SIC as four digits, or None if it is not one.
|
| 66 |
+
|
| 67 |
+
EDGAR writes agriculture as `100` in one place and `0100` in another, and
|
| 68 |
+
an empty string where a filer has no assigned code.
|
| 69 |
+
"""
|
| 70 |
+
if code is None:
|
| 71 |
+
return None
|
| 72 |
+
text = str(code).strip()
|
| 73 |
+
if not text or not text.isdigit():
|
| 74 |
+
return None
|
| 75 |
+
text = text.lstrip("0") or "0"
|
| 76 |
+
if len(text) > 4 or text == "0":
|
| 77 |
+
return None
|
| 78 |
+
return text.zfill(4)
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def major_group(code: str) -> str:
|
| 82 |
+
return code[:2]
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
def industry_group(code: str) -> str:
|
| 86 |
+
return code[:3]
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def code_level(code: str) -> str:
|
| 90 |
+
"""How precise an EDGAR code is: a real industry, or a padded roll-up."""
|
| 91 |
+
if code.endswith("00"):
|
| 92 |
+
return "major_group"
|
| 93 |
+
if code.endswith("0"):
|
| 94 |
+
return "industry_group"
|
| 95 |
+
return "industry"
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def division_of(code: str) -> Division | None:
|
| 99 |
+
"""The 1987 division a code sits in, or None where the range has no meaning.
|
| 100 |
+
|
| 101 |
+
`8880` and `8888` fall in major group 88 arithmetically, and major group 88
|
| 102 |
+
is Private Households. Returning Services for an American Depositary
|
| 103 |
+
Receipt would be worse than returning nothing.
|
| 104 |
+
"""
|
| 105 |
+
if code in EDGAR_ONLY_CODES:
|
| 106 |
+
return None
|
| 107 |
+
group = int(major_group(code))
|
| 108 |
+
for letter, low, high, title in DIVISIONS:
|
| 109 |
+
if low <= group <= high:
|
| 110 |
+
return Division(letter, title)
|
| 111 |
+
return None
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def prefix_of(code: str) -> str:
|
| 115 |
+
"""The digits of a code that actually carry meaning.
|
| 116 |
+
|
| 117 |
+
`2000` means all of major group 20, `2020` all of industry group 202, and
|
| 118 |
+
`2834` exactly one industry. Used to expand a roll-up into the real 1987
|
| 119 |
+
industries it stands for.
|
| 120 |
+
"""
|
| 121 |
+
level = code_level(code)
|
| 122 |
+
if level == "major_group":
|
| 123 |
+
return code[:2]
|
| 124 |
+
if level == "industry_group":
|
| 125 |
+
return code[:3]
|
| 126 |
+
return code
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
__all__ = [
|
| 130 |
+
"DIVISIONS",
|
| 131 |
+
"EDGAR_ONLY_CODES",
|
| 132 |
+
"MAJOR_GROUP_FALLBACKS",
|
| 133 |
+
"Division",
|
| 134 |
+
"code_level",
|
| 135 |
+
"division_of",
|
| 136 |
+
"industry_group",
|
| 137 |
+
"major_group",
|
| 138 |
+
"normalize",
|
| 139 |
+
"prefix_of",
|
| 140 |
+
]
|
recipe/sources.py
ADDED
|
@@ -0,0 +1,540 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Where the classification comes from.
|
| 2 |
+
|
| 3 |
+
Four sources, all free to redistribute:
|
| 4 |
+
|
| 5 |
+
* `company-fundamentals`, a sibling dataset, for the code the SEC had a filer
|
| 6 |
+
under on the day of each XBRL filing. 440 000 dated statements since 2009.
|
| 7 |
+
This is the only free source of SIC *history* -- EDGAR's own record of a
|
| 8 |
+
filer states today's code and nothing before it.
|
| 9 |
+
* EDGAR's per-filer submissions record, for the filers the first source never
|
| 10 |
+
sees: delisted before XBRL, a fund, a foreign issuer filing on paper. One
|
| 11 |
+
small request each, and it carries no history.
|
| 12 |
+
* The SEC's published list of the 444 codes it assigns, for the title of each
|
| 13 |
+
and the office that reviews it.
|
| 14 |
+
* The Census Bureau's 1987 SIC to 1997 NAICS concordance, for the bridge to
|
| 15 |
+
the classification the rest of the US statistical system uses -- and, as a
|
| 16 |
+
by-product, for the titles of the 1987 major groups and divisions.
|
| 17 |
+
|
| 18 |
+
All four are US government works or derived from them. Nothing licensed goes
|
| 19 |
+
in, which is the constraint the whole dataset is built around.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
import hashlib
|
| 25 |
+
import html
|
| 26 |
+
import logging
|
| 27 |
+
import re
|
| 28 |
+
import time
|
| 29 |
+
from datetime import UTC, datetime
|
| 30 |
+
from pathlib import Path
|
| 31 |
+
|
| 32 |
+
import httpx
|
| 33 |
+
import polars as pl
|
| 34 |
+
|
| 35 |
+
from .config import SIBLING_DIRS, SOURCE_REPOS, Settings
|
| 36 |
+
from .naics import sector_of
|
| 37 |
+
from .schema import OBSERVATION_SCHEMA, align, empty_frame
|
| 38 |
+
from .sic import MAJOR_GROUP_FALLBACKS, normalize
|
| 39 |
+
|
| 40 |
+
LOGGER = logging.getLogger(__name__)
|
| 41 |
+
|
| 42 |
+
SIC_LIST_URL = "https://www.sec.gov/search-filings/standard-industrial-classification-sic-code-list"
|
| 43 |
+
SUBMISSIONS_BULK_URL = (
|
| 44 |
+
"https://www.sec.gov/Archives/edgar/daily-index/bulkdata/submissions.zip"
|
| 45 |
+
)
|
| 46 |
+
CONCORDANCE_URL = "https://www.census.gov/naics/concordances/1987_SIC_to_1997_NAICS.xls"
|
| 47 |
+
|
| 48 |
+
# SEC rebuilds the archive nightly, but a filer's assigned code moves on the
|
| 49 |
+
# scale of years. A week-old copy is the same answer and one fewer gigabyte.
|
| 50 |
+
BULK_MAX_AGE_SECONDS = 7 * 24 * 3600
|
| 51 |
+
BULK_MAX_RESUMES = 12
|
| 52 |
+
|
| 53 |
+
ENTITY_KIND_SCHEMA = {"cik": pl.String, "entity_kind": pl.String, "source_ref": pl.String}
|
| 54 |
+
|
| 55 |
+
# census.gov answers 403 to the SEC-style User-Agent this project uses
|
| 56 |
+
# everywhere else, and 200 to an ordinary browser string. The file is a static
|
| 57 |
+
# reference table published for download, fetched once per build and cached.
|
| 58 |
+
CENSUS_USER_AGENT = (
|
| 59 |
+
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
|
| 60 |
+
"(KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
_ROW = re.compile(r"<tr[^>]*>(.*?)</tr>", re.DOTALL)
|
| 64 |
+
_CELL = re.compile(r"<t[dh][^>]*>(.*?)</t[dh]>", re.DOTALL)
|
| 65 |
+
_TAG = re.compile(r"<[^>]+>")
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _fresh(path: Path, max_age_seconds: float) -> bool:
|
| 69 |
+
return path.is_file() and (time.time() - path.stat().st_mtime) <= max_age_seconds
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _text(fragment: str) -> str:
|
| 73 |
+
return re.sub(r"\s+", " ", html.unescape(_TAG.sub(" ", fragment))).strip()
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
# ---------------------------------------------------------------- siblings
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def sibling_path(settings: Settings, name: str) -> Path | None:
|
| 80 |
+
if settings.siblings_dir is None:
|
| 81 |
+
return None
|
| 82 |
+
path = settings.siblings_dir / SIBLING_DIRS[name] / "data"
|
| 83 |
+
return path if path.is_dir() else None
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _parquet_files(root: Path) -> list[Path]:
|
| 87 |
+
return sorted(
|
| 88 |
+
path
|
| 89 |
+
for path in root.rglob("*.parquet")
|
| 90 |
+
if not any(part.endswith(".delta") or part == "_delta_log" for part in path.parts)
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def sibling_frame(
|
| 95 |
+
settings: Settings, name: str, config: str, columns: list[str], *, token: str | None = None
|
| 96 |
+
) -> pl.LazyFrame:
|
| 97 |
+
"""One config of a sibling dataset, local if available, else from the Hub."""
|
| 98 |
+
local = sibling_path(settings, name)
|
| 99 |
+
if local is not None:
|
| 100 |
+
files = _parquet_files(local / config)
|
| 101 |
+
if files:
|
| 102 |
+
LOGGER.info("reading %s/%s from %s", name, config, local)
|
| 103 |
+
return pl.scan_parquet(files).select(columns)
|
| 104 |
+
|
| 105 |
+
from huggingface_hub import snapshot_download
|
| 106 |
+
|
| 107 |
+
LOGGER.info("downloading data/%s from %s", config, SOURCE_REPOS[name])
|
| 108 |
+
root = Path(
|
| 109 |
+
snapshot_download(
|
| 110 |
+
repo_id=SOURCE_REPOS[name],
|
| 111 |
+
repo_type="dataset",
|
| 112 |
+
allow_patterns=[f"data/{config}/**"],
|
| 113 |
+
token=token,
|
| 114 |
+
)
|
| 115 |
+
)
|
| 116 |
+
files = _parquet_files(root / "data" / config)
|
| 117 |
+
if not files:
|
| 118 |
+
raise FileNotFoundError(f"{SOURCE_REPOS[name]} has no {config} parquet")
|
| 119 |
+
return pl.scan_parquet(files).select(columns)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def from_fundamental_filings(settings: Settings, *, token: str | None = None) -> pl.DataFrame:
|
| 123 |
+
"""The code the SEC had a filer under, on the day of each XBRL filing.
|
| 124 |
+
|
| 125 |
+
`accepted_at` is kept as the knowledge time rather than `filed_date`
|
| 126 |
+
because the two differ for anything filed after hours, and a classification
|
| 127 |
+
joined to intraday data on the filing date would be using a fact hours
|
| 128 |
+
before the market could have known it.
|
| 129 |
+
"""
|
| 130 |
+
frame = (
|
| 131 |
+
sibling_frame(
|
| 132 |
+
settings,
|
| 133 |
+
"fundamentals",
|
| 134 |
+
"filings",
|
| 135 |
+
["cik", "sic", "filed_date", "accepted_at", "accession_number"],
|
| 136 |
+
token=token,
|
| 137 |
+
)
|
| 138 |
+
.filter(
|
| 139 |
+
pl.col("cik").is_not_null()
|
| 140 |
+
& pl.col("filed_date").is_not_null()
|
| 141 |
+
& pl.col("sic").is_not_null()
|
| 142 |
+
& (pl.col("sic").str.strip_chars() != "")
|
| 143 |
+
)
|
| 144 |
+
.collect()
|
| 145 |
+
)
|
| 146 |
+
LOGGER.info("xbrl filings with a SIC: %d", frame.height)
|
| 147 |
+
return _observations(
|
| 148 |
+
frame.select(
|
| 149 |
+
pl.col("cik"),
|
| 150 |
+
pl.col("sic").map_elements(normalize, return_dtype=pl.String).alias("sic"),
|
| 151 |
+
pl.col("filed_date").alias("stated_on"),
|
| 152 |
+
pl.col("accepted_at").alias("knowledge_time"),
|
| 153 |
+
pl.lit("xbrl").alias("source"),
|
| 154 |
+
pl.col("accession_number").alias("source_ref"),
|
| 155 |
+
pl.lit(True).alias("is_dated"),
|
| 156 |
+
).filter(pl.col("sic").is_not_null())
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def ticker_spans(settings: Settings, *, token: str | None = None) -> pl.DataFrame:
|
| 161 |
+
"""Every ticker a filer has been seen under, and the window it held it."""
|
| 162 |
+
frame = (
|
| 163 |
+
sibling_frame(
|
| 164 |
+
settings,
|
| 165 |
+
"security_master",
|
| 166 |
+
"identifiers",
|
| 167 |
+
["cik", "kind", "value", "valid_from", "valid_to", "is_current"],
|
| 168 |
+
token=token,
|
| 169 |
+
)
|
| 170 |
+
.filter(pl.col("kind") == "ticker")
|
| 171 |
+
.collect()
|
| 172 |
+
)
|
| 173 |
+
LOGGER.info("ticker spans: %d over %d filers", frame.height, frame["cik"].n_unique())
|
| 174 |
+
return frame.rename({"value": "ticker"}).drop("kind")
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def issuers(settings: Settings, *, token: str | None = None) -> pl.DataFrame:
|
| 178 |
+
"""The filer directory: name, tickers, exchange, whether it still files."""
|
| 179 |
+
frame = sibling_frame(
|
| 180 |
+
settings,
|
| 181 |
+
"security_master",
|
| 182 |
+
"issuers",
|
| 183 |
+
["cik", "name", "primary_ticker", "all_tickers", "exchange", "is_active", "first_seen"],
|
| 184 |
+
token=token,
|
| 185 |
+
).collect()
|
| 186 |
+
LOGGER.info("issuers: %d", frame.height)
|
| 187 |
+
return frame
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
# -------------------------------------------------------------------- SEC
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def _observations(frame: pl.DataFrame) -> pl.DataFrame:
|
| 194 |
+
if frame.is_empty():
|
| 195 |
+
return empty_frame(OBSERVATION_SCHEMA)
|
| 196 |
+
return align(frame.with_columns(pl.lit(datetime.now(UTC)).alias("inserted_at")),
|
| 197 |
+
OBSERVATION_SCHEMA)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
# The page has carried 444 codes for years. A parse that returns far fewer
|
| 201 |
+
# has met a layout change, and the alternative to failing is a build that
|
| 202 |
+
# quietly loses the titles of two hundred industries.
|
| 203 |
+
MIN_SIC_CODES = 400
|
| 204 |
+
|
| 205 |
+
|
| 206 |
+
def parse_sic_list(page: str) -> pl.DataFrame:
|
| 207 |
+
"""The three-column table on the SEC's SIC code list page."""
|
| 208 |
+
rows: list[dict] = []
|
| 209 |
+
for fragment in _ROW.findall(page):
|
| 210 |
+
cells = [_text(cell) for cell in _CELL.findall(fragment)]
|
| 211 |
+
if len(cells) != 3 or cells[0].strip().lower() == "sic code":
|
| 212 |
+
continue
|
| 213 |
+
code = normalize(cells[0])
|
| 214 |
+
if code:
|
| 215 |
+
rows.append({"sic": code, "sec_office": cells[1] or None, "title": cells[2]})
|
| 216 |
+
if not rows:
|
| 217 |
+
return pl.DataFrame(schema={"sic": pl.String, "sec_office": pl.String,
|
| 218 |
+
"title": pl.String})
|
| 219 |
+
return pl.DataFrame(rows).unique(subset=["sic"], keep="first").sort("sic")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
async def edgar_sic_list(client) -> pl.DataFrame:
|
| 223 |
+
"""The 444 codes the SEC assigns, with the office that reviews each.
|
| 224 |
+
|
| 225 |
+
Scraped, because the SEC publishes this list as a web page and nowhere
|
| 226 |
+
else -- there is no CSV, no JSON and no bulk file.
|
| 227 |
+
"""
|
| 228 |
+
page = await client.get_text(SIC_LIST_URL, max_age_seconds=7 * 24 * 3600)
|
| 229 |
+
frame = parse_sic_list(page)
|
| 230 |
+
LOGGER.info("EDGAR SIC list: %d codes", frame.height)
|
| 231 |
+
if frame.height < MIN_SIC_CODES:
|
| 232 |
+
raise RuntimeError(
|
| 233 |
+
f"the SEC SIC code list parsed to {frame.height} rows; it has had 444 for "
|
| 234 |
+
"years, so the page layout has changed and the parser needs looking at"
|
| 235 |
+
)
|
| 236 |
+
return frame
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
async def download_bulk_submissions(client, cache_dir: Path) -> Path:
|
| 240 |
+
"""EDGAR's whole submissions directory, as one file.
|
| 241 |
+
|
| 242 |
+
The obvious implementation asks `data.sec.gov/submissions/CIK*.json` once
|
| 243 |
+
per filer. Measured on the six thousand filers this build needs, that runs
|
| 244 |
+
at a fifth of a request per second: SEC answers the first few hundred and
|
| 245 |
+
then throttles, and the client spends its time in backoff. Eight hours for
|
| 246 |
+
six thousand small files.
|
| 247 |
+
|
| 248 |
+
SEC publishes this archive for exactly that reason. It is 1.5 GB and one
|
| 249 |
+
request, which arrives in about four minutes, and it is kinder to the
|
| 250 |
+
service than a crawl it would rather we did not run.
|
| 251 |
+
|
| 252 |
+
Streamed to disk rather than held in memory, and resumed by byte range if
|
| 253 |
+
the transfer breaks -- EDGAR closes long connections often enough that
|
| 254 |
+
restarting a gigabyte from zero would be a way to never finish.
|
| 255 |
+
|
| 256 |
+
The resume is deliberately suspicious of its own partial file. Every
|
| 257 |
+
attempt re-reads the size from disk, a server that answers a ranged
|
| 258 |
+
request with a whole body restarts the file rather than appending to it,
|
| 259 |
+
and the result is accepted only when the byte count matches what the
|
| 260 |
+
server declared *and* the zip's directory can be read. A partial download
|
| 261 |
+
that is merely plausible produces a `BadZipFile` thousands of lines later,
|
| 262 |
+
which is how this was found.
|
| 263 |
+
"""
|
| 264 |
+
cache_dir = Path(cache_dir)
|
| 265 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 266 |
+
target = cache_dir / "submissions-bulk.zip"
|
| 267 |
+
partial = cache_dir / "submissions-bulk.zip.part"
|
| 268 |
+
if _fresh(target, BULK_MAX_AGE_SECONDS) and _is_readable_zip(target):
|
| 269 |
+
LOGGER.info("submissions archive: cached (%.2f GB)", target.stat().st_size / 1e9)
|
| 270 |
+
return target
|
| 271 |
+
target.unlink(missing_ok=True)
|
| 272 |
+
|
| 273 |
+
headers = {"User-Agent": client.user_agent, "Accept-Encoding": "identity"}
|
| 274 |
+
for attempt in range(1, BULK_MAX_RESUMES + 1):
|
| 275 |
+
have = partial.stat().st_size if partial.is_file() else 0
|
| 276 |
+
request = dict(headers) | ({"Range": f"bytes={have}-"} if have else {})
|
| 277 |
+
try:
|
| 278 |
+
async with (
|
| 279 |
+
httpx.AsyncClient(timeout=300.0, follow_redirects=True) as fetcher,
|
| 280 |
+
fetcher.stream("GET", SUBMISSIONS_BULK_URL, headers=request) as response,
|
| 281 |
+
):
|
| 282 |
+
response.raise_for_status()
|
| 283 |
+
# A server may answer a ranged request with the whole body.
|
| 284 |
+
# Appending that to what is already there is how a download
|
| 285 |
+
# ends up larger than the file it was copying.
|
| 286 |
+
resuming = response.status_code == 206
|
| 287 |
+
if have and not resuming:
|
| 288 |
+
have = 0
|
| 289 |
+
declared = response.headers.get("content-length")
|
| 290 |
+
total = (int(declared) + have) if declared else None
|
| 291 |
+
with partial.open("ab" if have else "wb") as handle:
|
| 292 |
+
if not have:
|
| 293 |
+
handle.truncate(0)
|
| 294 |
+
async for chunk in response.aiter_bytes(1 << 20):
|
| 295 |
+
handle.write(chunk)
|
| 296 |
+
except (httpx.TransportError, httpx.TimeoutException, httpx.HTTPStatusError) as error:
|
| 297 |
+
LOGGER.warning(
|
| 298 |
+
"submissions archive interrupted at %.2f GB (%s); resuming",
|
| 299 |
+
(partial.stat().st_size if partial.is_file() else 0) / 1e9,
|
| 300 |
+
type(error).__name__,
|
| 301 |
+
)
|
| 302 |
+
if attempt == BULK_MAX_RESUMES:
|
| 303 |
+
raise
|
| 304 |
+
continue
|
| 305 |
+
|
| 306 |
+
size = partial.stat().st_size
|
| 307 |
+
if total is not None and size != total:
|
| 308 |
+
LOGGER.warning("submissions archive is %d bytes, expected %d", size, total)
|
| 309 |
+
if size > total: # cannot be repaired by asking for more
|
| 310 |
+
partial.unlink(missing_ok=True)
|
| 311 |
+
continue
|
| 312 |
+
if not _is_readable_zip(partial):
|
| 313 |
+
LOGGER.warning("submissions archive did not open as a zip; starting over")
|
| 314 |
+
partial.unlink(missing_ok=True)
|
| 315 |
+
continue
|
| 316 |
+
partial.replace(target)
|
| 317 |
+
LOGGER.info("submissions archive: %.2f GB", target.stat().st_size / 1e9)
|
| 318 |
+
return target
|
| 319 |
+
raise RuntimeError("could not download EDGAR's submissions archive")
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def _is_readable_zip(path: Path) -> bool:
|
| 323 |
+
"""Whether the central directory parses. Cheap: it is at the end."""
|
| 324 |
+
import zipfile
|
| 325 |
+
|
| 326 |
+
if not path.is_file():
|
| 327 |
+
return False
|
| 328 |
+
try:
|
| 329 |
+
with zipfile.ZipFile(path) as bundle:
|
| 330 |
+
return bool(bundle.namelist())
|
| 331 |
+
except (zipfile.BadZipFile, OSError):
|
| 332 |
+
return False
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
# What a filer files says what kind of entity it is, where no industry code
|
| 336 |
+
# does. Both of these are definitions rather than guesses: N-CSR is the
|
| 337 |
+
# certified shareholder report of a registered management investment company,
|
| 338 |
+
# N-2 its registration statement; F-6 is the registration statement for
|
| 339 |
+
# American Depositary Receipts. A filer that files one is that kind of thing.
|
| 340 |
+
INVESTMENT_COMPANY_FORMS = frozenset(
|
| 341 |
+
{"N-CSR", "N-CSRS", "N-2", "N-PORT", "N-PORT/A", "N-Q", "N-CEN", "24F-2NT", "40-17G"}
|
| 342 |
+
)
|
| 343 |
+
DEPOSITARY_RECEIPT_PREFIX = "F-6"
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
def _entity_kind(payload: dict) -> str | None:
|
| 347 |
+
"""Investment company or depositary receipt programme, from the evidence.
|
| 348 |
+
|
| 349 |
+
Checked in that order: a fund that also sponsors a receipt programme is
|
| 350 |
+
still a fund, which is the stronger statement about what the entity is.
|
| 351 |
+
"""
|
| 352 |
+
recent = (payload.get("filings") or {}).get("recent") or {}
|
| 353 |
+
forms = {form for form in (recent.get("form") or []) if form}
|
| 354 |
+
if forms & INVESTMENT_COMPANY_FORMS or payload.get("entityType") == "investment":
|
| 355 |
+
return "investment_company"
|
| 356 |
+
if any(form.startswith(DEPOSITARY_RECEIPT_PREFIX) for form in forms):
|
| 357 |
+
return "depositary_receipt"
|
| 358 |
+
return None
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
def read_bulk_sic(archive: Path, ciks: list[str]) -> tuple[list[dict], list[dict]]:
|
| 362 |
+
"""What EDGAR currently holds for these filers: a code, or failing that,
|
| 363 |
+
what kind of entity they are.
|
| 364 |
+
|
| 365 |
+
Only the per-filer metadata member is read, never the paginated history
|
| 366 |
+
files beside it: `sic` is in the first one and the rest are filings.
|
| 367 |
+
|
| 368 |
+
The second return is the fallback. Sixteen hundred live symbols belong to
|
| 369 |
+
filers the SEC has never assigned an industry -- closed-end funds, ADR
|
| 370 |
+
programmes -- and `null` reads the same as "we failed" to anyone consuming
|
| 371 |
+
this. Saying "this is a fund" is both true and more useful, and it comes
|
| 372 |
+
from the forms rather than from the name.
|
| 373 |
+
"""
|
| 374 |
+
import json
|
| 375 |
+
import zipfile
|
| 376 |
+
|
| 377 |
+
wanted = {cik: f"CIK{cik}.json" for cik in ciks}
|
| 378 |
+
today = datetime.now(UTC).date()
|
| 379 |
+
now = datetime.now(UTC)
|
| 380 |
+
rows: list[dict] = []
|
| 381 |
+
kinds: list[dict] = []
|
| 382 |
+
missing = 0
|
| 383 |
+
with zipfile.ZipFile(archive) as bundle:
|
| 384 |
+
present = set(bundle.namelist())
|
| 385 |
+
for cik, member in wanted.items():
|
| 386 |
+
if member not in present:
|
| 387 |
+
missing += 1
|
| 388 |
+
continue
|
| 389 |
+
try:
|
| 390 |
+
payload = json.loads(bundle.read(member))
|
| 391 |
+
except (json.JSONDecodeError, KeyError, OSError):
|
| 392 |
+
missing += 1
|
| 393 |
+
continue
|
| 394 |
+
code = normalize(payload.get("sic"))
|
| 395 |
+
if code:
|
| 396 |
+
rows.append({
|
| 397 |
+
"cik": cik, "sic": code, "stated_on": today, "knowledge_time": now,
|
| 398 |
+
"source": "submissions", "source_ref": member, "is_dated": False,
|
| 399 |
+
})
|
| 400 |
+
continue
|
| 401 |
+
kind = _entity_kind(payload)
|
| 402 |
+
if kind:
|
| 403 |
+
kinds.append({"cik": cik, "entity_kind": kind, "source_ref": member})
|
| 404 |
+
LOGGER.info(
|
| 405 |
+
"submissions archive: %d codes, %d entity kinds, for %d filers (%d absent)",
|
| 406 |
+
len(rows), len(kinds), len(ciks), missing,
|
| 407 |
+
)
|
| 408 |
+
return rows, kinds
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
async def submissions_snapshot(
|
| 412 |
+
client, ciks: list[str], *, limit: int | None = None
|
| 413 |
+
) -> tuple[pl.DataFrame, pl.DataFrame]:
|
| 414 |
+
"""Today's code, and the entity kind where there is no code.
|
| 415 |
+
|
| 416 |
+
Explicitly undated. EDGAR states what the SEC has the filer under now,
|
| 417 |
+
with no record of when it was assigned, so `stated_on` is the day the
|
| 418 |
+
build ran and `is_dated` is false. Treating that as a dated observation
|
| 419 |
+
would put a 2026 opinion on a company that delisted in 2007.
|
| 420 |
+
"""
|
| 421 |
+
if limit is not None:
|
| 422 |
+
ciks = ciks[:limit]
|
| 423 |
+
if not ciks:
|
| 424 |
+
return empty_frame(OBSERVATION_SCHEMA), pl.DataFrame(schema=ENTITY_KIND_SCHEMA)
|
| 425 |
+
LOGGER.info("filers to resolve from the submissions archive: %d", len(ciks))
|
| 426 |
+
archive = await download_bulk_submissions(client, Path(client.cache_dir))
|
| 427 |
+
rows, kinds = read_bulk_sic(archive, ciks)
|
| 428 |
+
return (
|
| 429 |
+
_observations(pl.DataFrame(rows) if rows else pl.DataFrame()),
|
| 430 |
+
pl.DataFrame(kinds, schema=ENTITY_KIND_SCHEMA) if kinds
|
| 431 |
+
else pl.DataFrame(schema=ENTITY_KIND_SCHEMA),
|
| 432 |
+
)
|
| 433 |
+
|
| 434 |
+
|
| 435 |
+
# ----------------------------------------------------------------- Census
|
| 436 |
+
|
| 437 |
+
|
| 438 |
+
async def fetch_concordance(cache_dir: Path) -> bytes:
|
| 439 |
+
"""The Census SIC-to-NAICS workbook, cached on disk.
|
| 440 |
+
|
| 441 |
+
It is a 2008 file describing a 1997 classification: it does not change,
|
| 442 |
+
and a build that re-downloaded it every run would be asking the Census
|
| 443 |
+
Bureau for the same 360 KB every week for no reason.
|
| 444 |
+
"""
|
| 445 |
+
cache_dir = Path(cache_dir)
|
| 446 |
+
cache_dir.mkdir(parents=True, exist_ok=True)
|
| 447 |
+
digest = hashlib.sha256(CONCORDANCE_URL.encode()).hexdigest()[:16]
|
| 448 |
+
cached = cache_dir / f"concordance-{digest}.xls"
|
| 449 |
+
if cached.is_file() and cached.stat().st_size > 10_000:
|
| 450 |
+
return cached.read_bytes()
|
| 451 |
+
async with httpx.AsyncClient(
|
| 452 |
+
headers={"User-Agent": CENSUS_USER_AGENT}, timeout=60.0, follow_redirects=True
|
| 453 |
+
) as fetcher:
|
| 454 |
+
response = await fetcher.get(CONCORDANCE_URL)
|
| 455 |
+
response.raise_for_status()
|
| 456 |
+
payload = response.content
|
| 457 |
+
cached.write_bytes(payload)
|
| 458 |
+
LOGGER.info("census concordance: %d bytes", len(payload))
|
| 459 |
+
return payload
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
def parse_concordance(payload: bytes) -> tuple[pl.DataFrame, dict[str, str], list[str]]:
|
| 463 |
+
"""The crosswalk, the major group titles, and the division titles in order.
|
| 464 |
+
|
| 465 |
+
One file answers three questions because of how it is laid out: a row with
|
| 466 |
+
no SIC is a division heading, a two-digit SIC is a major group heading, and
|
| 467 |
+
a four-digit SIC is an industry with its NAICS counterparts. Reading the
|
| 468 |
+
hierarchy out of the same file as the crosswalk means the titles come from
|
| 469 |
+
the agency that maintains the classification rather than being typed in
|
| 470 |
+
here from a manual.
|
| 471 |
+
"""
|
| 472 |
+
import io
|
| 473 |
+
|
| 474 |
+
frame = pl.read_excel(io.BytesIO(payload), has_header=True, infer_schema_length=0)
|
| 475 |
+
if frame.width < 5:
|
| 476 |
+
raise RuntimeError(f"concordance has {frame.width} columns, expected 5")
|
| 477 |
+
frame.columns = ["sic", "part", "title", "naics", "naics_title"][: frame.width]
|
| 478 |
+
frame = frame.with_columns(pl.col("sic").str.strip_chars())
|
| 479 |
+
|
| 480 |
+
divisions = [
|
| 481 |
+
row["title"].strip()
|
| 482 |
+
for row in frame.filter(pl.col("sic").is_null() & pl.col("title").is_not_null())
|
| 483 |
+
.iter_rows(named=True)
|
| 484 |
+
]
|
| 485 |
+
major_groups = dict(MAJOR_GROUP_FALLBACKS)
|
| 486 |
+
major_groups.update({
|
| 487 |
+
row["sic"]: row["title"].strip()
|
| 488 |
+
for row in frame.filter(pl.col("sic").str.len_chars() == 2).iter_rows(named=True)
|
| 489 |
+
if row["title"]
|
| 490 |
+
})
|
| 491 |
+
|
| 492 |
+
now = datetime.now(UTC)
|
| 493 |
+
industries = frame.filter(
|
| 494 |
+
(pl.col("sic").str.len_chars() == 4) & pl.col("naics").is_not_null()
|
| 495 |
+
)
|
| 496 |
+
# A "pt" row is one slice of a 1987 industry that 1997 split up; its title
|
| 497 |
+
# column holds the slice's description, indented with dots in the source.
|
| 498 |
+
rows: list[dict] = []
|
| 499 |
+
titles: dict[str, str] = {}
|
| 500 |
+
for row in frame.filter(pl.col("sic").str.len_chars() == 4).iter_rows(named=True):
|
| 501 |
+
if not row["part"] and row["title"]:
|
| 502 |
+
titles.setdefault(row["sic"], row["title"].strip())
|
| 503 |
+
for row in industries.iter_rows(named=True):
|
| 504 |
+
is_part = bool(row["part"])
|
| 505 |
+
naics = (row["naics"] or "").strip()
|
| 506 |
+
sector, sector_title = sector_of(naics)
|
| 507 |
+
rows.append({
|
| 508 |
+
"sic": row["sic"],
|
| 509 |
+
"sic_title": titles.get(row["sic"]),
|
| 510 |
+
"is_part": is_part,
|
| 511 |
+
"part_description": (row["title"] or "").lstrip(". ").strip() if is_part else None,
|
| 512 |
+
"naics_1997": naics,
|
| 513 |
+
"naics_title": (row["naics_title"] or "").strip() or None,
|
| 514 |
+
"naics_sector": sector,
|
| 515 |
+
"naics_sector_title": sector_title,
|
| 516 |
+
"inserted_at": now,
|
| 517 |
+
})
|
| 518 |
+
LOGGER.info(
|
| 519 |
+
"concordance: %d pairs, %d major groups, %d divisions",
|
| 520 |
+
len(rows), len(major_groups), len(divisions),
|
| 521 |
+
)
|
| 522 |
+
return pl.DataFrame(rows), major_groups, divisions
|
| 523 |
+
|
| 524 |
+
|
| 525 |
+
__all__ = [
|
| 526 |
+
"ENTITY_KIND_SCHEMA",
|
| 527 |
+
"MIN_SIC_CODES",
|
| 528 |
+
"download_bulk_submissions",
|
| 529 |
+
"edgar_sic_list",
|
| 530 |
+
"fetch_concordance",
|
| 531 |
+
"from_fundamental_filings",
|
| 532 |
+
"issuers",
|
| 533 |
+
"parse_concordance",
|
| 534 |
+
"parse_sic_list",
|
| 535 |
+
"read_bulk_sic",
|
| 536 |
+
"sibling_frame",
|
| 537 |
+
"sibling_path",
|
| 538 |
+
"submissions_snapshot",
|
| 539 |
+
"ticker_spans",
|
| 540 |
+
]
|
recipe/store.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Write and read the published tables.
|
| 2 |
+
|
| 3 |
+
Every table here is rebuilt in full on each run, because every one of them is
|
| 4 |
+
a groupby over sources that are themselves rebuilt in full. There is no
|
| 5 |
+
append-only state to protect and no partition key worth having: the largest
|
| 6 |
+
table is half a million rows.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import os
|
| 12 |
+
import tempfile
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
|
| 15 |
+
import polars as pl
|
| 16 |
+
|
| 17 |
+
from .schema import CONFIG_SCHEMAS
|
| 18 |
+
|
| 19 |
+
PART_NAME = "part-00000.parquet"
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def atomic_write_parquet(frame: pl.DataFrame, target: Path) -> None:
|
| 23 |
+
"""Write through a temporary file in the same directory, then rename.
|
| 24 |
+
|
| 25 |
+
A partly written parquet is indistinguishable from a valid one until it is
|
| 26 |
+
read, and a build interrupted mid-write would leave the dataset in a state
|
| 27 |
+
that only fails later, in a consumer's process.
|
| 28 |
+
"""
|
| 29 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 30 |
+
descriptor, temporary = tempfile.mkstemp(prefix=".part-", suffix=".parquet", dir=target.parent)
|
| 31 |
+
os.close(descriptor)
|
| 32 |
+
try:
|
| 33 |
+
frame.write_parquet(temporary, compression="zstd", statistics=True)
|
| 34 |
+
os.replace(temporary, target)
|
| 35 |
+
finally:
|
| 36 |
+
if os.path.exists(temporary):
|
| 37 |
+
os.unlink(temporary)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def read_table(data_dir: Path, table: str) -> pl.LazyFrame:
|
| 41 |
+
root = Path(data_dir) / table
|
| 42 |
+
if not root.is_dir():
|
| 43 |
+
return pl.LazyFrame(schema=dict(CONFIG_SCHEMAS[table]))
|
| 44 |
+
files = sorted(root.rglob("*.parquet"))
|
| 45 |
+
if not files:
|
| 46 |
+
return pl.LazyFrame(schema=dict(CONFIG_SCHEMAS[table]))
|
| 47 |
+
return pl.scan_parquet(files)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def table_rows(data_dir: Path, table: str) -> int:
|
| 51 |
+
return int(read_table(data_dir, table).select(pl.len()).collect().item())
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def config_row_counts(data_dir: Path) -> dict[str, int]:
|
| 55 |
+
return {name: table_rows(data_dir, name) for name in CONFIG_SCHEMAS}
|
recipe/taxonomy.py
ADDED
|
@@ -0,0 +1,437 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""ZipLime's sector and industry taxonomy, defined over SIC ranges.
|
| 2 |
+
|
| 3 |
+
Why this exists
|
| 4 |
+
---------------
|
| 5 |
+
The two classifications everyone actually uses in equity research -- GICS and
|
| 6 |
+
ICB -- are licensed products. Their per-company assignments cannot be
|
| 7 |
+
redistributed, and neither can a table that reproduces their structure. So
|
| 8 |
+
this dataset does not contain them, does not approximate them, and should not
|
| 9 |
+
be described as compatible with them: a sector here and a GICS sector of the
|
| 10 |
+
same name will disagree on real companies, and the disagreements are listed
|
| 11 |
+
in PIPELINE.md.
|
| 12 |
+
|
| 13 |
+
What is free is the input: the SEC states a SIC code for every filer, and a
|
| 14 |
+
SIC code is a US government work. What is missing is the rollup, because the
|
| 15 |
+
SIC divisions are useless for investing -- Division D, Manufacturing, holds
|
| 16 |
+
pharmaceuticals, semiconductors, oil refining and breweries in one bucket
|
| 17 |
+
that covers a third of the listed universe.
|
| 18 |
+
|
| 19 |
+
So the rollup below is written here, by ZipLime, and licensed Apache-2.0 with
|
| 20 |
+
the rest of the recipe. It is an opinion about which businesses belong
|
| 21 |
+
together, stated as code so it can be argued with.
|
| 22 |
+
|
| 23 |
+
How to read it
|
| 24 |
+
--------------
|
| 25 |
+
`RULES` is ordered and the first match wins, so a narrow range always precedes
|
| 26 |
+
the wider one it sits inside. Ranges are over the four-digit code as an
|
| 27 |
+
integer, and they cover the EDGAR roll-up codes by construction: `2000` falls
|
| 28 |
+
in the food range just as `2011` does.
|
| 29 |
+
|
| 30 |
+
Judgement calls worth knowing about, each one a place where a reasonable
|
| 31 |
+
person would do something else:
|
| 32 |
+
|
| 33 |
+
* `6324` Hospital & Medical Service Plans is Health Care, not Financials.
|
| 34 |
+
Centene, Cigna, Elevance, Humana and Molina file under it, and an insurance
|
| 35 |
+
factor built over them measures hospital reimbursement, not underwriting.
|
| 36 |
+
* `7370` Computer Programming & Data Processing is its own industry rather
|
| 37 |
+
than being folded into IT services, because it is where Alphabet, Baidu and
|
| 38 |
+
AppLovin sit alongside consultancies. SIC cannot separate an advertising
|
| 39 |
+
platform from a systems integrator; naming the bucket honestly is better
|
| 40 |
+
than pretending the split exists.
|
| 41 |
+
* `8731` Commercial Physical & Biological Research holds contract research
|
| 42 |
+
organisations (Charles River, ICON) and research-stage drug developers
|
| 43 |
+
(Incyte) in one code. It is mapped to tools and services, which is wrong for
|
| 44 |
+
the drug developers, and there is nothing in the filing that would tell them
|
| 45 |
+
apart.
|
| 46 |
+
* `6770` Blank Checks gets a sector of its own rather than being hidden in
|
| 47 |
+
Financials. It is the third most common code in the corpus -- 1 340 filers
|
| 48 |
+
-- and a SPAC is not a financial company, it is an empty one. Anybody
|
| 49 |
+
building a universe wants to drop it by name.
|
| 50 |
+
* `3011` tyres sit with vehicle components rather than with rubber, and `2950`
|
| 51 |
+
asphalt with construction materials rather than with refining, because in
|
| 52 |
+
both cases the customer decides the cycle.
|
| 53 |
+
"""
|
| 54 |
+
|
| 55 |
+
from __future__ import annotations
|
| 56 |
+
|
| 57 |
+
from dataclasses import dataclass
|
| 58 |
+
|
| 59 |
+
TAXONOMY_VERSION = "1.0.0"
|
| 60 |
+
|
| 61 |
+
SECTORS: dict[str, str] = {
|
| 62 |
+
"ENER": "Energy",
|
| 63 |
+
"MATR": "Materials",
|
| 64 |
+
"INDU": "Industrials",
|
| 65 |
+
"CONC": "Consumer Cyclical",
|
| 66 |
+
"COND": "Consumer Defensive",
|
| 67 |
+
"HLTH": "Health Care",
|
| 68 |
+
"FINS": "Financials",
|
| 69 |
+
"TECH": "Technology",
|
| 70 |
+
"TLCM": "Telecom & Media",
|
| 71 |
+
"UTIL": "Utilities",
|
| 72 |
+
"REAL": "Real Estate",
|
| 73 |
+
"SHEL": "Shell & Blank Check",
|
| 74 |
+
"FUND": "Funds & Trusts",
|
| 75 |
+
"GOVT": "Government",
|
| 76 |
+
"UNCL": "Unclassified",
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
# industry code -> (sector code, industry title)
|
| 80 |
+
INDUSTRIES: dict[str, tuple[str, str]] = {
|
| 81 |
+
"ENER_EP": ("ENER", "Oil & Gas Exploration & Production"),
|
| 82 |
+
"ENER_SERVICES": ("ENER", "Oil & Gas Equipment & Services"),
|
| 83 |
+
"ENER_MIDSTREAM": ("ENER", "Oil & Gas Storage & Transportation"),
|
| 84 |
+
"ENER_REFINE": ("ENER", "Oil & Gas Refining & Marketing"),
|
| 85 |
+
"ENER_COAL": ("ENER", "Coal & Consumable Fuels"),
|
| 86 |
+
"MATR_CHEM": ("MATR", "Chemicals"),
|
| 87 |
+
"MATR_AGCHEM": ("MATR", "Fertilizers & Agricultural Chemicals"),
|
| 88 |
+
"MATR_METALMIN": ("MATR", "Metals & Mining"),
|
| 89 |
+
"MATR_PRECIOUS": ("MATR", "Gold & Precious Metals"),
|
| 90 |
+
"MATR_STEEL": ("MATR", "Steel"),
|
| 91 |
+
"MATR_NONFERROUS": ("MATR", "Aluminium & Nonferrous Metals"),
|
| 92 |
+
"MATR_FOREST": ("MATR", "Paper & Forest Products"),
|
| 93 |
+
"MATR_CONTAIN": ("MATR", "Containers & Packaging"),
|
| 94 |
+
"MATR_BLDGMAT": ("MATR", "Construction Materials"),
|
| 95 |
+
"MATR_RUBBER": ("MATR", "Rubber & Plastic Products"),
|
| 96 |
+
"INDU_AERO": ("INDU", "Aerospace & Defence"),
|
| 97 |
+
"INDU_MACH": ("INDU", "Machinery"),
|
| 98 |
+
"INDU_ELECEQ": ("INDU", "Electrical Equipment"),
|
| 99 |
+
"INDU_BLDGPROD": ("INDU", "Building Products"),
|
| 100 |
+
"INDU_CONSTR": ("INDU", "Construction & Engineering"),
|
| 101 |
+
"INDU_DISTRIB": ("INDU", "Trading Companies & Distributors"),
|
| 102 |
+
"INDU_COMMSVC": ("INDU", "Commercial Services & Supplies"),
|
| 103 |
+
"INDU_PROFSVC": ("INDU", "Professional Services"),
|
| 104 |
+
"INDU_WASTE": ("INDU", "Waste Management"),
|
| 105 |
+
"INDU_RAIL": ("INDU", "Rail Transportation"),
|
| 106 |
+
"INDU_GROUND": ("INDU", "Ground Transportation"),
|
| 107 |
+
"INDU_MARINE": ("INDU", "Marine Transportation"),
|
| 108 |
+
"INDU_AIRLINE": ("INDU", "Passenger Airlines"),
|
| 109 |
+
"INDU_LOGISTICS": ("INDU", "Air Freight & Logistics"),
|
| 110 |
+
"INDU_MISC": ("INDU", "Diversified Industrial Products"),
|
| 111 |
+
"CONC_AUTO": ("CONC", "Automobiles"),
|
| 112 |
+
"CONC_AUTOPART": ("CONC", "Automobile Components"),
|
| 113 |
+
"CONC_HOMEBLD": ("CONC", "Homebuilding"),
|
| 114 |
+
"CONC_DURABLES": ("CONC", "Household Durables"),
|
| 115 |
+
"CONC_LEISURE": ("CONC", "Leisure Products"),
|
| 116 |
+
"CONC_TEXTILE": ("CONC", "Textiles, Apparel & Luxury Goods"),
|
| 117 |
+
"CONC_RETAIL": ("CONC", "Specialty Retail"),
|
| 118 |
+
"CONC_BROADLINE": ("CONC", "Broadline Retail"),
|
| 119 |
+
"CONC_ECOMM": ("CONC", "Direct & Online Retail"),
|
| 120 |
+
"CONC_RESTAURANT": ("CONC", "Restaurants"),
|
| 121 |
+
"CONC_HOTEL": ("CONC", "Hotels, Gaming & Leisure Facilities"),
|
| 122 |
+
"CONC_EDUCATION": ("CONC", "Education Services"),
|
| 123 |
+
"CONC_CONSSVC": ("CONC", "Consumer Services"),
|
| 124 |
+
"COND_AGRI": ("COND", "Agricultural Products"),
|
| 125 |
+
"COND_FOOD": ("COND", "Food Products"),
|
| 126 |
+
"COND_BEV": ("COND", "Beverages"),
|
| 127 |
+
"COND_TOBACCO": ("COND", "Tobacco"),
|
| 128 |
+
"COND_HOUSEHOLD": ("COND", "Household & Personal Products"),
|
| 129 |
+
"COND_FOODDIST": ("COND", "Food & Beverage Distribution"),
|
| 130 |
+
"COND_FOODRETAIL": ("COND", "Food & Drug Retail"),
|
| 131 |
+
"HLTH_PHARMA": ("HLTH", "Pharmaceuticals"),
|
| 132 |
+
"HLTH_BIOTECH": ("HLTH", "Biotechnology"),
|
| 133 |
+
"HLTH_TOOLS": ("HLTH", "Life Sciences Tools & Diagnostics"),
|
| 134 |
+
"HLTH_DEVICE": ("HLTH", "Health Care Equipment & Supplies"),
|
| 135 |
+
"HLTH_PROVIDER": ("HLTH", "Health Care Providers & Services"),
|
| 136 |
+
"HLTH_MANAGED": ("HLTH", "Managed Health Care"),
|
| 137 |
+
"HLTH_DIST": ("HLTH", "Health Care Distributors"),
|
| 138 |
+
"FINS_BANK": ("FINS", "Banks"),
|
| 139 |
+
"FINS_THRIFT": ("FINS", "Thrifts & Savings Institutions"),
|
| 140 |
+
"FINS_CONSFIN": ("FINS", "Consumer Finance"),
|
| 141 |
+
"FINS_MORTGAGE": ("FINS", "Mortgage Finance"),
|
| 142 |
+
"FINS_CAPMKT": ("FINS", "Capital Markets"),
|
| 143 |
+
"FINS_INSURANCE": ("FINS", "Insurance"),
|
| 144 |
+
"FINS_DIVFIN": ("FINS", "Diversified Financial Services"),
|
| 145 |
+
"TECH_SOFTWARE": ("TECH", "Software"),
|
| 146 |
+
"TECH_INTERNET": ("TECH", "Internet Software & Services"),
|
| 147 |
+
"TECH_ITSVC": ("TECH", "IT Services"),
|
| 148 |
+
"TECH_SEMI": ("TECH", "Semiconductors & Semiconductor Equipment"),
|
| 149 |
+
"TECH_HARDWARE": ("TECH", "Technology Hardware & Equipment"),
|
| 150 |
+
"TECH_COMMEQ": ("TECH", "Communications Equipment"),
|
| 151 |
+
"TECH_ELECTRONIC": ("TECH", "Electronic Equipment & Components"),
|
| 152 |
+
"TLCM_TELECOM": ("TLCM", "Telecommunication Services"),
|
| 153 |
+
"TLCM_MEDIA": ("TLCM", "Media & Entertainment"),
|
| 154 |
+
"TLCM_PUBLISH": ("TLCM", "Publishing"),
|
| 155 |
+
"TLCM_ADVERT": ("TLCM", "Advertising & Marketing"),
|
| 156 |
+
"UTIL_ELEC": ("UTIL", "Electric Utilities"),
|
| 157 |
+
"UTIL_GAS": ("UTIL", "Gas Utilities"),
|
| 158 |
+
"UTIL_WATER": ("UTIL", "Water Utilities"),
|
| 159 |
+
"UTIL_MULTI": ("UTIL", "Multi-Utilities"),
|
| 160 |
+
"REAL_REIT": ("REAL", "Real Estate Investment Trusts"),
|
| 161 |
+
"REAL_MGMT": ("REAL", "Real Estate Management & Development"),
|
| 162 |
+
"SHEL_BLANK": ("SHEL", "Blank Check & Shell Companies"),
|
| 163 |
+
"SHEL_NONOP": ("SHEL", "Non-Operating Establishments"),
|
| 164 |
+
"FUND_INVEST": ("FUND", "Investment Companies & Funds"),
|
| 165 |
+
"FUND_TRUST": ("FUND", "Trusts"),
|
| 166 |
+
"FUND_ABS": ("FUND", "Asset-Backed Securities"),
|
| 167 |
+
"GOVT_SOVEREIGN": ("GOVT", "Sovereign & Supranational"),
|
| 168 |
+
"GOVT_PUBLIC": ("GOVT", "Public Administration"),
|
| 169 |
+
"UNCL_ADR": ("UNCL", "Depositary Receipts"),
|
| 170 |
+
"UNCL_OTHER": ("UNCL", "Unclassified"),
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
# (low, high, industry code) over the four-digit code read as an integer.
|
| 174 |
+
# Ordered: the first range that contains the code wins, so every exception
|
| 175 |
+
# precedes the range it is an exception to.
|
| 176 |
+
RULES: tuple[tuple[int, int, str], ...] = (
|
| 177 |
+
# -- Division A: agriculture, forestry, fishing ------------------------
|
| 178 |
+
(800, 899, "MATR_FOREST"),
|
| 179 |
+
(100, 799, "COND_AGRI"),
|
| 180 |
+
(900, 999, "COND_AGRI"),
|
| 181 |
+
# -- Division B: mining ------------------------------------------------
|
| 182 |
+
(1040, 1049, "MATR_PRECIOUS"),
|
| 183 |
+
(1000, 1099, "MATR_METALMIN"),
|
| 184 |
+
(1200, 1299, "ENER_COAL"),
|
| 185 |
+
(1380, 1389, "ENER_SERVICES"),
|
| 186 |
+
(1300, 1399, "ENER_EP"),
|
| 187 |
+
(1400, 1499, "MATR_BLDGMAT"),
|
| 188 |
+
# -- Division C: construction ------------------------------------------
|
| 189 |
+
(1520, 1539, "CONC_HOMEBLD"),
|
| 190 |
+
(1500, 1799, "INDU_CONSTR"),
|
| 191 |
+
# -- Division D: manufacturing -----------------------------------------
|
| 192 |
+
(2080, 2089, "COND_BEV"),
|
| 193 |
+
(2000, 2099, "COND_FOOD"),
|
| 194 |
+
(2100, 2199, "COND_TOBACCO"),
|
| 195 |
+
(2200, 2399, "CONC_TEXTILE"),
|
| 196 |
+
(2430, 2439, "INDU_BLDGPROD"),
|
| 197 |
+
(2440, 2449, "MATR_CONTAIN"),
|
| 198 |
+
(2450, 2459, "CONC_HOMEBLD"),
|
| 199 |
+
(2400, 2499, "MATR_FOREST"),
|
| 200 |
+
(2510, 2519, "CONC_DURABLES"),
|
| 201 |
+
(2520, 2549, "INDU_COMMSVC"),
|
| 202 |
+
(2590, 2599, "CONC_DURABLES"),
|
| 203 |
+
(2500, 2599, "CONC_DURABLES"),
|
| 204 |
+
(2650, 2659, "MATR_CONTAIN"),
|
| 205 |
+
(2600, 2699, "MATR_FOREST"),
|
| 206 |
+
(2750, 2799, "INDU_COMMSVC"),
|
| 207 |
+
(2700, 2749, "TLCM_PUBLISH"),
|
| 208 |
+
(2830, 2833, "HLTH_PHARMA"),
|
| 209 |
+
(2834, 2834, "HLTH_PHARMA"),
|
| 210 |
+
(2835, 2835, "HLTH_TOOLS"),
|
| 211 |
+
(2836, 2836, "HLTH_BIOTECH"),
|
| 212 |
+
(2837, 2839, "HLTH_PHARMA"),
|
| 213 |
+
(2840, 2849, "COND_HOUSEHOLD"),
|
| 214 |
+
(2870, 2879, "MATR_AGCHEM"),
|
| 215 |
+
(2800, 2899, "MATR_CHEM"),
|
| 216 |
+
(2950, 2959, "MATR_BLDGMAT"),
|
| 217 |
+
(2900, 2999, "ENER_REFINE"),
|
| 218 |
+
(3011, 3011, "CONC_AUTOPART"),
|
| 219 |
+
(3021, 3021, "CONC_TEXTILE"),
|
| 220 |
+
(3000, 3099, "MATR_RUBBER"),
|
| 221 |
+
(3100, 3199, "CONC_TEXTILE"),
|
| 222 |
+
(3220, 3229, "MATR_CONTAIN"),
|
| 223 |
+
(3200, 3299, "MATR_BLDGMAT"),
|
| 224 |
+
(3300, 3329, "MATR_STEEL"),
|
| 225 |
+
(3330, 3369, "MATR_NONFERROUS"),
|
| 226 |
+
(3370, 3399, "MATR_STEEL"),
|
| 227 |
+
(3411, 3412, "MATR_CONTAIN"),
|
| 228 |
+
(3420, 3449, "INDU_BLDGPROD"),
|
| 229 |
+
(3480, 3489, "INDU_AERO"),
|
| 230 |
+
(3400, 3499, "INDU_MACH"),
|
| 231 |
+
(3533, 3533, "ENER_SERVICES"),
|
| 232 |
+
(3559, 3559, "TECH_SEMI"),
|
| 233 |
+
(3500, 3569, "INDU_MACH"),
|
| 234 |
+
(3576, 3576, "TECH_COMMEQ"),
|
| 235 |
+
(3570, 3579, "TECH_HARDWARE"),
|
| 236 |
+
(3580, 3599, "INDU_MACH"),
|
| 237 |
+
(3630, 3639, "CONC_DURABLES"),
|
| 238 |
+
(3651, 3651, "CONC_DURABLES"),
|
| 239 |
+
(3652, 3659, "TLCM_MEDIA"),
|
| 240 |
+
(3650, 3650, "CONC_DURABLES"),
|
| 241 |
+
(3660, 3669, "TECH_COMMEQ"),
|
| 242 |
+
(3695, 3695, "TECH_ELECTRONIC"),
|
| 243 |
+
(3674, 3674, "TECH_SEMI"),
|
| 244 |
+
(3670, 3679, "TECH_ELECTRONIC"),
|
| 245 |
+
(3600, 3699, "INDU_ELECEQ"),
|
| 246 |
+
(3714, 3715, "CONC_AUTOPART"),
|
| 247 |
+
(3716, 3716, "CONC_LEISURE"),
|
| 248 |
+
(3700, 3713, "CONC_AUTO"),
|
| 249 |
+
(3717, 3719, "CONC_AUTOPART"),
|
| 250 |
+
(3720, 3739, "INDU_AERO"),
|
| 251 |
+
(3740, 3749, "INDU_MACH"),
|
| 252 |
+
(3750, 3759, "CONC_LEISURE"),
|
| 253 |
+
(3760, 3769, "INDU_AERO"),
|
| 254 |
+
(3790, 3799, "CONC_LEISURE"),
|
| 255 |
+
(3770, 3789, "CONC_AUTO"),
|
| 256 |
+
(3800, 3819, "INDU_AERO"),
|
| 257 |
+
(3826, 3826, "HLTH_TOOLS"),
|
| 258 |
+
(3820, 3829, "TECH_ELECTRONIC"),
|
| 259 |
+
(3840, 3851, "HLTH_DEVICE"),
|
| 260 |
+
(3830, 3839, "TECH_ELECTRONIC"),
|
| 261 |
+
(3852, 3869, "TECH_ELECTRONIC"),
|
| 262 |
+
(3870, 3879, "CONC_TEXTILE"),
|
| 263 |
+
(3900, 3919, "CONC_TEXTILE"),
|
| 264 |
+
(3920, 3949, "CONC_LEISURE"),
|
| 265 |
+
(3950, 3959, "INDU_COMMSVC"),
|
| 266 |
+
(3960, 3969, "CONC_TEXTILE"),
|
| 267 |
+
(3970, 3989, "CONC_LEISURE"),
|
| 268 |
+
(3990, 3999, "INDU_MISC"),
|
| 269 |
+
# -- Division E: transport, communications, utilities ------------------
|
| 270 |
+
(4000, 4099, "INDU_RAIL"),
|
| 271 |
+
(4100, 4199, "INDU_GROUND"),
|
| 272 |
+
(4220, 4229, "INDU_LOGISTICS"),
|
| 273 |
+
(4200, 4299, "INDU_GROUND"),
|
| 274 |
+
(4300, 4399, "INDU_LOGISTICS"),
|
| 275 |
+
(4400, 4499, "INDU_MARINE"),
|
| 276 |
+
(4513, 4513, "INDU_LOGISTICS"),
|
| 277 |
+
(4580, 4599, "INDU_LOGISTICS"),
|
| 278 |
+
(4500, 4579, "INDU_AIRLINE"),
|
| 279 |
+
(4600, 4699, "ENER_MIDSTREAM"),
|
| 280 |
+
(4700, 4799, "INDU_LOGISTICS"),
|
| 281 |
+
(4830, 4849, "TLCM_MEDIA"),
|
| 282 |
+
(4800, 4899, "TLCM_TELECOM"),
|
| 283 |
+
(4920, 4929, "UTIL_GAS"),
|
| 284 |
+
(4930, 4939, "UTIL_MULTI"),
|
| 285 |
+
(4940, 4949, "UTIL_WATER"),
|
| 286 |
+
(4950, 4959, "INDU_WASTE"),
|
| 287 |
+
(4960, 4989, "UTIL_MULTI"),
|
| 288 |
+
(4900, 4999, "UTIL_ELEC"),
|
| 289 |
+
# -- Divisions F and G: wholesale and retail ---------------------------
|
| 290 |
+
(5047, 5047, "HLTH_DIST"),
|
| 291 |
+
(5122, 5122, "HLTH_DIST"),
|
| 292 |
+
(5140, 5149, "COND_FOODDIST"),
|
| 293 |
+
(5171, 5172, "ENER_REFINE"),
|
| 294 |
+
(5180, 5189, "COND_FOODDIST"),
|
| 295 |
+
(5000, 5199, "INDU_DISTRIB"),
|
| 296 |
+
(5200, 5299, "CONC_RETAIL"),
|
| 297 |
+
(5300, 5399, "CONC_BROADLINE"),
|
| 298 |
+
(5400, 5499, "COND_FOODRETAIL"),
|
| 299 |
+
(5500, 5799, "CONC_RETAIL"),
|
| 300 |
+
(5800, 5899, "CONC_RESTAURANT"),
|
| 301 |
+
(5912, 5912, "COND_FOODRETAIL"),
|
| 302 |
+
(5960, 5969, "CONC_ECOMM"),
|
| 303 |
+
(5900, 5999, "CONC_RETAIL"),
|
| 304 |
+
# -- Division H: finance, insurance, real estate -----------------------
|
| 305 |
+
(6035, 6036, "FINS_THRIFT"),
|
| 306 |
+
(6030, 6039, "FINS_THRIFT"),
|
| 307 |
+
(6000, 6099, "FINS_BANK"),
|
| 308 |
+
(6120, 6129, "FINS_THRIFT"),
|
| 309 |
+
(6140, 6149, "FINS_CONSFIN"),
|
| 310 |
+
(6111, 6111, "FINS_MORTGAGE"),
|
| 311 |
+
(6160, 6169, "FINS_MORTGAGE"),
|
| 312 |
+
(6189, 6189, "FUND_ABS"),
|
| 313 |
+
(6100, 6199, "FINS_DIVFIN"),
|
| 314 |
+
(6200, 6299, "FINS_CAPMKT"),
|
| 315 |
+
(6324, 6324, "HLTH_MANAGED"),
|
| 316 |
+
(6300, 6499, "FINS_INSURANCE"),
|
| 317 |
+
(6500, 6599, "REAL_MGMT"),
|
| 318 |
+
(6711, 6711, "FINS_BANK"),
|
| 319 |
+
(6700, 6719, "FINS_DIVFIN"),
|
| 320 |
+
(6720, 6729, "FUND_INVEST"),
|
| 321 |
+
(6730, 6739, "FUND_TRUST"),
|
| 322 |
+
(6740, 6769, "FINS_DIVFIN"),
|
| 323 |
+
(6770, 6770, "SHEL_BLANK"),
|
| 324 |
+
(6792, 6792, "ENER_EP"),
|
| 325 |
+
(6794, 6794, "INDU_PROFSVC"),
|
| 326 |
+
(6795, 6795, "ENER_EP"),
|
| 327 |
+
(6798, 6798, "REAL_REIT"),
|
| 328 |
+
(6771, 6799, "FUND_INVEST"),
|
| 329 |
+
# -- Division I: services ----------------------------------------------
|
| 330 |
+
(7000, 7099, "CONC_HOTEL"),
|
| 331 |
+
(7200, 7299, "CONC_CONSSVC"),
|
| 332 |
+
(7310, 7319, "TLCM_ADVERT"),
|
| 333 |
+
(7320, 7329, "INDU_PROFSVC"),
|
| 334 |
+
(7350, 7359, "INDU_DISTRIB"),
|
| 335 |
+
(7360, 7369, "INDU_PROFSVC"),
|
| 336 |
+
(7370, 7370, "TECH_INTERNET"),
|
| 337 |
+
(7372, 7372, "TECH_SOFTWARE"),
|
| 338 |
+
(7371, 7371, "TECH_ITSVC"),
|
| 339 |
+
(7373, 7379, "TECH_ITSVC"),
|
| 340 |
+
(7385, 7385, "TLCM_TELECOM"),
|
| 341 |
+
(7300, 7399, "INDU_COMMSVC"),
|
| 342 |
+
(7510, 7519, "INDU_GROUND"),
|
| 343 |
+
(7500, 7699, "CONC_CONSSVC"),
|
| 344 |
+
(7700, 7899, "TLCM_MEDIA"),
|
| 345 |
+
(7900, 7999, "CONC_HOTEL"),
|
| 346 |
+
(8071, 8071, "HLTH_TOOLS"),
|
| 347 |
+
(8000, 8099, "HLTH_PROVIDER"),
|
| 348 |
+
(8100, 8199, "INDU_PROFSVC"),
|
| 349 |
+
(8200, 8299, "CONC_EDUCATION"),
|
| 350 |
+
(8300, 8399, "CONC_CONSSVC"),
|
| 351 |
+
(8400, 8499, "CONC_HOTEL"),
|
| 352 |
+
(8500, 8699, "CONC_CONSSVC"),
|
| 353 |
+
(8711, 8711, "INDU_CONSTR"),
|
| 354 |
+
(8731, 8734, "HLTH_TOOLS"),
|
| 355 |
+
(8700, 8710, "INDU_CONSTR"),
|
| 356 |
+
(8712, 8730, "INDU_PROFSVC"),
|
| 357 |
+
(8735, 8799, "INDU_PROFSVC"),
|
| 358 |
+
(8880, 8880, "UNCL_ADR"),
|
| 359 |
+
(8888, 8888, "GOVT_SOVEREIGN"),
|
| 360 |
+
(8800, 8879, "UNCL_OTHER"),
|
| 361 |
+
(8881, 8887, "UNCL_OTHER"),
|
| 362 |
+
(8889, 8899, "UNCL_OTHER"),
|
| 363 |
+
(8900, 8999, "INDU_PROFSVC"),
|
| 364 |
+
# -- Divisions J and K: public administration, nonclassifiable ---------
|
| 365 |
+
(9721, 9721, "GOVT_SOVEREIGN"),
|
| 366 |
+
(9100, 9729, "GOVT_PUBLIC"),
|
| 367 |
+
(9995, 9995, "SHEL_NONOP"),
|
| 368 |
+
(9000, 9999, "UNCL_OTHER"),
|
| 369 |
+
)
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
@dataclass(frozen=True, slots=True)
|
| 373 |
+
class Assignment:
|
| 374 |
+
industry_code: str
|
| 375 |
+
industry: str
|
| 376 |
+
sector_code: str
|
| 377 |
+
sector: str
|
| 378 |
+
|
| 379 |
+
|
| 380 |
+
def _assignment(industry_code: str) -> Assignment:
|
| 381 |
+
sector_code, industry = INDUSTRIES[industry_code]
|
| 382 |
+
return Assignment(industry_code, industry, sector_code, SECTORS[sector_code])
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
UNCLASSIFIED = _assignment("UNCL_OTHER")
|
| 386 |
+
|
| 387 |
+
# Where there is no industry code at all, what the filer files still says what
|
| 388 |
+
# kind of thing it is. A closed-end fund has no industry and never will; a
|
| 389 |
+
# depositary receipt programme has whatever industry its underlying has, which
|
| 390 |
+
# EDGAR does not record. Both are better stated than left as a bare null,
|
| 391 |
+
# which reads the same as a failure.
|
| 392 |
+
ENTITY_KIND_INDUSTRY: dict[str, str] = {
|
| 393 |
+
"investment_company": "FUND_INVEST",
|
| 394 |
+
"depositary_receipt": "UNCL_ADR",
|
| 395 |
+
}
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def classify_entity(kind: str | None) -> Assignment | None:
|
| 399 |
+
"""Sector and industry implied by what a filer files, or None."""
|
| 400 |
+
industry_code = ENTITY_KIND_INDUSTRY.get(kind or "")
|
| 401 |
+
return _assignment(industry_code) if industry_code else None
|
| 402 |
+
|
| 403 |
+
|
| 404 |
+
def classify(code: str | None) -> Assignment:
|
| 405 |
+
"""Sector and industry for a four-digit SIC code.
|
| 406 |
+
|
| 407 |
+
A code nothing matches is unclassified rather than an error. EDGAR has
|
| 408 |
+
added codes before -- asset-backed securities and crypto assets both
|
| 409 |
+
arrived after the 1987 manual -- and a build that refused to run because
|
| 410 |
+
the SEC invented a code would be worse than one that labels it honestly
|
| 411 |
+
and lets the quality gate count how many there are.
|
| 412 |
+
"""
|
| 413 |
+
if not code or not code.isdigit() or len(code) != 4:
|
| 414 |
+
return UNCLASSIFIED
|
| 415 |
+
value = int(code)
|
| 416 |
+
for low, high, industry_code in RULES:
|
| 417 |
+
if low <= value <= high:
|
| 418 |
+
return _assignment(industry_code)
|
| 419 |
+
return UNCLASSIFIED
|
| 420 |
+
|
| 421 |
+
|
| 422 |
+
def sector_of(code: str | None) -> str:
|
| 423 |
+
return classify(code).sector_code
|
| 424 |
+
|
| 425 |
+
|
| 426 |
+
__all__ = [
|
| 427 |
+
"ENTITY_KIND_INDUSTRY",
|
| 428 |
+
"INDUSTRIES",
|
| 429 |
+
"RULES",
|
| 430 |
+
"SECTORS",
|
| 431 |
+
"TAXONOMY_VERSION",
|
| 432 |
+
"UNCLASSIFIED",
|
| 433 |
+
"Assignment",
|
| 434 |
+
"classify",
|
| 435 |
+
"classify_entity",
|
| 436 |
+
"sector_of",
|
| 437 |
+
]
|
tests/conftest.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 statement(cik, sic, day, *, source="xbrl", ref="acc-1", dated=True):
|
| 16 |
+
return {
|
| 17 |
+
"cik": cik, "sic": sic, "stated_on": day,
|
| 18 |
+
"knowledge_time": datetime.combine(day, datetime.min.time(), tzinfo=UTC),
|
| 19 |
+
"source": source, "source_ref": ref, "is_dated": dated,
|
| 20 |
+
"inserted_at": datetime.now(UTC),
|
| 21 |
+
}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@pytest.fixture
|
| 25 |
+
def observations() -> pl.DataFrame:
|
| 26 |
+
"""A de-SPAC, a steady company, and a filer EDGAR only knows about today.
|
| 27 |
+
|
| 28 |
+
Filer 1 is the case the point-in-time columns exist for: it filed as a
|
| 29 |
+
blank check, merged with a car maker and was reclassified. A dataset that
|
| 30 |
+
stated only today's code would put an automotive sector on its 2020
|
| 31 |
+
filings, when it was an empty shell.
|
| 32 |
+
"""
|
| 33 |
+
rows = [
|
| 34 |
+
statement("0000000001", "6770", date(2020, 3, 2), ref="a1"),
|
| 35 |
+
statement("0000000001", "6770", date(2020, 8, 2), ref="a2"),
|
| 36 |
+
statement("0000000001", "3711", date(2021, 5, 2), ref="a3"),
|
| 37 |
+
statement("0000000001", "3711", date(2024, 5, 2), ref="a4"),
|
| 38 |
+
statement("0000000002", "2834", date(2012, 1, 5), ref="b1"),
|
| 39 |
+
statement("0000000002", "2834", date(2023, 1, 5), ref="b2"),
|
| 40 |
+
statement("0000000003", "6022", date(2026, 10, 1), source="submissions",
|
| 41 |
+
ref="CIK0000000003.json", dated=False),
|
| 42 |
+
]
|
| 43 |
+
return pl.DataFrame(rows)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@pytest.fixture
|
| 47 |
+
def tickers() -> pl.DataFrame:
|
| 48 |
+
"""Ticker spans as the security master publishes them."""
|
| 49 |
+
return pl.DataFrame([
|
| 50 |
+
{"cik": "0000000001", "ticker": "SPAC", "valid_from": date(2020, 3, 2),
|
| 51 |
+
"valid_to": date(2021, 2, 1), "is_current": False},
|
| 52 |
+
{"cik": "0000000001", "ticker": "CARZ", "valid_from": date(2021, 5, 2),
|
| 53 |
+
"valid_to": date(2024, 5, 2), "is_current": True},
|
| 54 |
+
{"cik": "0000000002", "ticker": "PILL", "valid_from": date(2012, 1, 5),
|
| 55 |
+
"valid_to": date(2023, 1, 5), "is_current": True},
|
| 56 |
+
# Delisted in 2007: the only code EDGAR holds for it is today's.
|
| 57 |
+
{"cik": "0000000003", "ticker": "GONE", "valid_from": date(2006, 4, 1),
|
| 58 |
+
"valid_to": date(2007, 9, 1), "is_current": False},
|
| 59 |
+
# A filer nothing knows a code for at all.
|
| 60 |
+
{"cik": "0000000004", "ticker": "HUH", "valid_from": date(2011, 1, 1),
|
| 61 |
+
"valid_to": date(2012, 1, 1), "is_current": False},
|
| 62 |
+
])
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
@pytest.fixture
|
| 66 |
+
def directory() -> pl.DataFrame:
|
| 67 |
+
return pl.DataFrame([
|
| 68 |
+
{"cik": f"000000000{n}", "name": name, "primary_ticker": ticker,
|
| 69 |
+
"all_tickers": ticker, "exchange": "NYSE", "is_active": active,
|
| 70 |
+
"first_seen": date(2006, 1, 1)}
|
| 71 |
+
for n, name, ticker, active in (
|
| 72 |
+
(1, "Car Co", "CARZ", True), (2, "Pill Co", "PILL", True),
|
| 73 |
+
(3, "Gone Co", "GONE", False), (4, "Huh Co", "HUH", False),
|
| 74 |
+
)
|
| 75 |
+
])
|
tests/test_build.py
ADDED
|
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""What the derived tables must say about a company that changed business."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from datetime import date
|
| 6 |
+
|
| 7 |
+
import polars as pl
|
| 8 |
+
|
| 9 |
+
from recipe.build import (
|
| 10 |
+
build_by_ticker,
|
| 11 |
+
build_classification,
|
| 12 |
+
build_spans,
|
| 13 |
+
build_taxonomy_table,
|
| 14 |
+
entity_fallback,
|
| 15 |
+
)
|
| 16 |
+
from recipe.schema import CONFIG_SCHEMAS
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def test_spans_are_runs_not_groups(observations):
|
| 20 |
+
spans = build_spans(observations)
|
| 21 |
+
first = spans.filter(pl.col("cik") == "0000000001").sort("valid_from")
|
| 22 |
+
assert first["sic"].to_list() == ["6770", "3711"]
|
| 23 |
+
assert first["valid_from"].to_list() == [date(2020, 3, 2), date(2021, 5, 2)]
|
| 24 |
+
# valid_to is the last filing that said so, not the day before the next.
|
| 25 |
+
assert first["valid_to"].to_list() == [date(2020, 8, 2), date(2024, 5, 2)]
|
| 26 |
+
assert first["observations"].to_list() == [2, 2]
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_a_company_reclassified_back_keeps_both_spans():
|
| 30 |
+
"""A groupby on (filer, code) would merge these and lose the order."""
|
| 31 |
+
rows = [
|
| 32 |
+
{"cik": "1", "sic": "6770", "stated_on": date(2020, 1, 1), "knowledge_time": None,
|
| 33 |
+
"source": "xbrl", "source_ref": "a", "is_dated": True, "inserted_at": None},
|
| 34 |
+
{"cik": "1", "sic": "3711", "stated_on": date(2021, 1, 1), "knowledge_time": None,
|
| 35 |
+
"source": "xbrl", "source_ref": "b", "is_dated": True, "inserted_at": None},
|
| 36 |
+
{"cik": "1", "sic": "6770", "stated_on": date(2022, 1, 1), "knowledge_time": None,
|
| 37 |
+
"source": "xbrl", "source_ref": "c", "is_dated": True, "inserted_at": None},
|
| 38 |
+
]
|
| 39 |
+
spans = build_spans(pl.DataFrame(rows)).sort("valid_from")
|
| 40 |
+
assert spans.height == 3
|
| 41 |
+
assert spans["rank_for_filer"].to_list() == [3, 2, 1]
|
| 42 |
+
assert spans["is_latest"].to_list() == [False, False, True]
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def test_the_latest_span_is_the_one_marked(observations):
|
| 46 |
+
spans = build_spans(observations)
|
| 47 |
+
latest = spans.filter(pl.col("is_latest")).sort("cik")
|
| 48 |
+
assert latest["cik"].to_list() == ["0000000001", "0000000002", "0000000003"]
|
| 49 |
+
assert latest["sic"].to_list() == ["3711", "2834", "6022"]
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def test_classification_is_one_row_per_filer(observations, directory):
|
| 53 |
+
spans = build_spans(observations)
|
| 54 |
+
reference = pl.DataFrame({
|
| 55 |
+
"sic": ["3711", "2834", "6022"],
|
| 56 |
+
"title": ["MOTOR VEHICLES", "PHARMACEUTICAL PREPARATIONS", "STATE COMMERCIAL BANKS"],
|
| 57 |
+
"sic_level": ["industry"] * 3, "sec_office": [None] * 3,
|
| 58 |
+
"division": ["D", "D", "H"], "division_title": ["Manufacturing"] * 2 + ["Finance"],
|
| 59 |
+
"major_group": ["37", "28", "60"], "major_group_title": [None] * 3,
|
| 60 |
+
"industry_group": ["371", "283", "602"],
|
| 61 |
+
"sector_code": ["CONC", "HLTH", "FINS"],
|
| 62 |
+
"sector": ["Consumer Cyclical", "Health Care", "Financials"],
|
| 63 |
+
"industry_code": ["CONC_AUTO", "HLTH_PHARMA", "FINS_BANK"],
|
| 64 |
+
"industry": ["Automobiles", "Pharmaceuticals", "Banks"],
|
| 65 |
+
"naics_1997": [None] * 3, "naics_title": [None] * 3,
|
| 66 |
+
"naics_sector": [None] * 3, "naics_sector_title": [None] * 3,
|
| 67 |
+
"naics_candidates": [0, 0, 0],
|
| 68 |
+
})
|
| 69 |
+
frame = build_classification(spans, directory, reference, entity_fallback(pl.DataFrame()))
|
| 70 |
+
assert frame.height == frame["cik"].n_unique() == 3
|
| 71 |
+
car = frame.filter(pl.col("cik") == "0000000001").row(0, named=True)
|
| 72 |
+
assert (car["sector_code"], car["sic"]) == ("CONC", "3711")
|
| 73 |
+
assert car["is_dated"] is True
|
| 74 |
+
bank = frame.filter(pl.col("cik") == "0000000003").row(0, named=True)
|
| 75 |
+
# Its only code came from today's snapshot, so it carries no history.
|
| 76 |
+
assert bank["is_dated"] is False
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def test_by_ticker_clips_to_the_overlap(observations, tickers, directory):
|
| 80 |
+
spans = build_spans(observations)
|
| 81 |
+
frame = build_by_ticker(tickers, spans, directory)
|
| 82 |
+
|
| 83 |
+
spac = frame.filter(pl.col("ticker") == "SPAC").row(0, named=True)
|
| 84 |
+
assert spac["sector_code"] == "SHEL"
|
| 85 |
+
assert spac["valid_to"] == date(2020, 8, 2) # the SIC span ends first
|
| 86 |
+
assert spac["date_basis"] == "dated"
|
| 87 |
+
|
| 88 |
+
carz = frame.filter(pl.col("ticker") == "CARZ").row(0, named=True)
|
| 89 |
+
assert (carz["sector_code"], carz["is_current"]) == ("CONC", True)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_a_ticker_that_predates_the_evidence_still_gets_a_row(tickers, observations, directory):
|
| 93 |
+
"""Delisted in 2007, so no filing overlaps; dropping it would leave the
|
| 94 |
+
universe made of survivors."""
|
| 95 |
+
frame = build_by_ticker(tickers, build_spans(observations), directory)
|
| 96 |
+
gone = frame.filter(pl.col("ticker") == "GONE").row(0, named=True)
|
| 97 |
+
assert gone["date_basis"] == "undated"
|
| 98 |
+
assert gone["sector_code"] == "FINS"
|
| 99 |
+
assert (gone["valid_from"], gone["valid_to"]) == (date(2006, 4, 1), date(2007, 9, 1))
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_a_ticker_with_no_code_at_all_is_present_and_unclassified(
|
| 103 |
+
tickers, observations, directory
|
| 104 |
+
):
|
| 105 |
+
frame = build_by_ticker(tickers, build_spans(observations), directory)
|
| 106 |
+
huh = frame.filter(pl.col("ticker") == "HUH").row(0, named=True)
|
| 107 |
+
assert (huh["date_basis"], huh["sector_code"], huh["sic"]) == ("unknown", "UNCL", None)
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def test_is_current_marks_exactly_one_row_per_live_ticker(tickers, observations, directory):
|
| 111 |
+
"""A live ticker whose company was reclassified must not come back current
|
| 112 |
+
under both its old sector and its new one."""
|
| 113 |
+
frame = build_by_ticker(tickers, build_spans(observations), directory)
|
| 114 |
+
current = frame.filter(pl.col("is_current"))
|
| 115 |
+
assert current.height == current["ticker"].n_unique()
|
| 116 |
+
assert set(current["ticker"]) == {"CARZ", "PILL"}
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_taxonomy_table_lists_every_industry():
|
| 120 |
+
frame = build_taxonomy_table()
|
| 121 |
+
assert set(frame.columns) <= set(CONFIG_SCHEMAS["taxonomy"])
|
| 122 |
+
assert frame["industry_code"].n_unique() == frame.height
|
| 123 |
+
assert frame.filter(pl.col("industry_code") == "HLTH_PHARMA")["sic_ranges"].item()
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def test_a_filer_known_only_by_its_forms_still_gets_classified(
|
| 127 |
+
observations, tickers, directory
|
| 128 |
+
):
|
| 129 |
+
"""A closed-end fund has no industry code and never will. Saying "fund"
|
| 130 |
+
beats a null, which reads the same as a failure."""
|
| 131 |
+
kinds = pl.DataFrame({
|
| 132 |
+
"cik": ["0000000004"], "entity_kind": ["investment_company"],
|
| 133 |
+
"source_ref": ["CIK0000000004.json"],
|
| 134 |
+
})
|
| 135 |
+
fallback = entity_fallback(kinds)
|
| 136 |
+
assert fallback.row(0, named=True)["sector_code"] == "FUND"
|
| 137 |
+
|
| 138 |
+
frame = build_by_ticker(tickers, build_spans(observations), directory, fallback)
|
| 139 |
+
huh = frame.filter(pl.col("ticker") == "HUH").row(0, named=True)
|
| 140 |
+
assert (huh["sector_code"], huh["industry_code"]) == ("FUND", "FUND_INVEST")
|
| 141 |
+
assert huh["date_basis"] == "unknown" # still no date behind it
|
| 142 |
+
assert huh["sic"] is None # and no code was invented for it
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def test_the_fallback_never_overrides_an_assigned_code(observations, tickers, directory):
|
| 146 |
+
kinds = pl.DataFrame({
|
| 147 |
+
"cik": ["0000000002"], "entity_kind": ["investment_company"],
|
| 148 |
+
"source_ref": ["x"],
|
| 149 |
+
})
|
| 150 |
+
frame = build_by_ticker(
|
| 151 |
+
tickers, build_spans(observations), directory, entity_fallback(kinds)
|
| 152 |
+
)
|
| 153 |
+
pill = frame.filter(pl.col("ticker") == "PILL").row(0, named=True)
|
| 154 |
+
assert pill["sector_code"] == "HLTH"
|
tests/test_docs_and_jobs.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from recipe.taxonomy import SECTORS
|
| 15 |
+
|
| 16 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _readme() -> str:
|
| 20 |
+
return (ROOT / "README.md").read_text(encoding="utf-8")
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _frontmatter() -> dict:
|
| 24 |
+
text = _readme()
|
| 25 |
+
assert text.startswith("---\n")
|
| 26 |
+
return yaml.safe_load(text.split("---\n", 2)[1])
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def test_readme_declares_every_config():
|
| 30 |
+
assert {entry["config_name"] for entry in _frontmatter()["configs"]} == set(CONFIG_SCHEMAS)
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def test_readme_has_no_unfilled_placeholders():
|
| 34 |
+
assert not re.findall(r"\{\{[A-Z_]+\}\}", _readme())
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def test_readme_names_every_sector():
|
| 38 |
+
"""The card is where somebody decides whether the taxonomy suits them."""
|
| 39 |
+
text = _readme()
|
| 40 |
+
for code, name in SECTORS.items():
|
| 41 |
+
assert name in text, f"sector {code} ({name}) is not in the dataset card"
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def test_readme_states_that_this_is_not_gics_or_icb():
|
| 45 |
+
"""The one claim that would be wrong and expensive to leave implied."""
|
| 46 |
+
text = _readme().lower()
|
| 47 |
+
assert "gics" in text and "icb" in text
|
| 48 |
+
assert "not gics" in text or "is not gics" in text or "neither gics" in text
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def test_job_script_declares_every_runtime_dependency():
|
| 52 |
+
"""A Job installs from the script header alone; a gap fails only in the cloud."""
|
| 53 |
+
project = tomllib.loads((ROOT / "pyproject.toml").read_text(encoding="utf-8"))["project"]
|
| 54 |
+
required = {
|
| 55 |
+
re.split(r"[<>=]", n, maxsplit=1)[0].strip().lower() for n in project["dependencies"]
|
| 56 |
+
}
|
| 57 |
+
for group in ("dev", "publish"):
|
| 58 |
+
required |= {
|
| 59 |
+
re.split(r"[<>=]", n, maxsplit=1)[0].strip().lower()
|
| 60 |
+
for n in project.get("optional-dependencies", {}).get(group, [])
|
| 61 |
+
}
|
| 62 |
+
header = (ROOT / JOB_SCRIPT).read_text(encoding="utf-8").split("# ///")[1]
|
| 63 |
+
declared = {m.group(1).lower() for m in re.finditer(r'"\s*([A-Za-z0-9_.-]+)\s*[<>=]', header)}
|
| 64 |
+
assert required <= declared, required - declared
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_schedule_runs_after_the_datasets_it_reads():
|
| 68 |
+
"""Assembled from company-fundamentals (07:10 Mon) and security-master
|
| 69 |
+
(07:40 Mon); running before either publishes a week-old classification."""
|
| 70 |
+
minute, hour, _, _, weekday = DEFAULT_SCHEDULE.split()
|
| 71 |
+
assert weekday == "1", DEFAULT_SCHEDULE
|
| 72 |
+
assert (int(hour), int(minute)) > (7, 40), DEFAULT_SCHEDULE
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def test_manifest_lists_the_same_configs_as_the_schema():
|
| 76 |
+
path = ROOT / "manifest.json"
|
| 77 |
+
if not path.is_file():
|
| 78 |
+
return # written by the first build
|
| 79 |
+
manifest = json.loads(path.read_text(encoding="utf-8"))
|
| 80 |
+
assert set(manifest["configs"]) == set(CONFIG_SCHEMAS)
|
| 81 |
+
assert set(manifest["sectors"]) == set(SECTORS)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def test_notice_credits_every_source():
|
| 85 |
+
notice = (ROOT / "NOTICE").read_text(encoding="utf-8")
|
| 86 |
+
for source in ("Securities and Exchange Commission", "Census Bureau"):
|
| 87 |
+
assert source in notice
|
tests/test_sources.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Parsing the two scraped sources: a web page and a 2008 spreadsheet."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import polars as pl
|
| 6 |
+
|
| 7 |
+
from recipe.sic import DIVISIONS
|
| 8 |
+
from recipe.sources import parse_concordance
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
class _FakePage:
|
| 12 |
+
def __init__(self, text: str) -> None:
|
| 13 |
+
self._text = text
|
| 14 |
+
|
| 15 |
+
async def get_text(self, *_args, **_kwargs) -> str:
|
| 16 |
+
return self._text
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
SIC_PAGE = """
|
| 20 |
+
<table>
|
| 21 |
+
<tr><th>SIC Code</th><th>Office</th><th>Industry Title</th></tr>
|
| 22 |
+
<tr><td>100</td><td>Industrial Applications and Services</td>
|
| 23 |
+
<td>AGRICULTURAL PRODUCTION-CROPS</td></tr>
|
| 24 |
+
<tr><td>2834</td><td>Office of Life Sciences</td><td>PHARMACEUTICAL PREPARATIONS</td></tr>
|
| 25 |
+
<tr><td>6770</td><td>Multiple Offices</td><td>BLANK CHECKS</td></tr>
|
| 26 |
+
</table>
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def test_sic_list_parses_three_column_rows():
|
| 31 |
+
from recipe.sources import parse_sic_list
|
| 32 |
+
|
| 33 |
+
frame = parse_sic_list(SIC_PAGE)
|
| 34 |
+
assert frame["sic"].to_list() == ["0100", "2834", "6770"]
|
| 35 |
+
assert frame.filter(pl.col("sic") == "2834")["title"].item() == "PHARMACEUTICAL PREPARATIONS"
|
| 36 |
+
assert frame.filter(pl.col("sic") == "6770")["sec_office"].item() == "Multiple Offices"
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
async def test_sic_list_refuses_a_page_that_lost_its_table():
|
| 40 |
+
"""A layout change must fail the build, not silently drop 200 titles."""
|
| 41 |
+
from recipe.sources import edgar_sic_list
|
| 42 |
+
|
| 43 |
+
try:
|
| 44 |
+
await edgar_sic_list(_FakePage(SIC_PAGE))
|
| 45 |
+
except RuntimeError as error:
|
| 46 |
+
assert "444" in str(error)
|
| 47 |
+
else: # pragma: no cover - the guard is the point of the test
|
| 48 |
+
raise AssertionError("a three-row page should not have been accepted")
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
CONCORDANCE = pl.DataFrame(
|
| 52 |
+
{
|
| 53 |
+
"SIC": [None, "28", "2834", "2836", "2836", None, "99", "9999"],
|
| 54 |
+
"Part Indicator": [None, None, None, "pt", "pt", None, None, None],
|
| 55 |
+
"SIC Titles and Part Descriptions": [
|
| 56 |
+
"Manufacturing", "Chemicals and allied products", "Pharmaceutical Preparations",
|
| 57 |
+
". Vaccines", ". Other", "Nonclassifiable establishments",
|
| 58 |
+
"Nonclassifiable", "Nonclassifiable Establishments",
|
| 59 |
+
],
|
| 60 |
+
"1997 NAICS": [None, None, "325412", "325414", "325411", None, None, "99999"],
|
| 61 |
+
"1997 NAICS Titles and Part Indicators": [
|
| 62 |
+
None, None, "Pharmaceutical Preparation Manufacturing",
|
| 63 |
+
"Biological Product Manufacturing", "Medicinal and Botanical Manufacturing",
|
| 64 |
+
None, None, "Unclassified Establishments",
|
| 65 |
+
],
|
| 66 |
+
}
|
| 67 |
+
)
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _workbook() -> bytes:
|
| 71 |
+
import io
|
| 72 |
+
|
| 73 |
+
buffer = io.BytesIO()
|
| 74 |
+
CONCORDANCE.write_excel(buffer)
|
| 75 |
+
return buffer.getvalue()
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_concordance_separates_hierarchy_from_crosswalk():
|
| 79 |
+
crosswalk, major_groups, divisions = parse_concordance(_workbook())
|
| 80 |
+
assert divisions == ["Manufacturing", "Nonclassifiable establishments"]
|
| 81 |
+
assert major_groups["28"] == "Chemicals and allied products"
|
| 82 |
+
# Supplied here because the Census file never prints a header row for them.
|
| 83 |
+
assert major_groups["40"] == "Railroad Transportation"
|
| 84 |
+
assert set(crosswalk["sic"]) == {"2834", "2836", "9999"}
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_a_split_industry_keeps_every_candidate():
|
| 88 |
+
crosswalk, _, _ = parse_concordance(_workbook())
|
| 89 |
+
split = crosswalk.filter(pl.col("sic") == "2836")
|
| 90 |
+
assert split.height == 2
|
| 91 |
+
assert split["is_part"].to_list() == [True, True]
|
| 92 |
+
assert split["part_description"].to_list() == ["Vaccines", "Other"]
|
| 93 |
+
assert set(split["naics_sector"]) == {"32"}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_division_ranges_are_ordered_and_do_not_overlap():
|
| 97 |
+
"""The letters are asserted in code rather than read from a source, so
|
| 98 |
+
the structure they claim has to hold on its own terms."""
|
| 99 |
+
previous_high = 0
|
| 100 |
+
for letter, low, high, title in DIVISIONS:
|
| 101 |
+
assert low <= high, letter
|
| 102 |
+
assert low > previous_high, f"division {letter} overlaps the one before it"
|
| 103 |
+
assert title.strip() == title and title
|
| 104 |
+
previous_high = high
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def test_concordance_divisions_match_the_declared_count():
|
| 108 |
+
_, _, divisions = parse_concordance(_workbook())
|
| 109 |
+
assert len(set(divisions)) == len(divisions)
|
| 110 |
+
assert divisions[0] == "Manufacturing"
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def test_a_truncated_archive_is_not_accepted(tmp_path):
|
| 114 |
+
"""Half the bug this guards: a partial download that fails as a
|
| 115 |
+
`BadZipFile` thousands of lines later instead of at the download."""
|
| 116 |
+
import zipfile
|
| 117 |
+
|
| 118 |
+
from recipe.sources import _is_readable_zip
|
| 119 |
+
|
| 120 |
+
good = tmp_path / "good.zip"
|
| 121 |
+
with zipfile.ZipFile(good, "w") as bundle:
|
| 122 |
+
bundle.writestr("CIK0000000001.json", '{"sic": "2834"}')
|
| 123 |
+
assert _is_readable_zip(good)
|
| 124 |
+
|
| 125 |
+
payload = good.read_bytes()
|
| 126 |
+
truncated = tmp_path / "truncated.zip"
|
| 127 |
+
truncated.write_bytes(payload[: len(payload) // 2])
|
| 128 |
+
assert not _is_readable_zip(truncated)
|
| 129 |
+
|
| 130 |
+
assert not _is_readable_zip(tmp_path / "absent.zip")
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def test_an_overlong_archive_still_opens_which_is_why_the_size_is_checked(tmp_path):
|
| 134 |
+
"""The other half, and the reason there are two checks rather than one.
|
| 135 |
+
|
| 136 |
+
The real failure was a `.part` file another process was still writing:
|
| 137 |
+
the downloader appended to it and ended up 10 MB past the declared length.
|
| 138 |
+
A zip with bytes after its directory still opens -- the reader scans
|
| 139 |
+
backwards for the end record -- so only comparing the byte count against
|
| 140 |
+
what the server declared catches this.
|
| 141 |
+
"""
|
| 142 |
+
import zipfile
|
| 143 |
+
|
| 144 |
+
from recipe.sources import _is_readable_zip
|
| 145 |
+
|
| 146 |
+
good = tmp_path / "good.zip"
|
| 147 |
+
with zipfile.ZipFile(good, "w") as bundle:
|
| 148 |
+
bundle.writestr("CIK0000000001.json", '{"sic": "2834"}')
|
| 149 |
+
overlong = tmp_path / "overlong.zip"
|
| 150 |
+
overlong.write_bytes(good.read_bytes() + b"\x00" * 4096)
|
| 151 |
+
|
| 152 |
+
assert _is_readable_zip(overlong)
|
| 153 |
+
assert overlong.stat().st_size != good.stat().st_size
|
| 154 |
+
|
| 155 |
+
|
| 156 |
+
def test_read_bulk_sic_takes_only_the_metadata_member(tmp_path):
|
| 157 |
+
import zipfile
|
| 158 |
+
|
| 159 |
+
from recipe.sources import read_bulk_sic
|
| 160 |
+
|
| 161 |
+
archive = tmp_path / "submissions.zip"
|
| 162 |
+
with zipfile.ZipFile(archive, "w") as bundle:
|
| 163 |
+
bundle.writestr("CIK0000000001.json", '{"sic": "2834", "name": "Pill Co"}')
|
| 164 |
+
# The paginated history files beside it hold filings, not metadata.
|
| 165 |
+
bundle.writestr("CIK0000000001-submissions-001.json", '{"filings": []}')
|
| 166 |
+
bundle.writestr("CIK0000000002.json", '{"sic": "", "name": "No Code Co"}')
|
| 167 |
+
bundle.writestr("CIK0000000003.json", "not json at all")
|
| 168 |
+
|
| 169 |
+
rows, kinds = read_bulk_sic(
|
| 170 |
+
archive, ["0000000001", "0000000002", "0000000003", "0000000009"]
|
| 171 |
+
)
|
| 172 |
+
assert [row["sic"] for row in rows] == ["2834"]
|
| 173 |
+
assert rows[0]["is_dated"] is False
|
| 174 |
+
assert rows[0]["source"] == "submissions"
|
| 175 |
+
assert kinds == []
|
| 176 |
+
|
| 177 |
+
|
| 178 |
+
def test_a_filer_with_no_code_is_identified_by_what_it_files(tmp_path):
|
| 179 |
+
"""Sixteen hundred live symbols belong to filers the SEC never assigned an
|
| 180 |
+
industry. N-CSR and F-6 say what they are, by definition of the forms."""
|
| 181 |
+
import json
|
| 182 |
+
import zipfile
|
| 183 |
+
|
| 184 |
+
from recipe.sources import read_bulk_sic
|
| 185 |
+
|
| 186 |
+
def record(name, forms, entity="other"):
|
| 187 |
+
return json.dumps(
|
| 188 |
+
{"sic": "", "name": name, "entityType": entity,
|
| 189 |
+
"filings": {"recent": {"form": forms}}}
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
archive = tmp_path / "submissions.zip"
|
| 193 |
+
with zipfile.ZipFile(archive, "w") as bundle:
|
| 194 |
+
bundle.writestr("CIK0000000001.json", record("A Closed-End Fund", ["N-CSR", "4"]))
|
| 195 |
+
bundle.writestr("CIK0000000002.json", record("Foreign Co ADR", ["F-6EF", "SC 13D"]))
|
| 196 |
+
bundle.writestr("CIK0000000003.json", record("Dormant Shell", ["4"]))
|
| 197 |
+
bundle.writestr("CIK0000000004.json", record("A Fund", [], entity="investment"))
|
| 198 |
+
# A fund that also sponsors a receipt programme is still a fund.
|
| 199 |
+
bundle.writestr("CIK0000000005.json", record("Both", ["N-2", "F-6"]))
|
| 200 |
+
|
| 201 |
+
_, kinds = read_bulk_sic(archive, [f"000000000{n}" for n in range(1, 6)])
|
| 202 |
+
assert {row["cik"]: row["entity_kind"] for row in kinds} == {
|
| 203 |
+
"0000000001": "investment_company",
|
| 204 |
+
"0000000002": "depositary_receipt",
|
| 205 |
+
"0000000004": "investment_company",
|
| 206 |
+
"0000000005": "investment_company",
|
| 207 |
+
}
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def test_entity_kinds_resolve_to_a_fund_and_a_receipt():
|
| 211 |
+
from recipe.taxonomy import classify_entity
|
| 212 |
+
|
| 213 |
+
assert classify_entity("investment_company").sector_code == "FUND"
|
| 214 |
+
assert classify_entity("depositary_receipt").industry_code == "UNCL_ADR"
|
| 215 |
+
assert classify_entity(None) is None
|
| 216 |
+
assert classify_entity("something else") is None
|
tests/test_taxonomy.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""The taxonomy is code, and the things that would break it quietly."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
|
| 7 |
+
from recipe.quality import QualityReport, check_taxonomy
|
| 8 |
+
from recipe.sic import EDGAR_ONLY_CODES, code_level, division_of, normalize, prefix_of
|
| 9 |
+
from recipe.taxonomy import INDUSTRIES, RULES, SECTORS, classify
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def test_every_rule_names_a_real_industry_and_sector():
|
| 13 |
+
report = QualityReport()
|
| 14 |
+
check_taxonomy(report)
|
| 15 |
+
assert report.errors == []
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def test_every_industry_is_reachable_from_some_rule():
|
| 19 |
+
"""An industry no rule points at is a title nothing will ever carry."""
|
| 20 |
+
reachable = {code for _, _, code in RULES}
|
| 21 |
+
# The three catch-alls exist for codes outside EDGAR's current list.
|
| 22 |
+
unreachable = set(INDUSTRIES) - reachable
|
| 23 |
+
assert unreachable <= {"UNCL_OTHER", "FUND_TRUST", "GOVT_PUBLIC"}, unreachable
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def test_every_four_digit_code_classifies():
|
| 27 |
+
"""No gap in the rules: every code the SEC could invent lands somewhere."""
|
| 28 |
+
for value in range(100, 10_000):
|
| 29 |
+
assignment = classify(f"{value:04d}")
|
| 30 |
+
assert assignment.industry_code in INDUSTRIES
|
| 31 |
+
assert assignment.sector_code in SECTORS
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@pytest.mark.parametrize(
|
| 35 |
+
("sic", "sector", "industry"),
|
| 36 |
+
[
|
| 37 |
+
("2834", "HLTH", "HLTH_PHARMA"),
|
| 38 |
+
("2836", "HLTH", "HLTH_BIOTECH"),
|
| 39 |
+
# Managed care files under an insurance code and is not insurance.
|
| 40 |
+
("6324", "HLTH", "HLTH_MANAGED"),
|
| 41 |
+
("3674", "TECH", "TECH_SEMI"),
|
| 42 |
+
# Semiconductor equipment hides inside "special industry machinery".
|
| 43 |
+
("3559", "TECH", "TECH_SEMI"),
|
| 44 |
+
("7372", "TECH", "TECH_SOFTWARE"),
|
| 45 |
+
("6022", "FINS", "FINS_BANK"),
|
| 46 |
+
("6798", "REAL", "REAL_REIT"),
|
| 47 |
+
("6770", "SHEL", "SHEL_BLANK"),
|
| 48 |
+
("4911", "UTIL", "UTIL_ELEC"),
|
| 49 |
+
("1311", "ENER", "ENER_EP"),
|
| 50 |
+
# A roll-up resolves to the same place as the industries beneath it.
|
| 51 |
+
("2000", "COND", "COND_FOOD"),
|
| 52 |
+
("2011", "COND", "COND_FOOD"),
|
| 53 |
+
("8888", "GOVT", "GOVT_SOVEREIGN"),
|
| 54 |
+
("8880", "UNCL", "UNCL_ADR"),
|
| 55 |
+
],
|
| 56 |
+
)
|
| 57 |
+
def test_known_codes(sic, sector, industry):
|
| 58 |
+
assignment = classify(sic)
|
| 59 |
+
assert (assignment.sector_code, assignment.industry_code) == (sector, industry)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def test_narrow_rules_beat_the_ranges_that_contain_them():
|
| 63 |
+
"""First match wins, so an exception placed after its range is dead code."""
|
| 64 |
+
for index, (low, high, _) in enumerate(RULES):
|
| 65 |
+
for other_low, other_high, _ in RULES[index + 1:]:
|
| 66 |
+
contained = other_low >= low and other_high <= high
|
| 67 |
+
assert not (contained and (other_low, other_high) != (low, high)), (
|
| 68 |
+
f"range {other_low}-{other_high} sits inside the earlier "
|
| 69 |
+
f"{low}-{high} and can never match"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def test_unclassified_rather_than_raising():
|
| 74 |
+
for value in (None, "", "abc", "12345", "0"):
|
| 75 |
+
assert classify(value).sector_code == "UNCL"
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def test_normalize_accepts_what_edgar_actually_writes():
|
| 79 |
+
assert normalize("100") == "0100"
|
| 80 |
+
assert normalize(2834) == "2834"
|
| 81 |
+
assert normalize(" 3571 ") == "3571"
|
| 82 |
+
assert normalize("") is None
|
| 83 |
+
assert normalize("0000") is None
|
| 84 |
+
assert normalize("12345") is None
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def test_code_level_reads_the_padding():
|
| 88 |
+
assert code_level("2000") == "major_group"
|
| 89 |
+
assert code_level("2020") == "industry_group"
|
| 90 |
+
assert code_level("2834") == "industry"
|
| 91 |
+
assert prefix_of("2000") == "20"
|
| 92 |
+
assert prefix_of("2020") == "202"
|
| 93 |
+
assert prefix_of("2834") == "2834"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def test_divisions_cover_every_major_group_the_sec_uses():
|
| 97 |
+
assert division_of("2834").letter == "D"
|
| 98 |
+
assert division_of("6022").letter == "H"
|
| 99 |
+
assert division_of("9995") is None
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def test_edgar_inventions_have_no_division():
|
| 103 |
+
"""88 is Private Households; calling an ADR a household service is worse
|
| 104 |
+
than saying nothing."""
|
| 105 |
+
for code in EDGAR_ONLY_CODES:
|
| 106 |
+
assert division_of(code) is None
|