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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# postprocess_form4.py
|
| 2 |
+
# Cleans up form4_transactions.csv:
|
| 3 |
+
# 1. Drops footnote columns (*_fn)
|
| 4 |
+
# 2. Converts date format from 30-MAR-2006 → 2006-03-30
|
| 5 |
+
# 3. Re-fetches is_officer / is_director / officer_title from one sample
|
| 6 |
+
# quarter to confirm correct column names, then re-downloads all quarters
|
| 7 |
+
# to add these columns to the existing data
|
| 8 |
+
# 4. Renames columns for clarity
|
| 9 |
+
# 5. Overwrites form4_transactions.csv with the clean version
|
| 10 |
+
#
|
| 11 |
+
# Run: python scripts/postprocess_form4.py
|
| 12 |
+
|
| 13 |
+
import io
|
| 14 |
+
import os
|
| 15 |
+
import time
|
| 16 |
+
import zipfile
|
| 17 |
+
import requests
|
| 18 |
+
import pandas as pd
|
| 19 |
+
from tqdm import tqdm
|
| 20 |
+
|
| 21 |
+
# ── Paths ──────────────────────────────────────────────────────────────────────
|
| 22 |
+
OUT_PATH = r"D:\UoE AI\Dissertation\IPP Draft\datasets\form4_transactions.csv"
|
| 23 |
+
HEADERS = {'User-Agent': 'S2880814 University of Edinburgh s.g.vishnu@sms.ed.ac.uk'}
|
| 24 |
+
SLEEP = 0.5
|
| 25 |
+
TIMEOUT = 120
|
| 26 |
+
|
| 27 |
+
# ── 1. Load existing data ──────────────────────────────────────────────────────
|
| 28 |
+
print("Loading form4_transactions.csv...")
|
| 29 |
+
df = pd.read_csv(OUT_PATH, low_memory=False)
|
| 30 |
+
print(f" {len(df):,} rows, {len(df.columns)} columns")
|
| 31 |
+
|
| 32 |
+
# ── 2. Drop footnote columns ───────────────────────────────────────────────────
|
| 33 |
+
fn_cols = [c for c in df.columns if c.endswith('_fn')]
|
| 34 |
+
df.drop(columns=fn_cols, inplace=True)
|
| 35 |
+
print(f" Dropped {len(fn_cols)} footnote columns → {len(df.columns)} columns remain")
|
| 36 |
+
|
| 37 |
+
# ── 3. Fix date format: 30-MAR-2006 → 2006-03-30 ─────────────────────────────
|
| 38 |
+
print(" Converting dates...")
|
| 39 |
+
df['transaction_date'] = pd.to_datetime(
|
| 40 |
+
df['transaction_date'], format='mixed', dayfirst=True, errors='coerce'
|
| 41 |
+
).dt.strftime('%Y-%m-%d')
|
| 42 |
+
print(f" Sample dates after fix: {df['transaction_date'].dropna().head(3).tolist()}")
|
| 43 |
+
|
| 44 |
+
# ── 4. Discover correct REPORTINGOWNER column names from one sample quarter ────
|
| 45 |
+
print("\nChecking REPORTINGOWNER column names from 2024 Q1...")
|
| 46 |
+
sample_url = "https://www.sec.gov/files/structureddata/data/insider-transactions-data-sets/2024q1_form345.zip"
|
| 47 |
+
r = requests.get(sample_url, headers=HEADERS, timeout=TIMEOUT)
|
| 48 |
+
zf = zipfile.ZipFile(io.BytesIO(r.content))
|
| 49 |
+
owner_file = next((n for n in zf.namelist() if 'reportingowner' in n.lower()), None)
|
| 50 |
+
sample_own = pd.read_csv(io.BytesIO(zf.read(owner_file)), sep='\t', low_memory=False, nrows=5)
|
| 51 |
+
sample_own.columns = sample_own.columns.str.lower().str.strip()
|
| 52 |
+
print(f" REPORTINGOWNER columns: {sample_own.columns.tolist()}")
|
| 53 |
+
|
| 54 |
+
# Identify the correct column names
|
| 55 |
+
col_map = {}
|
| 56 |
+
for col in sample_own.columns:
|
| 57 |
+
if col in ('isdir', 'isdirector'):
|
| 58 |
+
col_map['is_director'] = col
|
| 59 |
+
elif col == 'isofficer':
|
| 60 |
+
col_map['is_officer'] = col
|
| 61 |
+
elif col == 'istenpercentowner':
|
| 62 |
+
col_map['is_ten_pct_owner'] = col
|
| 63 |
+
elif col == 'officertitle':
|
| 64 |
+
col_map['officer_title'] = col
|
| 65 |
+
elif 'accession' in col:
|
| 66 |
+
col_map['accession_col'] = col
|
| 67 |
+
|
| 68 |
+
print(f" Mapped columns: {col_map}")
|
| 69 |
+
|
| 70 |
+
# ── 5. Re-download all quarters to get owner role columns ─────────────────────
|
| 71 |
+
def quarter_urls():
|
| 72 |
+
urls = []
|
| 73 |
+
year, qtr = 2006, 1
|
| 74 |
+
while (year, qtr) <= (2026, 1):
|
| 75 |
+
url = f"https://www.sec.gov/files/structureddata/data/insider-transactions-data-sets/{year}q{qtr}_form345.zip"
|
| 76 |
+
urls.append((year, qtr, url))
|
| 77 |
+
qtr += 1
|
| 78 |
+
if qtr > 4:
|
| 79 |
+
qtr, year = 1, year + 1
|
| 80 |
+
return urls
|
| 81 |
+
|
| 82 |
+
# Get accession numbers already in our dataset
|
| 83 |
+
our_accessions = set(df['accession_number'].dropna())
|
| 84 |
+
print(f"\nRe-fetching owner role columns for {len(our_accessions):,} accessions...")
|
| 85 |
+
|
| 86 |
+
acc_col = col_map.get('accession_col', 'accession_number')
|
| 87 |
+
dir_col = col_map.get('is_director')
|
| 88 |
+
off_col = col_map.get('is_officer')
|
| 89 |
+
pct_col = col_map.get('is_ten_pct_owner')
|
| 90 |
+
title_col = col_map.get('officer_title')
|
| 91 |
+
keep_own = [c for c in [acc_col, 'rptownercik', dir_col, off_col, pct_col, title_col] if c]
|
| 92 |
+
|
| 93 |
+
owner_frames = []
|
| 94 |
+
|
| 95 |
+
for year, qtr, url in tqdm(quarter_urls(), desc="Re-fetching owner data"):
|
| 96 |
+
time.sleep(SLEEP)
|
| 97 |
+
try:
|
| 98 |
+
r = requests.get(url, headers=HEADERS, timeout=TIMEOUT)
|
| 99 |
+
if r.status_code != 200:
|
| 100 |
+
continue
|
| 101 |
+
zf = zipfile.ZipFile(io.BytesIO(r.content))
|
| 102 |
+
own_file = next((n for n in zf.namelist() if 'reportingowner' in n.lower()), None)
|
| 103 |
+
if not own_file:
|
| 104 |
+
continue
|
| 105 |
+
own = pd.read_csv(io.BytesIO(zf.read(own_file)), sep='\t', low_memory=False, on_bad_lines='skip')
|
| 106 |
+
own.columns = own.columns.str.lower().str.strip()
|
| 107 |
+
|
| 108 |
+
acc_col_q = next((c for c in own.columns if 'accession' in c), None)
|
| 109 |
+
if not acc_col_q:
|
| 110 |
+
continue
|
| 111 |
+
|
| 112 |
+
# Only keep rows for our accessions
|
| 113 |
+
own = own[own[acc_col_q].isin(our_accessions)]
|
| 114 |
+
if own.empty:
|
| 115 |
+
continue
|
| 116 |
+
|
| 117 |
+
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]
|
| 118 |
+
owner_frames.append(own[cols_to_keep].copy())
|
| 119 |
+
|
| 120 |
+
except Exception as e:
|
| 121 |
+
tqdm.write(f" [WARN] {year} Q{qtr}: {e}")
|
| 122 |
+
continue
|
| 123 |
+
|
| 124 |
+
if owner_frames:
|
| 125 |
+
owner_df = pd.concat(owner_frames, ignore_index=True)
|
| 126 |
+
owner_df.columns = owner_df.columns.str.lower().str.strip()
|
| 127 |
+
|
| 128 |
+
# Rename to standard names
|
| 129 |
+
rename_own = {}
|
| 130 |
+
if dir_col and dir_col in owner_df.columns: rename_own[dir_col] = 'is_director'
|
| 131 |
+
if off_col and off_col in owner_df.columns: rename_own[off_col] = 'is_officer'
|
| 132 |
+
if pct_col and pct_col in owner_df.columns: rename_own[pct_col] = 'is_ten_pct_owner'
|
| 133 |
+
if title_col and title_col in owner_df.columns: rename_own[title_col] = 'officer_title'
|
| 134 |
+
owner_df.rename(columns=rename_own, inplace=True)
|
| 135 |
+
|
| 136 |
+
# Deduplicate: one row per accession + rptownercik
|
| 137 |
+
acc_col_own = next((c for c in owner_df.columns if 'accession' in c), None)
|
| 138 |
+
if acc_col_own:
|
| 139 |
+
owner_df = owner_df.drop_duplicates(subset=[acc_col_own, 'rptownercik'])
|
| 140 |
+
|
| 141 |
+
print(f" Owner rows fetched: {len(owner_df):,}")
|
| 142 |
+
print(f" Owner columns: {owner_df.columns.tolist()}")
|
| 143 |
+
|
| 144 |
+
# Merge onto main df
|
| 145 |
+
df = df.merge(
|
| 146 |
+
owner_df,
|
| 147 |
+
left_on=['accession_number', 'rptownercik'],
|
| 148 |
+
right_on=[acc_col_own, 'rptownercik'],
|
| 149 |
+
how='left'
|
| 150 |
+
)
|
| 151 |
+
# Drop duplicate accession col if created
|
| 152 |
+
if acc_col_own != 'accession_number' and acc_col_own in df.columns:
|
| 153 |
+
df.drop(columns=[acc_col_own], inplace=True)
|
| 154 |
+
|
| 155 |
+
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")
|
| 156 |
+
else:
|
| 157 |
+
print(" [WARN] No owner role data retrieved — skipping merge")
|
| 158 |
+
|
| 159 |
+
# ── 6. Final column rename + reorder ──────────────────────────────────────────
|
| 160 |
+
rename_final = {
|
| 161 |
+
'shrs_ownd_folwng_trans': 'shares_after_txn',
|
| 162 |
+
'valu_ownd_folwng_trans': 'value_after_txn',
|
| 163 |
+
'direct_indirect_ownership': 'ownership_type',
|
| 164 |
+
'trans_form_type': 'form_type',
|
| 165 |
+
'nonderiv_trans_sk': 'trans_sk',
|
| 166 |
+
}
|
| 167 |
+
df.rename(columns={k: v for k, v in rename_final.items() if k in df.columns}, inplace=True)
|
| 168 |
+
|
| 169 |
+
# Preferred column order
|
| 170 |
+
priority = ['ticker', 'issuer_cik', 'accession_number', 'filing_date' if 'filing_date' in df.columns else None,
|
| 171 |
+
'owner_name', 'rptownercik', 'is_officer', 'is_director', 'is_ten_pct_owner', 'officer_title',
|
| 172 |
+
'transaction_date', 'transaction_code', 'acquired_disposed',
|
| 173 |
+
'shares', 'price_per_share', 'shares_after_txn', 'value_after_txn',
|
| 174 |
+
'security_title', 'ownership_type', 'form_type']
|
| 175 |
+
priority = [c for c in priority if c and c in df.columns]
|
| 176 |
+
rest = [c for c in df.columns if c not in priority]
|
| 177 |
+
df = df[priority + rest]
|
| 178 |
+
|
| 179 |
+
# ── 7. Save ────────────────────────────────────────────────────────────────────
|
| 180 |
+
df.to_csv(OUT_PATH, index=False)
|
| 181 |
+
|
| 182 |
+
print(f"\n{'='*60}")
|
| 183 |
+
print(f"Post-processing complete.")
|
| 184 |
+
print(f" Final shape : {df.shape}")
|
| 185 |
+
print(f" Size on disk : {os.path.getsize(OUT_PATH)/1024/1024:.1f} MB")
|
| 186 |
+
print(f" Columns : {df.columns.tolist()}")
|
| 187 |
+
print(f"\nSample (first 5 rows):")
|
| 188 |
+
preview = [c for c in ['ticker','owner_name','officer_title','is_officer',
|
| 189 |
+
'transaction_date','transaction_code','acquired_disposed',
|
| 190 |
+
'shares','price_per_share'] if c in df.columns]
|
| 191 |
+
print(df[preview].head().to_string(index=False))
|
| 192 |
+
print(f"\nSaved -> {OUT_PATH}")
|