SarthakVishnu commited on
Commit
e68d72a
·
verified ·
1 Parent(s): cc133c1

Upload scripts/collect_form4_topup.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/collect_form4_topup.py +251 -0
scripts/collect_form4_topup.py ADDED
@@ -0,0 +1,251 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # collect_form4_topup.py
2
+ # Collects Form 4 insider transactions for the 22 CIKs identified by Sean Choi
3
+ # (PhD verifier) that are in the ground-truth S&P 500 list but were missing
4
+ # from the original sp500_union_constituents(1).csv / crsp_dsenames.csv universe.
5
+ #
6
+ # These 22 represent ~4% of the full S&P 500 universe that were not covered in
7
+ # the original 656-CIK collection run. This script:
8
+ # 1. Downloads all 81 quarters from SEC EDGAR Insider Transactions flat files
9
+ # 2. Filters to the 22 new CIKs only
10
+ # 3. Joins REPORTINGOWNER role columns (is_officer, is_director, is_ten_pct_owner)
11
+ # 4. Applies the same post-processing as the main pipeline
12
+ # 5. APPENDS to the existing datasets/form4_transactions.csv
13
+ #
14
+ # Run AFTER the main pipeline (collect_form4.py → postprocess_form4.py →
15
+ # form4_add_roles.py) has completed successfully.
16
+ #
17
+ # Run: python scripts/collect_form4_topup.py
18
+
19
+ import io
20
+ import time
21
+ import zipfile
22
+ import requests
23
+ import pandas as pd
24
+ from tqdm import tqdm
25
+
26
+ # ── Config ─────────────────────────────────────────────────────────────────────
27
+ OUT_PATH = r"D:\UoE AI\Dissertation\IPP Draft\datasets\form4_transactions.csv"
28
+ HEADERS = {'User-Agent': 'S2880814 University of Edinburgh s.g.vishnu@sms.ed.ac.uk'}
29
+ SLEEP = 0.12 # ~8 req/sec — well under EDGAR 10 req/sec limit
30
+ TIMEOUT = 120
31
+
32
+ # ── 22 missing CIK → Ticker pairs (from Sean Choi, 02 Jun 2026) ───────────────
33
+ NEW_UNIVERSE = {
34
+ 1725057: 'DAY',
35
+ 14693: 'BF.B',
36
+ 827099: 'CPWR',
37
+ 1751008: 'APP',
38
+ 1176948: 'ARES',
39
+ 1679788: 'COIN',
40
+ 849395: 'CRH',
41
+ 1690820: 'CVNA',
42
+ 1792789: 'DASH',
43
+ 1561550: 'DDOG',
44
+ 105634: 'EME',
45
+ 895126: 'EXE',
46
+ 1035983: 'FIX',
47
+ 1783869: 'HOOD',
48
+ 1381197: 'IBKR',
49
+ 62709: 'MRSH',
50
+ 2041610: 'PSKY',
51
+ 2064953: 'SOLS',
52
+ 1973266: 'TKO',
53
+ 1671933: 'TTD',
54
+ 719955: 'WSM',
55
+ 1512673: 'XYZ',
56
+ }
57
+
58
+ # Zero-pad CIKs to 10 digits (EDGAR format)
59
+ new_ciks = {str(cik).zfill(10) for cik in NEW_UNIVERSE}
60
+ cik_to_ticker = {str(cik).zfill(10): tkr for cik, tkr in NEW_UNIVERSE.items()}
61
+
62
+ print(f"Top-up target: {len(new_ciks)} CIKs")
63
+ print(f"CIKs: {sorted(new_ciks)}")
64
+
65
+
66
+ # ── Quarter URL generator (2006 Q1 → 2026 Q1) ─────────────────────────────────
67
+ def quarter_urls():
68
+ urls, year, qtr = [], 2006, 1
69
+ while (year, qtr) <= (2026, 1):
70
+ urls.append((year, qtr,
71
+ f"https://www.sec.gov/files/structureddata/data/insider-transactions-data-sets/{year}q{qtr}_form345.zip"))
72
+ qtr += 1
73
+ if qtr > 4:
74
+ qtr, year = 1, year + 1
75
+ return urls
76
+
77
+
78
+ # ── Pass 1: Collect SUBMISSION + NONDERIV_TRANS ───────────────────────────────
79
+ print("\n" + "=" * 60)
80
+ print("Pass 1 of 2: SUBMISSION + NONDERIV_TRANS (transactions)")
81
+ print("=" * 60)
82
+
83
+ trans_frames = []
84
+ found_accessions = set()
85
+
86
+ for year, qtr, url in tqdm(quarter_urls(), desc="Quarters (transactions)"):
87
+ time.sleep(SLEEP)
88
+ try:
89
+ r = requests.get(url, headers=HEADERS, timeout=TIMEOUT)
90
+ if r.status_code != 200:
91
+ tqdm.write(f" [SKIP] {year} Q{qtr} — HTTP {r.status_code}")
92
+ continue
93
+
94
+ zf = zipfile.ZipFile(io.BytesIO(r.content))
95
+ names_lc = {n.lower(): n for n in zf.namelist()}
96
+
97
+ # ── SUBMISSION ────────────────────────────────────────────────────────
98
+ sub_file = next((v for k, v in names_lc.items() if 'submission' in k), None)
99
+ if not sub_file:
100
+ continue
101
+ sub = pd.read_csv(io.BytesIO(zf.read(sub_file)), sep='\t',
102
+ low_memory=False, on_bad_lines='skip')
103
+ sub.columns = sub.columns.str.lower().str.strip()
104
+
105
+ # issuer_cik in SUBMISSION is stored as an integer — zero-pad it
106
+ if 'issuercik' in sub.columns:
107
+ sub['issuercik'] = sub['issuercik'].astype(str).str.strip().str.zfill(10)
108
+ sub_match = sub[sub['issuercik'].isin(new_ciks)]
109
+ if sub_match.empty:
110
+ continue
111
+
112
+ matched_acc = set(sub_match['accession_number'].dropna())
113
+
114
+ # ── NONDERIV_TRANS ────────────────────────────────────────────────────
115
+ nd_file = next((v for k, v in names_lc.items() if 'nonderiv_trans' in k), None)
116
+ if not nd_file:
117
+ continue
118
+ nd = pd.read_csv(io.BytesIO(zf.read(nd_file)), sep='\t',
119
+ low_memory=False, on_bad_lines='skip')
120
+ nd.columns = nd.columns.str.lower().str.strip()
121
+ nd = nd[nd['accession_number'].isin(matched_acc)]
122
+ if nd.empty:
123
+ continue
124
+
125
+ # Join submission metadata
126
+ sub_keep = [c for c in ['accession_number', 'issuercik', 'rptownercik',
127
+ 'rptowner_name', 'period_of_report'] if c in sub_match.columns]
128
+ merged = nd.merge(sub_match[sub_keep].drop_duplicates('accession_number'),
129
+ on='accession_number', how='left')
130
+
131
+ # Map ticker
132
+ merged['ticker'] = merged['issuercik'].map(cik_to_ticker)
133
+ merged.rename(columns={'issuercik': 'issuer_cik',
134
+ 'rptowner_name': 'owner_name'}, inplace=True)
135
+
136
+ trans_frames.append(merged)
137
+ found_accessions.update(matched_acc)
138
+ tqdm.write(f" {year} Q{qtr}: {len(nd):,} transactions, {len(matched_acc)} filings")
139
+
140
+ except Exception as e:
141
+ tqdm.write(f" [WARN] {year} Q{qtr}: {e}")
142
+
143
+ if not trans_frames:
144
+ print("\n[ERROR] No transactions found for any of the 22 new CIKs.")
145
+ raise SystemExit(1)
146
+
147
+ df_new = pd.concat(trans_frames, ignore_index=True)
148
+ print(f"\nPass 1 complete: {len(df_new):,} transactions across {df_new['issuer_cik'].nunique()} companies")
149
+ print(f"Unique accession numbers: {len(found_accessions):,}")
150
+
151
+
152
+ # ── Pass 2: Collect REPORTINGOWNER for role flags ─────────────────────────────
153
+ print("\n" + "=" * 60)
154
+ print("Pass 2 of 2: REPORTINGOWNER (is_officer / is_director / is_ten_pct_owner)")
155
+ print("=" * 60)
156
+
157
+ owner_frames = []
158
+
159
+ for year, qtr, url in tqdm(quarter_urls(), desc="Quarters (owner roles)"):
160
+ time.sleep(SLEEP)
161
+ try:
162
+ r = requests.get(url, headers=HEADERS, timeout=TIMEOUT)
163
+ if r.status_code != 200:
164
+ continue
165
+
166
+ zf = zipfile.ZipFile(io.BytesIO(r.content))
167
+ names_lc = {n.lower(): n for n in zf.namelist()}
168
+
169
+ own_file = next((v for k, v in names_lc.items() if 'reportingowner' in k), None)
170
+ if not own_file:
171
+ continue
172
+ own = pd.read_csv(io.BytesIO(zf.read(own_file)), sep='\t',
173
+ low_memory=False, on_bad_lines='skip')
174
+ own.columns = own.columns.str.lower().str.strip()
175
+
176
+ own = own[own['accession_number'].isin(found_accessions)]
177
+ if own.empty:
178
+ continue
179
+
180
+ keep = [c for c in ['accession_number', 'rptownercik',
181
+ 'rptowner_relationship', 'rptowner_title'] if c in own.columns]
182
+ owner_frames.append(own[keep].copy())
183
+
184
+ except Exception as e:
185
+ tqdm.write(f" [WARN] {year} Q{qtr}: {e}")
186
+
187
+ # ── Build roles lookup ────────────────────────────────────────────────────────
188
+ if owner_frames:
189
+ owner_df = pd.concat(owner_frames, ignore_index=True)
190
+ owner_df = owner_df.drop_duplicates(subset=['accession_number', 'rptownercik'])
191
+
192
+ rel = owner_df['rptowner_relationship'].fillna('')
193
+ owner_df['is_officer'] = rel.str.contains('Officer', case=False).astype(int)
194
+ owner_df['is_director'] = rel.str.contains('Director', case=False).astype(int)
195
+ owner_df['is_ten_pct_owner'] = rel.str.contains('TenPercentOwner',case=False).astype(int)
196
+ if 'rptowner_title' in owner_df.columns:
197
+ owner_df.rename(columns={'rptowner_title': 'officer_title'}, inplace=True)
198
+ owner_df.drop(columns=['rptowner_relationship'], inplace=True)
199
+
200
+ print(f" Owner rows: {len(owner_df):,}")
201
+ print(f" Officers : {owner_df['is_officer'].sum():,}")
202
+ print(f" Directors : {owner_df['is_director'].sum():,}")
203
+
204
+ df_new = df_new.merge(owner_df, on=['accession_number', 'rptownercik'], how='left')
205
+ else:
206
+ print(" [WARN] No owner role data retrieved — role columns will be NaN")
207
+ for col in ['is_officer', 'is_director', 'is_ten_pct_owner', 'officer_title']:
208
+ df_new[col] = pd.NA
209
+
210
+
211
+ # ── Post-process dates ────────────────────────────────────────────────────────
212
+ print("\nPost-processing dates...")
213
+ for date_col in ['transaction_date', 'deemed_execution_date']:
214
+ if date_col in df_new.columns:
215
+ df_new[date_col] = pd.to_datetime(
216
+ df_new[date_col], format='mixed', dayfirst=True, errors='coerce'
217
+ ).dt.strftime('%Y-%m-%d')
218
+
219
+ # Drop footnote columns
220
+ fn_cols = [c for c in df_new.columns if c.endswith('_fn')]
221
+ df_new.drop(columns=fn_cols, inplace=True)
222
+
223
+
224
+ # ── Load existing and append ──────────────────────────────────────────────────
225
+ print("\nLoading existing form4_transactions.csv...")
226
+ df_existing = pd.read_csv(OUT_PATH, low_memory=False)
227
+ print(f" Existing: {len(df_existing):,} rows, {len(df_existing.columns)} columns")
228
+
229
+ # Align columns — add any missing cols as NaN in either direction
230
+ all_cols = list(df_existing.columns)
231
+ for c in all_cols:
232
+ if c not in df_new.columns:
233
+ df_new[c] = pd.NA
234
+ df_new = df_new[all_cols] # reorder to match existing
235
+
236
+ # Guard against duplicate accessions (e.g., companies that were already in the 656)
237
+ existing_acc = set(df_existing['accession_number'].dropna())
238
+ df_new = df_new[~df_new['accession_number'].isin(existing_acc)]
239
+ print(f" New rows after dedup: {len(df_new):,}")
240
+
241
+ df_combined = pd.concat([df_existing, df_new], ignore_index=True)
242
+ df_combined.to_csv(OUT_PATH, index=False)
243
+
244
+ print(f"\n{'='*60}")
245
+ print(f"Top-up complete.")
246
+ print(f" Previous rows : {len(df_existing):,}")
247
+ print(f" Added rows : {len(df_new):,}")
248
+ print(f" Total rows : {len(df_combined):,}")
249
+ print(f" Companies : {df_combined['ticker'].nunique()}")
250
+ print(f" Date range : {df_combined['transaction_date'].min()} → {df_combined['transaction_date'].max()}")
251
+ print(f"\nSaved → {OUT_PATH}")