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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# collect_form4.py
|
| 2 |
+
# Collects SEC Form 4 (insider trading) data for all 656 S&P 500 CIKs.
|
| 3 |
+
#
|
| 4 |
+
# Source: SEC EDGAR Insider Transactions Data Sets (official quarterly flat files)
|
| 5 |
+
# https://www.sec.gov/data-research/sec-markets-data/insider-transactions-data-sets
|
| 6 |
+
#
|
| 7 |
+
# The SEC pre-parses all Form 3/4/5 XML submissions into quarterly ZIP files.
|
| 8 |
+
# This is vastly faster than scraping individual XMLs (~20 min vs ~11 hours).
|
| 9 |
+
#
|
| 10 |
+
# Method:
|
| 11 |
+
# 1. Download quarterly ZIP files for 2006 Q1 → 2026 Q1 (~80 files)
|
| 12 |
+
# 2. From each ZIP, read SUBMISSION.tsv + REPORTINGOWNER.tsv + NONDERIV_TRANS.tsv
|
| 13 |
+
# 3. Filter SUBMISSION rows where issuer_cik is in our 656-company universe
|
| 14 |
+
# 4. Join owner and transaction details
|
| 15 |
+
# 5. Output clean form4_transactions.csv
|
| 16 |
+
#
|
| 17 |
+
# Output:
|
| 18 |
+
# datasets/form4_transactions.csv — one row per non-derivative transaction
|
| 19 |
+
#
|
| 20 |
+
# Run: python scripts/collect_form4.py
|
| 21 |
+
|
| 22 |
+
import io
|
| 23 |
+
import os
|
| 24 |
+
import time
|
| 25 |
+
import zipfile
|
| 26 |
+
import requests
|
| 27 |
+
import pandas as pd
|
| 28 |
+
from tqdm import tqdm
|
| 29 |
+
|
| 30 |
+
# ── Paths ──────────────────────────────────────────────────────────────────────
|
| 31 |
+
UNIVERSE_PATH = r"D:\UoE AI\Dissertation\IPP Draft\datasets\sp500_union_constituents(1).csv"
|
| 32 |
+
OUT_PATH = r"D:\UoE AI\Dissertation\IPP Draft\datasets\form4_transactions.csv"
|
| 33 |
+
|
| 34 |
+
# ── Config ─────────────────────────────────────────────────────────────────────
|
| 35 |
+
HEADERS = {'User-Agent': 'S2880814 University of Edinburgh s.g.vishnu@sms.ed.ac.uk'}
|
| 36 |
+
SLEEP = 0.5 # conservative — these are bulk files, not per-filing requests
|
| 37 |
+
TIMEOUT = 120 # ZIP files can be large, allow more time
|
| 38 |
+
|
| 39 |
+
# Date range: 2006 Q1 → 2026 Q1
|
| 40 |
+
START_YEAR, START_QTR = 2006, 1
|
| 41 |
+
END_YEAR, END_QTR = 2026, 1
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# ── 1. Load S&P 500 universe ───────────────────────────────────────────────────
|
| 45 |
+
print("Loading S&P 500 universe...")
|
| 46 |
+
universe = pd.read_csv(UNIVERSE_PATH)
|
| 47 |
+
cik_col = [c for c in universe.columns if 'cik' in c.lower()][0]
|
| 48 |
+
tkr_col = [c for c in universe.columns if any(k in c.lower() for k in ('ticker', 'symbol', 'tic'))][0]
|
| 49 |
+
universe[cik_col] = universe[cik_col].astype(int)
|
| 50 |
+
cik_set = set(universe[cik_col].dropna().astype(int))
|
| 51 |
+
cik2tkr = dict(zip(universe[cik_col], universe[tkr_col]))
|
| 52 |
+
print(f" {len(cik_set)} unique CIKs loaded")
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# ── 2. Build list of quarterly ZIP URLs ───────────────────────────────────────
|
| 56 |
+
# SEC URL pattern: https://www.sec.gov/files/dera/data/insider-transactions/{YYYY}q{Q}_form345.zip
|
| 57 |
+
def quarter_urls():
|
| 58 |
+
urls = []
|
| 59 |
+
year, qtr = START_YEAR, START_QTR
|
| 60 |
+
while (year, qtr) <= (END_YEAR, END_QTR):
|
| 61 |
+
url = f"https://www.sec.gov/files/structureddata/data/insider-transactions-data-sets/{year}q{qtr}_form345.zip"
|
| 62 |
+
urls.append((year, qtr, url))
|
| 63 |
+
qtr += 1
|
| 64 |
+
if qtr > 4:
|
| 65 |
+
qtr = 1
|
| 66 |
+
year += 1
|
| 67 |
+
return urls
|
| 68 |
+
|
| 69 |
+
quarters = quarter_urls()
|
| 70 |
+
print(f"\n{len(quarters)} quarterly ZIP files to process (2006 Q1 → 2026 Q1)")
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
# ── 3. Process each quarterly ZIP ─────────────────────────────────────────────
|
| 74 |
+
all_records = []
|
| 75 |
+
failed_quarters = []
|
| 76 |
+
|
| 77 |
+
for year, qtr, url in tqdm(quarters, desc="Quarters"):
|
| 78 |
+
time.sleep(SLEEP)
|
| 79 |
+
|
| 80 |
+
# Download ZIP into memory
|
| 81 |
+
try:
|
| 82 |
+
r = requests.get(url, headers=HEADERS, timeout=TIMEOUT)
|
| 83 |
+
except requests.RequestException as e:
|
| 84 |
+
tqdm.write(f" [SKIP] {year} Q{qtr} — request error: {e}")
|
| 85 |
+
failed_quarters.append((year, qtr))
|
| 86 |
+
continue
|
| 87 |
+
|
| 88 |
+
if r.status_code == 404:
|
| 89 |
+
tqdm.write(f" [SKIP] {year} Q{qtr} — not yet published (404)")
|
| 90 |
+
continue
|
| 91 |
+
if r.status_code != 200:
|
| 92 |
+
tqdm.write(f" [SKIP] {year} Q{qtr} — HTTP {r.status_code}")
|
| 93 |
+
failed_quarters.append((year, qtr))
|
| 94 |
+
continue
|
| 95 |
+
|
| 96 |
+
try:
|
| 97 |
+
zf = zipfile.ZipFile(io.BytesIO(r.content))
|
| 98 |
+
except zipfile.BadZipFile:
|
| 99 |
+
tqdm.write(f" [SKIP] {year} Q{qtr} — bad ZIP file")
|
| 100 |
+
failed_quarters.append((year, qtr))
|
| 101 |
+
continue
|
| 102 |
+
|
| 103 |
+
zip_names = zf.namelist()
|
| 104 |
+
|
| 105 |
+
# ── Read SUBMISSION table (issuer CIK + filing metadata) ──────────────────
|
| 106 |
+
sub_file = next((n for n in zip_names if 'submission' in n.lower()), None)
|
| 107 |
+
if not sub_file:
|
| 108 |
+
tqdm.write(f" [SKIP] {year} Q{qtr} — SUBMISSION file not found in ZIP")
|
| 109 |
+
continue
|
| 110 |
+
|
| 111 |
+
sub = pd.read_csv(
|
| 112 |
+
io.BytesIO(zf.read(sub_file)),
|
| 113 |
+
sep='\t', low_memory=False,
|
| 114 |
+
on_bad_lines='skip'
|
| 115 |
+
)
|
| 116 |
+
sub.columns = sub.columns.str.lower().str.strip()
|
| 117 |
+
|
| 118 |
+
# Identify issuer CIK column (varies slightly across years)
|
| 119 |
+
issuer_col = next((c for c in sub.columns if 'issuer' in c and 'cik' in c), None) \
|
| 120 |
+
or next((c for c in sub.columns if c == 'issuercik'), None)
|
| 121 |
+
if not issuer_col:
|
| 122 |
+
tqdm.write(f" [SKIP] {year} Q{qtr} — can't find issuer CIK column. Cols: {sub.columns.tolist()[:8]}")
|
| 123 |
+
continue
|
| 124 |
+
|
| 125 |
+
sub[issuer_col] = pd.to_numeric(sub[issuer_col], errors='coerce')
|
| 126 |
+
sub_filtered = sub[sub[issuer_col].isin(cik_set)].copy()
|
| 127 |
+
|
| 128 |
+
if sub_filtered.empty:
|
| 129 |
+
continue # none of our companies filed this quarter
|
| 130 |
+
|
| 131 |
+
accessions = set(sub_filtered['accession_number'] if 'accession_number' in sub_filtered.columns
|
| 132 |
+
else sub_filtered[sub_filtered.columns[0]])
|
| 133 |
+
|
| 134 |
+
# ── Read REPORTINGOWNER table (insider details) ────────────────────────────
|
| 135 |
+
owner_file = next((n for n in zip_names if 'reportingowner' in n.lower()), None)
|
| 136 |
+
if owner_file:
|
| 137 |
+
own = pd.read_csv(
|
| 138 |
+
io.BytesIO(zf.read(owner_file)),
|
| 139 |
+
sep='\t', low_memory=False,
|
| 140 |
+
on_bad_lines='skip'
|
| 141 |
+
)
|
| 142 |
+
own.columns = own.columns.str.lower().str.strip()
|
| 143 |
+
acc_col_own = next((c for c in own.columns if 'accession' in c), None)
|
| 144 |
+
if acc_col_own:
|
| 145 |
+
own = own[own[acc_col_own].isin(accessions)]
|
| 146 |
+
else:
|
| 147 |
+
own = pd.DataFrame()
|
| 148 |
+
|
| 149 |
+
# ── Read NONDERIV_TRANS table (actual buy/sell transactions) ───────────────
|
| 150 |
+
txn_file = next((n for n in zip_names if 'nonderiv_trans' in n.lower()), None)
|
| 151 |
+
if not txn_file:
|
| 152 |
+
continue
|
| 153 |
+
|
| 154 |
+
txn = pd.read_csv(
|
| 155 |
+
io.BytesIO(zf.read(txn_file)),
|
| 156 |
+
sep='\t', low_memory=False,
|
| 157 |
+
on_bad_lines='skip'
|
| 158 |
+
)
|
| 159 |
+
txn.columns = txn.columns.str.lower().str.strip()
|
| 160 |
+
acc_col_txn = next((c for c in txn.columns if 'accession' in c), None)
|
| 161 |
+
if not acc_col_txn:
|
| 162 |
+
continue
|
| 163 |
+
|
| 164 |
+
txn = txn[txn[acc_col_txn].isin(accessions)].copy()
|
| 165 |
+
if txn.empty:
|
| 166 |
+
continue
|
| 167 |
+
|
| 168 |
+
# ── Join: txn + submission (issuer info) + owner (insider info) ───────────
|
| 169 |
+
# Merge txn with submission on accession number
|
| 170 |
+
merge_on = acc_col_txn
|
| 171 |
+
sub_cols = [issuer_col, 'accession_number' if 'accession_number' in sub_filtered.columns
|
| 172 |
+
else sub_filtered.columns[0],
|
| 173 |
+
'periodofreport', 'filingdate'] if 'filingdate' in sub_filtered.columns \
|
| 174 |
+
else [issuer_col, sub_filtered.columns[0]]
|
| 175 |
+
|
| 176 |
+
# Keep only useful submission columns that exist
|
| 177 |
+
useful_sub = [c for c in [issuer_col, 'accession_number', 'periodofreport',
|
| 178 |
+
'filingdate', 'reporttype'] if c in sub_filtered.columns]
|
| 179 |
+
merged = txn.merge(
|
| 180 |
+
sub_filtered[useful_sub].rename(columns={issuer_col: 'issuer_cik'}),
|
| 181 |
+
left_on=acc_col_txn, right_on='accession_number', how='left'
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
# Merge with owner info if available
|
| 185 |
+
if not own.empty and acc_col_own in own.columns:
|
| 186 |
+
useful_own = [c for c in [acc_col_own, 'rptownername', 'rptownercik',
|
| 187 |
+
'isofficer', 'isdirector', 'istenpercentowner',
|
| 188 |
+
'officertitle'] if c in own.columns]
|
| 189 |
+
merged = merged.merge(
|
| 190 |
+
own[useful_own],
|
| 191 |
+
left_on=acc_col_txn, right_on=acc_col_own, how='left'
|
| 192 |
+
)
|
| 193 |
+
|
| 194 |
+
# Add ticker from our universe mapping
|
| 195 |
+
if 'issuer_cik' in merged.columns:
|
| 196 |
+
merged['ticker'] = merged['issuer_cik'].map(cik2tkr)
|
| 197 |
+
|
| 198 |
+
all_records.append(merged)
|
| 199 |
+
tqdm.write(f" {year} Q{qtr}: {len(merged):,} transactions for {sub_filtered[issuer_col].nunique()} companies")
|
| 200 |
+
|
| 201 |
+
|
| 202 |
+
# ── 4. Combine and save ────────────────────────────────────────────────────────
|
| 203 |
+
if not all_records:
|
| 204 |
+
print("\nNo records collected — check URL pattern or network connection.")
|
| 205 |
+
else:
|
| 206 |
+
df = pd.concat(all_records, ignore_index=True)
|
| 207 |
+
|
| 208 |
+
# Standardise key column names where possible
|
| 209 |
+
rename_map = {
|
| 210 |
+
'trans_date': 'transaction_date',
|
| 211 |
+
'transaction_date': 'transaction_date',
|
| 212 |
+
'trans_shares': 'shares',
|
| 213 |
+
'transaction_shares':'shares',
|
| 214 |
+
'trans_pricepershare': 'price_per_share',
|
| 215 |
+
'trans_acquired_disp_cd': 'acquired_disposed',
|
| 216 |
+
'trans_code': 'transaction_code',
|
| 217 |
+
'rptownername': 'owner_name',
|
| 218 |
+
'isofficer': 'is_officer',
|
| 219 |
+
'isdirector': 'is_director',
|
| 220 |
+
'istenpercentowner': 'is_ten_pct_owner',
|
| 221 |
+
'officertitle': 'officer_title',
|
| 222 |
+
'filingdate': 'filing_date',
|
| 223 |
+
}
|
| 224 |
+
df.rename(columns={k: v for k, v in rename_map.items() if k in df.columns}, inplace=True)
|
| 225 |
+
|
| 226 |
+
df.to_csv(OUT_PATH, index=False)
|
| 227 |
+
|
| 228 |
+
print(f"\n{'='*60}")
|
| 229 |
+
print(f"Form 4 collection complete.")
|
| 230 |
+
print(f" Total transactions : {len(df):,}")
|
| 231 |
+
print(f" Unique companies : {df['issuer_cik'].nunique() if 'issuer_cik' in df.columns else 'N/A'}")
|
| 232 |
+
print(f" Columns : {df.columns.tolist()}")
|
| 233 |
+
if failed_quarters:
|
| 234 |
+
print(f" Failed quarters : {failed_quarters}")
|
| 235 |
+
print(f"\nSaved -> {OUT_PATH}")
|
| 236 |
+
|
| 237 |
+
print("\nSample (first 5 rows):")
|
| 238 |
+
preview_cols = [c for c in ['ticker', 'owner_name', 'officer_title',
|
| 239 |
+
'transaction_date', 'transaction_code',
|
| 240 |
+
'acquired_disposed', 'shares', 'price_per_share']
|
| 241 |
+
if c in df.columns]
|
| 242 |
+
print(df[preview_cols].head().to_string(index=False))
|