How to Convert SEC XBRL to JSON in Python
Convert SEC XBRL to JSON in Python with Arelle: pull a filing from EDGAR, export xBRL-JSON, then filter dimensions, instants and Q3 vs 9-month values.

Every US public company files its financial statements with the SEC in XBRL, a tagged XML format built for machines. This guide shows how to convert SEC XBRL to JSON in Python, start to finish: find a filing on EDGAR, export every fact to JSON with the open-source Arelle processor, then load that JSON and filter it into numbers you can actually use.
The running example is Apple's 10-Q for fiscal Q3 2025, the quarter ended June 28, 2025. Every output block below comes from running the code against that filing. You need Python 3.10 or later and about ten minutes. The last sections compare the approach with py-xbrl and the XBRL-JSON standard, and show where an API removes the work. For a tour of the filings themselves, from the 10-K and 10-Q to the 8-K, see the SEC Forms field guide.
What is inside an SEC XBRL filing
XBRL (eXtensible Business Reporting Language) is XML with a heavy domain layer on top. A filing ships an instance with the actual numbers, a taxonomy schema that defines the concepts, and linkbases that describe how concepts relate (presentation, calculation, definition, label). The SEC requires the us-gaap taxonomy plus an issuer-specific extension taxonomy where companies coin their own concepts. Since inline XBRL became mandatory, the instance is embedded in the HTML document you read on EDGAR, so the 10-Q page itself is the file you parse. For how tags, contexts and units fit together, and why one company's revenue can sit under several concepts over the years, see XBRL financial data explained.
Each fact carries a concept name, a value, a unit, a context (entity and period), an optional set of dimensions (axis → member pairs) and a decimals attribute. Here is a simplified fact and its context:
<us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax
contextRef="c-1" unitRef="usd" decimals="-6">391035000000</us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax>
<xbrli:context id="c-1">
<xbrli:entity><xbrli:identifier scheme="http://www.sec.gov/CIK">0000320193</xbrli:identifier></xbrli:entity>
<xbrli:period>
<xbrli:startDate>2023-10-01</xbrli:startDate>
<xbrli:endDate>2024-09-28</xbrli:endDate>
</xbrli:period>
</xbrli:context>That fact says Apple reported $391.035B of revenue for the fiscal year ended September 28, 2024, rounded to the nearest million. To use it you have to resolve the context, parse the dates, resolve the unit and decide whether this concept is the “revenue” you want. A processor does the first three for you, which is why the pipeline below starts with one.
Step 1: Install Arelle and the SEC transforms plugin
Arelle is a mature open-source XBRL processor; its SEC inline transforms plugin is maintained by the SEC itself. It resolves schemas and linkbases, caches taxonomies, applies inline XBRL transformations and can write the result as JSON. Install it from PyPI:
pip install arelle-release
arelleCmdLine --help
# The SEC transforms plugin is not in the pip package. Put the Arelle/EDGAR repo in Arelle's plugin folder:
PLUGIN_DIR=$(python -c "import arelle, os; print(os.path.join(os.path.dirname(arelle.__file__), 'plugin'))")
git clone https://github.com/Arelle/EDGAR.git "$PLUGIN_DIR/EDGAR"The second part matters for SEC filings. Inline XBRL values pass through transformation rules that turn “NASDAQ” or “Delaware” on the page into a canonical value, and the SEC publishes its own transformation registry. Arelle's EDGAR plugin docs state that a pip install does not include the EDGAR plugins and that they must be installed separately. Without the transforms plugin, our run on Apple's 10-Q logged ix11.10.1.2:invalidTransformation errors for facts such as dei:SecurityExchangeName. With it, the log is clean.
Step 2: Find a filing's XBRL on EDGAR with Python
EDGAR publishes a JSON list of every company's recent filings at data.sec.gov/submissions/CIK##########.json. It gives the accession number and the primary document of each filing, and for a 10-Q or 10-K filed in inline XBRL that primary document is the instance Arelle reads. The SEC's fair-access rules ask for a declared User-Agent with a contact address and a maximum of 10 requests per second, so the helper sets the header and sleeps between calls. Replace the placeholder with your own company name and email. For the other data.sec.gov endpoints and the limits that trip people up, see our guide to the SEC EDGAR API in Python.
import json
import time
import urllib.request
# SEC fair access: identify yourself and stay under 10 requests per second.
USER_AGENT = "YourCompany your-email@example.com"
def sec_get(url: str) -> bytes:
req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})
with urllib.request.urlopen(req, timeout=30) as resp:
body = resp.read()
time.sleep(0.2)
return body
def find_filing(cik: int, form: str, report_date: str) -> str:
"""URL of the primary (inline XBRL) document of one filing."""
data = json.loads(sec_get(f"https://data.sec.gov/submissions/CIK{cik:010d}.json"))
recent = data["filings"]["recent"]
for i, f in enumerate(recent["form"]):
if f == form and recent["reportDate"][i] == report_date:
accession = recent["accessionNumber"][i].replace("-", "")
doc = recent["primaryDocument"][i]
return f"https://www.sec.gov/Archives/edgar/data/{cik}/{accession}/{doc}"
raise LookupError(f"No {form} for CIK {cik} with report date {report_date}")
url = find_filing(320193, "10-Q", "2025-06-28") # Apple, fiscal Q3 2025
print(url)https://www.sec.gov/Archives/edgar/data/320193/000032019325000073/aapl-20250628.htmApple's CIK is 320193. To look up another company, search EDGAR or use the /api/lookup/cik endpoint. The recent block holds only the most recent filings; older ones sit in the extra files listed under filings.files in the same JSON.
Step 3: Convert XBRL to JSON with the Arelle command line
Arelle's Save Loadable OIM plugin writes a loaded filing as JSON in the Open Information Model format, better known as xBRL-JSON. Arelle downloads the inline document plus its extension schema and linkbases, so pass the same User-Agent through --httpUserAgent. From Python it is one subprocess call:
import subprocess
def export_xbrl_json(filing_url: str, out_path: str) -> None:
subprocess.run([
"arelleCmdLine",
"--file", filing_url,
"--plugins", "saveLoadableOIM|EDGAR/transform",
"--saveLoadableOIM", out_path,
"--httpUserAgent", USER_AGENT,
"--internetConnectivity", "online",
"--logFile", "arelle.log",
], check=True)
export_xbrl_json(url, "aapl-20250628.json")The equivalent shell command, if you would rather run it by hand:
arelleCmdLine --file "https://www.sec.gov/Archives/edgar/data/320193/000032019325000073/aapl-20250628.htm" --plugins "saveLoadableOIM|EDGAR/transform" --saveLoadableOIM aapl-20250628.json --httpUserAgent "YourCompany your-email@example.com" --internetConnectivity onlineThe first run took about 15 seconds, most of it downloading taxonomy files. Arelle caches them, so the next run on a filing from the same taxonomy year loaded in under 2 seconds. The output for Apple's 10-Q is a 770 KB file with 769 facts. Its documentInfo.documentType is https://xbrl.org/2021/xbrl-json, and every fact is an object keyed by its id. Here is the quarter's revenue and the quarter-end cash balance, exactly as Arelle wrote them:
"f-59": {
"value": "94036000000.0",
"decimals": -6,
"dimensions": {
"concept": "us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax",
"entity": "cik:0000320193",
"period": "2025-03-30T00:00:00/2025-06-29T00:00:00",
"unit": "iso4217:USD"
}
},
"f-167": {
"value": "36269000000.0",
"decimals": -6,
"dimensions": {
"concept": "us-gaap:CashAndCashEquivalentsAtCarryingValue",
"entity": "cik:0000320193",
"period": "2025-06-29T00:00:00",
"unit": "iso4217:USD"
}
}Three details trip people up. Values are strings, so parse them as Decimal rather than float if you care about exact sums. The period uses date-times, and the quarter that ends on June 28 is written as ending at 2025-06-29T00:00:00, the midnight that closes June 28. And anything that is not a core aspect (concept, entity, period, unit, language) inside dimensions is an XBRL dimension, such as srt:ProductOrServiceAxis.
arelleCmdLine --webserver localhost:8080 keeps taxonomies in memory and serves the same output over a local REST interface. One server processes one request at a time, so for hundreds of thousands of historical filings we run a pool of servers on consecutive ports behind a bounded queue.Step 4: Load the JSON and filter the facts in Python
The raw JSON still holds everything: cover-page text, footnote text blocks, every segment breakdown and every prior-year comparative. The loader below keeps numeric facts, converts periods back to the inclusive dates printed in the filing and records each fact's dimensions. Then it splits facts into consolidated and dimensional, and consolidated facts into instants and durations.
import json
from datetime import date, datetime, timedelta
from decimal import Decimal
CORE = {"concept", "entity", "period", "unit", "language", "noteId"}
def inclusive_period(period: str):
"""xBRL-JSON ends a period at the next midnight; filings print the day before."""
def day_before(ts: str) -> date:
return datetime.fromisoformat(ts).date() - timedelta(days=1)
if "/" not in period:
return None, day_before(period)
start, end = period.split("/")
return datetime.fromisoformat(start).date(), day_before(end)
def load_numeric_facts(path: str) -> list[dict]:
with open(path, encoding="utf-8") as fh:
doc = json.load(fh)
seen, rows = set(), []
for fact in doc["facts"].values():
aspects = fact["dimensions"]
if "unit" not in aspects or fact["value"] is None:
continue # text, dates, flags and xsi:nil facts
axes = {k: v for k, v in aspects.items() if k not in CORE}
key = (aspects["concept"], aspects["period"], aspects["unit"], tuple(sorted(axes.items())))
if key in seen:
continue # inline XBRL repeats a fact wherever the number is shown
seen.add(key)
start, end = inclusive_period(aspects["period"])
rows.append({
"concept": aspects["concept"],
"value": Decimal(fact["value"]),
"unit": aspects["unit"],
"start": start,
"end": end,
"axes": axes,
})
return rows
facts = load_numeric_facts("aapl-20250628.json")
consolidated = [f for f in facts if not f["axes"]]
instants = [f for f in consolidated if f["start"] is None]
durations = [f for f in consolidated if f["start"] is not None]
print(len(facts), "numeric,", len(consolidated), "consolidated,",
len(instants), "instant,", len(durations), "duration")603 numeric, 267 consolidated, 93 instant, 174 durationRemove the duplicate facts
Inline XBRL tags a number everywhere it is displayed, so the same fact appears more than once when a figure is repeated in the statements and the notes. In this filing, consolidated Q3 revenue appears twice with identical aspects and value. Deduplicating on concept, period, unit and dimensions removed 64 of the 667 numeric facts. Skip this step and every sum you build is wrong.
Drop dimensional facts, or keep only them
A fact with an axis is a slice of a total, not another total. 336 of the 603 unique numeric facts in Apple's 10-Q carry at least one dimension. For a top-of-statement dataset, keep only not f["axes"]. For segment work, keep exactly the dimensional ones, grouped by axis. The trap runs both ways: for some multi-class issuers, EPS and share counts exist only as dimensional facts, as covered in extracting EPS and share count with Arelle.
Separate instant and duration contexts
Balance sheet items are instants, a value on one date, and their period has no slash. Income statement and cash flow items are durations with a start and an end. The 10-Q has 93 consolidated instants, including both the June 28, 2025 balance sheet and the September 28, 2024 comparative, and 174 consolidated durations.
Separate the Q3 three-month value from the 9-month year to date
A Q3 10-Q reports the income statement twice for the same end date: once for the three months and once for the nine months year to date. They share the concept and the end date and differ only in the start date. Bucket durations by length, then pick the one you want:
def months(f: dict) -> int:
return round(((f["end"] - f["start"]).days + 1) / 30.4)
REVENUE = "us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax"
period_end = date(2025, 6, 28)
current = [f for f in durations if f["concept"] == REVENUE and f["end"] == period_end]
by_length = {months(f): f for f in current}
q3, ytd = by_length[3], by_length[9]
print("Q3 (3 months): ", q3["start"], "to", q3["end"], q3["value"])
print("9M year to date:", ytd["start"], "to", ytd["end"], ytd["value"])
segments = [f for f in facts if f["concept"] == REVENUE and f["axes"]
and f["start"] == q3["start"] and f["end"] == period_end]
for f in segments:
print("segment", f["axes"], f["value"])Q3 (3 months): 2025-03-30 to 2025-06-28 94036000000.0
9M year to date: 2024-09-29 to 2025-06-28 313695000000.0
segment {'srt:ProductOrServiceAxis': 'us-gaap:ProductMember'} 66613000000.0
segment {'srt:ProductOrServiceAxis': 'us-gaap:ServiceMember'} 27423000000.0
segment {'srt:ProductOrServiceAxis': 'aapl:IPhoneMember'} 44582000000.0
segment {'srt:ProductOrServiceAxis': 'aapl:MacMember'} 8046000000.0
segment {'srt:ProductOrServiceAxis': 'aapl:IPadMember'} 6581000000.0
segment {'srt:ProductOrServiceAxis': 'aapl:WearablesHomeandAccessoriesMember'} 7404000000.0
segment {'us-gaap:StatementBusinessSegmentsAxis': 'aapl:AmericasSegmentMember'} 41198000000.0
segment {'us-gaap:StatementBusinessSegmentsAxis': 'aapl:EuropeSegmentMember'} 24014000000.0
segment {'us-gaap:StatementBusinessSegmentsAxis': 'aapl:GreaterChinaSegmentMember'} 15369000000.0
segment {'us-gaap:StatementBusinessSegmentsAxis': 'aapl:JapanSegmentMember'} 5782000000.0
segment {'us-gaap:StatementBusinessSegmentsAxis': 'aapl:RestOfAsiaPacificSegmentMember'} 7673000000.0Apple's fiscal Q3 revenue is $94.036B, and the nine months to June 28 total $313.695B. Load every duration as “quarterly” and Q3 shows up as both. The segment lines show why dimensions need care: products plus services add up to the same $94.036B, and so do the five regions, so summing every revenue fact in the file would count the quarter several times over.
Cash flow statements break the pattern. Most filers report them only year to date in a 10-Q. In this filing, us-gaap:DepreciationDepletionAndAmortization has a nine-month value and no three-month value, so a discrete Q3 figure has to be computed as 9M minus H1 from the prior 10-Q.
Five problems no one warns you about
The script above works for one filing. Run it across thousands of companies and years and the same five issues come up again and again.
1. Concept proliferation
Revenue is not one concept. The us-gaap taxonomy alone has Revenues, SalesRevenueNet, SalesRevenueGoodsNet, RevenueFromContractWithCustomerExcludingAssessedTax and more, and different companies, or the same company in different years, pick different ones. Extension taxonomies add issuer-specific concepts on top. A parser that looks for one concept name silently misses whole companies, so production pipelines map each company's concepts onto a fixed list of canonical fields.
2. Dimensional facts
As the Apple output shows, the same concept appears consolidated and split along several axes in one filing. Treating the slices as separate totals double-counts; dropping them blindly loses data that only exists in dimensional form.
3. Period classification
| Duration | Means | Comes from |
|---|---|---|
| ~365 days | FY (annual) | 10-K |
| ~270 days | 9M (year to date through Q3) | Q3 10-Q |
| ~180 days | H1 (year to date through Q2) | Q2 10-Q |
| ~90 days | A single quarter | Any 10-Q |
| 0 days | Instant (balance sheet date) | Any filing |
Classify every fact by length, with a few days of tolerance, because 52/53-week calendars make quarters 91 days one year and 98 days another.
4. Fiscal calendars
Apple's fiscal year ends in late September, Costco's in late August and Walmart's in late January, and on a 52/53-week calendar the exact end date drifts by a few days from year to year. Grouping facts by calendar year breaks every cross-company comparison. Label each period with the company's fiscal year instead: Apple's June 2025 quarter is fiscal Q3 2025, which the filing itself confirms in dei:DocumentFiscalPeriodFocus.
5. The missing Q4
There is no fourth-quarter 10-Q. The 10-K reports the full year, so a discrete Q4 has to be derived from the annual and year-to-date figures. The section on backtesting below links to the full method.
py-xbrl, XBRL-JSON and Arelle compared
Arelle is not the only way to get JSON out of a filing. The usual options, based on each project's own documentation:
| Option | What it is | Good for | Watch out for |
|---|---|---|---|
| Arelle CLI + saveLoadableOIM | Full XBRL processor; the plugin writes OIM JSON, CSV or XLSX | Correct period, unit and dimension handling; SEC transforms; validation | Heavier install; EDGAR plugin installed separately; slow per call without server mode |
| py-xbrl | Pure Python parser for XBRL and iXBRL instances; XbrlInstance.json() converts to JSON | Lightweight scripts; downloads and caches a filing and its taxonomies from a URL | GPL-3.0 license; requires a cache directory and SEC headers via HttpCache.set_headers; its docs note some EDGAR filings reference taxonomies that are not imported properly |
| XBRL-JSON (OIM) itself | The XBRL International standard JSON shape, not a tool | A stable target format; output from Arelle and py-xbrl both follow it | You still have to filter, deduplicate and map concepts yourself |
StockFit /api/financials/as-reported | Hosted API over the same filings, already parsed | Skip the pipeline; consistent fiscal labels and filing dates | Consolidated facts only; segment slices come from separate endpoints; Free returns the latest four quarters |
The py-xbrl usage guide says its JSON output follows the 2021 recommendation from XBRL International, which is the xBRL-JSON specification: a facts object keyed by fact id, each fact with a string value and a dimensions object holding concept, entity, period, unit and any taxonomy-defined dimensions. That makes the loader in Step 4 a reasonable starting point for either tool's output. Arelle is the choice when correctness on odd filings matters, since it is a full processor rather than a parser.
When an API saves the work: as-reported JSON
Steps 1 to 4 are a weekend project for one filing and an ongoing job for a whole market: taxonomy updates, new extension concepts, amended filings, cash flow items that need de-cumulating. If what you need is the JSON rather than the pipeline, /api/financials/as-reported returns the consolidated facts of each period keyed by the concept the filer used, including company-specific extensions, on every plan from Free up.
import json
import os
import urllib.request
req = urllib.request.Request(
"https://api.stockfit.io/v1/api/financials/as-reported?symbol=AAPL&period=quarter&limit=4",
headers={"Authorization": f"Bearer {os.environ['STOCKFIT_API_KEY']}"},
)
with urllib.request.urlopen(req, timeout=30) as resp:
periods = json.load(resp)
q3 = next(p for p in periods if p["fiscalPeriod"] == "Q3")
revenue = q3["facts"]["us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax"]
print(q3["fiscalYear"], q3["fiscalPeriod"], q3["dateFiled"], revenue)2026 Q3 2026-07-31 109417000000That is Apple's fiscal Q3 2026, the latest Q3 when this was written in November 2026. The Free plan returns the latest four quarters and one fiscal year; Starter goes back 40 quarters, which reaches the fiscal Q3 2025 filing parsed above, served with the same 94036000000. Each period carries fiscalYear and fiscalPeriod, so the Q3 lookup above needs no date arithmetic, plus dateFiled and acceptedAt from the original filing. A sources map names the filing that supplied each value. For each concept the most recently filed value is served, so a comparative restated in a later report replaces the original figure. Quarterly entries also include derived values for items filers report only year to date, under synthetic keys such as Q3-Recon-9M-H1, so the D&A gap from Step 4 is already filled and labeled.
When you want stable field names instead of concept names, /api/financials/income-statement, /api/financials/balance-sheet and /api/financials/cash-flow-statement map every company onto the same canonical fields, such as revenue and netIncome, and add a per-fact restatement trail. A field that a company did not report is simply absent from facts, and fields computed rather than tagged are listed in derived. Ratios come from /api/financials/key-metrics from the Starter plan up, and every free account includes 50 premium calls on paid endpoints to try it.
From XBRL JSON to Q4 data and backtests
Once the facts are in JSON, three problems decide whether the data is usable for research. Each has its own guide.
Reconstructing Q4
Q4 is the annual value minus the nine-month year to date, with fallbacks when a 10-Q is missing. How to calculate Q4 earnings from the 10-K and 10-Q walks through the formula and its edge cases.
Point-in-time data
A backtest may only use a number after the filing that contains it was public, and restatements must not leak backwards. Point-in-time data for backtesting shows a real restatement and how to avoid lookahead bias.
A backtesting workflow
Filter on filing dates, then unwind amendments filed after your as-of date. The Holy Grail API for stock backtesting builds that panel with working code.
FAQ
Q.How do I convert SEC XBRL to JSON in Python?
pip install arelle-release plus the SEC transforms plugin from the Arelle/EDGAR repository. Find the filing's inline XBRL document through data.sec.gov/submissions, then run arelleCmdLine --file <url> --plugins "saveLoadableOIM|EDGAR/transform" --saveLoadableOIM out.json --httpUserAgent "YourCompany your-email@example.com" from Python with subprocess. Load the result with json.load and filter the facts object.Q.What does Arelle's xBRL-JSON output look like?
documentInfo header with documentType set to https://xbrl.org/2021/xbrl-json, and a facts object keyed by fact id. Each fact has a string value, an optional decimals, and a dimensions object with concept, entity, period, unit and any XBRL dimensions such as srt:ProductOrServiceAxis.Q.How do I separate quarterly from year-to-date values in a 10-Q?
Q.Why does the same XBRL fact appear twice in the JSON?
Q.Should I use py-xbrl or Arelle?
.json() method follows the XBRL-JSON recommendation, and it suits quick scripts. Arelle is a full XBRL processor with SEC transformation support and validation, and it is the safer choice across many companies and years. py-xbrl is GPL-3.0 licensed, which matters if you ship it in a product.Q.Do I need a User-Agent to download XBRL from SEC EDGAR?
--httpUserAgent, since Arelle downloads the filing's schema and linkbases too.Q.Is there an API that returns SEC XBRL financials as JSON?
Ready to build?
Free API key, no credit card.