| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
| |
|
|
| import io |
| import os |
| import time |
| import zipfile |
| import requests |
| import pandas as pd |
| from tqdm import tqdm |
|
|
| |
| OUT_PATH = r"D:\UoE AI\Dissertation\IPP Draft\datasets\form4_transactions.csv" |
| HEADERS = {'User-Agent': 'S2880814 University of Edinburgh s.g.vishnu@sms.ed.ac.uk'} |
| SLEEP = 0.5 |
| TIMEOUT = 120 |
|
|
| |
| print("Loading form4_transactions.csv...") |
| df = pd.read_csv(OUT_PATH, low_memory=False) |
| print(f" {len(df):,} rows, {len(df.columns)} columns") |
|
|
| |
| fn_cols = [c for c in df.columns if c.endswith('_fn')] |
| df.drop(columns=fn_cols, inplace=True) |
| print(f" Dropped {len(fn_cols)} footnote columns → {len(df.columns)} columns remain") |
|
|
| |
| print(" Converting dates...") |
| df['transaction_date'] = pd.to_datetime( |
| df['transaction_date'], format='mixed', dayfirst=True, errors='coerce' |
| ).dt.strftime('%Y-%m-%d') |
| print(f" Sample dates after fix: {df['transaction_date'].dropna().head(3).tolist()}") |
|
|
| |
| print("\nChecking REPORTINGOWNER column names from 2024 Q1...") |
| sample_url = "https://www.sec.gov/files/structureddata/data/insider-transactions-data-sets/2024q1_form345.zip" |
| r = requests.get(sample_url, headers=HEADERS, timeout=TIMEOUT) |
| zf = zipfile.ZipFile(io.BytesIO(r.content)) |
| owner_file = next((n for n in zf.namelist() if 'reportingowner' in n.lower()), None) |
| sample_own = pd.read_csv(io.BytesIO(zf.read(owner_file)), sep='\t', low_memory=False, nrows=5) |
| sample_own.columns = sample_own.columns.str.lower().str.strip() |
| print(f" REPORTINGOWNER columns: {sample_own.columns.tolist()}") |
|
|
| |
| col_map = {} |
| for col in sample_own.columns: |
| if col in ('isdir', 'isdirector'): |
| col_map['is_director'] = col |
| elif col == 'isofficer': |
| col_map['is_officer'] = col |
| elif col == 'istenpercentowner': |
| col_map['is_ten_pct_owner'] = col |
| elif col == 'officertitle': |
| col_map['officer_title'] = col |
| elif 'accession' in col: |
| col_map['accession_col'] = col |
|
|
| print(f" Mapped columns: {col_map}") |
|
|
| |
| def quarter_urls(): |
| urls = [] |
| year, qtr = 2006, 1 |
| while (year, qtr) <= (2026, 1): |
| url = f"https://www.sec.gov/files/structureddata/data/insider-transactions-data-sets/{year}q{qtr}_form345.zip" |
| urls.append((year, qtr, url)) |
| qtr += 1 |
| if qtr > 4: |
| qtr, year = 1, year + 1 |
| return urls |
|
|
| |
| our_accessions = set(df['accession_number'].dropna()) |
| print(f"\nRe-fetching owner role columns for {len(our_accessions):,} accessions...") |
|
|
| acc_col = col_map.get('accession_col', 'accession_number') |
| dir_col = col_map.get('is_director') |
| off_col = col_map.get('is_officer') |
| pct_col = col_map.get('is_ten_pct_owner') |
| title_col = col_map.get('officer_title') |
| keep_own = [c for c in [acc_col, 'rptownercik', dir_col, off_col, pct_col, title_col] if c] |
|
|
| owner_frames = [] |
|
|
| for year, qtr, url in tqdm(quarter_urls(), desc="Re-fetching owner data"): |
| time.sleep(SLEEP) |
| try: |
| r = requests.get(url, headers=HEADERS, timeout=TIMEOUT) |
| if r.status_code != 200: |
| continue |
| zf = zipfile.ZipFile(io.BytesIO(r.content)) |
| own_file = next((n for n in zf.namelist() if 'reportingowner' in n.lower()), None) |
| if not own_file: |
| continue |
| own = pd.read_csv(io.BytesIO(zf.read(own_file)), sep='\t', low_memory=False, on_bad_lines='skip') |
| own.columns = own.columns.str.lower().str.strip() |
|
|
| acc_col_q = next((c for c in own.columns if 'accession' in c), None) |
| if not acc_col_q: |
| continue |
|
|
| |
| own = own[own[acc_col_q].isin(our_accessions)] |
| if own.empty: |
| continue |
|
|
| cols_to_keep = [c for c in [acc_col_q, 'rptownercik', dir_col, off_col, pct_col, title_col] if c and c in own.columns] |
| owner_frames.append(own[cols_to_keep].copy()) |
|
|
| except Exception as e: |
| tqdm.write(f" [WARN] {year} Q{qtr}: {e}") |
| continue |
|
|
| if owner_frames: |
| owner_df = pd.concat(owner_frames, ignore_index=True) |
| owner_df.columns = owner_df.columns.str.lower().str.strip() |
|
|
| |
| rename_own = {} |
| if dir_col and dir_col in owner_df.columns: rename_own[dir_col] = 'is_director' |
| if off_col and off_col in owner_df.columns: rename_own[off_col] = 'is_officer' |
| if pct_col and pct_col in owner_df.columns: rename_own[pct_col] = 'is_ten_pct_owner' |
| if title_col and title_col in owner_df.columns: rename_own[title_col] = 'officer_title' |
| owner_df.rename(columns=rename_own, inplace=True) |
|
|
| |
| acc_col_own = next((c for c in owner_df.columns if 'accession' in c), None) |
| if acc_col_own: |
| owner_df = owner_df.drop_duplicates(subset=[acc_col_own, 'rptownercik']) |
|
|
| print(f" Owner rows fetched: {len(owner_df):,}") |
| print(f" Owner columns: {owner_df.columns.tolist()}") |
|
|
| |
| df = df.merge( |
| owner_df, |
| left_on=['accession_number', 'rptownercik'], |
| right_on=[acc_col_own, 'rptownercik'], |
| how='left' |
| ) |
| |
| if acc_col_own != 'accession_number' and acc_col_own in df.columns: |
| df.drop(columns=[acc_col_own], inplace=True) |
|
|
| print(f" is_officer populated: {df['is_officer'].notna().sum():,} rows" if 'is_officer' in df.columns else " [WARN] is_officer not in merged result") |
| else: |
| print(" [WARN] No owner role data retrieved — skipping merge") |
|
|
| |
| rename_final = { |
| 'shrs_ownd_folwng_trans': 'shares_after_txn', |
| 'valu_ownd_folwng_trans': 'value_after_txn', |
| 'direct_indirect_ownership': 'ownership_type', |
| 'trans_form_type': 'form_type', |
| 'nonderiv_trans_sk': 'trans_sk', |
| } |
| df.rename(columns={k: v for k, v in rename_final.items() if k in df.columns}, inplace=True) |
|
|
| |
| priority = ['ticker', 'issuer_cik', 'accession_number', 'filing_date' if 'filing_date' in df.columns else None, |
| 'owner_name', 'rptownercik', 'is_officer', 'is_director', 'is_ten_pct_owner', 'officer_title', |
| 'transaction_date', 'transaction_code', 'acquired_disposed', |
| 'shares', 'price_per_share', 'shares_after_txn', 'value_after_txn', |
| 'security_title', 'ownership_type', 'form_type'] |
| priority = [c for c in priority if c and c in df.columns] |
| rest = [c for c in df.columns if c not in priority] |
| df = df[priority + rest] |
|
|
| |
| df.to_csv(OUT_PATH, index=False) |
|
|
| print(f"\n{'='*60}") |
| print(f"Post-processing complete.") |
| print(f" Final shape : {df.shape}") |
| print(f" Size on disk : {os.path.getsize(OUT_PATH)/1024/1024:.1f} MB") |
| print(f" Columns : {df.columns.tolist()}") |
| print(f"\nSample (first 5 rows):") |
| preview = [c for c in ['ticker','owner_name','officer_title','is_officer', |
| 'transaction_date','transaction_code','acquired_disposed', |
| 'shares','price_per_share'] if c in df.columns] |
| print(df[preview].head().to_string(index=False)) |
| print(f"\nSaved -> {OUT_PATH}") |
|
|