Point-in-Time Fundamentals from SEC EDGAR XBRL: Building a Leak-Free Equity Panel in Python

SEC EDGAR’s JSON APIs expose XBRL fundamentals with two dates per fact: the period it measures and the date it was filed. Backtests that join on period end silently trade on filings that did not exist yet. This post builds the panel the other way — availability keyed on filed, materialized as an as-of panel joined to a trading calendar with pd.merge_asof.
What this post is based on:
- SEC’s EDGAR API documentation for endpoint semantics, update latency, and the bulk archives.
- SEC’s fair-access rules for rate limits, User-Agent requirements, and crawling policy.
- A live probe of the
companyconceptendpoint (https://data.sec.gov/api/xbrl/companyconcept/CIK0000320193/us-gaap/Revenues.json, HTTP 200) on 2026-11-16, whose exact field values are quoted below. - Peer-reviewed survivorship research — Carhart, Carpenter, Lynch & Musto (2002) and Elton, Gruber & Blake (2001) — plus vendor guidance on testing for it.
- We did not run a full backtest for this article. Every number is either quoted from a source or produced by the code below, which you can run yourself.
Why end-keyed joins leak: the Apple FY2016 artifact
Joining fundamentals to prices on period end uses data that did not exist when the period ended. Apple’s fiscal-2016 annual revenue — the period ending 2016-09-24 — entered the XBRL API in a filing dated 2018-11-05. An end-keyed backtest would therefore trade on a 2018 filing in 2016, and never notice.
The probe of the companyconcept endpoint for Apple (CIK0000320193, us-gaap/Revenues) returned this fact object verbatim:
{"start": "2015-09-27", "end": "2016-09-24", "val": 215639000000,
"accn": "0000320193-18-000145", "form": "10-K", "filed": "2018-11-05"}
Read that again: end 2016-09-24, filed 2018-11-05. The full response holds eleven facts, and every one of them carries the same accession number and the same filed date — including periods that ended in September 2016. If your join keys on end, the FY2016 row arrives stamped with a filing that post-dates the period by two years, and a backtest dated 2016 will treat that value as available. The period tells you what the number describes; it never tells you when you could have used it.
The fact object and the three clocks
Every fact in the XBRL APIs carries nine fields: start, end, val, accn, fy, fp, form, filed, frame. The rule that matters: fy, fp, form and accn describe the filing, while start and end define the fact’s own period. A leak-free panel enforces the ordering research clock ≥ disclosure clock ≥ economic period end.
The proof that filing metadata and fact period are independent comes from the same probe: Apple’s FY2018 10-K (under fy 2018 / fp FY) also carries quarterly comparatives tagged with frames CY2016Q4, CY2017Q1, CY2017Q2 and later. One filing, many periods. So fy/fp/form/accn tell you which filing a fact came from; start/end tell you what it measures; only filed tells you when you could have known it.
That yields three clocks and one eligibility rule:
- Economic clock — the period the fact measures (
start→end). - Disclosure clock — the
fileddate, plus an embargo you choose and state in advance. - Research clock — the date your model acts (rebalance date).
Eligibility rule: research clock ≥ disclosure clock ≥ economic period end. A row enters the panel at date t only if filed + embargo ≤ t. Any backtest that relaxes this chain has leakage by construction, regardless of how good the results look.
A compliant session
SEC’s fair-access rules cap EDGAR at 10 requests per second, require a User-Agent in a declared format like Sample Company Name AdminContact@<sample company domain>.com, and prohibit botnets or automated crawling. The JSON APIs need no authentication or API keys, but data.sec.gov does not support CORS, so fetching must happen server-side, not in a browser.
import time
import requests
class EdgarSession:
"""Rate-limited session per SEC fair-access rules (max 10 req/s)."""
def __init__(self, contact: str):
self.s = requests.Session()
self.s.headers.update({
# Documented format: 'Sample Company Name AdminContact@yourdomain.com'
"User-Agent": f"QuantBrainAI Research {contact}",
"Accept-Encoding": "gzip, deflate",
})
self._last = 0.0
self._min_interval = 0.11 # ~9 req/s, safely under the 10/s cap
def get(self, url: str, **kw) -> requests.Response:
wait = self._last + self._min_interval - time.monotonic()
if wait > 0:
time.sleep(wait)
self._last = time.monotonic()
r = self.s.get(url, timeout=30, **kw)
r.raise_for_status()
return r
sess = EdgarSession("admin@yourdomain.com")
Throttling is not optional courtesy — it is the documented condition of access, and the SEC explicitly disallows automated crawling of the site. A client-side limiter like this one is the minimum compliant design.
Resolving CIKs
The submissions endpoint keys on a 10-digit zero-padded CIK and returns current and former names, exchanges, tickers, and at least one year or 1,000 of the most recent filings, whichever is more. Older filings live in additional JSON files referenced from the same response, so full history exists but is paginated.
def cik10(cik: int) -> str:
"""submissions/companyconcept URLs need CIK + 10 zero-padded digits."""
return f"CIK{cik:010d}"
def filer_profile(sess: EdgarSession, cik: int) -> dict:
"""Current name, former names, exchanges, tickers, and recent filings.
Filings beyond the >=1-year-or-1,000 retention are in the additional
JSON files listed under j['filings']['files']."""
j = sess.get(f"https://data.sec.gov/submissions/{cik10(cik)}.json").json()
return {
"cik": cik10(cik),
"name": j["name"],
"former_names": j.get("formerNames", []),
"tickers": j.get("tickers", []),
"exchanges": j.get("exchanges", []),
"recent_accn": j["filings"]["recent"]["accessionNumber"],
"recent_form": j["filings"]["recent"]["form"],
"older_files": j["filings"].get("files", []),
}
def find_cik_by_ticker(sess: EdgarSession, candidate_ciks, ticker: str):
"""Sketch: there is no global ticker->CIK endpoint, so scan a candidate
CIK list (e.g. enumerated from the bulk archives below) and match."""
t = ticker.upper()
for cik in candidate_ciks:
p = filer_profile(sess, cik)
if t in p["tickers"]:
return p["cik"]
return None
Because the submissions response includes former names and historical tickers, it is also your tool for point-in-time identity resolution — the question “what was this company called, and did it exist, at date t?” that survivorship handling depends on.
Endpoint decision guide: companyconcept vs companyfacts vs frames
Use companyconcept for one CIK and one concept, companyfacts for all concepts of one CIK in a single call, and frames for a cross-section at one calendrical period. Frames returns the last filed fact that most closely fits the period requested — which is exactly why frames is not point-in-time.
companyconcept—https://data.sec.gov/api/xbrl/companyconcept/CIK##########/us-gaap/AccountsPayableCurrent.json. All disclosures for one CIK and one concept, with a separate array per unit of measure. This is the workhorse for building a panel, because each fact carries its ownfileddate and accession — but the Apple case above is the warning: do not assume the array contains every historical filing for that tag.companyfacts—https://data.sec.gov/api/xbrl/companyfacts/CIK##########.json. All concepts for a company in one call. Convenient for wide panels, heavy in payload; same per-fact schema.frames—https://data.sec.gov/api/xbrl/frames/us-gaap/AccountsPayableCurrent/USD/CY2019Q1I.json. Period formats areCY####for annual data (duration 365 days ± 30 days),CY####Q#for quarterly data (duration 91 days ± 30 days), andCY####Q#Ifor instantaneous data. The “last filed that most closely fits” semantics means a frames snapshot taken today reflects today’s restatements — a snapshot taken in 2016 would differ. Frames is fine for exploratory cross-sections; it is wrong for backtest inputs.
Two scope limits apply to all three endpoints: the XBRL APIs include only facts that use a non-custom taxonomy (us-gaap, ifrs-full, dei, srt) and apply to the entire filing entity. Segment-level and product-level facts, and companies’ custom extension tags, are absent — so any panel built this way is incomplete by construction, and you should plan your concept coverage around that.
Normalizing companyconcept into a long panel
A companyconcept response stores facts in arrays keyed by unit of measure. Normalizing it into a long DataFrame — one row per fact, with filed as a proper timestamp — gives you the raw material for as-of joins. The function below also keeps accn so every value carries provenance for restatement audits.
import pandas as pd
def fetch_concept(sess: EdgarSession, cik: int,
taxonomy: str = "us-gaap", concept: str = "Revenues") -> pd.DataFrame:
"""Fetch one CIK + one concept and normalize to a long panel."""
url = f"https://data.sec.gov/api/xbrl/companyconcept/{cik10(cik)}/{taxonomy}/{concept}.json"
j = sess.get(url).json()
rows = []
for unit, facts in j["units"].items(): # one array per unit of measure
for f in facts:
rows.append({
"cik": cik10(cik),
"concept": concept,
"unit": unit,
"start": f.get("start"), # fact's own period
"end": f["end"],
"val": f["val"],
"accn": f["accn"],
"fy": f["fy"], "fp": f["fp"],
"form": f["form"],
"filed": f["filed"], # when it became public
"frame": f.get("frame"),
})
df = pd.DataFrame(rows)
for col in ("filed", "start", "end"):
df[col] = pd.to_datetime(df[col])
return df
Keep accn in the panel permanently. When a value changes for an old period, the accession number tells you which filing changed it — the audit trail for restatement handling, and the join key back to the original filing documents if you need to inspect context.
The as-of panel: sort, dedupe, merge_asof
The build order is: filter facts to those filed by the cutoff minus your embargo, sort by filed, deduplicate to the last-filed value per (cik, start, end), then merge_asof onto the decision calendar. The embargo is your choice — state it, keep it constant, and never tune it after seeing results.
def as_of_panel(facts: pd.DataFrame, cutoff: pd.Timestamp,
embargo_days: int = 0) -> pd.DataFrame:
"""Last-filed value per (cik, start, end) public by cutoff - embargo.
embargo_days: your stated research lag on top of the filed date."""
pub = facts[facts["filed"] <= cutoff - pd.Timedelta(days=embargo_days)]
pub = pub.sort_values("filed")
# Last filed wins: restatements supersede originals as of their filed date.
return pub.drop_duplicates(["cik", "start", "end"], keep="last")
def join_to_calendar(panel: pd.DataFrame, calendar: pd.DataFrame,
embargo_days: int = 0) -> pd.DataFrame:
"""calendar needs columns ['asof', 'cik'] (decision dates per name).
Both frames must be sorted on 'asof' for merge_asof. Backward join
attaches the most recent fact whose filed date + embargo <= asof."""
ev = panel.copy()
ev["asof"] = ev["filed"] + pd.Timedelta(days=embargo_days)
ev = ev.sort_values("asof")
cal = calendar.sort_values("asof")
return pd.merge_asof(cal, ev, on="asof", by="cik", direction="backward")
Two design notes. First, deduplicating on (cik, start, end) with keep="last" after sorting by filed is what makes restatements behave correctly: the panel shows whatever was knowable at the cutoff, not the original or the final value, but the value as of that date. Second, the embargo belongs in the eligibility condition, not bolted on afterward — a 90-day embargo means a fact filed 2026-03-01 first becomes eligible on 2026-05-30, and the asof shift in join_to_calendar enforces that inside the merge itself.
Because the XBRL APIs are updated in real time as submissions are disseminated (submissions in under a second, XBRL APIs typically under a minute), there are no versioned historical snapshots of the API itself. You cannot query “what did companyconcept return in 2019.” The panel must be rebuilt from filed/accn — which is why those fields are the load-bearing columns of this design. For backfill, use the bulk archives companyfacts.zip (all XBRL frame and company-facts data) and submissions.zip (all filers’ filing history), recompiled nightly at approximately 3:00 a.m. ET.
Point-in-time universes and survivorship evidence
Point-in-time universes require keeping delisted CIKs and sizing membership with data known at each date. The best published evidence on the cost of getting this wrong comes from fund databases: annual survivorship bias rising from 0.07% for 1-year samples to 1% for samples longer than 15 years, and an omission bias of 35.9 basis points. These are fund-database results — they motivate, not measure, the equity case.
Be precise about what transfers. Carhart, Carpenter, Lynch & Musto studied 2,071 diversified equity funds (1,346 still operating at end-1995), found nonsurviving funds underperform survivors by about 4% per year, and measured average annual attrition of 3.6% from 1962 to 1995; they also found survivor conditioning weakens evidence of performance persistence. Elton, Gruber & Blake found the CRSP mutual fund database free of traditional survivorship bias but subject to omission bias, estimated at 35.9 basis points — about 40% as large as traditional survivorship bias — and recommended restricting to funds over $15 million in total net assets at the start of each observation period. CRSP’s own product page describes the database as preserving data on retired funds to eliminate survivorship bias. None of these sources measures the bias in an equity-factor backtest built from EDGAR XBRL; the honest position is that the direction of the effect is well documented, its magnitude for your stock panel is not.
For EDGAR specifically, the universe hazard is structural: the submissions endpoint returns a filer’s history, but nothing flags “this CIK stopped filing” at the moment of delisting. A universe assembled from currently filing companies is survivorship-filtered by construction. The fix is to build membership from filing activity as of each date — a CIK is in the universe at date t if its filing history (including archived submissions from the bulk files) shows it was a reporting company at t — and to never prune on current status.
def survivorship_screen(backtest_fn, universe, rebalance_dates):
"""Sketch of the two-run test from vendor guidance: run once on the full
point-in-time universe, once restricted to the 100 largest names by size
at each point in time. Illustrative structure — no measured numbers."""
full = backtest_fn(universe, rebalance_dates)
top100 = (universe.sort_values(["rebalance_date", "market_cap"],
ascending=[True, False])
.groupby("rebalance_date", group_keys=False)
.head(100))
restricted = backtest_fn(top100, rebalance_dates)
return {"full_sharpe": sharpe(full["returns"]),
"top100_sharpe": sharpe(restricted["returns"])}
The replay test and operational limits
Two assertions make leakage detectable: no panel row may carry a filed date after the cutoff, and replaying panel construction at a historical date must reproduce what a live run would have seen. Pair those with the two-run universe test and a Sharpe heuristic from vendor guidance: roughly 1.0 counts as solid and anything above 2.0 starts to look too good.
def assert_no_leak(panel: pd.DataFrame, cutoff: pd.Timestamp, embargo_days: int = 0):
"""Hard gate: no row may carry a filed date after cutoff - embargo."""
limit = cutoff - pd.Timedelta(days=embargo_days)
leaked = panel[panel["filed"] > limit]
assert leaked.empty, f"{len(leaked)} rows filed after {limit.date()}"
def replay(facts: pd.DataFrame, decision_dates, embargo_days: int = 0) -> dict:
"""Rebuild the panel at each historical decision date. A leak-free build
is idempotent: replaying an old date reproduces exactly what a live run
at that date would have seen, because eligibility depends only on filed."""
snapshots = {}
for d in decision_dates:
cutoff = pd.Timestamp(d)
p = as_of_panel(facts, cutoff, embargo_days)
assert_no_leak(p, cutoff, embargo_days)
snapshots[d] = p
return snapshots
The two-run test from vendor guidance — full universe versus the 100 largest companies by size at each point in time — is a diagnostic, not a verdict: a large Sharpe gap between the runs signals that your results depend on today’s survivors. The vendor’s worked Sharpe numbers are presented there purely as an illustration, and we present them the same way. If your full-universe Sharpe lands above 2.0 while the restricted run collapses, suspect the universe; if both are high, suspect the embargo.
Four operational facts bound the whole design:
- No auth, no CORS. The JSON APIs require no authentication or API keys, but data.sec.gov does not support CORS — fetch server-side.
- History starts in 2009. XBRL was first required by the SEC in 2009, so the panel cannot reach further back, and early-year tag coverage is thinner.
- Bulk alternative. The Financial Statement Data Sets extract numeric face-financials from XBRL, updated quarterly (filings after the last business day of a quarter appear in the subsequent posting); a December 2024 reprocessing added a
segmentsfield to the NUM file, and the SEC disclaims that the sets are derived from registrant information and are not a substitute for the filings themselves. - Scope gaps are permanent. Segment-level facts and custom extension tags are absent from the XBRL APIs by design; if your factors need them, this panel is an input, not the whole dataset.
Key Takeaways
- Every XBRL fact carries both its measurement period (
start,end) and its publication date (filed,accn). In the Apple probe all eleven facts forus-gaap/Revenues— the FY2016 period included — carry one accession filed 2018-11-05, so an end-keyed join stamps 2018 availability onto a 2016 period. - The eligibility rule is research clock ≥ disclosure clock (
filed+ a stated embargo) ≥ economic period end. Pick the embargo before looking at results and never move it afterward. fy/fp/form/accndescribe the filing;start/enddescribe the fact. The FY2018 10-K carrying CY2016Q4 comparatives proves the two are independent — andframes’ “last filed that most closely fits” semantics is why frames snapshots are not point-in-time.- Build the panel as: filter by
filed≤ cutoff − embargo, sort byfiled, dedupe last-filed per(cik, start, end), thenpd.merge_asofonto the decision calendar. Keepaccnas provenance for restatement audits, since the APIs have no versioned snapshots — rebuild fromfiled/accnand backfill via the nightly bulk ZIPs. - Fund-database studies document survivorship and omission bias (0.07%→1% annually; 35.9 bps), but none measures it for equity factors built from EDGAR XBRL — treat those numbers as motivation, and run the two-universe replay test yourself.
- Respect fair access (10 req/s, declared User-Agent, no crawling), fetch server-side (no CORS), and remember the panel starts in 2009 and excludes segment-level and custom-tag facts.
FAQ
Can I just use the frames API with historical snapshots to get point-in-time data?
No. Frames returns, per the SEC’s documentation, the fact for each entity that is “last filed that most closely fits the calendrical period requested” — evaluated when you call it. There is no historical snapshot of frames, so a call made today embeds today’s restatements. Build point-in-time panels from companyconcept or companyfacts, keyed on filed.
How should I handle restated values for old periods?
Keep every disclosure, sort by filed, and take the last-filed value per (cik, start, end) as of your cutoff — that reproduces what was knowable at the time, whether it was the original or a restatement. Retain accn so you can audit which filing changed a value. Never dedupe on period alone across the full history, or you will silently backfill final values into earlier dates.
Does the 10 requests/second limit make full-universe backfills impractical?
At 10 requests per second you can pull roughly 600 endpoints per minute; with companyfacts returning all concepts per CIK in one call, a few thousand CIKs is a manageable overnight job. For bulk loads, prefer the nightly archives — companyfacts.zip and submissions.zip, recompiled around 3:00 a.m. ET — and reserve the per-CIK APIs for incremental updates.


