ZipLime commited on
Commit
72eadef
·
verified ·
1 Parent(s): 12f18b8

Update the security master

Browse files
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,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ZipLime US Corporate Actions
2
+ Copyright 2026 ZipLime
3
+
4
+ Derived from ZipLime/company-fundamentals, which is itself the SEC's Financial
5
+ Statement Data Sets — a US Government work in the public domain.
6
+
7
+ Split events other than those the filer tagged are inferred from restated
8
+ per-share figures and are labelled with the method and confidence that produced
9
+ them. They are not statements of record.
10
+
11
+ The SEC does not endorse, certify or verify this dataset.
PIPELINE.md ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # How this dataset is built
2
+
3
+ Every step is in [`recipe/`](recipe/), at the same revision as the data.
4
+
5
+ ## What could not be built, and why it matters
6
+
7
+ The first job was finding out what is actually reachable. The answer is
8
+ narrower than the name "corporate actions" suggests, and worth stating plainly
9
+ because everything else follows from it.
10
+
11
+ SEC's Financial Statement Data Sets carry `num.txt` — **numeric facts only**.
12
+ Dividend dates are typed as dates in XBRL, so they are in the filings and not
13
+ in the bulk data. The XBRL API is not a way around it: a request for
14
+ `DividendsPayableDateOfRecordDayMonthAndYear` returns 404, because that
15
+ endpoint serves unit-bearing facts and a date has no unit.
16
+
17
+ So there are no ex-dates, no record dates, no pay dates here. There is no free
18
+ structured source for them. What remains is still worth having: per-share
19
+ amounts by fiscal period, and split ratios.
20
+
21
+ ## Dividends
22
+
23
+ Six tags carry per-share dividends, and they mean different things.
24
+ `CommonStockDividendsPerShareDeclared` is a decision; `…CashPaid` is a cash
25
+ movement; the preferred variants are a claim that ranks ahead of the common
26
+ holder. They are kept apart rather than coalesced into one number.
27
+
28
+ Facts from both the consolidated and the dimensional tables are read. The
29
+ dimensional ones matter: a dividend declared after the period closed is tagged
30
+ `SubsequentEventType=SubsequentEvent`, which makes it the one dividend fact
31
+ that is not history — the declaration is already public when the filing is.
32
+
33
+ `period_start` is derived from `period_end` and the fact's own `quarters`. A
34
+ per-share dividend dated to an instant is a filer error and is dropped rather
35
+ than assigned a day it did not cover.
36
+
37
+ ## Splits: the trace, not the event
38
+
39
+ There is no free feed of US stock splits. There is, in a dataset that never
40
+ overwrites what a filing said, the trace a split leaves: it forces the company
41
+ to restate every earlier per-share figure by the ratio. Two filings covering
42
+ the same quarter, one before the split and one after, differ by exactly that
43
+ factor.
44
+
45
+ This is stronger than the signal most people reach for. A jump in shares
46
+ outstanding looks identical for a two-for-one split and for an equity raise
47
+ that doubled the count. Only a split reaches back and rewrites the past.
48
+
49
+ Three sources are combined and each is labelled:
50
+
51
+ | Method | Filers | Standing |
52
+ |---|---|---|
53
+ | `xbrl_tag` | 514 rows | the filer tagged the conversion ratio — authority |
54
+ | `eps_restatement` | 5 105 rows | inferred from restated per-share figures |
55
+ | `share_count` | — | never used alone; cannot tell a split from an issuance |
56
+
57
+ Validated against the tagged ratios: **73% of the companies with a tagged ratio
58
+ also have the same ratio inferred**, and the inferred method reaches seven
59
+ times as many companies.
60
+
61
+ ### Four things this got wrong first
62
+
63
+ **The ratio list was handwritten and incomplete.** It had 2:1 through 20:1 and
64
+ a few m:n forms, and no 6:1 — so Deckers' 2024 split, the very case this
65
+ dataset exists to fix, was invisible. The evidence was all there; the ratio
66
+ simply was not in the table.
67
+
68
+ **Generating the list instead was worse.** Every simple fraction with small
69
+ numerator and denominator gives 144 ratios, thirteen of whose tolerance bands
70
+ overlap, and an ordinary 1.83× restatement then resolved to "eleven-for-six".
71
+ The list is written out again, completed, and nothing between 0.85 and 1.18 is
72
+ admitted at all: a five percent stock dividend and a five percent restatement
73
+ leave the same trace.
74
+
75
+ **One restated period is not evidence.** A single figure that happens to land
76
+ on a clean ratio produced a four-for-one Tesla split in 2020 that never
77
+ happened. Two is the floor; four or more earns `medium`; the count grades the
78
+ claim rather than gating it, because a real split restates every prior period a
79
+ filing shows — Apple's 2020 split left 36 of them.
80
+
81
+ **Extreme ratios need more.** Earnings of minus two cents restated to minus
82
+ forty dollars is a genuine one-for-a-thousand consolidation, and it is also
83
+ what a rounding change looks like on a company whose EPS never left the third
84
+ decimal. Ratios past 50× or under 0.02 now require the stronger evidence
85
+ threshold.
86
+
87
+ ### The detection window
88
+
89
+ A split gets a window, never a date. `detected_after` is the acceptance of the
90
+ last filing that still used the old figures; `detected_before` the first that
91
+ used the new. Deckers lands in 2024-08-01 → 2024-10-31, and the split was
92
+ 2024-09-16.
93
+
94
+ Combining windows across restated periods takes their intersection, which is
95
+ tighter. The intersection can be empty, and when it is, that is not an
96
+ arithmetic slip — it means the evidence spans two events at the same ratio, a
97
+ company that split two-for-one twice. The union is used then, a window that
98
+ certainly contains them, rather than publishing one that ends before it starts.
99
+
100
+ ## The adjustment factor
101
+
102
+ The table the rest of it is for. Walking the splits backwards from today gives,
103
+ for every span, the product of every split that happened after it: Apple is
104
+ 28.0 before 2014, 4.0 between, 1.0 now. Multiply an as-filed share count by it,
105
+ or divide an as-filed EPS, and the figure lines up with a split-adjusted price
106
+ series.
107
+
108
+ The gate checks that the newest span of every filer has a factor of exactly
109
+ one. Anything else means the walk started from the wrong end, and the whole
110
+ company's history would be off by a constant.
111
+
112
+ ## Verification
113
+
114
+ [`quality.py`](recipe/quality.py) gates publication. Beyond the usual null and
115
+ range checks: every published ratio must be one companies actually declare
116
+ (1.83 is a restatement that slipped through, not a split), detection windows
117
+ must not end before they start, and the agreement between the tagged and
118
+ inferred methods must stay above 65% — a drop means the restatement signal has
119
+ started picking up something that is not a split.
120
+
121
+ ## Schedule
122
+
123
+ A Hugging Face Job runs weekly on Monday at 08:10 UTC, half an hour after the
124
+ fundamentals rebuild it reads. Nothing else is fetched: this dataset has no
125
+ source of its own.
126
+
127
+ ## What is not done
128
+
129
+ * **No dates for dividends.** See the top of this document.
130
+ * **No splits before 2009.** The restatement trace needs XBRL.
131
+ * **No separation of special from regular dividends.** The filings usually do
132
+ not distinguish them either.
133
+ * **No stock dividends under 18%.** Indistinguishable from a restatement.
134
+ * **`share_count` is computed but not published as a method.** It corroborates;
135
+ it cannot stand alone.
README.md ADDED
@@ -0,0 +1,177 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: apache-2.0
3
+ language:
4
+ - en
5
+ pretty_name: US Corporate Actions — dividends and splits, point-in-time
6
+ size_categories:
7
+ - 100K<n<1M
8
+ task_categories:
9
+ - tabular-regression
10
+ - time-series-forecasting
11
+ tags:
12
+ - finance
13
+ - sec
14
+ - edgar
15
+ - xbrl
16
+ - dividends
17
+ - stock-splits
18
+ - corporate-actions
19
+ - point-in-time
20
+ - ziplime
21
+ configs:
22
+ - config_name: dividends
23
+ data_files:
24
+ - split: train
25
+ path: "data/dividends/*.parquet"
26
+ - config_name: splits
27
+ data_files:
28
+ - split: train
29
+ path: "data/splits/*.parquet"
30
+ - config_name: adjustment_factors
31
+ data_files:
32
+ - split: train
33
+ path: "data/adjustment_factors/*.parquet"
34
+ - config_name: pit
35
+ data_files:
36
+ - split: train
37
+ path: "data/pit/*.parquet"
38
+ ---
39
+
40
+ # US Corporate Actions — dividends and splits
41
+
42
+ **391 639 dividends from 3 327 filers · 5 619 splits from 3 814 filers ·
43
+ 2005 to 2026**
44
+
45
+ Built to close a specific hole. A filing states shares and earnings per share
46
+ as of the day it was made; every price series is adjusted for splits since.
47
+ Multiply one by the other and the answer is wrong by the split factor — on
48
+ Deckers that turned a 6.9% earnings yield into 41.7%, a P/E of 1.8.
49
+
50
+ The pipeline lives in [`recipe/`](recipe/) at the same revision as the data.
51
+ See [PIPELINE.md](PIPELINE.md) for the method.
52
+
53
+ ## Read this before anything else
54
+
55
+ **There are no ex-dates, record dates or pay dates here, and there is no free
56
+ source for them.** SEC's structured data carries only numeric facts; the
57
+ date-typed XBRL facts exist inside filings but not in the bulk data sets, and
58
+ the XBRL API returns 404 for them. What this dataset has is what can be had
59
+ from public filings: how much per share, over which fiscal period, known from
60
+ when — and split ratios recovered from the trace a split leaves in restated
61
+ figures.
62
+
63
+ If you need an ex-date calendar, this is not it, and nothing free is.
64
+
65
+ ## The adjustment factor
66
+
67
+ This is the table most people want. Multiply an as-filed per-share figure by
68
+ `cumulative_split_factor` to put it on the same basis as a split-adjusted price
69
+ series.
70
+
71
+ ```python
72
+ import polars as pl
73
+
74
+ factors = pl.read_parquet("data/adjustment_factors/*.parquet")
75
+
76
+ # Deckers: a 6-for-1 split detected between 2024-08-01 and 2024-10-31
77
+ factors.filter(pl.col("cik") == "0000910521")
78
+ # valid_from valid_to cumulative_split_factor splits_after
79
+ # null 2024-10-31 6.0 1
80
+ # 2024-10-31 null 1.0 0
81
+ ```
82
+
83
+ Shares outstanding filed before that window need multiplying by six; earnings
84
+ per share need dividing by it. Apple carries 28.0 before its 2014 seven-for-one
85
+ (7 × 4), 4.0 between the two, and 1.0 today.
86
+
87
+ ## Splits, and how confident to be
88
+
89
+ No free feed of US splits exists. What exists, in a dataset that keeps every
90
+ filing's own version of a period, is the trace: a split forces the company to
91
+ restate every earlier per-share figure by the ratio. Two filings covering the
92
+ same quarter, one before and one after, differ by exactly that factor.
93
+
94
+ That is stronger than the obvious signal. A jump in shares outstanding looks
95
+ identical for a two-for-one split and an equity raise that doubled the count;
96
+ only a split reaches back and rewrites the past.
97
+
98
+ | Confidence | Rows | What it means |
99
+ |---|---|---|
100
+ | `high` | 514 | the filer tagged the conversion ratio, or both methods found it |
101
+ | `medium` | 3 728 | inferred from four or more restated figures |
102
+ | `low` | 1 377 | inferred from two or three |
103
+
104
+ Verified against the ratios filers tagged themselves: the two methods agree for
105
+ **73%** of the companies where both exist, and the inferred method reaches
106
+ seven times as many companies.
107
+
108
+ Each split carries a **window**, not a date: `detected_after` is the last
109
+ filing that still used the old figures, `detected_before` the first that used
110
+ the new. Deckers' September 2024 split lands in 2024-08-01 → 2024-10-31. That
111
+ is as precise as filings allow, and a date invented inside that window would be
112
+ a fiction.
113
+
114
+ Reverse splits outnumber forward ones almost three to one — 3 933 to 1 686 —
115
+ which is what the SEC filer universe actually looks like once you leave the
116
+ index names: shells consolidate to keep a listing far more often than
117
+ successful companies split.
118
+
119
+ ## Dividends
120
+
121
+ Per-share amounts as filings stated them, for a fiscal period.
122
+
123
+ | | |
124
+ |---|---|
125
+ | `declared` | 276 299 — a decision made in the period |
126
+ | `cash_paid` | 115 340 — cash that moved in the period |
127
+ | common / preferred | 369 413 / 22 226 |
128
+ | restated later | 223 583 rows are a second or later report of the same period |
129
+ | subsequent events | 769 declared after the period closed, disclosed in the filing that follows |
130
+
131
+ Declared and paid are kept apart rather than merged: they are different facts,
132
+ and a company can declare in one quarter and pay in the next. Preferred
133
+ dividends are included because a preferred coupon ranks ahead of the common
134
+ holder, and a yield computed without it is wrong for exactly the companies
135
+ where it matters.
136
+
137
+ `period_start` is derived from `period_end` and `quarters`; a dividend fact
138
+ dated to an instant is dropped rather than assigned a day it did not cover.
139
+
140
+ ## Configs
141
+
142
+ | Config | Rows | What one row is |
143
+ |---|---|---|
144
+ | `dividends` | 391 639 | one per-share dividend a filing stated for one period |
145
+ | `splits` | 5 619 | one split, with the window it must have happened in |
146
+ | `adjustment_factors` | 9 433 | one span and the factor that puts an as-filed figure on today's basis |
147
+ | `pit` | 397 258 | one point-in-time action event, plus a Delta table for ziplime |
148
+
149
+ `entity_id` in `pit` is the issuer CIK, the same key used across the family, so
150
+ this joins directly to
151
+ [company-fundamentals](https://huggingface.co/datasets/ZipLime/company-fundamentals),
152
+ [insider-trading](https://huggingface.co/datasets/ZipLime/insider-trading) and
153
+ [security-master](https://huggingface.co/datasets/ZipLime/security-master).
154
+
155
+ ## Known gaps
156
+
157
+ * **No dividend dates.** See above. The period is the finest granularity
158
+ available.
159
+ * **A split window is a window.** Typically one quarter wide.
160
+ * **Splits before 2009 are not visible.** The restatement trace needs XBRL, and
161
+ XBRL starts in 2009 Q1. A company that split in 2006 shows no split here.
162
+ * **Stock dividends under 18% are not detected.** A five percent stock dividend
163
+ and a five percent restatement leave the same trace, so nothing between 0.85
164
+ and 1.18 is admitted as a split rather than risk phantom factors.
165
+ * **Special and irregular dividends are not separated** from regular ones. The
166
+ filing usually does not distinguish them either.
167
+ * **Low-confidence splits are published, not hidden.** Filter on `confidence`
168
+ if a wrong factor would be worse than a missing one.
169
+
170
+ ## Provenance and updates
171
+
172
+ Derived entirely from
173
+ [ZipLime/company-fundamentals](https://huggingface.co/datasets/ZipLime/company-fundamentals),
174
+ which is itself SEC XBRL — US Government work, public domain. No source of its
175
+ own is fetched.
176
+
177
+ Rebuilt weekly, Monday 08:10 UTC, after the dataset it reads.
data/adjustment_factors/part-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7ef1120da44a5b0b59c668b6e3b7a9993ff4de067d89f4584cb71d9254e6c154
3
+ size 74991
data/dividends/part-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:7537a4b86b38114300a11481695a7e87549f251f6bd2a4eff7cfc07b4481107e
3
+ size 3857316
data/pit/corporate_actions.delta/_delta_log/00000000000000000000.json ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ {"commitInfo":{"timestamp":1788777421655,"operation":"WRITE","operationParameters":{"mode":"Overwrite"},"engineInfo":"delta-rs:py-1.6.2","operationMetrics":{"execution_time_ms":173,"num_added_files":1,"num_added_rows":397258,"num_partitions":0,"num_removed_files":0},"clientVersion":"delta-rs.py-1.6.2"}}
2
+ {"protocol":{"minReaderVersion":1,"minWriterVersion":2}}
3
+ {"metaData":{"id":"c997adf7-aa2c-45f7-920b-2e446f6ac9b6","name":null,"description":null,"format":{"provider":"parquet","options":{}},"schemaString":"{\"type\":\"struct\",\"fields\":[{\"name\":\"pit_event_id\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"entity_id\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"event_date\",\"type\":\"date\",\"nullable\":true,\"metadata\":{}},{\"name\":\"knowledge_date\",\"type\":\"timestamp\",\"nullable\":true,\"metadata\":{}},{\"name\":\"knowledge_estimated\",\"type\":\"boolean\",\"nullable\":true,\"metadata\":{}},{\"name\":\"action_type\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"amount_per_share\",\"type\":\"double\",\"nullable\":true,\"metadata\":{}},{\"name\":\"currency\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"split_ratio\",\"type\":\"double\",\"nullable\":true,\"metadata\":{}},{\"name\":\"security_class\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"quarters\",\"type\":\"integer\",\"nullable\":true,\"metadata\":{}},{\"name\":\"is_subsequent_event\",\"type\":\"boolean\",\"nullable\":true,\"metadata\":{}},{\"name\":\"confidence\",\"type\":\"string\",\"nullable\":true,\"metadata\":{}},{\"name\":\"ingested_at\",\"type\":\"timestamp\",\"nullable\":true,\"metadata\":{}}]}","partitionColumns":[],"createdTime":1788777421485,"configuration":{}}}
4
+ {"add":{"path":"part-00000-b78602dd-42f6-4e85-9422-9c3d727a372e-c000.snappy.parquet","partitionValues":{},"size":5546989,"modificationTime":1788777421653,"dataChange":true,"stats":"{\"numRecords\":397258,\"minValues\":{\"action_type\":\"dividend_cash_paid\",\"amount_per_share\":-0.0,\"pit_event_id\":\"0000001961|split|0.2\",\"quarters\":1,\"entity_id\":\"0000001750\",\"event_date\":\"2005-03-31\",\"currency\":\"AFN\",\"split_ratio\":0.001,\"security_class\":\"common\",\"is_subsequent_event\":false,\"confidence\":\"high\",\"knowledge_date\":\"2009-04-15T20:44:00Z\",\"ingested_at\":\"2026-09-07T10:36:48.268812Z\",\"knowledge_estimated\":false},\"maxValues\":{\"confidence\":\"medium\",\"ingested_at\":\"2026-09-07T10:36:48.268812Z\",\"entity_id\":\"0002115119\",\"pit_event_id\":\"0002082866|split|1.8\",\"security_class\":\"preferred\",\"knowledge_date\":\"2026-06-30T20:51:00Z\",\"action_type\":\"split\",\"event_date\":\"2026-12-31\",\"quarters\":53,\"knowledge_estimated\":true,\"currency\":\"shares/USD\",\"split_ratio\":30.0,\"amount_per_share\":1125000000.0,\"is_subsequent_event\":true},\"nullCount\":{\"split_ratio\":391639,\"security_class\":5619,\"confidence\":0,\"event_date\":0,\"is_subsequent_event\":0,\"amount_per_share\":5619,\"action_type\":0,\"entity_id\":0,\"ingested_at\":0,\"currency\":5619,\"knowledge_estimated\":0,\"quarters\":5619,\"pit_event_id\":0,\"knowledge_date\":0}}","tags":null,"baseRowId":null,"defaultRowCommitVersion":null,"clusteringProvider":null}}
data/pit/corporate_actions.delta/part-00000-b78602dd-42f6-4e85-9422-9c3d727a372e-c000.snappy.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a3a510908b1adbde5ba3ce9eb3e66f717f1ccb0d9b3f8435e24d1aeaf758dd75
3
+ size 5546989
data/pit/part-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:60f595610d3438f8dd3a6b13716bc8932f405e620d2b00f4b561a7f83e9780c6
3
+ size 4264876
data/splits/part-00000.parquet ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1827a2b8c1d99e2d6df6be49338e49c92852d9ddded60ccb069d6bfb06de288a
3
+ size 121433
jobs/run.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "httpx>=0.27,<1",
5
+ # "polars>=1.24,<2",
6
+ # "pyarrow>=18,<21",
7
+ # "deltalake>=0.22,<2",
8
+ # "huggingface-hub>=1.19,<2",
9
+ # "pytest>=8,<9",
10
+ # "pytest-asyncio>=0.24,<1",
11
+ # "ruff>=0.11,<1",
12
+ # "pyyaml>=6,<7",
13
+ # ]
14
+ # ///
15
+ """Hugging Face Jobs entry point for the ZipLime corporate-actions dataset.
16
+
17
+ restore repository -> lint -> tests -> build -> verify -> publish
18
+
19
+ The build reads two sibling datasets from the Hub. That is the point of this
20
+ one: it is glue, and what it says has to be derivable from what the others
21
+ published, not from a working copy that only exists on somebody's laptop.
22
+ """
23
+
24
+ from __future__ import annotations
25
+
26
+ import argparse
27
+ import os
28
+ import subprocess
29
+ import sys
30
+ from pathlib import Path
31
+
32
+ DEFAULT_REPO = "ZipLime/corporate-actions"
33
+ DEFAULT_WORKSPACE = "/tmp/corporate-actions"
34
+
35
+
36
+ def log(message: str) -> None:
37
+ print(f"[corporate-actions] {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("--workspace", default=os.environ.get("JOB_WORKSPACE", DEFAULT_WORKSPACE))
70
+ parser.add_argument("--skip-gates", action="store_true")
71
+ args = parser.parse_args(argv)
72
+
73
+ token = os.environ.get("HF_TOKEN")
74
+ if not token:
75
+ raise SystemExit("the HF_TOKEN secret is required")
76
+ repo_id = os.environ.get("HF_DATASET_REPO", DEFAULT_REPO)
77
+
78
+ workspace = restore_repository(repo_id, token, Path(args.workspace))
79
+ env = {**os.environ, "PYTHONPATH": str(workspace), "DATA_DIR": "data"}
80
+
81
+ if not args.skip_gates:
82
+ for name, command in (("lint", ["ruff", "check", "."]), ("tests", ["pytest", "-q"])):
83
+ code = run(command, cwd=workspace, env=env)
84
+ if code != 0:
85
+ log(f"{name} failed; nothing was fetched and nothing was published")
86
+ return code
87
+
88
+ code = run([sys.executable, "-m", "recipe.cli", "build"], cwd=workspace, env=env)
89
+ if code != 0:
90
+ log("build or verification failed; nothing published")
91
+ return code
92
+ if args.mode == "build":
93
+ return 0
94
+ return run(
95
+ [sys.executable, "-m", "recipe.cli", "publish", "--repo", repo_id],
96
+ cwd=workspace, env=env,
97
+ )
98
+
99
+
100
+ if __name__ == "__main__":
101
+ raise SystemExit(main())
manifest.json ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bundle_storage_class": "ziplime.data.services.file_system_delta_lake_bundle_storage.FileSystemDeltaLakeBundleStorage",
3
+ "bundle_storage_data": {
4
+ "table_uri": "data/pit/corporate_actions.delta"
5
+ },
6
+ "config_rows": {
7
+ "adjustment_factors": 9433,
8
+ "dividends": 391639,
9
+ "pit": 397258,
10
+ "splits": 5619
11
+ },
12
+ "config_schemas": {
13
+ "adjustment_factors": {
14
+ "cik": "String",
15
+ "confidence": "String",
16
+ "cumulative_split_factor": "Float64",
17
+ "inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
18
+ "splits_after": "Int32",
19
+ "valid_from": "Date",
20
+ "valid_to": "Date"
21
+ },
22
+ "dividends": {
23
+ "accepted_at": "Datetime(time_unit='us', time_zone='UTC')",
24
+ "accession_number": "String",
25
+ "amount_per_share": "Float64",
26
+ "cik": "String",
27
+ "currency": "String",
28
+ "filed_date": "Date",
29
+ "fiscal_period": "String",
30
+ "fiscal_year": "Int32",
31
+ "form": "String",
32
+ "inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
33
+ "is_subsequent_event": "Boolean",
34
+ "kind": "String",
35
+ "period_end": "Date",
36
+ "period_start": "Date",
37
+ "quarters": "Int32",
38
+ "revision": "Int32",
39
+ "security_class": "String"
40
+ },
41
+ "pit": {
42
+ "action_type": "String",
43
+ "amount_per_share": "Float64",
44
+ "confidence": "String",
45
+ "currency": "String",
46
+ "entity_id": "String",
47
+ "event_date": "Date",
48
+ "ingested_at": "Datetime(time_unit='us', time_zone='UTC')",
49
+ "is_subsequent_event": "Boolean",
50
+ "knowledge_date": "Datetime(time_unit='us', time_zone='UTC')",
51
+ "knowledge_estimated": "Boolean",
52
+ "pit_event_id": "String",
53
+ "quarters": "Int32",
54
+ "security_class": "String",
55
+ "split_ratio": "Float64"
56
+ },
57
+ "splits": {
58
+ "cik": "String",
59
+ "confidence": "String",
60
+ "corroborated_by": "String",
61
+ "detected_after": "Datetime(time_unit='us', time_zone='UTC')",
62
+ "detected_before": "Datetime(time_unit='us', time_zone='UTC')",
63
+ "effective_period_end": "Date",
64
+ "evidence_observations": "Int32",
65
+ "inserted_at": "Datetime(time_unit='us', time_zone='UTC')",
66
+ "is_reverse": "Boolean",
67
+ "method": "String",
68
+ "ratio": "Float64",
69
+ "ratio_label": "String"
70
+ }
71
+ },
72
+ "configs": {
73
+ "adjustment_factors": {
74
+ "grain": "one span and the factor that puts an as-filed per-share figure on today's basis",
75
+ "path": "data/adjustment_factors/**/*.parquet"
76
+ },
77
+ "dividends": {
78
+ "grain": "one per-share dividend a filing stated for one period",
79
+ "path": "data/dividends/**/*.parquet"
80
+ },
81
+ "pit": {
82
+ "delta_path": "data/pit/corporate_actions.delta",
83
+ "grain": "one point-in-time corporate action event",
84
+ "path": "data/pit/**/*.parquet"
85
+ },
86
+ "splits": {
87
+ "grain": "one split, with the window it must have happened in",
88
+ "path": "data/splits/**/*.parquet"
89
+ }
90
+ },
91
+ "coverage": {
92
+ "max_event": "2026-12-31",
93
+ "max_knowledge": "2026-06-30T20:51:00+00:00",
94
+ "min_event": "2005-03-31",
95
+ "min_knowledge": "2009-04-15T20:44:00+00:00"
96
+ },
97
+ "data_type": "PIT_DATA",
98
+ "dataset": "corporate-actions",
99
+ "entity_domain": "us_equities",
100
+ "entity_id": "issuer_cik",
101
+ "event_date": "period_end for dividends, detection window end for splits",
102
+ "event_date_type": "date",
103
+ "frequency_seconds": null,
104
+ "generated_at": "2026-09-07T10:38:46.006778+00:00",
105
+ "knowledge_date": "accepted_at",
106
+ "knowledge_date_policy": {
107
+ "note": "A split's knowledge date is the earliest moment it was demonstrably public, which is later than it happened and therefore safe. No ex-date, record date or pay date exists in any free structured source.",
108
+ "primary": "EDGAR acceptance of the filing that stated the dividend, or of the first filing showing split-restated figures"
109
+ },
110
+ "knowledge_date_type": "timestamp[us, tz=UTC]",
111
+ "name": "corporate_actions",
112
+ "pit": {
113
+ "append_only": false,
114
+ "knowledge_lag_model": "sec_edgar_acceptance",
115
+ "restatement_policy": "dividends carry a revision per re-report; splits are rebuilt from the full restatement history each run"
116
+ },
117
+ "pretty_name": "ZipLime US Corporate Actions: dividends and splits (PIT)",
118
+ "quality_ok": true,
119
+ "rows": 397258,
120
+ "source": {
121
+ "build_version": "1.0.0",
122
+ "coverage_note": "Split detection requires XBRL restatement history, which begins in 2009 Q1. Dividend periods reach back to 2005 through comparative figures in early filings.",
123
+ "coverage_start": "2009-01-01",
124
+ "license": "US Government work — public domain",
125
+ "origin": "ZipLime/company-fundamentals (SEC Financial Statement Data Sets)",
126
+ "package_version": "1.0.0",
127
+ "recipe": "recipe/",
128
+ "recipe_hash": "sha256:f7aabfcffe4c240efda7e95e223e2602c3fe9cf292ee6a9fe17629eaf5fa92d8",
129
+ "schedule": "10 8 * * 1"
130
+ },
131
+ "split_ratios_recognised": [
132
+ "1:1000",
133
+ "1:750",
134
+ "1:500",
135
+ "1:400",
136
+ "1:300",
137
+ "1:250",
138
+ "1:200",
139
+ "1:150",
140
+ "1:120",
141
+ "1:100",
142
+ "1:80",
143
+ "1:75",
144
+ "1:60",
145
+ "1:50",
146
+ "1:40",
147
+ "1:35",
148
+ "1:30",
149
+ "1:25",
150
+ "1:20",
151
+ "1:16",
152
+ "1:15",
153
+ "1:12",
154
+ "1:10",
155
+ "1:8",
156
+ "1:7",
157
+ "1:6",
158
+ "1:5",
159
+ "1:4",
160
+ "1:3",
161
+ "1:2",
162
+ "5:4",
163
+ "4:3",
164
+ "3:2",
165
+ "5:3",
166
+ "7:4",
167
+ "9:5",
168
+ "2:1",
169
+ "5:2",
170
+ "3:1",
171
+ "7:2",
172
+ "4:1",
173
+ "5:1",
174
+ "6:1",
175
+ "7:1",
176
+ "8:1",
177
+ "9:1",
178
+ "10:1",
179
+ "12:1",
180
+ "15:1",
181
+ "20:1",
182
+ "25:1",
183
+ "30:1"
184
+ ],
185
+ "trading_calendar_name": null,
186
+ "version": "1.0.0"
187
+ }
pyproject.toml ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [build-system]
2
+ requires = ["setuptools>=75", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "ziplime-corporate-actions"
7
+ version = "1.0.0"
8
+ description = "Point-in-time US corporate actions: dividends and stock splits"
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = {text = "Apache-2.0"}
12
+ authors = [{name = "ZipLime"}]
13
+ dependencies = [
14
+ "httpx>=0.27,<1",
15
+ "polars>=1.24,<2",
16
+ "pyarrow>=18,<21",
17
+ "deltalake>=0.22,<2",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ dev = [
22
+ "pytest>=8,<9",
23
+ "pytest-asyncio>=0.24,<1",
24
+ "ruff>=0.11,<1",
25
+ "pyyaml>=6,<7",
26
+ ]
27
+ publish = ["huggingface-hub>=1.19,<2"]
28
+
29
+ [project.scripts]
30
+ ziplime-corporate-actions = "recipe.cli:main"
31
+
32
+ [tool.setuptools.packages.find]
33
+ include = ["recipe*"]
34
+
35
+ [tool.pytest.ini_options]
36
+ addopts = "-ra"
37
+ testpaths = ["tests"]
38
+ asyncio_mode = "auto"
39
+
40
+ [tool.ruff]
41
+ target-version = "py311"
42
+ line-length = 100
43
+ extend-exclude = ["data", ".cache"]
44
+
45
+ [tool.ruff.lint]
46
+ select = ["E", "F", "I", "UP", "B", "SIM", "RUF"]
47
+ ignore = ["E501"]
recipe/__init__.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ """US corporate actions: dividends per period and split ratios, point in time."""
2
+
3
+ __version__ = "1.0.0"
recipe/build.py ADDED
@@ -0,0 +1,213 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Read the fundamentals dataset, derive the actions, write the tables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import shutil
7
+ from datetime import UTC, datetime, time
8
+ from pathlib import Path
9
+
10
+ import polars as pl
11
+
12
+ from .config import SIBLING_DIR, SOURCE_REPO, Settings
13
+ from .dividends import build_dividends
14
+ from .schema import ADJUSTMENT_SCHEMA, CONFIG_SCHEMAS, PIT_SCHEMA, align, empty_frame
15
+ from .splits import combine, from_restatements, from_tags
16
+ from .store import atomic_write_parquet
17
+
18
+ LOGGER = logging.getLogger(__name__)
19
+
20
+ PIT_DELTA_NAME = "corporate_actions.delta"
21
+ MAX_ROWS_PER_FILE = 5_000_000
22
+
23
+
24
+ def _source_files(settings: Settings, config: str, token: str | None) -> list[Path]:
25
+ if settings.siblings_dir is not None:
26
+ local = settings.siblings_dir / SIBLING_DIR / "data" / config
27
+ files = sorted(
28
+ path for path in local.rglob("*.parquet")
29
+ if not any(part.endswith(".delta") for part in path.parts)
30
+ )
31
+ if files:
32
+ return files
33
+ from huggingface_hub import snapshot_download
34
+
35
+ LOGGER.info("downloading %s/%s", SOURCE_REPO, config)
36
+ root = Path(
37
+ snapshot_download(
38
+ repo_id=SOURCE_REPO, repo_type="dataset",
39
+ allow_patterns=[f"data/{config}/**"], token=token,
40
+ )
41
+ )
42
+ return sorted(
43
+ path for path in (root / "data" / config).rglob("*.parquet")
44
+ if not any(part.endswith(".delta") for part in path.parts)
45
+ )
46
+
47
+
48
+ def _write(data_dir: Path, table: str, frame: pl.DataFrame) -> int:
49
+ root = Path(data_dir) / table
50
+ if root.exists():
51
+ shutil.rmtree(root)
52
+ root.mkdir(parents=True, exist_ok=True)
53
+ frame = align(frame, CONFIG_SCHEMAS[table])
54
+ if frame.is_empty():
55
+ atomic_write_parquet(frame, root / "part-00000.parquet")
56
+ return 0
57
+ for index, start in enumerate(range(0, frame.height, MAX_ROWS_PER_FILE)):
58
+ atomic_write_parquet(frame.slice(start, MAX_ROWS_PER_FILE), root / f"part-{index:05d}.parquet")
59
+ return frame.height
60
+
61
+
62
+ def build_adjustment_factors(splits: pl.DataFrame, *, horizon: datetime) -> pl.DataFrame:
63
+ """What to multiply an as-filed per-share figure by, to match today's prices.
64
+
65
+ This is the table that closes the hole. A filing states shares as of the
66
+ day it was made; every price series is adjusted for splits since. Multiply
67
+ one by the other and the answer is wrong by the split factor -- the failure
68
+ that turned a 6.9% earnings yield into 41.7% and a P/E of 1.8.
69
+
70
+ The factor is cumulative and stepwise: for a company that split two-for-one
71
+ in 2020 and three-for-one in 2024, a figure filed in 2019 needs six, one
72
+ filed in 2021 needs three, one filed today needs one.
73
+ """
74
+ if splits.is_empty():
75
+ return empty_frame(ADJUSTMENT_SCHEMA)
76
+
77
+ events = (
78
+ splits.filter(pl.col("detected_before").is_not_null())
79
+ .select("cik", "ratio", "confidence", pl.col("detected_before").dt.date().alias("on"))
80
+ .sort(["cik", "on"])
81
+ )
82
+ rows: list[dict] = []
83
+ horizon_day = horizon.date()
84
+ for cik, group in events.group_by("cik", maintain_order=True):
85
+ cik_value = cik[0] if isinstance(cik, tuple) else cik
86
+ days = group["on"].to_list()
87
+ ratios = group["ratio"].to_list()
88
+ confidences = group["confidence"].to_list()
89
+ # Walk backwards: the factor for a span is the product of every split
90
+ # that happened after it.
91
+ cumulative = 1.0
92
+ boundaries = [*days, horizon_day]
93
+ for index in range(len(days) - 1, -1, -1):
94
+ cumulative *= ratios[index]
95
+ rows.append({
96
+ "cik": cik_value,
97
+ "valid_from": None if index == 0 else boundaries[index - 1],
98
+ "valid_to": boundaries[index],
99
+ "cumulative_split_factor": cumulative,
100
+ "splits_after": len(days) - index,
101
+ "confidence": min(confidences[index:], key=lambda c: {"high": 0, "medium": 1}.get(c, 2)),
102
+ })
103
+ rows.append({
104
+ "cik": cik_value, "valid_from": boundaries[-2], "valid_to": None,
105
+ "cumulative_split_factor": 1.0, "splits_after": 0,
106
+ "confidence": "high",
107
+ })
108
+ frame = pl.DataFrame(rows, strict=False).with_columns(
109
+ pl.lit(datetime.now(UTC)).alias("inserted_at")
110
+ )
111
+ return align(frame, ADJUSTMENT_SCHEMA).sort(["cik", "valid_to"])
112
+
113
+
114
+ def build_pit(dividends: pl.DataFrame, splits: pl.DataFrame, *, run_at: datetime) -> pl.DataFrame:
115
+ """Both action types in one point-in-time table.
116
+
117
+ A dividend's knowledge date is the acceptance of the filing that stated it,
118
+ to the second. A split's is the acceptance of the first filing that showed
119
+ the restated figures -- the earliest moment the split was demonstrably
120
+ public, which is later than it happened and therefore safe.
121
+ """
122
+ parts: list[pl.DataFrame] = []
123
+ if not dividends.is_empty():
124
+ parts.append(
125
+ dividends.with_columns(
126
+ pl.concat_str(
127
+ [pl.col("accession_number"), pl.col("kind"), pl.col("security_class"),
128
+ pl.col("period_end").cast(pl.String)], separator="|"
129
+ ).alias("pit_event_id"),
130
+ pl.col("cik").alias("entity_id"),
131
+ pl.col("period_end").alias("event_date"),
132
+ pl.col("accepted_at").alias("knowledge_date"),
133
+ pl.lit(False).alias("knowledge_estimated"),
134
+ pl.concat_str([pl.lit("dividend_"), pl.col("kind")]).alias("action_type"),
135
+ pl.lit(None, dtype=pl.Float64).alias("split_ratio"),
136
+ pl.lit("high").alias("confidence"),
137
+ )
138
+ )
139
+ if not splits.is_empty():
140
+ parts.append(
141
+ splits.with_columns(
142
+ pl.concat_str(
143
+ [pl.col("cik"), pl.lit("split"), pl.col("ratio").cast(pl.String)],
144
+ separator="|",
145
+ ).alias("pit_event_id"),
146
+ pl.col("cik").alias("entity_id"),
147
+ pl.col("detected_before").dt.date().alias("event_date"),
148
+ pl.col("detected_before").alias("knowledge_date"),
149
+ pl.lit(True).alias("knowledge_estimated"),
150
+ pl.lit("split").alias("action_type"),
151
+ pl.col("ratio").alias("split_ratio"),
152
+ pl.lit(None, dtype=pl.Float64).alias("amount_per_share"),
153
+ pl.lit(None, dtype=pl.String).alias("currency"),
154
+ pl.lit(None, dtype=pl.String).alias("security_class"),
155
+ pl.lit(None, dtype=pl.Int32).alias("quarters"),
156
+ pl.lit(False).alias("is_subsequent_event"),
157
+ )
158
+ )
159
+ if not parts:
160
+ return empty_frame(PIT_SCHEMA)
161
+ frame = pl.concat([align(part, PIT_SCHEMA) for part in parts], how="vertical_relaxed")
162
+ return frame.with_columns(pl.lit(run_at).alias("ingested_at")).sort(
163
+ ["entity_id", "event_date", "knowledge_date"]
164
+ )
165
+
166
+
167
+ def run_build(*, settings: Settings, token: str | None = None) -> dict[str, int]:
168
+ data_dir = Path(settings.data_dir)
169
+ run_at = datetime.now(UTC)
170
+
171
+ facts = pl.scan_parquet(_source_files(settings, "facts", token))
172
+ dimensional = pl.scan_parquet(_source_files(settings, "facts_dimensional", token))
173
+ fundamentals = pl.scan_parquet(_source_files(settings, "fundamentals", token))
174
+
175
+ dividends = build_dividends(
176
+ pl.concat(
177
+ [facts.select(
178
+ "cik", "accession_number", "tag", "value", "unit", "period_end", "quarters",
179
+ "form", "fiscal_year", "fiscal_period", "filed_date", "accepted_at",
180
+ ).with_columns(pl.lit(None, dtype=pl.String).alias("segments")),
181
+ dimensional.select(
182
+ "cik", "accession_number", "tag", "value", "unit", "period_end", "quarters",
183
+ "form", "fiscal_year", "fiscal_period", "filed_date", "accepted_at", "segments",
184
+ )],
185
+ how="vertical_relaxed",
186
+ )
187
+ )
188
+ LOGGER.info("dividends: %d rows, %d filers", dividends.height, dividends["cik"].n_unique())
189
+
190
+ tagged = from_tags(pl.concat([facts, dimensional], how="diagonal_relaxed"))
191
+ inferred = from_restatements(fundamentals)
192
+ splits = combine(tagged, inferred)
193
+ LOGGER.info(
194
+ "splits: %d (tagged %d, inferred %d), %d filers",
195
+ splits.height, tagged.height, inferred.height, splits["cik"].n_unique(),
196
+ )
197
+
198
+ factors = build_adjustment_factors(splits, horizon=run_at)
199
+ pit = build_pit(dividends, splits, run_at=run_at)
200
+
201
+ counts = {
202
+ "dividends": _write(data_dir, "dividends", dividends),
203
+ "splits": _write(data_dir, "splits", splits),
204
+ "adjustment_factors": _write(data_dir, "adjustment_factors", factors),
205
+ "pit": _write(data_dir, "pit", pit),
206
+ }
207
+ delta = data_dir / "pit" / PIT_DELTA_NAME
208
+ if delta.exists():
209
+ shutil.rmtree(delta)
210
+ if not pit.is_empty():
211
+ align(pit, PIT_SCHEMA).write_delta(str(delta), mode="overwrite")
212
+ _ = time
213
+ return counts
recipe/cli.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Command line for the corporate actions recipe."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import logging
8
+ from pathlib import Path
9
+
10
+ from .build import run_build
11
+ from .config import Settings
12
+
13
+
14
+ def main(argv: list[str] | None = None) -> int:
15
+ parser = argparse.ArgumentParser(prog="corporate-actions", description=__doc__)
16
+ sub = parser.add_subparsers(dest="command", required=True)
17
+ sub.add_parser("build", help="derive dividends, splits and adjustment factors")
18
+ verify = sub.add_parser("verify", help="run the quality gate and write the manifest")
19
+ verify.add_argument("--strict", action="store_true")
20
+ publish = sub.add_parser("publish", help="mirror the built tree to Hugging Face")
21
+ publish.add_argument("--repo", default=None)
22
+
23
+ args = parser.parse_args(argv)
24
+ logging.basicConfig(
25
+ level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s | %(message)s"
26
+ )
27
+ settings = Settings.from_env()
28
+ data_dir = Path(settings.data_dir)
29
+
30
+ if args.command == "build":
31
+ from .manifest import build_manifest
32
+ from .quality import validate
33
+
34
+ counts = run_build(settings=settings)
35
+ report = validate(data_dir)
36
+ report.write(data_dir.parent / "quality_report.json")
37
+ build_manifest(data_dir=data_dir, row_counts=counts, quality_ok=report.ok)
38
+ print(json.dumps({"rows": counts, "quality_ok": report.ok,
39
+ "errors": report.errors, "warnings": report.warnings}, indent=2))
40
+ return 0 if report.ok else 1
41
+
42
+ if args.command == "verify":
43
+ from .manifest import build_manifest
44
+ from .quality import validate
45
+ from .store import config_row_counts
46
+
47
+ report = validate(data_dir)
48
+ report.write(data_dir.parent / "quality_report.json")
49
+ build_manifest(
50
+ data_dir=data_dir, row_counts=config_row_counts(data_dir), quality_ok=report.ok
51
+ )
52
+ print(json.dumps(report.as_dict(), indent=2, default=str))
53
+ return 0 if report.ok else 1
54
+
55
+ if args.command == "publish":
56
+ from .publish import hf_token, publish_to_hf
57
+ from .quality import validate
58
+
59
+ report = validate(data_dir)
60
+ if not report.ok:
61
+ print(json.dumps({"quality_ok": False, "errors": report.errors}, indent=2))
62
+ return 1
63
+ commit = publish_to_hf(
64
+ project_root=data_dir.resolve().parent,
65
+ repo_id=args.repo or settings.hf_repo,
66
+ token=hf_token(),
67
+ )
68
+ print(json.dumps({"commit": commit}, indent=2))
69
+ return 0
70
+ return 1
71
+
72
+
73
+ if __name__ == "__main__":
74
+ raise SystemExit(main())
recipe/config.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Runtime configuration."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from dataclasses import dataclass
7
+ from pathlib import Path
8
+
9
+ DEFAULT_HF_REPO = "ZipLime/corporate-actions"
10
+
11
+ # Everything here is derived from one sibling dataset. No new source is
12
+ # fetched: the dividends were already parsed out of XBRL, and the splits are
13
+ # recovered from the restatement history that dataset keeps precisely because
14
+ # it never overwrites what a filing said.
15
+ SOURCE_REPO = "ZipLime/company-fundamentals"
16
+ SIBLING_DIR = "Company_fundamentals"
17
+
18
+
19
+ @dataclass(frozen=True, slots=True)
20
+ class Settings:
21
+ data_dir: Path = Path("data")
22
+ hf_repo: str = DEFAULT_HF_REPO
23
+ siblings_dir: Path | None = None
24
+
25
+ @classmethod
26
+ def from_env(cls, **overrides) -> Settings:
27
+ siblings = os.environ.get("CORPORATE_ACTIONS_SIBLINGS")
28
+ return cls(
29
+ data_dir=Path(overrides.get("data_dir") or os.environ.get("DATA_DIR", "data")),
30
+ hf_repo=overrides.get("hf_repo") or os.environ.get("HF_DATASET_REPO", DEFAULT_HF_REPO),
31
+ siblings_dir=Path(siblings) if siblings else None,
32
+ )
recipe/dividends.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dividends per share, as filings stated them.
2
+
3
+ The tag zoo is smaller here than for the income statement but still real:
4
+ `CommonStockDividendsPerShareDeclared` is what most filers use,
5
+ `CommonStockDividendsPerShareCashPaid` is what the rest use, and the two mean
6
+ different things -- declared is a decision, paid is a cash movement in the
7
+ period. They are kept apart rather than coalesced.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ from datetime import UTC, datetime
13
+
14
+ import polars as pl
15
+
16
+ from .schema import DIVIDEND_SCHEMA, align, empty_frame
17
+
18
+ # tag -> (kind, security class). Preferred dividends are included because a
19
+ # preferred coupon is a claim ahead of the common holder, and a yield computed
20
+ # without it is wrong for exactly the companies where it matters.
21
+ DIVIDEND_TAGS: dict[str, tuple[str, str]] = {
22
+ "CommonStockDividendsPerShareDeclared": ("declared", "common"),
23
+ "CommonStockDividendsPerShareCashPaid": ("cash_paid", "common"),
24
+ "PreferredStockDividendsPerShareDeclared": ("declared", "preferred"),
25
+ "PreferredStockDividendsPerShareCashPaid": ("cash_paid", "preferred"),
26
+ "DividendsPayableAmountPerShare": ("payable", "common"),
27
+ "CommonStockDividendsPerShareCashPaidNetOfTax": ("cash_paid", "common"),
28
+ }
29
+
30
+ # A filing may state a dividend declared after the period closed, tagged as a
31
+ # subsequent event. It is forward-looking information -- the declaration is
32
+ # already public when the filing is -- and dropping it would discard the one
33
+ # dividend fact that is not history.
34
+ SUBSEQUENT_EVENT = "SubsequentEvent"
35
+
36
+
37
+ def build_dividends(facts: pl.LazyFrame | pl.DataFrame) -> pl.DataFrame:
38
+ """Every per-share dividend fact, consolidated and dimensional alike."""
39
+ lazy = facts.lazy() if isinstance(facts, pl.DataFrame) else facts
40
+ mapping = pl.DataFrame(
41
+ [
42
+ {"tag": tag, "kind": kind, "security_class": security}
43
+ for tag, (kind, security) in DIVIDEND_TAGS.items()
44
+ ]
45
+ ).lazy()
46
+
47
+ frame = (
48
+ lazy.filter(pl.col("value").is_not_null() & (pl.col("value") >= 0))
49
+ .join(mapping, on="tag", how="inner")
50
+ .with_columns(
51
+ pl.col("segments").fill_null("").str.contains(SUBSEQUENT_EVENT)
52
+ .alias("is_subsequent_event"),
53
+ pl.col("unit").alias("currency"),
54
+ pl.col("value").alias("amount_per_share"),
55
+ )
56
+ .collect()
57
+ )
58
+ if frame.is_empty():
59
+ return empty_frame(DIVIDEND_SCHEMA)
60
+
61
+ # The period a per-share dividend covers is a duration, and the fact's own
62
+ # `quarters` says how long. An instant-dated dividend per share is a filer
63
+ # error and is dropped rather than dated to a day it did not cover.
64
+ frame = frame.filter(pl.col("quarters") > 0).with_columns(
65
+ pl.col("period_end")
66
+ .dt.offset_by(pl.format("-{}mo", pl.col("quarters") * 3))
67
+ .alias("period_start")
68
+ )
69
+
70
+ frame = frame.sort(["cik", "kind", "security_class", "period_end", "quarters", "accepted_at"])
71
+ frame = frame.with_columns(
72
+ pl.col("accepted_at")
73
+ .rank("ordinal")
74
+ .over(["cik", "kind", "security_class", "period_end", "quarters"])
75
+ .cast(pl.Int32)
76
+ .alias("revision"),
77
+ pl.lit(datetime.now(UTC)).alias("inserted_at"),
78
+ )
79
+ return align(frame, DIVIDEND_SCHEMA)
recipe/hf_jobs.py ADDED
@@ -0,0 +1,228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Declarative management of the Hugging Face Jobs that run this recipe.
2
+
3
+ Scheduling lives on Hugging Face rather than in an external CI system: the data,
4
+ the recipe revision, and the compute that produces them stay in one place, and a
5
+ job is not bound by an external runner's disk or wall-clock limits.
6
+
7
+ The scheduled job executes a UV script published in this same dataset
8
+ repository, so the code that produced a revision is always recoverable from the
9
+ revision itself.
10
+ """
11
+
12
+ from __future__ import annotations
13
+
14
+ from dataclasses import dataclass
15
+ from typing import Any
16
+
17
+ from .config import DEFAULT_HF_REPO, validate_sec_user_agent
18
+
19
+ # The work is downloading the sibling datasets and four hundred settlement
20
+ # archives, then a few minutes of grouping. Memory is modest; bandwidth is not.
21
+ UPDATE_FLAVOR = "cpu-upgrade"
22
+ BACKFILL_FLAVOR = "cpu-upgrade"
23
+ UPDATE_TIMEOUT = "3h"
24
+ BACKFILL_TIMEOUT = "4h"
25
+ # Monday 08:10 UTC, an hour after the fundamentals rebuild: this dataset is
26
+ # derived entirely from that one, and reading last week's revision would
27
+ # publish corporate actions that lag their own source.
28
+ DEFAULT_SCHEDULE = "10 8 * * 1"
29
+ # One self-contained UV script serves both modes: a Job downloads a single file.
30
+ JOB_SCRIPT = "jobs/run.py"
31
+ UPDATE_JOB_NAME = "corporate-actions-update"
32
+ BACKFILL_JOB_NAME = "corporate-actions-rebuild"
33
+
34
+
35
+ def script_url(
36
+ *, repo_id: str = DEFAULT_HF_REPO, script: str = JOB_SCRIPT, revision: str = "main"
37
+ ) -> str:
38
+ return f"https://huggingface.co/datasets/{repo_id}/resolve/{revision}/{script}"
39
+
40
+
41
+ @dataclass(frozen=True, slots=True)
42
+ class JobSpec:
43
+ """Everything needed to launch or schedule one run, minus the credentials."""
44
+
45
+ script: str
46
+ script_url: str
47
+ flavor: str
48
+ timeout: str
49
+ script_args: tuple[str, ...]
50
+ env: dict[str, str]
51
+ name: str
52
+
53
+ def as_kwargs(self, *, secrets: dict[str, str]) -> dict[str, Any]:
54
+ """Build the huggingface_hub call arguments.
55
+
56
+ The Jobs API takes no ``name`` parameter; a job's display name is the
57
+ ``name`` label. Credentials go through ``secrets`` so they are encrypted
58
+ server side instead of travelling as plain environment variables.
59
+ """
60
+
61
+ return {
62
+ "script": self.script_url,
63
+ "script_args": list(self.script_args),
64
+ "flavor": self.flavor,
65
+ "timeout": self.timeout,
66
+ "env": dict(self.env),
67
+ "secrets": secrets,
68
+ "labels": {"name": self.name, "project": "insider-trading"},
69
+ }
70
+
71
+
72
+ def update_spec(
73
+ *,
74
+ repo_id: str = DEFAULT_HF_REPO,
75
+ revision: str = "main",
76
+ flavor: str = UPDATE_FLAVOR,
77
+ timeout: str = UPDATE_TIMEOUT,
78
+ ) -> JobSpec:
79
+ return JobSpec(
80
+ script=JOB_SCRIPT,
81
+ script_url=script_url(repo_id=repo_id, revision=revision),
82
+ flavor=flavor,
83
+ timeout=timeout,
84
+ script_args=("--mode", "update"),
85
+ env={"HF_DATASET_REPO": repo_id},
86
+ name=UPDATE_JOB_NAME,
87
+ )
88
+
89
+
90
+ def backfill_spec(
91
+ *,
92
+ repo_id: str = DEFAULT_HF_REPO,
93
+ revision: str = "main",
94
+ start: str | None = None,
95
+ end: str | None = None,
96
+ flavor: str = BACKFILL_FLAVOR,
97
+ timeout: str = BACKFILL_TIMEOUT,
98
+ ) -> JobSpec:
99
+ args = ["--mode", "build"]
100
+ _ = (start, end)
101
+ return JobSpec(
102
+ script=JOB_SCRIPT,
103
+ script_url=script_url(repo_id=repo_id, revision=revision),
104
+ flavor=flavor,
105
+ timeout=timeout,
106
+ script_args=tuple(args),
107
+ env={"HF_DATASET_REPO": repo_id},
108
+ name=BACKFILL_JOB_NAME,
109
+ )
110
+
111
+
112
+ def job_secrets(*, hf_token: str, sec_user_agent: str) -> dict[str, str]:
113
+ """Validate credentials locally so a misconfigured job fails before it costs money."""
114
+
115
+ if not hf_token.strip():
116
+ raise ValueError("HF_TOKEN is required to create or run a Hugging Face Job")
117
+ return {
118
+ "HF_TOKEN": hf_token.strip(),
119
+ "SEC_USER_AGENT": validate_sec_user_agent(sec_user_agent),
120
+ }
121
+
122
+
123
+ def _api(token: str | None) -> Any:
124
+ try:
125
+ from huggingface_hub import HfApi
126
+ except ImportError as error: # pragma: no cover - exercised in the job environment
127
+ raise RuntimeError("install the 'publish' extra to manage Hugging Face Jobs") from error
128
+ return HfApi(token=token)
129
+
130
+
131
+ def _require(api: Any, method: str) -> Any:
132
+ """Fail with an actionable message when the installed hub predates a Jobs API."""
133
+
134
+ function = getattr(api, method, None)
135
+ if function is None:
136
+ raise RuntimeError(
137
+ f"the installed huggingface_hub has no {method}(); "
138
+ "upgrade with: pip install -U 'huggingface-hub>=1.19'"
139
+ )
140
+ return function
141
+
142
+
143
+ def create_schedule(
144
+ spec: JobSpec,
145
+ *,
146
+ schedule: str = DEFAULT_SCHEDULE,
147
+ secrets: dict[str, str],
148
+ namespace: str | None = None,
149
+ token: str | None = None,
150
+ ) -> Any:
151
+ api = _api(token)
152
+ return _require(api, "create_scheduled_uv_job")(
153
+ schedule=schedule,
154
+ namespace=namespace,
155
+ **spec.as_kwargs(secrets=secrets),
156
+ )
157
+
158
+
159
+ def run_once(
160
+ spec: JobSpec,
161
+ *,
162
+ secrets: dict[str, str],
163
+ namespace: str | None = None,
164
+ token: str | None = None,
165
+ ) -> Any:
166
+ api = _api(token)
167
+ return _require(api, "run_uv_job")(namespace=namespace, **spec.as_kwargs(secrets=secrets))
168
+
169
+
170
+ def list_schedules(*, namespace: str | None = None, token: str | None = None) -> list[Any]:
171
+ api = _api(token)
172
+ return list(_require(api, "list_scheduled_jobs")(namespace=namespace))
173
+
174
+
175
+ def inspect_schedule(
176
+ scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
177
+ ) -> Any:
178
+ api = _api(token)
179
+ return _require(api, "inspect_scheduled_job")(
180
+ scheduled_job_id=scheduled_job_id, namespace=namespace
181
+ )
182
+
183
+
184
+ def delete_schedule(
185
+ scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
186
+ ) -> None:
187
+ api = _api(token)
188
+ _require(api, "delete_scheduled_job")(scheduled_job_id=scheduled_job_id, namespace=namespace)
189
+
190
+
191
+ def suspend_schedule(
192
+ scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
193
+ ) -> Any:
194
+ api = _api(token)
195
+ return _require(api, "suspend_scheduled_job")(
196
+ scheduled_job_id=scheduled_job_id, namespace=namespace
197
+ )
198
+
199
+
200
+ def resume_schedule(
201
+ scheduled_job_id: str, *, namespace: str | None = None, token: str | None = None
202
+ ) -> Any:
203
+ api = _api(token)
204
+ return _require(api, "resume_scheduled_job")(
205
+ scheduled_job_id=scheduled_job_id, namespace=namespace
206
+ )
207
+
208
+
209
+ __all__ = [
210
+ "BACKFILL_FLAVOR",
211
+ "BACKFILL_TIMEOUT",
212
+ "DEFAULT_SCHEDULE",
213
+ "JOB_SCRIPT",
214
+ "UPDATE_FLAVOR",
215
+ "UPDATE_TIMEOUT",
216
+ "JobSpec",
217
+ "backfill_spec",
218
+ "create_schedule",
219
+ "delete_schedule",
220
+ "inspect_schedule",
221
+ "job_secrets",
222
+ "list_schedules",
223
+ "resume_schedule",
224
+ "run_once",
225
+ "script_url",
226
+ "suspend_schedule",
227
+ "update_spec",
228
+ ]
recipe/manifest.py ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The bundle descriptor, rebuilt from what is actually on disk."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ import os
8
+ import tempfile
9
+ from datetime import UTC, datetime
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ import polars as pl
14
+
15
+ from . import __version__
16
+ from .build import PIT_DELTA_NAME
17
+ from .schema import BUILD_VERSION, CONFIG_SCHEMAS
18
+ from .store import read_table
19
+
20
+ RECIPE_ROOT = Path(__file__).resolve().parent.parent
21
+
22
+ CONFIG_DESCRIPTIONS: dict[str, dict[str, str]] = {
23
+ "dividends": {
24
+ "path": "data/dividends/**/*.parquet",
25
+ "grain": "one per-share dividend a filing stated for one period",
26
+ },
27
+ "splits": {
28
+ "path": "data/splits/**/*.parquet",
29
+ "grain": "one split, with the window it must have happened in",
30
+ },
31
+ "adjustment_factors": {
32
+ "path": "data/adjustment_factors/**/*.parquet",
33
+ "grain": "one span and the factor that puts an as-filed per-share figure on today's basis",
34
+ },
35
+ "pit": {
36
+ "path": "data/pit/**/*.parquet",
37
+ "delta_path": f"data/pit/{PIT_DELTA_NAME}",
38
+ "grain": "one point-in-time corporate action event",
39
+ },
40
+ }
41
+
42
+
43
+ def recipe_hash(project_root: Path | None = None) -> str:
44
+ """Hash of the code that produced a build.
45
+
46
+ The root defaults to the installed recipe rather than being derived from
47
+ `data_dir`: a run writing elsewhere would otherwise hash an empty file set,
48
+ which reads as a valid hash and proves nothing.
49
+ """
50
+ root = (project_root or RECIPE_ROOT).resolve()
51
+ digest = hashlib.sha256()
52
+ files = sorted(
53
+ {
54
+ path
55
+ for pattern in ("recipe/**/*.py", "jobs/**/*.py", "tests/**/*.py", "pyproject.toml")
56
+ for path in root.glob(pattern)
57
+ if path.is_file()
58
+ }
59
+ )
60
+ if not files:
61
+ raise FileNotFoundError(f"no recipe sources under {root}")
62
+ for path in files:
63
+ digest.update(str(path.relative_to(root)).encode())
64
+ digest.update(b"\0")
65
+ digest.update(path.read_bytes())
66
+ digest.update(b"\0")
67
+ return f"sha256:{digest.hexdigest()}"
68
+
69
+
70
+ def _coverage(data_dir: Path) -> dict[str, str | None]:
71
+ bounds = read_table(data_dir, "pit").select(
72
+ pl.col("event_date").min().alias("min_event"),
73
+ pl.col("event_date").max().alias("max_event"),
74
+ pl.col("knowledge_date").min().alias("min_knowledge"),
75
+ pl.col("knowledge_date").max().alias("max_knowledge"),
76
+ ).collect()
77
+ if bounds.is_empty():
78
+ return {}
79
+ row = bounds.row(0, named=True)
80
+ return {k: (v.isoformat() if v is not None else None) for k, v in row.items()}
81
+
82
+
83
+ def build_manifest(*, data_dir: Path, row_counts: dict[str, int], quality_ok: bool) -> dict[str, Any]:
84
+ data_dir = Path(data_dir)
85
+ project_root = data_dir.resolve().parent
86
+ path = project_root / "manifest.json"
87
+ manifest: dict[str, Any] = json.loads(path.read_text()) if path.exists() else {}
88
+
89
+ manifest["generated_at"] = datetime.now(UTC).isoformat()
90
+ manifest["rows"] = row_counts.get("pit", 0)
91
+ manifest["config_rows"] = row_counts
92
+ manifest["configs"] = CONFIG_DESCRIPTIONS
93
+ manifest["coverage"] = _coverage(data_dir)
94
+ manifest["quality_ok"] = quality_ok
95
+ from .splits import KNOWN_RATIOS
96
+
97
+ manifest["split_ratios_recognised"] = [label for _ratio, label in KNOWN_RATIOS]
98
+ manifest["config_schemas"] = {
99
+ name: {column: str(dtype) for column, dtype in schema.items()}
100
+ for name, schema in CONFIG_SCHEMAS.items()
101
+ }
102
+ source = dict(manifest.get("source") or {})
103
+ source["recipe_hash"] = recipe_hash()
104
+ source["build_version"] = BUILD_VERSION
105
+ source["package_version"] = __version__
106
+ manifest["source"] = source
107
+
108
+ descriptor, temporary = tempfile.mkstemp(prefix=".manifest-", suffix=".json", dir=project_root)
109
+ try:
110
+ with os.fdopen(descriptor, "w", encoding="utf-8") as handle:
111
+ json.dump(manifest, handle, indent=2, sort_keys=True, ensure_ascii=False)
112
+ handle.write("\n")
113
+ handle.flush()
114
+ os.fsync(handle.fileno())
115
+ os.replace(temporary, path)
116
+ finally:
117
+ if os.path.exists(temporary):
118
+ os.unlink(temporary)
119
+ return manifest
recipe/publish.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Bootstrap and atomic same-revision publication through Hugging Face Hub."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import os
7
+ import shutil
8
+ import tempfile
9
+ from pathlib import Path
10
+
11
+ logger = logging.getLogger(__name__)
12
+
13
+
14
+ def bootstrap_from_hf(
15
+ *, data_dir: Path, repo_id: str, token: str | None = None
16
+ ) -> bool:
17
+ """Hydrate prior append-only state on an ephemeral scheduled runner."""
18
+
19
+ if any((data_dir / "filings").glob("**/*.parquet")):
20
+ return False
21
+ try:
22
+ from huggingface_hub import snapshot_download
23
+ from huggingface_hub.errors import HfHubHTTPError, RepositoryNotFoundError
24
+ except ImportError as error: # pragma: no cover - exercised in publish environment
25
+ raise RuntimeError("install the 'publish' extra to bootstrap from Hugging Face") from error
26
+
27
+ temporary = Path(tempfile.mkdtemp(prefix="insider-hf-bootstrap-"))
28
+ try:
29
+ try:
30
+ snapshot_download(
31
+ repo_id=repo_id,
32
+ repo_type="dataset",
33
+ token=token,
34
+ allow_patterns=["data/**"],
35
+ local_dir=temporary,
36
+ )
37
+ except RepositoryNotFoundError:
38
+ return False # first publication
39
+ except HfHubHTTPError as error:
40
+ if getattr(error.response, "status_code", None) == 404:
41
+ return False
42
+ raise
43
+ downloaded = temporary / "data"
44
+ if not downloaded.exists():
45
+ return False
46
+ data_dir.mkdir(parents=True, exist_ok=True)
47
+ for source in downloaded.glob("**/*"):
48
+ if not source.is_file():
49
+ continue
50
+ target = data_dir / source.relative_to(downloaded)
51
+ target.parent.mkdir(parents=True, exist_ok=True)
52
+ if not target.exists():
53
+ shutil.copy2(source, target)
54
+ return True
55
+ finally:
56
+ shutil.rmtree(temporary, ignore_errors=True)
57
+
58
+
59
+ def publish_to_hf(
60
+ *, project_root: Path, repo_id: str, token: str | None = None
61
+ ) -> str:
62
+ try:
63
+ from huggingface_hub import HfApi
64
+ except ImportError as error: # pragma: no cover - exercised in publish environment
65
+ raise RuntimeError("install the 'publish' extra to publish to Hugging Face") from error
66
+
67
+ api = HfApi(token=token)
68
+ api.create_repo(repo_id=repo_id, repo_type="dataset", exist_ok=True)
69
+ local = {
70
+ str(path.relative_to(project_root))
71
+ for path in project_root.glob("data/**/*.parquet")
72
+ }
73
+ commit = api.upload_folder(
74
+ repo_id=repo_id,
75
+ repo_type="dataset",
76
+ folder_path=project_root,
77
+ # Without this, an upload only ever adds. Partition file names are
78
+ # derived from their contents, so a rebuild writes different names and
79
+ # the previous build's files stay behind -- every row then appears
80
+ # twice, and years dropped from the rebuild come back from the dead.
81
+ # The published tree has to be what is on disk, not the union of every
82
+ # build that ever ran.
83
+ delete_patterns=["data/**"],
84
+ allow_patterns=[
85
+ "data/**",
86
+ "recipe/**",
87
+ "tests/**",
88
+ "jobs/**",
89
+ "README.md",
90
+ "PIPELINE.md",
91
+ "manifest.json",
92
+ "pyproject.toml",
93
+ "LICENSE",
94
+ "NOTICE",
95
+ ],
96
+ # The append lock is local coordination state, not published data.
97
+ ignore_patterns=["**/__pycache__/**", "**/*.pyc", "**/.append.lock"],
98
+ commit_message="Update the security master",
99
+ )
100
+ # A mirror that quietly failed to mirror is the failure this guards. Names
101
+ # are enough: a partition file's name is derived from its contents, so a
102
+ # set difference catches both a leftover from a previous build and a file
103
+ # that never arrived -- without downloading anything.
104
+ published = {
105
+ sibling.rfilename
106
+ for sibling in api.dataset_info(repo_id).siblings
107
+ if sibling.rfilename.startswith("data/") and sibling.rfilename.endswith(".parquet")
108
+ }
109
+ stale, missing = published - local, local - published
110
+ if stale or missing:
111
+ raise RuntimeError(
112
+ f"published tree does not match the local one: {len(stale)} stale file(s) "
113
+ f"left behind, {len(missing)} missing. Examples: "
114
+ f"stale={sorted(stale)[:3]} missing={sorted(missing)[:3]}"
115
+ )
116
+ logger.info("published tree mirrors %d local data files", len(local))
117
+ return str(commit.oid)
118
+
119
+
120
+ def hf_token() -> str | None:
121
+ """The token to act with: the environment first, then a stored login.
122
+
123
+ A scheduled job receives HF_TOKEN as a secret; a person running the same
124
+ command locally has usually run `hf auth login` instead, and should not
125
+ have to export the token again to use it.
126
+ """
127
+
128
+ token = os.environ.get("HF_TOKEN")
129
+ if token:
130
+ return token
131
+ try:
132
+ from huggingface_hub import get_token
133
+ except ImportError: # pragma: no cover - exercised in the publish environment
134
+ return None
135
+ return get_token()
recipe/quality.py ADDED
@@ -0,0 +1,162 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Checks that decide whether a build may be published.
2
+
3
+ Splits are the risky half. A wrong ratio does not raise -- it rescales a
4
+ company's whole per-share history by a factor of two and the result still looks
5
+ like a price series. So the checks are about the ratios being declared ones,
6
+ the factors composing consistently, and the inferred set not drifting away from
7
+ the tagged set that validates it.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import json
13
+ from dataclasses import dataclass, field
14
+ from datetime import UTC, datetime
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ import polars as pl
19
+
20
+ from .splits import KNOWN_RATIOS
21
+ from .store import read_table
22
+
23
+ MIN_DIVIDEND_FILERS = 2_000
24
+ MIN_SPLIT_FILERS = 800
25
+ # The inferred method agreed with the tagged ratio for 79% of the companies
26
+ # where both exist. The floor sits below that: a drop means the restatement
27
+ # signal has started picking up something that is not a split.
28
+ MIN_METHOD_AGREEMENT = 0.65
29
+
30
+
31
+ @dataclass
32
+ class QualityReport:
33
+ errors: list[str] = field(default_factory=list)
34
+ warnings: list[str] = field(default_factory=list)
35
+ metrics: dict[str, Any] = field(default_factory=dict)
36
+
37
+ def error(self, message: str) -> None:
38
+ self.errors.append(message)
39
+
40
+ def warn(self, message: str) -> None:
41
+ self.warnings.append(message)
42
+
43
+ def metric(self, name: str, value: Any) -> None:
44
+ self.metrics[name] = value
45
+
46
+ @property
47
+ def ok(self) -> bool:
48
+ return not self.errors
49
+
50
+ def as_dict(self) -> dict[str, Any]:
51
+ return {
52
+ "ok": self.ok,
53
+ "generated_at": datetime.now(UTC).isoformat(),
54
+ "errors": self.errors,
55
+ "warnings": self.warnings,
56
+ "metrics": self.metrics,
57
+ }
58
+
59
+ def write(self, path: Path) -> None:
60
+ path.parent.mkdir(parents=True, exist_ok=True)
61
+ path.write_text(json.dumps(self.as_dict(), indent=2, default=str), encoding="utf-8")
62
+
63
+
64
+ def validate(data_dir: Path) -> QualityReport:
65
+ report = QualityReport()
66
+ data_dir = Path(data_dir)
67
+ dividends = read_table(data_dir, "dividends").collect()
68
+ splits = read_table(data_dir, "splits").collect()
69
+ factors = read_table(data_dir, "adjustment_factors").collect()
70
+ pit = read_table(data_dir, "pit").collect()
71
+
72
+ for name, frame in (("dividends", dividends), ("splits", splits),
73
+ ("adjustment_factors", factors), ("pit", pit)):
74
+ report.metric(f"rows_{name}", frame.height)
75
+
76
+ if dividends.is_empty():
77
+ report.error("dividends table is empty")
78
+ return report
79
+
80
+ filers = dividends["cik"].n_unique()
81
+ report.metric("dividend_filers", filers)
82
+ if filers < MIN_DIVIDEND_FILERS:
83
+ report.error(f"only {filers} filers pay dividends, below the {MIN_DIVIDEND_FILERS} floor")
84
+ negative = dividends.filter(pl.col("amount_per_share") < 0).height
85
+ if negative:
86
+ report.error(f"dividends: {negative} negative amounts per share")
87
+ report.metric(
88
+ "dividends_by_kind",
89
+ {r["kind"]: r["n"] for r in dividends.group_by("kind").agg(pl.len().alias("n")).iter_rows(named=True)},
90
+ )
91
+ report.metric(
92
+ "dividend_subsequent_events",
93
+ dividends.filter(pl.col("is_subsequent_event")).height,
94
+ )
95
+ restated = dividends.filter(pl.col("revision") > 1).height
96
+ report.metric("dividend_restated_rows", restated)
97
+
98
+ if splits.is_empty():
99
+ report.error("splits table is empty")
100
+ return report
101
+
102
+ split_filers = splits["cik"].n_unique()
103
+ report.metric("split_filers", split_filers)
104
+ report.metric(
105
+ "splits_by_method",
106
+ {r["method"]: r["n"] for r in splits.group_by("method").agg(pl.len().alias("n")).iter_rows(named=True)},
107
+ )
108
+ report.metric(
109
+ "splits_by_confidence",
110
+ {r["confidence"]: r["n"] for r in splits.group_by("confidence").agg(pl.len().alias("n")).iter_rows(named=True)},
111
+ )
112
+ if split_filers < MIN_SPLIT_FILERS:
113
+ report.error(f"only {split_filers} filers have a split, below the {MIN_SPLIT_FILERS} floor")
114
+
115
+ # Every published ratio has to be one companies actually declare. A ratio of
116
+ # 1.83 is a restatement that slipped through, not a split.
117
+ allowed = [ratio for ratio, _label in KNOWN_RATIOS]
118
+ stray = splits.filter(~pl.col("ratio").is_in(allowed)).height
119
+ if stray:
120
+ report.error(f"splits: {stray} rows carry a ratio that is not a declared one")
121
+ if splits.filter(pl.col("detected_before") < pl.col("detected_after")).height:
122
+ report.error("splits: detection windows that end before they start")
123
+
124
+ # Agreement is measured over the events strong enough to be relied on. The
125
+ # low-confidence tail is published for completeness, not for gating.
126
+ strong = splits.filter(pl.col("confidence").is_in(["high", "medium"]))
127
+ both = strong.filter(pl.col("corroborated_by") == "xbrl_tag+eps_restatement")["cik"].n_unique()
128
+ tagged_filers = strong.filter(pl.col("method") == "xbrl_tag")["cik"].n_unique()
129
+ if tagged_filers:
130
+ agreement = both / tagged_filers
131
+ report.metric("method_agreement", round(agreement, 4))
132
+ if agreement < MIN_METHOD_AGREEMENT:
133
+ report.error(
134
+ f"the inferred and tagged methods agree for {agreement:.1%} of tagged filers, "
135
+ f"below the {MIN_METHOD_AGREEMENT:.0%} floor"
136
+ )
137
+
138
+ if not factors.is_empty():
139
+ report.metric("factor_filers", factors["cik"].n_unique())
140
+ if factors.filter(pl.col("cumulative_split_factor") <= 0).height:
141
+ report.error("adjustment_factors: non-positive factor")
142
+ # The newest span of every filer is the present, where nothing needs
143
+ # adjusting. A factor other than one there means the walk backwards
144
+ # started from the wrong end.
145
+ latest = factors.filter(pl.col("valid_to").is_null())
146
+ wrong = latest.filter(pl.col("cumulative_split_factor") != 1.0).height
147
+ if wrong:
148
+ report.error(f"adjustment_factors: {wrong} filers whose current factor is not 1.0")
149
+ report.metric("factor_max", float(factors["cumulative_split_factor"].max()))
150
+
151
+ if not pit.is_empty():
152
+ for column in ("entity_id", "event_date", "knowledge_date"):
153
+ if pit[column].null_count():
154
+ report.error(f"pit.{column}: {pit[column].null_count()} nulls")
155
+ report.metric(
156
+ "pit_by_action",
157
+ {r["action_type"]: r["n"] for r in pit.group_by("action_type").agg(pl.len().alias("n")).iter_rows(named=True)},
158
+ )
159
+ return report
160
+
161
+
162
+ __all__ = ["QualityReport", "validate"]
recipe/schema.py ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 dividend as a filing stated it: an amount per share for a fiscal period.
14
+ #
15
+ # Not an event with an ex-date. SEC's structured data carries no dividend dates
16
+ # at all -- the date-typed XBRL facts exist in filings but `num.txt` holds only
17
+ # numeric ones, and the XBRL API returns 404 for them. What is here is what can
18
+ # be had: how much per share, over which period, known from when.
19
+ DIVIDEND_SCHEMA: dict[str, pl.DataType] = {
20
+ "cik": pl.String,
21
+ "accession_number": pl.String,
22
+ "kind": pl.String,
23
+ "security_class": pl.String,
24
+ "period_start": pl.Date,
25
+ "period_end": pl.Date,
26
+ "quarters": pl.Int32,
27
+ "amount_per_share": pl.Float64,
28
+ "currency": pl.String,
29
+ "is_subsequent_event": pl.Boolean,
30
+ "form": pl.String,
31
+ "fiscal_year": pl.Int32,
32
+ "fiscal_period": pl.String,
33
+ "filed_date": pl.Date,
34
+ "accepted_at": UTC_DATETIME,
35
+ "revision": pl.Int32,
36
+ "inserted_at": UTC_DATETIME,
37
+ }
38
+
39
+ # One split, and the window it must have happened in.
40
+ #
41
+ # A split has no date here either, and saying otherwise would be invention. It
42
+ # is detected by the trace it leaves: a filing restates an earlier period's per
43
+ # share figures by the split ratio, so the split falls between the filing that
44
+ # still used the old numbers and the one that used the new.
45
+ SPLIT_SCHEMA: dict[str, pl.DataType] = {
46
+ "cik": pl.String,
47
+ "ratio": pl.Float64,
48
+ "ratio_label": pl.String,
49
+ "is_reverse": pl.Boolean,
50
+ "detected_after": UTC_DATETIME,
51
+ "detected_before": UTC_DATETIME,
52
+ "effective_period_end": pl.Date,
53
+ "method": pl.String,
54
+ "confidence": pl.String,
55
+ "corroborated_by": pl.String,
56
+ "evidence_observations": pl.Int32,
57
+ "inserted_at": UTC_DATETIME,
58
+ }
59
+
60
+ # The number a user actually needs: multiply an as-filed per-share figure by
61
+ # this to put it on the same footing as a split-adjusted price series.
62
+ ADJUSTMENT_SCHEMA: dict[str, pl.DataType] = {
63
+ "cik": pl.String,
64
+ "valid_from": pl.Date,
65
+ "valid_to": pl.Date,
66
+ "cumulative_split_factor": pl.Float64,
67
+ "splits_after": pl.Int32,
68
+ "confidence": pl.String,
69
+ "inserted_at": UTC_DATETIME,
70
+ }
71
+
72
+ PIT_SCHEMA: dict[str, pl.DataType] = {
73
+ "pit_event_id": pl.String,
74
+ "entity_id": pl.String,
75
+ "event_date": pl.Date,
76
+ "knowledge_date": UTC_DATETIME,
77
+ "knowledge_estimated": pl.Boolean,
78
+ "action_type": pl.String,
79
+ "amount_per_share": pl.Float64,
80
+ "currency": pl.String,
81
+ "split_ratio": pl.Float64,
82
+ "security_class": pl.String,
83
+ "quarters": pl.Int32,
84
+ "is_subsequent_event": pl.Boolean,
85
+ "confidence": pl.String,
86
+ "ingested_at": UTC_DATETIME,
87
+ }
88
+
89
+ CONFIG_SCHEMAS: dict[str, dict[str, pl.DataType]] = {
90
+ "dividends": DIVIDEND_SCHEMA,
91
+ "splits": SPLIT_SCHEMA,
92
+ "adjustment_factors": ADJUSTMENT_SCHEMA,
93
+ "pit": PIT_SCHEMA,
94
+ }
95
+
96
+
97
+ def empty_frame(schema: Mapping[str, pl.DataType]) -> pl.DataFrame:
98
+ return pl.DataFrame(schema=dict(schema))
99
+
100
+
101
+ def align(frame: pl.DataFrame, schema: Mapping[str, pl.DataType]) -> pl.DataFrame:
102
+ missing = [
103
+ pl.lit(None, dtype=dtype).alias(name)
104
+ for name, dtype in schema.items()
105
+ if name not in frame.columns
106
+ ]
107
+ if missing:
108
+ frame = frame.with_columns(missing)
109
+ return frame.select([pl.col(n).cast(d, strict=False) for n, d in schema.items()])
recipe/splits.py ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Finding splits in the trace they leave behind.
2
+
3
+ There is no free structured feed of US stock splits. What there is, in a
4
+ dataset that keeps every filing's own version of a period, is the trace: a
5
+ split forces a company to restate every earlier per-share figure by the split
6
+ ratio. Two filings covering the same quarter, one before the split and one
7
+ after, differ by exactly that factor.
8
+
9
+ That is a stronger signal than the obvious one. A jump in shares outstanding
10
+ looks the same for a two-for-one split and for an equity raise that doubled the
11
+ count; only a split reaches back and rewrites the past.
12
+
13
+ Three methods are combined, each labelled:
14
+
15
+ xbrl_tag the filer tagged the conversion ratio itself
16
+ eps_restatement an earlier period's EPS was restated by a clean ratio
17
+ share_count shares outstanding jumped by a clean ratio
18
+
19
+ `xbrl_tag` is authority. `eps_restatement` covers three times as many companies
20
+ and agrees with the tagged ratio for 79% of the firms where both exist.
21
+ `share_count` is never used alone -- it cannot tell a split from an issuance --
22
+ only to corroborate.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import logging
28
+ from datetime import UTC, datetime
29
+
30
+ import polars as pl
31
+
32
+ from .schema import SPLIT_SCHEMA, align, empty_frame
33
+
34
+ LOGGER = logging.getLogger(__name__)
35
+
36
+ # Ratios a split is actually declared in.
37
+ #
38
+ # Written out rather than generated. The first version of this list was also
39
+ # written out and omitted six-for-one, which made Deckers' 2024 split invisible
40
+ # -- the evidence was there, the ratio was not in the table. The fix was to
41
+ # complete the list, not to accept any simple fraction: generating them gave a
42
+ # hundred and forty ratios, and an ordinary 1.83x restatement then resolved to
43
+ # "eleven-for-six".
44
+ #
45
+ # Nothing between 0.85 and 1.18 is admitted at all. A five percent stock
46
+ # dividend and a five percent restatement leave the same trace, and calling one
47
+ # the other would put a phantom split into the adjustment factors.
48
+ FORWARD_RATIOS: tuple[tuple[float, str], ...] = (
49
+ (1.25, "5:4"), (4 / 3, "4:3"), (1.5, "3:2"), (5 / 3, "5:3"), (1.75, "7:4"),
50
+ (1.8, "9:5"), (2.0, "2:1"), (2.5, "5:2"), (3.0, "3:1"), (3.5, "7:2"),
51
+ (4.0, "4:1"), (5.0, "5:1"), (6.0, "6:1"), (7.0, "7:1"), (8.0, "8:1"),
52
+ (9.0, "9:1"), (10.0, "10:1"), (12.0, "12:1"), (15.0, "15:1"), (20.0, "20:1"),
53
+ (25.0, "25:1"), (30.0, "30:1"),
54
+ )
55
+ # Reverse splits run to much larger denominators: a shell consolidating
56
+ # one-for-a-thousand to regain a listing is routine.
57
+ REVERSE_DENOMINATORS: tuple[int, ...] = (
58
+ 2, 3, 4, 5, 6, 7, 8, 10, 12, 15, 16, 20, 25, 30, 35, 40, 50, 60, 75, 80,
59
+ 100, 120, 150, 200, 250, 300, 400, 500, 750, 1000,
60
+ )
61
+
62
+ KNOWN_RATIOS: tuple[tuple[float, str], ...] = tuple(
63
+ sorted(
64
+ {
65
+ **{round(1 / denominator, 10): f"1:{denominator}" for denominator in REVERSE_DENOMINATORS},
66
+ **{round(ratio, 10): label for ratio, label in FORWARD_RATIOS},
67
+ }.items()
68
+ )
69
+ )
70
+
71
+ # Tight enough that no two admitted ratios can claim the same measurement.
72
+ RATIO_TOLERANCE = 0.01
73
+
74
+ # One restated figure is not evidence: a single period whose EPS happens to land
75
+ # on a clean ratio after a correction produced a four-for-one Tesla split in
76
+ # 2020 that never happened. Two is the floor for publishing at all.
77
+ #
78
+ # Above the floor the count grades the claim instead of gating it. A real split
79
+ # restates every prior period a filing shows -- Apple's 2020 split left 36 of
80
+ # them -- so a handful is weaker evidence than a pile, and the reader should be
81
+ # told which they have rather than have the thin cases silently removed.
82
+ MIN_RESTATEMENT_EVIDENCE = 2
83
+ STRONG_RESTATEMENT_EVIDENCE = 4
84
+
85
+ # An extreme ratio is where a tiny denominator does the most damage: earnings of
86
+ # minus two cents restated to minus forty dollars is a genuine one-for-a-
87
+ # thousand consolidation, and so is a rounding change on a company whose EPS
88
+ # never left the third decimal. Shells really do consolidate at these ratios --
89
+ # 4 305 of the reverse splits found here are theirs -- so the answer is not to
90
+ # refuse them but to demand the corroboration that separates the two.
91
+ EXTREME_RATIO_HIGH = 50.0
92
+ EXTREME_RATIO_LOW = 0.02
93
+
94
+ SPLIT_RATIO_TAGS = (
95
+ "StockholdersEquityNoteStockSplitConversionRatio1",
96
+ "StockholdersEquityNoteStockSplitConversionRatio",
97
+ "StockholdersEquityNoteStockSplitConversionRatio2",
98
+ )
99
+
100
+
101
+ def snap_ratio(value: float | None) -> tuple[float, str] | None:
102
+ """The declared ratio a measurement corresponds to, or nothing."""
103
+ if value is None or value <= 0:
104
+ return None
105
+ for ratio, label in KNOWN_RATIOS:
106
+ if abs(value - ratio) <= RATIO_TOLERANCE * ratio:
107
+ return ratio, label
108
+ return None
109
+
110
+
111
+ def _snapped(column: str) -> pl.Expr:
112
+ expr = pl.when(pl.lit(False)).then(pl.lit(None, dtype=pl.Float64))
113
+ for ratio, _label in KNOWN_RATIOS:
114
+ tolerance = RATIO_TOLERANCE * ratio
115
+ expr = expr.when(
116
+ (pl.col(column) > ratio - tolerance) & (pl.col(column) < ratio + tolerance)
117
+ ).then(pl.lit(ratio))
118
+ return expr.otherwise(pl.lit(None, dtype=pl.Float64))
119
+
120
+
121
+ def _label() -> pl.Expr:
122
+ expr = pl.when(pl.lit(False)).then(pl.lit(None, dtype=pl.String))
123
+ for ratio, label in KNOWN_RATIOS:
124
+ expr = expr.when(pl.col("ratio") == ratio).then(pl.lit(label))
125
+ return expr.otherwise(pl.lit(None, dtype=pl.String))
126
+
127
+
128
+ def from_restatements(fundamentals: pl.LazyFrame | pl.DataFrame) -> pl.DataFrame:
129
+ """Splits inferred from per-share figures being restated.
130
+
131
+ Both EPS and the weighted share count are used, and they move in opposite
132
+ directions: after a two-for-one split the restated EPS is half of what was
133
+ first reported, and the restated share count is double. Taking the ratio in
134
+ the direction that yields the split factor for each keeps the two
135
+ comparable.
136
+ """
137
+ lazy = fundamentals.lazy() if isinstance(fundamentals, pl.DataFrame) else fundamentals
138
+ per_share = ["eps_diluted", "eps_basic"]
139
+ counts = ["shares_diluted_weighted", "shares_basic_weighted"]
140
+
141
+ frame = (
142
+ lazy.filter(pl.col("concept").is_in([*per_share, *counts]))
143
+ .filter(pl.col("value").is_not_null() & (pl.col("value").abs() > 0.01))
144
+ .collect()
145
+ )
146
+ if frame.is_empty():
147
+ return empty_frame(SPLIT_SCHEMA)
148
+
149
+ grouped = (
150
+ frame.sort("accepted_at")
151
+ .group_by(["cik", "concept", "period_end", "quarters"])
152
+ .agg(
153
+ pl.col("value").first().alias("first_value"),
154
+ pl.col("value").last().alias("last_value"),
155
+ pl.col("accepted_at").first().alias("detected_after"),
156
+ pl.col("accepted_at").last().alias("detected_before"),
157
+ pl.len().alias("reports"),
158
+ )
159
+ .filter(pl.col("reports") > 1)
160
+ )
161
+ grouped = grouped.with_columns(
162
+ pl.when(pl.col("concept").is_in(per_share))
163
+ .then(pl.col("first_value") / pl.col("last_value"))
164
+ .otherwise(pl.col("last_value") / pl.col("first_value"))
165
+ .alias("measured")
166
+ )
167
+ grouped = grouped.with_columns(_snapped("measured").alias("ratio")).filter(
168
+ pl.col("ratio").is_not_null()
169
+ )
170
+ if grouped.is_empty():
171
+ return empty_frame(SPLIT_SCHEMA)
172
+
173
+ # Every period the company restated by the same factor is evidence of one
174
+ # split, not of many, so the windows are combined.
175
+ #
176
+ # The tight combination is the intersection: the split happened after the
177
+ # last filing that still used the old numbers and before the first that
178
+ # used the new. That intersection can be empty, and when it is, it is not
179
+ # an arithmetic slip -- it means the evidence spans more than one event at
180
+ # the same ratio, a company that split two-for-one twice. Falling back to
181
+ # the union keeps a window that certainly contains them, instead of
182
+ # publishing one that ends before it starts.
183
+ events = (
184
+ grouped.group_by(["cik", "ratio"])
185
+ .agg(
186
+ pl.col("detected_after").max().alias("tight_after"),
187
+ pl.col("detected_before").min().alias("tight_before"),
188
+ pl.col("detected_after").min().alias("wide_after"),
189
+ pl.col("detected_before").max().alias("wide_before"),
190
+ pl.col("period_end").max().alias("effective_period_end"),
191
+ pl.len().cast(pl.Int32).alias("evidence_observations"),
192
+ pl.col("concept").unique().sort().str.join("|").alias("corroborated_by"),
193
+ )
194
+ .with_columns(
195
+ pl.lit("eps_restatement").alias("method"),
196
+ _label().alias("ratio_label"),
197
+ (pl.col("ratio") < 1).alias("is_reverse"),
198
+ )
199
+ .with_columns(
200
+ (pl.col("tight_after") <= pl.col("tight_before")).alias("_tight"),
201
+ )
202
+ .with_columns(
203
+ pl.when(pl.col("_tight"))
204
+ .then(pl.col("tight_after"))
205
+ .otherwise(pl.col("wide_after"))
206
+ .alias("detected_after"),
207
+ pl.when(pl.col("_tight"))
208
+ .then(pl.col("tight_before"))
209
+ .otherwise(pl.col("wide_before"))
210
+ .alias("detected_before"),
211
+ )
212
+ )
213
+ enough = pl.when(
214
+ (pl.col("ratio") >= EXTREME_RATIO_HIGH) | (pl.col("ratio") <= EXTREME_RATIO_LOW)
215
+ ).then(pl.lit(STRONG_RESTATEMENT_EVIDENCE)).otherwise(pl.lit(MIN_RESTATEMENT_EVIDENCE))
216
+ return align(events.filter(pl.col("evidence_observations") >= enough), SPLIT_SCHEMA)
217
+
218
+
219
+ def from_tags(facts: pl.LazyFrame | pl.DataFrame) -> pl.DataFrame:
220
+ """Splits the filer tagged with a conversion ratio."""
221
+ lazy = facts.lazy() if isinstance(facts, pl.DataFrame) else facts
222
+ frame = (
223
+ lazy.filter(pl.col("tag").is_in(SPLIT_RATIO_TAGS))
224
+ .filter(pl.col("value").is_not_null() & (pl.col("value") > 0) & (pl.col("value") < 200))
225
+ .select("cik", "value", "period_end", "accepted_at")
226
+ .collect()
227
+ )
228
+ if frame.is_empty():
229
+ return empty_frame(SPLIT_SCHEMA)
230
+
231
+ # A filer may write a three-for-two split as 1.5 or as its reciprocal.
232
+ # Both readings are snapped and whichever lands on a declared ratio wins.
233
+ frame = frame.with_columns(
234
+ pl.coalesce([_snapped("value"), _snapped_reciprocal()]).alias("ratio")
235
+ ).filter(pl.col("ratio").is_not_null())
236
+ if frame.is_empty():
237
+ return empty_frame(SPLIT_SCHEMA)
238
+
239
+ events = (
240
+ frame.group_by(["cik", "ratio"])
241
+ .agg(
242
+ pl.col("accepted_at").min().alias("detected_after"),
243
+ pl.col("accepted_at").min().alias("detected_before"),
244
+ pl.col("period_end").max().alias("effective_period_end"),
245
+ pl.len().cast(pl.Int32).alias("evidence_observations"),
246
+ )
247
+ .with_columns(
248
+ pl.lit("xbrl_tag").alias("method"),
249
+ pl.lit("tagged_ratio").alias("corroborated_by"),
250
+ _label().alias("ratio_label"),
251
+ (pl.col("ratio") < 1).alias("is_reverse"),
252
+ )
253
+ )
254
+ return align(events, SPLIT_SCHEMA)
255
+
256
+
257
+ def _snapped_reciprocal() -> pl.Expr:
258
+ expr = pl.when(pl.lit(False)).then(pl.lit(None, dtype=pl.Float64))
259
+ for ratio, _label in KNOWN_RATIOS:
260
+ tolerance = RATIO_TOLERANCE * ratio
261
+ expr = expr.when(
262
+ (1 / pl.col("value") > ratio - tolerance) & (1 / pl.col("value") < ratio + tolerance)
263
+ ).then(pl.lit(ratio))
264
+ return expr.otherwise(pl.lit(None, dtype=pl.Float64))
265
+
266
+
267
+ def combine(tagged: pl.DataFrame, inferred: pl.DataFrame) -> pl.DataFrame:
268
+ """One row per split, with the strongest method that found it.
269
+
270
+ A split found both ways is one split with high confidence, not two rows.
271
+ A split found only by restatement keeps the medium label: it agreed with
272
+ the tagged ratio for 79% of the companies where both exist, which is worth
273
+ publishing and not worth calling certain.
274
+ """
275
+ if tagged.is_empty() and inferred.is_empty():
276
+ return empty_frame(SPLIT_SCHEMA)
277
+ both = pl.concat([tagged, inferred], how="vertical_relaxed")
278
+ ranked = (
279
+ both.with_columns(
280
+ pl.col("method").replace_strict({"xbrl_tag": 0, "eps_restatement": 1}, default=2)
281
+ .alias("_rank")
282
+ )
283
+ .sort(["cik", "ratio", "_rank"])
284
+ .group_by(["cik", "ratio"], maintain_order=True)
285
+ .agg(
286
+ pl.all().exclude("_rank").first(),
287
+ pl.col("method").n_unique().alias("_methods"),
288
+ )
289
+ )
290
+ ranked = ranked.with_columns(
291
+ pl.when(pl.col("_methods") > 1)
292
+ .then(pl.lit("high"))
293
+ .when(pl.col("method") == "xbrl_tag")
294
+ .then(pl.lit("high"))
295
+ .when(pl.col("evidence_observations") >= STRONG_RESTATEMENT_EVIDENCE)
296
+ .then(pl.lit("medium"))
297
+ .otherwise(pl.lit("low"))
298
+ .alias("confidence"),
299
+ pl.when(pl.col("_methods") > 1)
300
+ .then(pl.lit("xbrl_tag+eps_restatement"))
301
+ .otherwise(pl.col("corroborated_by"))
302
+ .alias("corroborated_by"),
303
+ pl.lit(datetime.now(UTC)).alias("inserted_at"),
304
+ )
305
+ return align(ranked, SPLIT_SCHEMA).sort(["cik", "detected_before"])
recipe/store.py ADDED
@@ -0,0 +1,120 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Write and read the published tables.
2
+
3
+ Storage is deliberately simpler here than in the sibling datasets. There, rows
4
+ arrive one filing at a time from a feed and an append-only store with a primary
5
+ key is the only way to tell a new row from one already held. Here the unit of
6
+ arrival is a whole quarterly archive, and every accession appears in exactly
7
+ one archive -- verified across four quarters, zero overlap. So a quarter is
8
+ written as one partition that a rebuild reproduces byte for byte, no key column
9
+ is needed, and re-ingesting a quarter is idempotent by construction rather than
10
+ by comparison.
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import shutil
17
+ import tempfile
18
+ from collections.abc import Mapping
19
+ from pathlib import Path
20
+
21
+ import polars as pl
22
+
23
+ from .schema import CONFIG_SCHEMAS, align
24
+
25
+ PARTITION = "kind"
26
+ # Facts of one quarter run to about forty megabytes of parquet; splitting that
27
+ # into several files would only multiply metadata. One file per quarter also
28
+ # makes the partition trivially replaceable.
29
+ PART_NAME = "part-00000.parquet"
30
+
31
+
32
+ def partition_dir(data_dir: Path, table: str, quarter: str) -> Path:
33
+ return Path(data_dir) / table / f"{PARTITION}={quarter}"
34
+
35
+
36
+ def atomic_write_parquet(frame: pl.DataFrame, target: Path) -> None:
37
+ """Write through a temporary file in the same directory, then rename.
38
+
39
+ A partly written parquet is indistinguishable from a valid one until it is
40
+ read, and a build interrupted mid-write would leave the dataset in a state
41
+ that only fails later, in a consumer's process.
42
+ """
43
+ target.parent.mkdir(parents=True, exist_ok=True)
44
+ descriptor, temporary = tempfile.mkstemp(
45
+ prefix=".part-", suffix=".parquet", dir=target.parent
46
+ )
47
+ os.close(descriptor)
48
+ try:
49
+ frame.write_parquet(temporary, compression="zstd", statistics=True)
50
+ os.replace(temporary, target)
51
+ finally:
52
+ if os.path.exists(temporary):
53
+ os.unlink(temporary)
54
+
55
+
56
+ def write_quarter(
57
+ data_dir: Path, table: str, quarter: str, frame: pl.DataFrame
58
+ ) -> tuple[Path, int]:
59
+ """Replace one quarter's partition of one table."""
60
+ schema = CONFIG_SCHEMAS[table]
61
+ directory = partition_dir(data_dir, table, quarter)
62
+ if directory.exists():
63
+ shutil.rmtree(directory)
64
+ target = directory / PART_NAME
65
+ atomic_write_parquet(align(frame, schema), target)
66
+ return target, frame.height
67
+
68
+
69
+ def ingested_quarters(data_dir: Path, table: str = "facts") -> set[str]:
70
+ """Quarters already on disk, read from the partition names themselves.
71
+
72
+ A separate ledger file would be a second source of truth about what was
73
+ built, and the two would disagree the first time a run was interrupted.
74
+ """
75
+ root = Path(data_dir) / table
76
+ if not root.is_dir():
77
+ return set()
78
+ return {
79
+ path.name.split("=", 1)[1]
80
+ for path in root.iterdir()
81
+ if path.is_dir() and path.name.startswith(f"{PARTITION}=") and any(path.iterdir())
82
+ }
83
+
84
+
85
+ def read_table(
86
+ data_dir: Path, table: str, *, quarters: set[str] | None = None
87
+ ) -> pl.LazyFrame:
88
+ """Lazy scan of a table, optionally restricted to some quarters."""
89
+ root = Path(data_dir) / table
90
+ if not root.is_dir():
91
+ return pl.LazyFrame(schema=dict(CONFIG_SCHEMAS[table]))
92
+ # The Delta table lives inside the pit directory and is made of parquet
93
+ # files holding the very same rows. Globbing them alongside the partitions
94
+ # returns every point-in-time event twice, which reads as a broken
95
+ # projection rather than as a directory-listing mistake.
96
+ files = sorted(
97
+ path
98
+ for path in root.rglob("*.parquet")
99
+ if not any(part.endswith(".delta") or part == "_delta_log" for part in path.parts)
100
+ and (quarters is None or path.parent.name.split("=", 1)[-1] in quarters)
101
+ )
102
+ if not files:
103
+ return pl.LazyFrame(schema=dict(CONFIG_SCHEMAS[table]))
104
+ return pl.scan_parquet(files)
105
+
106
+
107
+ def table_rows(data_dir: Path, table: str) -> int:
108
+ return int(read_table(data_dir, table).select(pl.len()).collect().item())
109
+
110
+
111
+ def write_singleton(data_dir: Path, table: str, frame: pl.DataFrame) -> Path:
112
+ """A table small enough to live in one file, such as the archive ledger."""
113
+ target = Path(data_dir) / table / PART_NAME
114
+ atomic_write_parquet(align(frame, CONFIG_SCHEMAS[table]), target)
115
+ return target
116
+
117
+
118
+ def config_row_counts(data_dir: Path, tables: Mapping[str, object] | None = None) -> dict[str, int]:
119
+ names = list(tables or CONFIG_SCHEMAS)
120
+ return {name: table_rows(data_dir, name) for name in names}
tests/conftest.py ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 _eps(cik, period_end, quarters, value, accepted, concept="eps_diluted"):
16
+ return {"cik": cik, "concept": concept, "period_end": period_end, "quarters": quarters,
17
+ "value": value, "accepted_at": accepted, "accession_number": f"acc-{accepted:%Y%m%d}"}
18
+
19
+
20
+ @pytest.fixture
21
+ def fundamentals() -> pl.DataFrame:
22
+ """A four-for-one split: every prior period's EPS is restated to a quarter."""
23
+ before = datetime(2020, 5, 1, tzinfo=UTC)
24
+ after = datetime(2020, 11, 1, tzinfo=UTC)
25
+ rows = []
26
+ for index, period in enumerate(
27
+ [date(2018, 12, 31), date(2019, 3, 31), date(2019, 6, 30), date(2019, 9, 30),
28
+ date(2019, 12, 31)]
29
+ ):
30
+ rows.append(_eps("0000000001", period, 4 if index in (0, 4) else 1, 4.0, before))
31
+ rows.append(_eps("0000000001", period, 4 if index in (0, 4) else 1, 1.0, after))
32
+ # A company whose EPS was merely corrected, by a ratio no split is declared in.
33
+ rows.append(_eps("0000000002", date(2019, 12, 31), 4, 1.83, before))
34
+ rows.append(_eps("0000000002", date(2019, 12, 31), 4, 1.0, after))
35
+ # A single restated period at a clean ratio: too thin to publish.
36
+ rows.append(_eps("0000000003", date(2019, 12, 31), 4, 2.0, before))
37
+ rows.append(_eps("0000000003", date(2019, 12, 31), 4, 1.0, after))
38
+ return pl.DataFrame(rows, strict=False)
39
+
40
+
41
+ @pytest.fixture
42
+ def facts() -> pl.DataFrame:
43
+ """Dividend facts and one tagged split ratio."""
44
+ rows = [
45
+ {"cik": "0000000001", "accession_number": "acc-1", "tag": "CommonStockDividendsPerShareDeclared",
46
+ "value": 0.25, "unit": "USD", "period_end": date(2020, 3, 31), "quarters": 1,
47
+ "form": "10-Q", "fiscal_year": 2020, "fiscal_period": "Q1",
48
+ "filed_date": date(2020, 5, 1), "accepted_at": datetime(2020, 5, 1, tzinfo=UTC),
49
+ "segments": None},
50
+ {"cik": "0000000001", "accession_number": "acc-2", "tag": "CommonStockDividendsPerShareDeclared",
51
+ "value": 0.30, "unit": "USD", "period_end": date(2020, 6, 30), "quarters": 1,
52
+ "form": "10-Q", "fiscal_year": 2020, "fiscal_period": "Q2",
53
+ "filed_date": date(2020, 8, 1), "accepted_at": datetime(2020, 8, 1, tzinfo=UTC),
54
+ "segments": "SubsequentEventType=SubsequentEvent;"},
55
+ {"cik": "0000000004", "accession_number": "acc-3",
56
+ "tag": "StockholdersEquityNoteStockSplitConversionRatio1",
57
+ "value": 6.0, "unit": "pure", "period_end": date(2024, 9, 30), "quarters": 0,
58
+ "form": "10-Q", "fiscal_year": 2024, "fiscal_period": "Q3",
59
+ "filed_date": date(2024, 10, 31), "accepted_at": datetime(2024, 10, 31, tzinfo=UTC),
60
+ "segments": None},
61
+ ]
62
+ return pl.DataFrame(rows, strict=False)
tests/test_corporate_actions.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Dividends, split detection, and the factor that reconciles filings to prices."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import UTC, date, datetime
6
+ from itertools import pairwise
7
+
8
+ import polars as pl
9
+ import pytest
10
+
11
+ from recipe.build import build_adjustment_factors, build_pit
12
+ from recipe.dividends import build_dividends
13
+ from recipe.splits import (
14
+ KNOWN_RATIOS,
15
+ RATIO_TOLERANCE,
16
+ combine,
17
+ from_restatements,
18
+ from_tags,
19
+ snap_ratio,
20
+ )
21
+
22
+
23
+ def test_no_two_ratios_can_claim_one_measurement():
24
+ """Bands must not touch, or a measurement resolves to whichever is listed first."""
25
+ ratios = [ratio for ratio, _label in KNOWN_RATIOS]
26
+ touching = [
27
+ (low, high)
28
+ for low, high in pairwise(ratios)
29
+ if high - low <= RATIO_TOLERANCE * (low + high)
30
+ ]
31
+ assert not touching, touching
32
+
33
+
34
+ @pytest.mark.parametrize(
35
+ ("measured", "expected"),
36
+ [
37
+ (6.0, "6:1"), (5.97, "6:1"), (2.0, "2:1"), (1.5, "3:2"), (0.1, "1:10"),
38
+ (0.001, "1:1000"),
39
+ # A five percent stock dividend and a five percent restatement leave the
40
+ # same trace, so nothing near one is admitted.
41
+ (1.05, None), (0.96, None),
42
+ # An ordinary restatement that lands on no declared ratio.
43
+ (1.83, None), (2.31, None),
44
+ ],
45
+ )
46
+ def test_only_declared_ratios_are_recognised(measured, expected):
47
+ got = snap_ratio(measured)
48
+ assert (got[1] if got else None) == expected
49
+
50
+
51
+ def test_six_for_one_is_recognised():
52
+ """Deckers' 2024 split was invisible because 6:1 was missing from the list."""
53
+ assert snap_ratio(6.0) == (6.0, "6:1")
54
+
55
+
56
+ def test_a_split_is_found_in_the_restated_periods(fundamentals):
57
+ splits = from_restatements(fundamentals)
58
+ row = splits.filter(pl.col("cik") == "0000000001").row(0, named=True)
59
+ assert row["ratio"] == 4.0 and row["ratio_label"] == "4:1"
60
+ assert row["method"] == "eps_restatement"
61
+ assert row["evidence_observations"] == 5
62
+ assert row["detected_after"] <= row["detected_before"]
63
+
64
+
65
+ def test_an_ordinary_restatement_is_not_a_split(fundamentals):
66
+ splits = from_restatements(fundamentals)
67
+ assert splits.filter(pl.col("cik") == "0000000002").is_empty()
68
+
69
+
70
+ def test_one_restated_period_is_too_thin(fundamentals):
71
+ splits = from_restatements(fundamentals)
72
+ assert splits.filter(pl.col("cik") == "0000000003").is_empty()
73
+
74
+
75
+ def test_a_tagged_ratio_outranks_an_inferred_one(fundamentals, facts):
76
+ combined = combine(from_tags(facts), from_restatements(fundamentals))
77
+ tagged = combined.filter(pl.col("cik") == "0000000004").row(0, named=True)
78
+ assert tagged["method"] == "xbrl_tag" and tagged["confidence"] == "high"
79
+ inferred = combined.filter(pl.col("cik") == "0000000001").row(0, named=True)
80
+ assert inferred["confidence"] == "medium", "inferred alone is not certain"
81
+
82
+
83
+ def test_dividends_keep_their_amount_and_period(facts):
84
+ """Regression: the amount column was never populated and every row was null."""
85
+ dividends = build_dividends(facts)
86
+ row = dividends.filter(pl.col("period_end") == date(2020, 3, 31)).row(0, named=True)
87
+ assert row["amount_per_share"] == 0.25
88
+ assert row["currency"] == "USD"
89
+ assert row["period_start"] == date(2019, 12, 31)
90
+ assert row["kind"] == "declared" and row["security_class"] == "common"
91
+
92
+
93
+ def test_a_dividend_declared_after_the_period_is_flagged(facts):
94
+ dividends = build_dividends(facts)
95
+ row = dividends.filter(pl.col("period_end") == date(2020, 6, 30)).row(0, named=True)
96
+ assert row["is_subsequent_event"] is True
97
+
98
+
99
+ def test_the_factor_undoes_the_split(fundamentals, facts):
100
+ """The number that turns a 41.7% earnings yield back into 6.9%."""
101
+ splits = combine(from_tags(facts), from_restatements(fundamentals))
102
+ factors = build_adjustment_factors(splits, horizon=datetime(2026, 1, 1, tzinfo=UTC))
103
+ company = factors.filter(pl.col("cik") == "0000000001").sort("cumulative_split_factor")
104
+ assert company["cumulative_split_factor"].to_list() == [1.0, 4.0]
105
+ current = company.filter(pl.col("valid_to").is_null()).row(0, named=True)
106
+ assert current["cumulative_split_factor"] == 1.0, "nothing to adjust in the present"
107
+ past = company.filter(pl.col("valid_from").is_null()).row(0, named=True)
108
+ assert past["cumulative_split_factor"] == 4.0 and past["splits_after"] == 1
109
+
110
+
111
+ def test_factors_compose_across_two_splits():
112
+ splits = pl.DataFrame(
113
+ [
114
+ {"cik": "1", "ratio": 7.0, "confidence": "high",
115
+ "detected_before": datetime(2014, 7, 23, tzinfo=UTC)},
116
+ {"cik": "1", "ratio": 4.0, "confidence": "high",
117
+ "detected_before": datetime(2020, 10, 29, tzinfo=UTC)},
118
+ ],
119
+ strict=False,
120
+ )
121
+ factors = build_adjustment_factors(splits, horizon=datetime(2026, 1, 1, tzinfo=UTC))
122
+ oldest = factors.filter(pl.col("valid_from").is_null()).row(0, named=True)
123
+ assert oldest["cumulative_split_factor"] == 28.0, "seven then four is twenty-eight"
124
+ assert oldest["splits_after"] == 2
125
+
126
+
127
+ def test_pit_carries_both_action_types(fundamentals, facts):
128
+ splits = combine(from_tags(facts), from_restatements(fundamentals))
129
+ pit = build_pit(build_dividends(facts), splits, run_at=datetime(2026, 1, 1, tzinfo=UTC))
130
+ kinds = set(pit["action_type"].to_list())
131
+ assert "split" in kinds and any(k.startswith("dividend_") for k in kinds)
132
+ assert pit["entity_id"].null_count() == 0
133
+ assert pit["knowledge_date"].null_count() == 0