Upload scripts/form4_add_roles.py with huggingface_hub
Browse files- scripts/form4_add_roles.py +120 -0
scripts/form4_add_roles.py
ADDED
|
@@ -0,0 +1,120 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# form4_add_roles.py
|
| 2 |
+
# Adds is_officer, is_director, is_ten_pct_owner, officer_title columns
|
| 3 |
+
# to the existing form4_transactions.csv.
|
| 4 |
+
#
|
| 5 |
+
# The SEC's new REPORTINGOWNER format encodes roles as a comma-separated
|
| 6 |
+
# string in rptowner_relationship, e.g. "Director,Officer,TenPercentOwner"
|
| 7 |
+
# and officer title in rptowner_title.
|
| 8 |
+
#
|
| 9 |
+
# Re-downloads all 81 quarterly ZIPs (REPORTINGOWNER table only — small),
|
| 10 |
+
# merges onto form4_transactions.csv, derives boolean flags, saves.
|
| 11 |
+
#
|
| 12 |
+
# Run: python scripts/form4_add_roles.py
|
| 13 |
+
|
| 14 |
+
import io
|
| 15 |
+
import time
|
| 16 |
+
import zipfile
|
| 17 |
+
import requests
|
| 18 |
+
import pandas as pd
|
| 19 |
+
from tqdm import tqdm
|
| 20 |
+
|
| 21 |
+
OUT_PATH = r"D:\UoE AI\Dissertation\IPP Draft\datasets\form4_transactions.csv"
|
| 22 |
+
HEADERS = {'User-Agent': 'S2880814 University of Edinburgh s.g.vishnu@sms.ed.ac.uk'}
|
| 23 |
+
SLEEP = 0.5
|
| 24 |
+
TIMEOUT = 120
|
| 25 |
+
|
| 26 |
+
# ── 1. Load existing clean file ────────────────────────────────────────────────
|
| 27 |
+
print("Loading form4_transactions.csv...")
|
| 28 |
+
df = pd.read_csv(OUT_PATH, low_memory=False)
|
| 29 |
+
print(f" {len(df):,} rows, {len(df.columns)} columns")
|
| 30 |
+
our_accessions = set(df['accession_number'].dropna())
|
| 31 |
+
|
| 32 |
+
# ── 2. Re-download REPORTINGOWNER from all 81 quarters ────────────────────────
|
| 33 |
+
def quarter_urls():
|
| 34 |
+
urls, year, qtr = [], 2006, 1
|
| 35 |
+
while (year, qtr) <= (2026, 1):
|
| 36 |
+
urls.append((year, qtr,
|
| 37 |
+
f"https://www.sec.gov/files/structureddata/data/insider-transactions-data-sets/{year}q{qtr}_form345.zip"))
|
| 38 |
+
qtr += 1
|
| 39 |
+
if qtr > 4:
|
| 40 |
+
qtr, year = 1, year + 1
|
| 41 |
+
return urls
|
| 42 |
+
|
| 43 |
+
print(f"\nFetching REPORTINGOWNER from 81 quarters for {len(our_accessions):,} accessions...")
|
| 44 |
+
owner_frames = []
|
| 45 |
+
|
| 46 |
+
for year, qtr, url in tqdm(quarter_urls(), desc="Quarters"):
|
| 47 |
+
time.sleep(SLEEP)
|
| 48 |
+
try:
|
| 49 |
+
r = requests.get(url, headers=HEADERS, timeout=TIMEOUT)
|
| 50 |
+
if r.status_code != 200:
|
| 51 |
+
continue
|
| 52 |
+
zf = zipfile.ZipFile(io.BytesIO(r.content))
|
| 53 |
+
own_file = next((n for n in zf.namelist() if 'reportingowner' in n.lower()), None)
|
| 54 |
+
if not own_file:
|
| 55 |
+
continue
|
| 56 |
+
own = pd.read_csv(io.BytesIO(zf.read(own_file)), sep='\t',
|
| 57 |
+
low_memory=False, on_bad_lines='skip')
|
| 58 |
+
own.columns = own.columns.str.lower().str.strip()
|
| 59 |
+
|
| 60 |
+
own = own[own['accession_number'].isin(our_accessions)]
|
| 61 |
+
if own.empty:
|
| 62 |
+
continue
|
| 63 |
+
|
| 64 |
+
keep = [c for c in ['accession_number', 'rptownercik',
|
| 65 |
+
'rptowner_relationship', 'rptowner_title'] if c in own.columns]
|
| 66 |
+
owner_frames.append(own[keep].copy())
|
| 67 |
+
|
| 68 |
+
except Exception as e:
|
| 69 |
+
tqdm.write(f" [WARN] {year} Q{qtr}: {e}")
|
| 70 |
+
|
| 71 |
+
# ── 3. Build roles lookup table ────────────────────────────────────────────────
|
| 72 |
+
print("\nBuilding roles lookup...")
|
| 73 |
+
owner_df = pd.concat(owner_frames, ignore_index=True)
|
| 74 |
+
owner_df = owner_df.drop_duplicates(subset=['accession_number', 'rptownercik'])
|
| 75 |
+
|
| 76 |
+
# Parse rptowner_relationship → boolean flags
|
| 77 |
+
rel = owner_df['rptowner_relationship'].fillna('')
|
| 78 |
+
owner_df['is_officer'] = rel.str.contains('Officer', case=False).astype(int)
|
| 79 |
+
owner_df['is_director'] = rel.str.contains('Director', case=False).astype(int)
|
| 80 |
+
owner_df['is_ten_pct_owner'] = rel.str.contains('TenPercentOwner', case=False).astype(int)
|
| 81 |
+
|
| 82 |
+
if 'rptowner_title' in owner_df.columns:
|
| 83 |
+
owner_df.rename(columns={'rptowner_title': 'officer_title'}, inplace=True)
|
| 84 |
+
|
| 85 |
+
owner_df.drop(columns=['rptowner_relationship'], inplace=True)
|
| 86 |
+
print(f" Owner rows: {len(owner_df):,}")
|
| 87 |
+
print(f" Officers : {owner_df['is_officer'].sum():,}")
|
| 88 |
+
print(f" Directors : {owner_df['is_director'].sum():,}")
|
| 89 |
+
|
| 90 |
+
# ── 4. Merge onto main dataframe ───────────────────────────────────────────────
|
| 91 |
+
print("\nMerging roles onto transactions...")
|
| 92 |
+
|
| 93 |
+
# Drop any stale role columns if re-running
|
| 94 |
+
for col in ['is_officer', 'is_director', 'is_ten_pct_owner', 'officer_title']:
|
| 95 |
+
if col in df.columns:
|
| 96 |
+
df.drop(columns=[col], inplace=True)
|
| 97 |
+
|
| 98 |
+
df = df.merge(owner_df, on=['accession_number', 'rptownercik'], how='left')
|
| 99 |
+
|
| 100 |
+
# Move role cols next to owner_name
|
| 101 |
+
cols = df.columns.tolist()
|
| 102 |
+
role_cols = [c for c in ['is_officer', 'is_director', 'is_ten_pct_owner', 'officer_title'] if c in cols]
|
| 103 |
+
for rc in reversed(role_cols):
|
| 104 |
+
cols.remove(rc)
|
| 105 |
+
insert_at = cols.index('rptownercik') + 1
|
| 106 |
+
cols.insert(insert_at, rc)
|
| 107 |
+
df = df[cols]
|
| 108 |
+
|
| 109 |
+
# ── 5. Save ────────────────────────────────────────────────────────────────────
|
| 110 |
+
df.to_csv(OUT_PATH, index=False)
|
| 111 |
+
|
| 112 |
+
print(f"\n{'='*60}")
|
| 113 |
+
print(f" Final shape : {df.shape}")
|
| 114 |
+
print(f" Columns : {df.columns.tolist()}")
|
| 115 |
+
print(f"\nSample:")
|
| 116 |
+
preview = [c for c in ['ticker', 'owner_name', 'officer_title', 'is_officer',
|
| 117 |
+
'is_director', 'transaction_date', 'transaction_code',
|
| 118 |
+
'acquired_disposed', 'shares', 'price_per_share'] if c in df.columns]
|
| 119 |
+
print(df[preview].head(8).to_string(index=False))
|
| 120 |
+
print(f"\nSaved -> {OUT_PATH}")
|