SEC EDGAR XBRL API: Automating Financial Extraction
How to query the official SEC EDGAR REST APIs, parse company facts JSON endpoints, decode US GAAP taxonomy tags, and build automated quantitative pipelines.
Executive Forensic Summary
- For decades, financial data vendors charged institutional funds tens of thousands of dollars annually for access to structured public company financial statements.
- Today, the Securities and Exchange Commission provides free, direct, real-time programmatic access to every public company's audited financial disclosures through the official **SEC EDGAR RESTful APIs and Inline XBRL (iXBRL) JSON data endpoints**.
- By querying endpoints like `api.sec.gov/edgar/companyfacts/CIK{cik}.json` and `api.sec.gov/edgar/companyconcept/`, quantitative researchers and algorithmic traders can extract clean, standardized multi-decade balance sheets, income statements, and cash flow data in milliseconds without scraping messy HTML.
- Crucially, building an institutional financial extraction engine requires mastering **US GAAP Taxonomy Concepts** (e.g., `us-gaap:Revenues`, `us-gaap:NetIncomeLoss`, `us-gaap:OperatingIncomeLoss`), handling custom extension tags, managing period types (instant vs. duration), and adhering strictly to the SEC's **10 requests-per-second Fair Access Policy**.
- This forensic guide provides an exhaustive technical blueprint for the SEC EDGAR API, details Python code architecture for automated statement parsing, maps core accounting taxonomy tags, and presents an institutional data validation framework.
§Table of Contents (11 sections)▾
#From PDF Scrapes to Machine-Readable Standardized Financial Data
Historically, public financial reporting was designed exclusively for human eyes. Companies submitted Form 10-K and 10-Q filings as unstructured text, PDF scans, or messy HTML tables. Financial data providers (Bloomberg, FactSet, S&P Capital IQ) employed armies of offshore data-entry clerks to manually copy and paste numbers into proprietary databases, introducing latency and transcription errors.[1]
To democratize capital markets data, the SEC adopted the **Interactive Data Mandate (Release No. 33-9002)** in 2009, requiring public companies to submit financial statements using **eXtensible Business Reporting Language (XBRL)**.
In 2018, the Commission modernized this framework by mandating **Inline XBRL (iXBRL; Release No. 33-10514)** under **Regulation S-T Rule 405**. Inline XBRL embeds standardized XML/XBRL metadata tags directly inside the human-readable HTML filing document itself.
Furthermore, the SEC made this entire repository programmatically accessible via official **RESTful JSON APIs on data.sec.gov and api.sec.gov**, completely eliminating the need for brittle HTML web scrapers and granting every developer, quantitative hedge fund, and retail investor direct access to audited corporate ledgers.
Direct Free Access to Audited Data
The SEC's official REST APIs provide free, direct programmatic access to every public company's audited XBRL financial statements in JSON format, bypassing expensive third-party data terminal paywalls.
Key Analysis Points
- Release No. 33-9002 (2009) and Release No. 33-10514 (2018) established mandatory iXBRL reporting.
- Inline XBRL embeds machine-readable tags directly inside human-readable HTML documents.
- The SEC exposes this structured data through public RESTful JSON endpoints at `data.sec.gov`.
#Understanding the Three Primary REST Endpoints for Programmatic Access
The SEC hosts its structured financial data APIs under the `data.sec.gov` domain. Quantitative developers utilize three foundational endpoints:[2]
**1. Company Submissions Endpoint:**
`https://data.sec.gov/submissions/CIK{cik_10_digits}.json`
Returns complete historical metadata for the registrant: formal legal name, CIK, SIC industry code, ticker symbols, fiscal year-end date, state of incorporation, and a complete chronological array of all filings submitted over the trailing 10 to 15 years (including accession numbers, filing dates, report dates, and form types).
**2. Company Facts Endpoint (The Institutional Workhorse):**
`https://data.sec.gov/api/xbrl/companyfacts/CIK{cik_10_digits}.json`
The single most powerful endpoint in financial data! It returns every single numerical fact ever tagged in any XBRL disclosure by that entity since 2009. The JSON response is categorized by taxonomy (`us-gaap`, `dei`, `invest`, or custom) and contains an exhaustive time-series array of every balance sheet, income statement, and cash flow item, tagged with units (USD, shares), filing forms (10-K, 10-Q), fiscal years, and fiscal quarters.
**3. Company Concept Endpoint:**
`https://data.sec.gov/api/xbrl/companyconcept/CIK{cik_10_digits}/{taxonomy}/{tag}.json`
Queries a specific accounting concept for a specific company across all historical filings (e.g., pulling all historical entries for `us-gaap/AccountsReceivableNetCurrent` for Apple CIK `0000320193`).
For foundational market context and trade execution mechanics, examine our core research on Dividend Reinvestment Plans (DRIP): Broker Synthetic DRIP and Clearing House Default Funds: The DTCC Backstop Against.
The 10-Digit CIK Formatting Rule
The SEC API strictly requires Central Index Keys (CIKs) to be formatted as zero-padded 10-digit strings. Apple's CIK `320193` must be formatted as `CIK0000320193` in API query URLs.
Key Analysis Points
- `/submissions/` returns complete filing metadata, accession numbers, and form types.
- `/companyfacts/` returns every numerical XBRL accounting fact ever reported by the company.
- `/companyconcept/` queries a single historical GAAP accounting concept across all periods.
#How to Avoid Getting Automatically Banned by SEC Webmaster Firewalls
To protect EDGAR infrastructure from denial-of-service degradation, the SEC enforces a strict **Fair Access Policy** across all automated API requests.[3]
Developers must comply with two non-negotiable technical requirements:
**1. The 10 Requests-Per-Second Hard Ceiling:** The SEC automated rate limiter restricts any single IP address or client to **no more than 10 requests per second**. Exceeding this threshold triggers an immediate **HTTP 429 (Too Many Requests)** response. Sustained violations result in an automated 10-minute to 24-hour firewall IP ban.
**2. Mandatory User-Agent Header Specification:** Standard automated HTTP clients (like Python `requests` or `urllib`) default to User-Agent strings like `python-requests/2.31.0`. **The SEC automatically blocks all requests with generic or missing User-Agent headers!**
Under SEC guidelines, the User-Agent header must follow a specific, declarative format identifying the organization and a technical contact email:
`User-Agent: ResearchDesk/1.0 (InstitutionalResearch; analytics@stockvaluecheck.com)`
In Python scripts, developers implement rate limiting using Python's `time.sleep(0.11)` between API calls or robust token-bucket rate limiters (`ratelimit` or `tenacity` libraries), accompanied by automated exponential backoff on retries.
The Mandatory User-Agent Format
Every SEC API request must include a custom User-Agent header containing your company name and contact email. Failure to include this header results in an immediate HTTP 403 Forbidden error.
Key Analysis Points
- The SEC enforces a strict rate limit of maximum 10 requests per second per IP address.
- User-Agent headers must declare organizational identity and an active contact email.
- Generic Python or cURL user-agents are permanently blocked by SEC Akamai firewalls.
#Navigating the Core Accounting Concepts Across Form 10-K Financial Statements
When parsing the `companyfacts` JSON payload, developers must map extracted data points to standardized **US GAAP Taxonomy Concepts** maintained by the Financial Accounting Standards Board (FASB).[4]
Forensic extraction engines map core line items to these standardized tags:
**1. Income Statement Core Concepts:**
- *Revenues:* `us-gaap:Revenues`, `us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax`, `us-gaap:SalesRevenueNet`
- *Cost of Goods Sold:* `us-gaap:CostOfGoodsAndServicesSold`, `us-gaap:CostOfRevenue`
- *Operating Income:* `us-gaap:OperatingIncomeLoss`
- *Net Income:* `us-gaap:NetIncomeLoss`
- *Diluted EPS:* `us-gaap:EarningsPerShareDiluted`
**2. Balance Sheet Core Concepts:**
- *Cash & Equivalents:* `us-gaap:CashAndCashEquivalentsAtCarryingValue`
- *Accounts Receivable:* `us-gaap:AccountsReceivableNetCurrent`
- *Inventories:* `us-gaap:InventoryNet`
- *Goodwill:* `us-gaap:Goodwill`
- *Total Assets:* `us-gaap:Assets`
- *Long-Term Debt:* `us-gaap:LongTermDebtNoncurrent`
- *Stockholders' Equity:* `us-gaap:StockholdersEquity`
**3. Cash Flow Statement Core Concepts:**
- *Operating Cash Flow:* `us-gaap:NetCashProvidedByUsedInOperatingActivities`
- *Capital Expenditures:* `us-gaap:PaymentsToAcquirePropertyPlantAndEquipment`
- *Share Repurchases:* `us-gaap:PaymentsForRepurchaseOfCommonStock`
The Revenue Tag Fallback Cascade
Companies use different revenue tags depending on their industry. Robust extraction pipelines implement a fallback cascade: check `RevenueFromContractWithCustomer...`, then `Revenues`, then `SalesRevenueNet`.
| Financial Statement Line | Primary US GAAP Taxonomy Tag | Period Type | Accounting Balance Type |
|---|---|---|---|
| Gross Revenue | `us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax` | Duration | Credit |
| Operating Income | `us-gaap:OperatingIncomeLoss` | Duration | Credit |
| Net Income | `us-gaap:NetIncomeLoss` | Duration | Credit |
| Cash & Equivalents | `us-gaap:CashAndCashEquivalentsAtCarryingValue` | Instant | Debit |
| Accounts Receivable | `us-gaap:AccountsReceivableNetCurrent` | Instant | Debit |
| Total Stockholders' Equity | `us-gaap:StockholdersEquity` | Instant | Credit |
| Operating Cash Flow | `us-gaap:NetCashProvidedByUsedInOperatingActivities` | Duration | Debit |
Source: IRS Statutory Code, Treasury Regulations & Revenue Procedures • Illustrative figures.
Key Analysis Points
- Standardized financial metrics map to specific FASB US GAAP taxonomy tags.
- Income statements, balance sheets, and cash flows use discrete standardized tag hierarchies.
- Pipelines must implement fallback cascades to handle industry-specific tag variations.
#How to Handle Instant Balance Sheets vs. Duration Income Statements
One of the most complex architectural hurdles in parsing SEC XBRL data is understanding the mathematical distinction between **Instant Concepts** and **Duration Concepts**:[1]
**1. Instant Concepts (Balance Sheet Points in Time):** Balance sheet items (e.g., Cash, Assets, Debt) represent an economic snapshot at an exact moment in time (e.g., as of December 31, 2025). The JSON facts array tags these with an `"end"` date (or `"instant"` date) with zero duration.
**2. Duration Concepts (Income and Cash Flow Statements):** Income and cash flow metrics represent economic activity occurring over an elapsed timeframe (e.g., 3 months, 6 months, 9 months, or 12 months). The JSON facts array tags these with a `"start"` and `"end"` date, alongside a `"form"` (10-Q or 10-K).
**The Infamous Q4 Unravelling Problem:**
Under SEC reporting rules, public companies file Form 10-Q for Q1, Q2, and Q3, but **they do not file a Form 10-Q for the fourth quarter**! Instead, they file the annual Form 10-K, which reports full-year (12-month) duration numbers.
To extract standalone Fourth Quarter (Q4) operating results, the data pipeline must perform a mathematical subtraction:
$$\text{Q4 Value} = \text{Full Year 10-K Value} - \left(\text{Q1 Value} + \text{Q2 Value} + \text{Q3 Value}\right)$$
Alternatively, the pipeline must subtract the **9-month duration figure reported in the Q3 Form 10-Q** from the **12-month duration figure in the Form 10-K**:
$$\text{Q4 Value} = \text{FY 10-K (12 Mo)} - \text{Q3 YTD (9 Mo)}$$
Automating this calculation is essential for constructing clean quarterly time-series models for quantitative earnings analysis.
The Q4 Calculation Rule
Companies do not report Q4 standalone numbers in Form 10-K; they report full-year 12-month totals. Your pipeline must subtract Q3 year-to-date (9-month) figures from full-year 10-K totals to extract pure Q4 performance.
Key Analysis Points
- Balance sheet concepts are 'Instant' snapshots; income/cash flow statements are 'Duration' flows.
- Companies do not file Q4 10-Q reports; fourth-quarter figures must be mathematically derived.
- Deduct Q3 9-month YTD totals from 12-month Form 10-K totals to isolate pure Q4 results.
#How to Prevent Extraction Failures When Companies Create Bespoke Concepts
While the FASB maintains thousands of standardized GAAP tags, public companies frequently create **Custom Extension Tags** under SEC rules.[2]
A custom extension tag is identified by the company's own ticker symbol or abbreviated name as the namespace prefix rather than `us-gaap:` (e.g., `tsla:AutomotiveRegulatoryCredits` or `aapl:ServicesRevenueNet`).
Custom tags introduce two primary challenges for automated data pipelines:
1. **Tag Drift Over Time:** A company might report revenue under `us-gaap:SalesRevenueNet` from 2012 to 2017, switch to `us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax` in 2018 upon adopting ASC 606, and then break out revenue using a custom tag in 2024. If an algorithm searches only for a single tag, historical charts display false zero-revenue gaps.
2. **The Calculation Linkbase Verification:** To confirm how custom tags roll up into consolidated financials, automated systems parse the **Calculation Linkbase XML file (`_cal.xml`)** attached to the filing submission. The calculation linkbase explicitly defines the mathematical parent-child tree, showing whether a custom tag is added to or subtracted from parent GAAP categories.
Advanced institutional extraction engines maintain dynamic synonym dictionaries and verify mathematical rollups against consolidated totals to ensure 100% extraction accuracy.
Tag Drift Resolution
Never hardcode a single XBRL tag for revenue or debt. Implement an ordered priority array of synonymous tags, checking for ASC 606 post-2018 standards first before falling back to legacy concepts.
Key Analysis Points
- Custom extension tags use company-specific namespaces rather than the standard `us-gaap:` prefix.
- Tag drift occurs when companies shift accounting concepts across different regulatory years.
- Parsing the calculation linkbase confirms how custom tags mathematically roll up into parent lines.
#A Resilient, Production-Ready Python Pipeline for Financial Statement Parsing
To construct a production-grade automated pipeline in Python, developers utilize `requests`, `pandas`, and token-bucket rate limiters.[3]
A resilient architecture follows a structured four-stage execution pipeline:
**Stage 1: Dynamic CIK Lookup:** Query the SEC's master ticker-to-CIK mapping file at `https://www.sec.gov/files/company_tickers.json`. Ingest the JSON mapping to resolve any input ticker symbol (e.g., 'MSFT') into its zero-padded 10-digit CIK (`0000789019`).
**Stage 2: Fetch and Cache Company Facts JSON:** Send a GET request to `https://data.sec.gov/api/xbrl/companyfacts/CIK0000789019.json` with an explicit User-Agent header. Cache the resulting JSON payload locally to disk to avoid repeated queries and respect rate limits.
**Stage 3: Extract and Filter Fact Arrays:** Navigate to `payload['facts']['us-gaap'][concept]['units']['USD']`. Filter the resulting list of fact dictionaries for entries where `"form" in ["10-K", "10-Q"]`, isolating audited periodic reports from preliminary 8-K exhibits.
**Stage 4: Deduplicate and Normalize Time-Series:** Sort entries by `"end"` date and `"filed"` date. When multiple filings report data for the same period (e.g., an original 10-K vs. a subsequent Form 10-K/A restatement), **always select the fact with the latest `"filed"` date** to automatically capture audited restatements.
Convert the sanitized records into a clean `pandas.DataFrame`, indexing by fiscal period for instant financial analysis.
The Latest-Filed Restatement Rule
When parsing XBRL fact arrays, always sort by `filed` date. Selecting the latest filed record for a given fiscal period automatically captures restated numbers from 10-K/A filings, preventing stale data errors.
Key Analysis Points
- Resolve tickers to 10-digit CIKs using the official SEC `company_tickers.json` mapping.
- Filter fact arrays for Form 10-K and 10-Q periodic filings to eliminate duplicate noise.
- Sort by `filed` date to ensure subsequent accounting restatements overwrite initial reports.
#Step-by-Step Quality Assurance Routine for Automated Financial Pipelines
To guarantee that automated financial pipelines produce audit-grade data free of corruption, quantitative developers enforce a five-step quality control protocol:[4]
**Step 1: The Balance Sheet Mathematical Identity Test:**
$$\text{Verification: } \left|\text{Total Assets} - \left(\text{Total Liabilities} + \text{Stockholders' Equity}\right)\right| < 1.00$$
The fundamental accounting equation must balance to within $1.00 for every extracted quarterly balance sheet. Any variance indicates an unmapped liability tag or custom equity class.
**Step 2: Operating Cash Flow vs. Net Income Reconciliation:** Audit the cash flow statement to verify that Net Income plus non-cash adjustments (depreciation, stock-based comp, working capital changes) mathematically reconciles to reported Operating Cash Flow.
**Step 3: Unit Verification (USD vs. Shares vs. Pure Ratios):** Verify unit headers: financial values must be tagged under `units['USD']`, share counts under `units['shares']`, and profit margins or tax rates under `units['pure']`.
**Step 4: Check for Negative Sign Inversions:** In XBRL, certain expenses (like cost of revenue or operating expenses) are tagged as positive debit balances, while on human-readable income statements they are displayed in parentheses as negative subtractions. Normalize sign conventions across all extracted statements.
**Step 5: Automated Alerting for Missing Historical Periods:** Flag any gap where a quarterly period is missing between sequential reports, triggering an automated inspection of Form 12b-25 late filing notifications.
The Accounting Identity Assertion
Never trust an automated data scrape without asserting: $\text{Assets} = \text{Liabilities} + \text{Equity}$. If this identity fails, your extraction pipeline has dropped a custom tag or misclassified a balance sheet line.
Key Analysis Points
- Enforce the fundamental balance sheet equation to verify 100% extraction tag completeness.
- Normalize XBRL debit/credit sign conventions against income statement display formats.
- Automate gap detection to flag missing quarterly filings or delinquent periodic reports.
#Transforming Raw JSON Fact Arrays into Audited Three-Statement Excel and SQL Models
Once raw XBRL facts have been validated, the final objective of the automated data pipeline is reconstructing the complete **Three-Statement Financial Model** (Balance Sheet, Income Statement, and Cash Flow Statement).[1]
Forensic extraction engines execute five standardization rules:
**1. Standardized Operating Income Rollups:** Companies calculate operating income with varying definitions: some include restructuring charges and asset impairments in operating costs, while others classify them as non-operating. Standardize operating income by programmatically isolating Gross Profit minus Selling, General, and Administrative (SG&A) and Research & Development (R&D).
**2. Cash Flow Statement Direct Cash Reconciliation:** Reconcile cash from operations, cash from investing, and cash from financing to ensure that: $\Delta \text{Cash} = \text{CFO} + \text{CFI} + \text{CFF}$. Verify that foreign exchange translation impacts on cash are correctly apportioned.
**3. Share Count Dilution Tracking:** Pull both Basic Shares Outstanding (`us-gaap:WeightedAverageNumberOfSharesOutstandingBasic`) and Diluted Shares Outstanding (`us-gaap:WeightedAverageNumberOfDilutedSharesOutstanding`). If diluted shares exceed basic shares by more than 15%, model potential equity overhang from stock option and RSU dilution.
**4. Automated Ratio Computation (ROIC, WACC, and Free Cash Flow):** Directly compute Free Cash Flow: $\text{FCF} = \text{Operating Cash Flow} - \text{CapEx}$. Programmatically calculate Return on Invested Capital (ROIC) across historical five-year horizons.
By automating this pipeline, fundamental research analysts can evaluate a newly filed Form 10-K within sixty seconds of release, generating fully populated DCF and DuPont models before Wall Street sell-side research notes are published.
Automated 3-Statement Generation
Parse the XBRL payload to automatically populate a three-statement financial model. Computing Free Cash Flow and ROIC directly from raw JSON facts delivers institutional research velocity in seconds.
Key Analysis Points
- Standardize operating income calculations across inconsistent corporate reporting formats.
- Reconcile net cash changes across operating, investing, and financing cash flow sections.
- Automate instantaneous Free Cash Flow and ROIC calculations upon 10-K filing release.
Quantitative Verification Suite
Forensic Valuation Tools for this Research
Apply deterministic financial algebra to verify the balance sheet mechanics explored in this research.
Piotroski F-Score Calculator
Programmatically calculate nine fundamental accounting tests
Reverse DCF Calculator
Feed historical cash flow data directly into reverse valuation models
#Frequently Asked Questions (FAQ)
What is the SEC EDGAR XBRL API?
The SEC EDGAR XBRL API is a free, public RESTful API maintained by the SEC at data.sec.gov that provides direct programmatic access to structured financial statement data (balance sheets, income statements, cash flows) submitted by public companies in JSON format.
What is the difference between XBRL and Inline XBRL (iXBRL)?
Traditional XBRL required companies to submit a separate XML data document alongside their human-readable filing. Inline XBRL (iXBRL) embeds the machine-readable XBRL tags directly inside the HTML filing document itself, allowing humans and computers to read the exact same file.
What is the SEC API rate limit and how do I avoid being blocked?
The SEC enforces a strict rate limit of no more than 10 requests per second per IP address. To avoid being blocked with an HTTP 429 error, developers must rate-limit requests to 10/sec and include a declared User-Agent header with their name and email.
How do I extract Fourth Quarter (Q4) results from the SEC API?
Companies do not report standalone Q4 results because they file annual 12-month 10-K reports instead of a fourth-quarter 10-Q. To extract Q4 numbers, subtract the 9-month year-to-date figures reported in the Q3 Form 10-Q from the full-year 12-month totals reported in the Form 10-K.
What are custom extension tags in XBRL?
Custom extension tags are company-created XBRL tags (prefixed by the company's ticker rather than 'us-gaap:') used when management believes standard US GAAP taxonomy tags do not adequately describe a unique business metric or revenue stream.
#Primary Regulatory Sources & Statutory Citations
Every legal, execution, and clearing claim in this guide is derived directly from verified US regulatory statutes:
SEC Interactive Data for Financial Reporting (Rule 405 of Regulation S-T) ↗
Foundational SEC rulemaking mandating the submission of structured XBRL financial data for all public operating companies.
SEC Inline XBRL Filing of Tagged Data (Final Rule) ↗
Comprehensive federal regulation mandating the transition from traditional XBRL to Inline XBRL (iXBRL) for all periodic reports.
SEC EDGAR Application Programming Interfaces (APIs) Developer Documentation ↗
Official technical API documentation detailing company facts, submissions, and concept JSON endpoints, rate limits, and schemas.
FASB US GAAP Financial Reporting Taxonomy Architecture ↗
Official accounting taxonomy defining standard elements, calculation linkbases, and mathematical relationships for financial line items.
What We Checked: Statutory Audit & Verification
This research report was cross-audited against certified SEC EDGAR releases, DTCC Continuous Net Settlement (CNS) operational manuals, and the FINRA Manual. Market figures and data points are provided for informational and educational purposes under the Broadsheet editorial standard.