Repository Public Research preview
1"""r3k_12_sec_shares_v2.py — Stage D (FIRC-0002, package L3-ii, cluster A: DATA-04, ECON-01, EDIT-10).2Point-in-time shares outstanding from SEC XBRL company facts, re-pulled with the raw per-class rows kept3(the author's r3k_01c kept only max() per filing and overwrote marketcap.parquet):4 1. dei:EntityCommonStockSharesOutstanding (cover-page count, by class) for every CIK of the panel;5 2. fallback for CIKs without any dei fact: us-gaap:CommonStockSharesOutstanding, then6 us-gaap:WeightedAverageNumberOfSharesOutstandingBasic;7 3. aggregation per (cik, filed): classes = distinct values reported for the latest `end` date of that filing ->8 shares_sum (sum of classes, canonical), shares_max (author's rule, for comparison), n_classes; unit = 'shares' only.9Writes data/processed_r3k_v2/sec_shares_raw.parquet (every row, with concept) and shares_history_v2.parquet10(ticker, cik, date = filing date, shares_sum, shares_max, n_classes, shares_source). Never touches data/processed_r3k/.11Rate: <= 8 requests/s (SEC fair-use limit is 10/s). Run: nice -n 10 .venv-review/bin/python -I scripts/r3k_12_sec_shares_v2.py12"""13import time, threading, datetime as dt, pandas as pd, numpy as np, httpx14from concurrent.futures import ThreadPoolExecutor, as_completed15OUT = "data/processed_r3k_v2"; R = "data/raw_russell3000"16comp = pd.read_parquet(f"{R}/companies")[["cik", "ticker"]]; panel = pd.read_parquet(f"{R}/annual_final")[["cik", "ticker"]].drop_duplicates()17m = pd.concat([comp, panel]).drop_duplicates(); m["cik"] = m["cik"].astype(str).str.zfill(10)18ciks = sorted(m.cik.unique()); print(len(ciks), "CIKs", dt.datetime.now().isoformat(), flush=True)19H = {"User-Agent": "UQO-Research simon-pierre.boucher@uqo.ca", "Accept": "application/json"}20cli = httpx.Client(timeout=30, headers=H, http2=False); lock = threading.Lock(); last = [0.0]21def rate():22 with lock:23 now = time.monotonic(); wait = max(0, last[0] + 0.125 - now)24 if wait: time.sleep(wait)25 last[0] = time.monotonic()26CONCEPTS = [("dei", "EntityCommonStockSharesOutstanding"), ("us-gaap", "CommonStockSharesOutstanding"), ("us-gaap", "WeightedAverageNumberOfSharesOutstandingBasic")]27def get(cik, tax, concept):28 for a in range(4):29 rate()30 try:31 r = cli.get(f"https://data.sec.gov/api/xbrl/companyconcept/CIK{cik}/{tax}/{concept}.json")32 if r.status_code == 404: return []33 if r.status_code in (403, 429): time.sleep(30); continue34 r.raise_for_status(); d = r.json(); units = d.get("units", {})35 rows = [(cik, tax + ":" + concept, x.get("filed"), x.get("end"), x.get("val"), x.get("form"), x.get("fy"), x.get("fp"), u) for u, lst in units.items() for x in lst]36 return rows37 except Exception:38 time.sleep(2)39 return None40def one(cik):41 out = []; src = None42 for tax, concept in CONCEPTS:43 rows = get(cik, tax, concept)44 if rows is None: return cik, None, None45 rows = [r for r in rows if r[8] == "shares" and r[4] is not None and r[4] > 0]46 if rows: out = rows; src = tax + ":" + concept; break47 return cik, out, src48import sys49REAGG = "--reaggregate" in sys.argv50rows, fail, done, srcs = [], 0, 0, {}51if REAGG: raw = pd.read_parquet(f"{OUT}/sec_shares_raw.parquet"); srcs = raw.drop_duplicates("cik").set_index("cik")["concept"].to_dict(); print("re-aggregating", len(raw), "stored rows (no network)", flush=True)52with ThreadPoolExecutor(4) as ex:53 if not REAGG:54 for f in as_completed([ex.submit(one, c) for c in ciks]):55 cik, rr, src = f.result(); done += 156 if rr is None: fail += 157 else: rows += rr; srcs[cik] = src58 if done % 250 == 0: print(f"{done}/{len(ciks)} fail={fail}", dt.datetime.now().strftime("%H:%M:%S"), flush=True)59if not REAGG:60 raw = pd.DataFrame(rows, columns=["cik", "concept", "filed", "end", "shares", "form", "fy", "fp", "unit"]); raw["filed"] = pd.to_datetime(raw["filed"]); raw["end"] = pd.to_datetime(raw["end"])61 raw.to_parquet(f"{OUT}/sec_shares_raw.parquet", index=False)62# aggregation: per filing, classes at the latest `end`63raw = raw.sort_values(["cik", "filed", "end"])64latest_end = raw.groupby(["cik", "filed"])["end"].transform("max"); le = raw[raw["end"] == latest_end]65# classes are summed ONLY for the instant cover-page concept (dei, one value per share class); the us-gaap fallbacks are duration66# facts (quarter and year-to-date values share the same `end`) -> max, never sum67le = le.copy(); le["is_dei"] = le["concept"].str.startswith("dei:")68agg = le.groupby(["cik", "filed"]).agg(shares_sum=("shares", lambda s: float(np.unique(s.values).sum())), shares_mx=("shares", "max"), n_classes=("shares", lambda s: int(len(np.unique(s.values)))), concept=("concept", "first"), is_dei=("is_dei", "first")).reset_index()69agg.loc[~agg.is_dei, "shares_sum"] = agg.loc[~agg.is_dei, "shares_mx"]; agg.loc[~agg.is_dei, "n_classes"] = 1; agg = agg.drop(columns=["shares_mx", "is_dei"])70mx = raw.groupby(["cik", "filed"])["shares"].max().rename("shares_max").reset_index()71agg = agg.merge(mx, on=["cik", "filed"]).merge(m, on="cik", how="inner").rename(columns={"filed": "date"})72agg["shares_source"] = agg["concept"]; agg = agg[["ticker", "cik", "date", "shares_sum", "shares_max", "n_classes", "shares_source"]].sort_values(["ticker", "date"])73agg.to_parquet(f"{OUT}/shares_history_v2.parquet", index=False)74multi = agg[agg.n_classes > 1].ticker.nunique()75msg = (f"DONE {dt.datetime.now().isoformat()} CIKs {len(ciks)} failures {fail} | raw rows {len(raw)} | filings {len(agg)} | tickers {agg.ticker.nunique()} | "76 f"source counts {pd.Series(srcs).value_counts().to_dict()} | tickers without any fact {len(set(m.ticker) - set(agg.ticker))} | tickers with >1 class on some filing {multi}")77print(msg, flush=True); open(f"{OUT}/sec_shares_v2.log", "a").write(msg + "\n")78