#!/usr/bin/env python3 """Pull a fund's full 13F holdings history from SEC EDGAR into one JSON panel. Reads the structured XML that SEC's own filing pages are rendered from, so there is no HTML scraping and no spreadsheet cleanup: data.sec.gov/submissions/CIK##########.json -> every filing for the CIK www.sec.gov/Archives/edgar/data///index.json -> that filing's files .../infotable.xml -> the holdings table itself Usage: python3 industry-reports/13f/fetch_13f.py --slug third-point-llc python3 industry-reports/13f/fetch_13f.py --cik 0001040273 --name "Third Point LLC" Writes industry-reports/13f/data/.json. Four things this handles that a naive scraper gets wrong -- see README.md: 1. switched from $thousands to whole dollars at the 2022-12-31 period. 2. The infotable filename varies (infotable.xml / form13fInfoTable.xml / ...). 3. A 13F-HR/A either RESTATES a period or adds NEW HOLDINGS to it; treating the latter as a replacement silently deletes most of the book. 4. Pre-2013 filings are fixed-width text, not XML, and are skipped. """ import argparse import json import pathlib import sys import time import urllib.error import urllib.request import xml.etree.ElementTree as ET from datetime import datetime, timezone HERE = pathlib.Path(__file__).parent DATA = HERE / "data" FUNDS = HERE / "funds.json" # SEC requires a descriptive UA with contact info, and asks for <=10 req/sec. USER_AGENT = "Yiqiao Yin y-yin.io research eagle0504@gmail.com" THROTTLE = 0.15 # Filings before this period are fixed-width plain text with per-filer layouts. XML_ERA_START = "2013-06-30" # Synthetic key for the pooled remainder when a book is truncated. OTHER = "__other__" def get(url, tries=4): req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) for attempt in range(tries): try: with urllib.request.urlopen(req, timeout=45) as r: return r.read() except (urllib.error.URLError, urllib.error.HTTPError, TimeoutError) as e: if attempt == tries - 1: raise # EDGAR throttles with 403/429; back off rather than hammering. time.sleep(1.5 * (attempt + 1)) print(f" retry {attempt + 1} ({e}) {url}", file=sys.stderr) def child_text(el, tag): """Text of the first descendant whose local name is `tag` ('' if absent). Namespace prefixes differ across filings (ns1: vs default), so match on the local name rather than a qualified tag. """ for c in el.iter(): if c.tag.split("}")[-1] == tag: return (c.text or "").strip() return "" def num(s): try: return float(str(s).replace(",", "").strip() or 0) except ValueError: return 0.0 def list_13f_filings(cik10): """Every 13F-HR / 13F-HR/A for a CIK, newest first.""" sub = json.loads(get(f"https://data.sec.gov/submissions/CIK{cik10}.json")) name = sub.get("name", "") rows = [] blocks = [sub["filings"]["recent"]] # Filers with long histories page older filings into separate files. for extra in sub["filings"].get("files", []): time.sleep(THROTTLE) blocks.append(json.loads(get(f"https://data.sec.gov/submissions/{extra['name']}"))) # Dedupe by accession. The paged blocks are disjoint today, but nothing # guarantees it, and a repeat would be applied twice below -- doubling the # rows of any NEW HOLDINGS amendment rather than failing loudly. seen = set() for r in blocks: for i, form in enumerate(r["form"]): if not form.startswith("13F-HR"): continue acc = r["accessionNumber"][i] if acc in seen: continue seen.add(acc) rows.append({ "form": form, "filed": r["filingDate"][i], "period": r["reportDate"][i] or r["filingDate"][i], "accession": acc, }) rows.sort(key=lambda x: (x["period"], x["filed"]), reverse=True) return name, rows def fetch_infotable(cik_int, accession): """Holdings rows for one filing, or None if it predates the XML era.""" accn = accession.replace("-", "") base = f"https://www.sec.gov/Archives/edgar/data/{cik_int}/{accn}" idx = json.loads(get(f"{base}/index.json")) time.sleep(THROTTLE) xmls = [i["name"] for i in idx["directory"]["item"] if i["name"].lower().endswith(".xml")] # primary_doc.xml is the cover page; the other XML is the holdings table. info = [n for n in xmls if "primary" not in n.lower()] if not info: return None root = ET.fromstring(get(f"{base}/{info[0]}")) time.sleep(THROTTLE) rows = [] for t in root: if t.tag.split("}")[-1] != "infoTable": continue rows.append({ "name": child_text(t, "nameOfIssuer"), "cls": child_text(t, "titleOfClass"), "cusip": child_text(t, "cusip").upper(), "value": num(child_text(t, "value")), "shares": num(child_text(t, "sshPrnamt")), "sh_type": child_text(t, "sshPrnamtType") or "SH", "put_call": child_text(t, "putCall"), }) return rows def _primary_doc(cik_int, accession): accn = accession.replace("-", "") base = f"https://www.sec.gov/Archives/edgar/data/{cik_int}/{accn}" try: root = ET.fromstring(get(f"{base}/primary_doc.xml")) except Exception: return None time.sleep(THROTTLE) return root def fetch_amendment_type(cik_int, accession): """'RESTATEMENT' or 'NEW HOLDINGS' for a 13F-HR/A, from its cover page.""" root = _primary_doc(cik_int, accession) return child_text(root, "amendmentType") if root is not None else None def fetch_signatory(cik_int, accession): """Who signed a filing, from its cover page: ('Daniel S. Loeb', 'CEO'). Taken from the filing itself rather than hardcoded, so the name on the page is always the person who actually attested to the most recent report. """ root = _primary_doc(cik_int, accession) if root is None: return None, None block = next((e for e in root.iter() if e.tag.split("}")[-1] == "signatureBlock"), None) if block is None: return None, None return child_text(block, "name") or None, child_text(block, "title") or None def value_scale(rows): """1000 if this filing reports in $thousands, else 1. The SEC's 2022 amendments switched 13F from thousands to whole dollars starting with the 2022-12-31 period. Rather than trust the date alone, sanity-check the implied share price: a median under $1 across a whole equity book means the values are thousands. """ px = sorted(r["value"] / r["shares"] for r in rows if r["shares"] > 0 and r["value"] > 0 and r["sh_type"] == "SH") if not px: return 1.0 return 1000.0 if px[len(px) // 2] < 1.0 else 1.0 def full_stats(agg): """Concentration measured on the COMPLETE book, before any truncation. Kept separate from the stored holdings so that a fund whose positions are truncated for page weight still reports a true position count, top-5 weight and HHI rather than one computed from the surviving rows. """ vals = sorted((v[1] for v in agg.values()), reverse=True) total = sum(vals) or 1 ws = [v / total for v in vals] hhi = sum(w * w for w in ws) return { "n": len(vals), "total": round(sum(vals)), "top5": round(sum(ws[:5]), 6), "top10": round(sum(ws[:10]), 6), "hhi": round(hhi, 6), } def truncate(agg, top_n): """Keep the top_n positions by value; pool the rest into one __other__ row. Quant books run to five figures of positions (AQR filed 21,077 for 2026-06-30), which no browser should be asked to render and no human reads line by line. The pooled remainder keeps every total and weight correct. """ if not top_n or len(agg) <= top_n: return agg, len(agg), False ranked = sorted(agg.items(), key=lambda kv: -kv[1][1]) kept = dict(ranked[:top_n]) rest = ranked[top_n:] if rest: kept[OTHER] = [0, sum(v[1] for _, v in rest)] return kept, top_n, True def build(cik, name_override=None, slug=None, since=XML_ERA_START, top_n=0): cik10 = str(cik).strip().lstrip("cikCIK").zfill(10) cik_int = int(cik10) edgar_name, filings = list_13f_filings(cik10) name = name_override or edgar_name print(f"{name} (CIK {cik10}): {len(filings)} 13F filings, " f"{filings[-1]['period']} -> {filings[0]['period']}") quarters, holdings = [], {} securities = {} skipped_old = 0 # Group by reporting period: one period can have several filings, and how # they combine depends on the amendment type -- see apply_filings(). by_period = {} for f in filings: if f["period"] < since: skipped_old += 1 continue by_period.setdefault(f["period"], []).append(f) for period in sorted(by_period): # Oldest first, so each amendment is applied on top of what preceded it. group = sorted(by_period[period], key=lambda x: (x["filed"], x["accession"])) rows, used, scaled_any, notes = [], [], False, [] applied = set() for f in group: if f["accession"] in applied: continue applied.add(f["accession"]) got = fetch_infotable(cik_int, f["accession"]) if got is None: continue scale = value_scale(got) scaled_any = scaled_any or scale != 1.0 for r in got: r["value"] *= scale mode = "replace" if f["form"].endswith("/A"): # A 13F-HR/A is either a RESTATEMENT (supersedes the original) or # NEW HOLDINGS (adds rows withheld earlier, e.g. under confidential # treatment). Treating the latter as a replacement silently deletes # the real book: Berkshire's 2025-03-31 amendment carries 4 rows # against an original of 110. atype = (fetch_amendment_type(cik_int, f["accession"]) or "").upper() mode = "merge" if "NEW HOLDINGS" in atype else "replace" notes.append(f"{f['form']}:{atype or 'UNKNOWN'}") if mode == "merge": rows.extend(got) else: rows = list(got) used.append(f) if not rows: print(f" {period} no XML infotable, skipped") continue agg = {} for r in rows: key = f"{r['cusip']}|{r['put_call']}" if key not in securities: securities[key] = { "name": r["name"], "cls": r["cls"], "cusip": r["cusip"], "put": r["put_call"], "type": r["sh_type"], } # One issuer can appear on several rows (split across managers or # discretion types); the position is their sum. slot = agg.setdefault(key, [0.0, 0.0]) slot[0] += r["shares"] slot[1] += r["value"] st = full_stats(agg) kept_agg, kept, was_cut = truncate(agg, top_n) holdings[period] = {k: [round(v[0]), round(v[1])] for k, v in kept_agg.items()} if was_cut and OTHER not in securities: securities[OTHER] = {"name": "Other positions", "cls": "pooled remainder", "cusip": "", "put": "", "type": "SH"} last = used[-1] quarters.append({ "period": period, "filed": last["filed"], "form": last["form"], "accession": last["accession"], "scaled": scaled_any, "filings": len(used), "kept": kept, "truncated": was_cut, **st, }) print(f" {period} {st['n']:5d} positions ${st['total'] / 1e9:7.2f}B" f"{' (x1000)' if scaled_any else ''}" f"{f' kept top {kept}' if was_cut else ''}" f"{' [' + ', '.join(notes) + ']' if notes else ''}") quarters.sort(key=lambda q: q["period"]) # Signatory of the most recent filing, straight from its cover page. sig_name = sig_title = None if quarters: sig_name, sig_title = fetch_signatory(cik_int, quarters[-1]["accession"]) print(f" signed by: {sig_name} — {sig_title}") if skipped_old: print(f" ({skipped_old} pre-{since} filings skipped: fixed-width text, not XML)") return { "slug": slug, "name": name, "cik": cik10, "edgar_url": (f"https://www.sec.gov/cgi-bin/browse-edgar?action=getcompany" f"&CIK={cik10}&type=13F&dateb=&owner=exclude&count=40"), "fetched_utc": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%SZ"), "signatory": sig_name, "signatory_title": sig_title, "top_n": top_n or 0, "quarters": quarters, "securities": securities, "holdings": holdings, } def main(): ap = argparse.ArgumentParser() ap.add_argument("--slug", help="fund slug from funds.json") ap.add_argument("--cik", help="CIK (overrides funds.json lookup)") ap.add_argument("--name", help="display name") ap.add_argument("--since", default=XML_ERA_START, help=f"earliest period (default {XML_ERA_START})") ap.add_argument("--out", metavar="DIR", help="write the panel to DIR instead of data/ (used for the complete, " "untruncated panels that feed the research dataset, so they do not " "overwrite the truncated ones the site renders)") ap.add_argument("--top-n", type=int, default=0, help="keep only the N largest positions per quarter, pooling the rest " "into one 'Other' row (0 = keep everything). Needed for quant books.") a = ap.parse_args() cik, name, slug = a.cik, a.name, a.slug if a.slug and FUNDS.exists(): funds = json.loads(FUNDS.read_text()) entry = next((f for f in funds if f["slug"] == a.slug), None) if entry: cik = cik or entry["cik"] name = name or entry["name"] # funds.json carries the per-fund truncation; an explicit flag wins, # and --out (the research panels) opts out of truncation entirely. if not a.top_n and not a.out: a.top_n = entry.get("top_n", 0) if not cik: raise SystemExit("need --cik, or a --slug present in funds.json") slug = slug or name.lower().replace(" ", "-") panel = build(cik, name, slug, a.since, a.top_n) outdir = pathlib.Path(a.out) if a.out else DATA outdir.mkdir(parents=True, exist_ok=True) out = outdir / f"{slug}.json" out.write_text(json.dumps(panel, separators=(",", ":")), encoding="utf-8") print(f"wrote {out} ({out.stat().st_size:,} bytes, {len(panel['quarters'])} quarters)") if __name__ == "__main__": main()