Source code · Python

secfacts.py

83 lines · Part of SEC filings reader · All code · Read only; the files run as published

"""Read a company's reported figures from SEC EDGAR XBRL company facts. Each value returned carries the filing it came from (form, accession number,filing date) and the period it covers, so every number in a report can betraced to a 10-K or 10-Q. Annual values use SEC's calendar frames (CY2025 for afiscal year, CY2025Q4I for the year-end balance), which handle 52/53-weekfiscal years. Year-to-date values are selected by their exact start and end. SEC asks automated clients to identify themselves; set SEC_USER_AGENT.""" import jsonimport osimport urllib.request UA = os.environ.get("SEC_USER_AGENT", "ChipStreetCapital-Research/1.0 (student equity research)")  def load(cik: str, cache_path: str) -> dict:    if not os.path.exists(cache_path):        req = urllib.request.Request(f"https://data.sec.gov/api/xbrl/companyfacts/CIK{cik}.json", headers={"User-Agent": UA})        with urllib.request.urlopen(req, timeout=60) as r, open(cache_path, "wb") as f:            f.write(r.read())    with open(cache_path) as f:        return json.load(f)  def _facts(gaap: dict, concepts):    for c in [concepts] if isinstance(concepts, str) else concepts:        if c in gaap:            for unit in gaap[c]["units"].values():                for f in unit:                    yield c, f  def _src(c, f):    period = f"{f['start']} to {f['end']}" if "start" in f else f"as of {f['end']}"    return {"concept": c, "form": f["form"], "accn": f["accn"], "filed": f["filed"], "period": period}  def frame(gaap: dict, concepts, fr: str):    """Value for an SEC frame (e.g. CY2025, CY2025Q4I, CY2026Q3). With a list of    concepts the first concept that has the frame wins (covers tag changes)."""    for c in [concepts] if isinstance(concepts, str) else concepts:        hits = [f for cc, f in _facts(gaap, c) if f.get("frame") == fr]        if hits:            f = sorted(hits, key=lambda x: x["filed"])[-1]            return {"value": f["val"], "source": _src(c, f)}    return None  def period(gaap: dict, concepts, start: str | None, end: str, forms=("10-Q", "10-K")):    """Value for an exact period (start None = balance at end)."""    for c in [concepts] if isinstance(concepts, str) else concepts:        hits = [f for cc, f in _facts(gaap, c) if f["end"] == end and f["form"] in forms                and ((start is None and "start" not in f) or f.get("start") == start)]        if hits:            f = sorted(hits, key=lambda x: x["filed"])[-1]            return {"value": f["val"], "source": _src(c, f)}    return None  def annual_table(gaap: dict, concept_map: dict, instant_map: dict, years) -> dict:    """{key: {year: {value, source}}} for durations (CY frames) and instants (CYQ4I)."""    out = {}    for key, concepts in concept_map.items():        out[key] = {}        for y in years:            v = frame(gaap, concepts, f"CY{y}")            if v:                out[key][str(y)] = v    for key, concepts in instant_map.items():        out[key] = {}        for y in years:            v = frame(gaap, concepts, f"CY{y}Q4I")            if v:                out[key][str(y)] = v    return out  def values(table: dict, key: str, scale: float = 1e6) -> dict:    """Plain {year: value} in $ millions (or per-share when scale=1)."""    return {y: v["value"] / scale for y, v in table.get(key, {}).items()}