File size: 5,349 Bytes
e3b40d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# form4_add_roles.py
# Adds is_officer, is_director, is_ten_pct_owner, officer_title columns
# to the existing form4_transactions.csv.
#
# The SEC's new REPORTINGOWNER format encodes roles as a comma-separated
# string in rptowner_relationship, e.g. "Director,Officer,TenPercentOwner"
# and officer title in rptowner_title.
#
# Re-downloads all 81 quarterly ZIPs (REPORTINGOWNER table only — small),
# merges onto form4_transactions.csv, derives boolean flags, saves.
#
# Run: python scripts/form4_add_roles.py

import io
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

# ── 1. Load existing clean file ────────────────────────────────────────────────
print("Loading form4_transactions.csv...")
df = pd.read_csv(OUT_PATH, low_memory=False)
print(f"  {len(df):,} rows, {len(df.columns)} columns")
our_accessions = set(df['accession_number'].dropna())

# ── 2. Re-download REPORTINGOWNER from all 81 quarters ────────────────────────
def quarter_urls():
    urls, year, qtr = [], 2006, 1
    while (year, qtr) <= (2026, 1):
        urls.append((year, qtr,
            f"https://www.sec.gov/files/structureddata/data/insider-transactions-data-sets/{year}q{qtr}_form345.zip"))
        qtr += 1
        if qtr > 4:
            qtr, year = 1, year + 1
    return urls

print(f"\nFetching REPORTINGOWNER from 81 quarters for {len(our_accessions):,} accessions...")
owner_frames = []

for year, qtr, url in tqdm(quarter_urls(), desc="Quarters"):
    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()

        own = own[own['accession_number'].isin(our_accessions)]
        if own.empty:
            continue

        keep = [c for c in ['accession_number', 'rptownercik',
                             'rptowner_relationship', 'rptowner_title'] if c in own.columns]
        owner_frames.append(own[keep].copy())

    except Exception as e:
        tqdm.write(f"  [WARN] {year} Q{qtr}: {e}")

# ── 3. Build roles lookup table ────────────────────────────────────────────────
print("\nBuilding roles lookup...")
owner_df = pd.concat(owner_frames, ignore_index=True)
owner_df = owner_df.drop_duplicates(subset=['accession_number', 'rptownercik'])

# Parse rptowner_relationship → boolean flags
rel = owner_df['rptowner_relationship'].fillna('')
owner_df['is_officer']       = rel.str.contains('Officer',          case=False).astype(int)
owner_df['is_director']      = rel.str.contains('Director',         case=False).astype(int)
owner_df['is_ten_pct_owner'] = rel.str.contains('TenPercentOwner',  case=False).astype(int)

if 'rptowner_title' in owner_df.columns:
    owner_df.rename(columns={'rptowner_title': 'officer_title'}, inplace=True)

owner_df.drop(columns=['rptowner_relationship'], inplace=True)
print(f"  Owner rows: {len(owner_df):,}")
print(f"  Officers  : {owner_df['is_officer'].sum():,}")
print(f"  Directors : {owner_df['is_director'].sum():,}")

# ── 4. Merge onto main dataframe ───────────────────────────────────────────────
print("\nMerging roles onto transactions...")

# Drop any stale role columns if re-running
for col in ['is_officer', 'is_director', 'is_ten_pct_owner', 'officer_title']:
    if col in df.columns:
        df.drop(columns=[col], inplace=True)

df = df.merge(owner_df, on=['accession_number', 'rptownercik'], how='left')

# Move role cols next to owner_name
cols = df.columns.tolist()
role_cols = [c for c in ['is_officer', 'is_director', 'is_ten_pct_owner', 'officer_title'] if c in cols]
for rc in reversed(role_cols):
    cols.remove(rc)
    insert_at = cols.index('rptownercik') + 1
    cols.insert(insert_at, rc)
df = df[cols]

# ── 5. Save ────────────────────────────────────────────────────────────────────
df.to_csv(OUT_PATH, index=False)

print(f"\n{'='*60}")
print(f"  Final shape  : {df.shape}")
print(f"  Columns      : {df.columns.tolist()}")
print(f"\nSample:")
preview = [c for c in ['ticker', 'owner_name', 'officer_title', 'is_officer',
                        'is_director', 'transaction_date', 'transaction_code',
                        'acquired_disposed', 'shares', 'price_per_share'] if c in df.columns]
print(df[preview].head(8).to_string(index=False))
print(f"\nSaved -> {OUT_PATH}")