File size: 14,417 Bytes
9f9035f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# test_form4_pipeline.py
# Quick smoke-test for the Form 4 collection pipeline.
# Runs the full pipeline (metadata fetch → XML download → parse) on
# 5 well-known S&P 500 companies for 2024 only (~2-5 minutes).
#
# Checks:
#   1. EDGAR submissions API is reachable and returns Form 4 metadata
#   2. XML download and parsing produces valid transaction rows
#   3. All expected columns are present
#   4. Values are sensible (dates, numeric fields, A/D codes)
#
# Run: python scripts/test_form4_pipeline.py

import time
import threading
import requests
import pandas as pd
from xml.etree import ElementTree as ET

# ── Test config ────────────────────────────────────────────────────────────────
TEST_CIKS = {
    320193:  'AAPL',    # Apple
    789019:  'MSFT',    # Microsoft
    1045810: 'NVDA',    # NVIDIA
    1018724: 'AMZN',    # Amazon
    1652044: 'GOOGL',   # Alphabet
}
DATE_START = '2024-01-01'
DATE_END   = '2024-12-31'
MAX_XML_PER_CIK = 3      # only parse first 3 XMLs per company — keeps test fast

HEADERS = {'User-Agent': 'S2880814 University of Edinburgh s.g.vishnu@sms.ed.ac.uk'}
TIMEOUT = 15

EXPECTED_INDEX_COLS = {'cik', 'ticker', 'filing_date', 'accession', 'primary_doc'}
EXPECTED_TXN_COLS   = {
    'cik', 'ticker', 'filing_date', 'accession',
    'owner_name', 'is_director', 'is_officer', 'is_ten_pct_owner', 'officer_title',
    'security_title', 'transaction_date', 'transaction_code',
    'acquired_disposed', 'shares', 'price_per_share', 'shares_after_txn',
}

PASS = '  [PASS]'
FAIL = '  [FAIL]'
INFO = '  [INFO]'


# ── Rate limiter (same as main script) ────────────────────────────────────────
class RateLimiter:
    def __init__(self, rate):
        self._lock    = threading.Lock()
        self._min_gap = 1.0 / rate
        self._last    = 0.0
    def wait(self):
        with self._lock:
            gap = self._min_gap - (time.monotonic() - self._last)
            if gap > 0:
                time.sleep(gap)
            self._last = time.monotonic()

limiter = RateLimiter(8.0)


def safe_get(url, retries=3):
    for attempt in range(retries):
        limiter.wait()
        try:
            r = requests.get(url, headers=HEADERS, timeout=TIMEOUT)
            if r.status_code == 200:
                return r
            elif r.status_code == 429:
                print(f"    [429] Rate limited, sleeping 10s...")
                time.sleep(10)
        except requests.RequestException as e:
            print(f"    [WARN] Request error (attempt {attempt+1}): {e}")
            time.sleep(2)
    return None


# ── Test 1: EDGAR API reachability ─────────────────────────────────────────────
print("=" * 60)
print("TEST 1 — EDGAR API reachability")
print("=" * 60)

r = safe_get("https://data.sec.gov/submissions/CIK0000320193.json")  # Apple
if r:
    data = r.json()
    company_name = data.get('name', 'unknown')
    print(f"{PASS} EDGAR submissions API reachable")
    print(f"{INFO} Response: {company_name} (CIK 320193 = Apple)")
else:
    print(f"{FAIL} Could not reach EDGAR API — check internet connection")
    exit(1)


# ── Test 2: Form 4 metadata fetch ──────────────────────────────────────────────
print()
print("=" * 60)
print("TEST 2 — Form 4 metadata fetch (5 companies, 2024 only)")
print("=" * 60)

def get_form4_meta(cik):
    r = safe_get(f"https://data.sec.gov/submissions/CIK{cik:010d}.json")
    if not r:
        return []
    data   = r.json()
    recent = data.get('filings', {}).get('recent', {})

    forms = recent.get('form', [])
    accs  = recent.get('accessionNumber', [])
    dates = recent.get('filingDate', [])
    docs  = recent.get('primaryDocument', [])

    result = []
    for form, acc, date, doc in zip(forms, accs, dates, docs):
        if form == '4' and DATE_START <= date <= DATE_END:
            result.append({'accession': acc, 'filing_date': date, 'primary_doc': doc})
    return result

index_rows = []
all_test_filings = []

for cik, ticker in TEST_CIKS.items():
    filings = get_form4_meta(cik)
    print(f"{INFO} {ticker:6s} (CIK {cik}): {len(filings):3d} Form 4 filings in 2024")
    if filings:
        print(f"{PASS} Metadata fetch OK — sample accession: {filings[0]['accession']}")
    else:
        print(f"{FAIL} No Form 4 filings found for {ticker} in 2024")

    for f in filings:
        index_rows.append({
            'cik': cik, 'ticker': ticker,
            'filing_date': f['filing_date'],
            'accession':   f['accession'],
            'primary_doc': f['primary_doc'],
        })
        all_test_filings.append((cik, ticker, f))

print(f"\n{INFO} Total filings collected across 5 companies: {len(index_rows)}")

# Column check on index
index_df = pd.DataFrame(index_rows)
missing_cols = EXPECTED_INDEX_COLS - set(index_df.columns)
if not missing_cols:
    print(f"{PASS} Index columns all present: {sorted(index_df.columns.tolist())}")
else:
    print(f"{FAIL} Missing index columns: {missing_cols}")


# ── Test 3: XML download and parsing ──────────────────────────────────────────
print()
print("=" * 60)
print(f"TEST 3 — XML download + parse (first {MAX_XML_PER_CIK} filings per company)")
print("=" * 60)

def find_xml_in_filing(cik, accession):
    """Fetch filing directory and return the XML data filename."""
    import re
    acc_clean = accession.replace('-', '')
    r = safe_get(f"https://www.sec.gov/Archives/edgar/data/{cik}/{acc_clean}/")
    if not r:
        return None
    matches = re.findall(r'href="([^"]+\.xml)"', r.text, re.IGNORECASE)
    for m in matches:
        fname = m.split('/')[-1]
        if fname and 'index' not in fname.lower():
            return fname
    return None


def parse_form4(cik, ticker, accession, primary_doc, filing_date):
    """
    Download Form 4 XML and extract non-derivative transactions.

    Resolution order (no extra API calls in the common case):
      1. If primaryDoc is .htm, try swapping extension to .xml first
      2. If that fails, fall back to directory listing (1 extra call)
      3. If all else fails, return error
    """
    acc_clean = accession.replace('-', '')

    candidates = [primary_doc]
    if primary_doc.lower().endswith(('.htm', '.html')):
        xml_variant = primary_doc.rsplit('.', 1)[0] + '.xml'
        candidates = [xml_variant, primary_doc]
        print(f"      [INFO] HTML primaryDoc — trying XML variant first: {xml_variant}")

    root = None
    tried = []
    for doc in candidates:
        url = f"https://www.sec.gov/Archives/edgar/data/{cik}/{acc_clean}/{doc}"
        r   = safe_get(url)
        tried.append(doc)
        if not r:
            print(f"      [WARN] HTTP failed for {doc}")
            continue
        try:
            root = ET.fromstring(r.content)
            print(f"      [INFO] Parsed successfully: {doc}")
            break
        except ET.ParseError as e:
            print(f"      [WARN] XML parse error on {doc}: {e}")
            continue

    # Last resort: directory listing
    if root is None:
        print(f"      [INFO] Trying directory listing fallback...")
        xml_fname = find_xml_in_filing(cik, accession)
        if xml_fname and xml_fname not in tried:
            url = f"https://www.sec.gov/Archives/edgar/data/{cik}/{acc_clean}/{xml_fname}"
            r   = safe_get(url)
            if r:
                try:
                    root = ET.fromstring(r.content)
                    print(f"      [INFO] Directory fallback succeeded: {xml_fname}")
                except ET.ParseError as e:
                    return None, f"All fallbacks exhausted. Last error: {e}"
            else:
                return None, "HTTP failed on directory fallback"
        elif xml_fname in tried:
            return None, "Directory fallback returned same filename already tried"
        else:
            return None, "No XML found in filing directory"

    if root is None:
        return None, "Could not obtain valid XML root"

    owner_name = ''
    is_dir = is_off = is_10pct = '0'
    officer_title = ''
    for rpt in root.findall('.//reportingOwner'):
        owner_name    = rpt.findtext('.//rptOwnerName', '').strip()
        rel = rpt.find('.//reportingOwnerRelationship')
        if rel is not None:
            is_dir        = rel.findtext('isDirector',        '0').strip()
            is_off        = rel.findtext('isOfficer',         '0').strip()
            is_10pct      = rel.findtext('isTenPercentOwner', '0').strip()
            officer_title = rel.findtext('officerTitle',      '').strip()

    records = []
    for txn in root.findall('.//nonDerivativeTransaction'):
        records.append({
            'cik':               cik,
            'ticker':            ticker,
            'filing_date':       filing_date,
            'accession':         accession,
            'owner_name':        owner_name,
            'is_director':       is_dir,
            'is_officer':        is_off,
            'is_ten_pct_owner':  is_10pct,
            'officer_title':     officer_title,
            'security_title':    txn.findtext('.//securityTitle/value',  '').strip(),
            'transaction_date':  txn.findtext('.//transactionDate/value', '').strip(),
            'transaction_code':  txn.findtext('.//transactionCoding/transactionCode', '').strip(),
            'acquired_disposed': txn.findtext(
                './/transactionAmounts/transactionAcquiredDisposedCode/value', '').strip(),
            'shares':            txn.findtext(
                './/transactionAmounts/transactionShares/value', ''),
            'price_per_share':   txn.findtext(
                './/transactionAmounts/transactionPricePerShare/value', ''),
            'shares_after_txn':  txn.findtext(
                './/postTransactionAmounts/sharesOwnedFollowingTransaction/value', ''),
        })
    return records, None

txn_rows   = []
xml_ok     = 0
xml_fail   = 0
xml_empty  = 0

# Group by CIK and limit to MAX_XML_PER_CIK each
from collections import defaultdict
by_cik = defaultdict(list)
for cik, ticker, f in all_test_filings:
    by_cik[cik].append((ticker, f))

for cik, items in by_cik.items():
    ticker  = items[0][0]
    sample  = items[:MAX_XML_PER_CIK]
    print(f"\n  {ticker} — parsing {len(sample)} XML(s):")
    for _, f in sample:
        records, err = parse_form4(cik, ticker, f['accession'], f['primary_doc'], f['filing_date'])
        if err:
            print(f"    {FAIL} {f['accession']}: {err}")
            xml_fail += 1
        elif records is None:
            print(f"    {FAIL} {f['accession']}: no result returned")
            xml_fail += 1
        elif len(records) == 0:
            print(f"    {INFO} {f['accession']}: parsed OK but 0 non-derivative transactions (options only filing)")
            xml_empty += 1
            xml_ok += 1
        else:
            r0 = records[0]
            print(f"    {PASS} {f['accession']}: {len(records)} transaction(s)")
            print(f"         Insider : {r0['owner_name']} | Title: {r0['officer_title']}")
            print(f"         Date    : {r0['transaction_date']} | Code: {r0['transaction_code']} | A/D: {r0['acquired_disposed']}")
            print(f"         Shares  : {r0['shares']} @ ${r0['price_per_share']}")
            xml_ok += 1
            txn_rows.extend(records)


# ── Test 4: Output validation ──────────────────────────────────────────────────
print()
print("=" * 60)
print("TEST 4 — Output validation")
print("=" * 60)

if txn_rows:
    txn_df = pd.DataFrame(txn_rows)

    # Column check
    missing = EXPECTED_TXN_COLS - set(txn_df.columns)
    if not missing:
        print(f"{PASS} All expected transaction columns present")
    else:
        print(f"{FAIL} Missing columns: {missing}")

    # A/D code check
    valid_ad = txn_df['acquired_disposed'].isin(['A', 'D', ''])
    if valid_ad.all():
        print(f"{PASS} acquired_disposed values all valid (A/D/blank)")
    else:
        bad = txn_df[~valid_ad]['acquired_disposed'].unique()
        print(f"{FAIL} Unexpected acquired_disposed values: {bad}")

    # Transaction code check
    known_codes = {'P', 'S', 'A', 'D', 'F', 'M', 'G', 'C', 'E', 'H', 'I', 'J', 'L', 'O', 'U', 'W', 'X', 'Z', ''}
    bad_codes = set(txn_df['transaction_code'].unique()) - known_codes
    if not bad_codes:
        print(f"{PASS} Transaction codes all recognised: {sorted(txn_df['transaction_code'].unique())}")
    else:
        print(f"{FAIL} Unknown transaction codes: {bad_codes}")

    # Date format check
    try:
        pd.to_datetime(txn_df['transaction_date'])
        print(f"{PASS} transaction_date parses as dates OK")
    except Exception:
        print(f"{FAIL} transaction_date has unparseable values")

    # Sample rows
    print(f"\n{INFO} Sample transactions (first 5 rows):")
    print(txn_df[['ticker', 'owner_name', 'officer_title',
                  'transaction_date', 'transaction_code',
                  'acquired_disposed', 'shares', 'price_per_share']].head().to_string(index=False))
else:
    print(f"{INFO} No non-derivative transactions found in sampled filings (may be options-only batch)")


# ── Summary ────────────────────────────────────────────────────────────────────
print()
print("=" * 60)
print("SUMMARY")
print("=" * 60)
print(f"  XMLs parsed successfully : {xml_ok}")
print(f"  XMLs failed              : {xml_fail}")
print(f"  Filings with 0 non-deriv : {xml_empty}")
print(f"  Transaction rows parsed  : {len(txn_rows)}")
print()
if xml_fail == 0:
    print("  ALL TESTS PASSED — pipeline is working correctly.")
    print("  Safe to run the full collect_form4.py overnight.")
else:
    print(f"  {xml_fail} XML(s) failed — check errors above before full run.")
print("=" * 60)