File size: 8,973 Bytes
1a5e56b | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 | # postprocess_form4.py
# Cleans up form4_transactions.csv:
# 1. Drops footnote columns (*_fn)
# 2. Converts date format from 30-MAR-2006 → 2006-03-30
# 3. Re-fetches is_officer / is_director / officer_title from one sample
# quarter to confirm correct column names, then re-downloads all quarters
# to add these columns to the existing data
# 4. Renames columns for clarity
# 5. Overwrites form4_transactions.csv with the clean version
#
# Run: python scripts/postprocess_form4.py
import io
import os
import time
import zipfile
import requests
import pandas as pd
from tqdm import tqdm
# ── Paths ──────────────────────────────────────────────────────────────────────
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
# ── 1. Load existing data ──────────────────────────────────────────────────────
print("Loading form4_transactions.csv...")
df = pd.read_csv(OUT_PATH, low_memory=False)
print(f" {len(df):,} rows, {len(df.columns)} columns")
# ── 2. Drop footnote 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")
# ── 3. Fix date format: 30-MAR-2006 → 2006-03-30 ─────────────────────────────
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()}")
# ── 4. Discover correct REPORTINGOWNER column names from one sample quarter ────
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()}")
# Identify the correct column names
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}")
# ── 5. Re-download all quarters to get owner role columns ─────────────────────
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
# Get accession numbers already in our dataset
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
# Only keep rows for our accessions
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 to standard names
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)
# Deduplicate: one row per accession + rptownercik
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()}")
# Merge onto main df
df = df.merge(
owner_df,
left_on=['accession_number', 'rptownercik'],
right_on=[acc_col_own, 'rptownercik'],
how='left'
)
# Drop duplicate accession col if created
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")
# ── 6. Final column rename + reorder ──────────────────────────────────────────
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)
# Preferred column order
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]
# ── 7. Save ────────────────────────────────────────────────────────────────────
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}")
|