EDGAR Analytics Analyze SEC EDGAR filings in seconds. Retrieve 10-K and 10-Q financial statements, compute 40+ GAAP/IFRS metrics and scoring models, forecast revenue with ARIMA/SARIMAX, and get actionable alerts — all from a single CLI command or Python import. New to the library? See the User Guide for real-world workflows and practical recipes, the Metrics Reference for every supported concept and metric with…
EDGAR Analytics – Python Library for Extracting, Analyzing, and Forecasting SEC EDGAR Filings. Streamline your financial analysis with comprehensive metrics, growth rates, and automated reporting capabilities.
Analyze SEC EDGAR filings in seconds. Retrieve 10-K and 10-Q financial statements, compute 40+ GAAP/IFRS metrics and scoring models, forecast revenue with ARIMA/SARIMAX, and get actionable alerts — all from a single CLI command or Python import.
import edgar_analytics as ea
result = ea.analyze("AAPL", peers=["MSFT", "GOOGL"])
print(result.main.annual_snapshot.metrics.revenue)
df = result.to_dataframe() # One row per ticker
New to the library? See the User Guide for real-world workflows and practical recipes, the Metrics Reference for every supported concept and metric with business context, and the Architecture Guide for how the data pipeline works.
Optionally forecast revenue using a strategy-based architecture (ARIMA by default).
Summarize results with rich, colorized console output and optional CSV exports.
It handles complexities such as:
Multi-year and multi-quarter filing retrieval (10-K and 10-Q).
Flexible synonyms to accommodate IFRS/GAAP labeling differences.
Automatic sign-flipping of negative expenses.
Common ratio calculations (Current Ratio, Debt-to-Equity, Free Cash Flow, etc.).
Alert detection for negative margins, high leverage, negative free cash flow streaks, spikes in working capital.
Strategy-based forecasting with a default ARIMA approach or customizable forecasting strategy.
A fully scriptable CLI with rich console output.
IFRS & GAAP Filers
Supports both U.S. GAAP and IFRS filers. Foreign private issuers that file IFRS-based statements (e.g., Form 20-F) are automatically handled if synonyms match IFRS-labeled line items.
Features
Typed Programmatic API: ea.analyze("AAPL", peers=["MSFT"]) returns an AnalysisResult dataclass with typed fields — no more dict-diving.
Annual & Quarterly Snapshots: Retrieve the latest 10-K (annual) and 10-Q (quarterly) metrics for a given company.
Multi-Year Analysis: Pull multiple 10-K and 10-Q statements (income, balance sheet, cash flow) to compute YoY growth, QoQ growth, and CAGR for all metrics including FCF, CapEx, ROE, ROA, and D/E.
Scoring Models: Piotroski F-Score, Altman Z-Score (manufacturing + non-manufacturing Z’’ variants with auto-detection), Beneish M-Score, DuPont Decomposition, Capital Efficiency (ROIC/WACC), Per-Share Metrics (basic + diluted EPS), Working Capital Cycle (DSO/DIO/DPO).
Financial Company Detection: Auto-detects banks and insurers via SIC code (6000-6999) and suppresses inapplicable models (Altman Z, working capital cycle) that produce garbage for financial institutions.
Valuation Ratios: P/E, P/B, EV/EBITDA, and Earnings Yield from live market data (requires pip install edgar-analytics[valuation]).
TTM (Trailing Twelve Months): Automatically computed from quarterly data and included in results.
Alerts:
Negative net margin
High leverage (debt-to-equity above threshold)
Consecutive quarters of negative free cash flow
Significant quarterly spikes in inventory/receivables
By default, uses an ARIMA-based strategy for annual or quarterly data.
Easily swap in your own forecasting logic by implementing a custom strategy (see Extensibility).
Disk Caching: SQLite-backed caching with TTL support. Past filings cached forever, current filings cached 24h. Install with pip install edgar-analytics[cache].
CompanyFacts Cross-Validation: Automatic cross-check against SEC XBRL CompanyFacts API. Discrepancies logged as warnings, never modifies parsed values.
Concurrent Peer Fetching: Peers analyzed in parallel with ThreadPoolExecutor and SEC rate-limit compliance (time-based 10 req/sec limiter).
Output Formats:
result.to_dataframe() — One row per ticker, columns for metrics
result.to_panel() — MultiIndex DataFrame (ticker × period × metric) for quant research
result.to_parquet(path) — Write to Parquet (pip install edgar-analytics[parquet])
Quick analysis without forecasting and minimal console output.
Programmatic Usage
The recommended entry point is ea.analyze(), which returns typed dataclasses:
import edgar_analytics as ea
# Full analysis with peers — returns AnalysisResult dataclass
result = ea.analyze("AAPL", peers=["MSFT", "GOOGL"])
# Access typed fields directly
metrics = result.main.annual_snapshot.metrics
print(f"Revenue: {metrics.revenue:,.0f}")
print(f"Net Margin: {metrics.net_margin_pct:.1f}%")
print(f"Piotroski Score: {metrics.scores.piotroski.score}")
# TTM data (trailing twelve months from quarterly)
print(f"TTM Revenue: {result.main.multiyear.ttm.get('Revenue', 0):,.0f}")
# Multi-period trends (FCF, ROE, D/E over time)
annual = result.main.multiyear.annual_data
print(f"ROE % by year: {annual.get('ROE %', {})}")
print(f"FCF by year: {annual.get('Free Cash Flow', {})}")
# Export to various formats
df = result.to_dataframe() # One row per ticker
panel = result.to_panel() # MultiIndex: ticker × period × metric
result.to_parquet("output.parquet") # Requires: pip install edgar-analytics[parquet]
Serialization round-trip (save/load results as JSON):
import json
import edgar_analytics as ea
result = ea.analyze("AAPL")
# Serialize (NaN/Inf safely converted to null)
with open("analysis.json", "w") as f:
json.dump(result.to_json_dict(), f)
# Deserialize
with open("analysis.json") as f:
restored = ea.AnalysisResult.from_json_dict(json.load(f))
For CLI-style console output with optional CSV export:
from edgar_analytics.orchestrator import TickerOrchestrator
# Context manager ensures cache file descriptors are released
with TickerOrchestrator() as orchestrator:
result = orchestrator.analyze_company(
ticker="AAPL",
peers=["MSFT", "GOOGL"],
csv_path="summary.csv",
n_years=5,
n_quarters=8,
identity="Name <email>"
)
Core Modules
models.py
Typed dataclass models: AnalysisResult, TickerAnalysis, FilingSnapshot, SnapshotMetrics, ScoresResult, etc.
multi_period_analysis.py
Multi-year/quarter data retrieval across income, balance sheet, and cash flow statements. Computes YoY growth, CAGR, FCF/CapEx/ROE/ROA/D/E time series, and derived margin ratios.
orchestrator.py
High-level orchestration with disk caching, concurrent peer fetching, CompanyFacts cross-validation, and TTM integration.
cache.py
SQLite-backed disk caching with TTL support (requires diskcache). Transparent no-op when not installed.
company_facts.py
SEC XBRL CompanyFacts API cross-validation. Logs discrepancies, never modifies parsed values.
Retrieves the latest 10-K or 10-Q for a Company, parses it into a dictionary of metrics + filing info.
Internally used by _analyze_ticker_for_metrics().
multi_period_analysis.retrieve_multi_year_data()
Fetches multiple 10-K/10-Q filings for multi-year or multi-quarter growth analysis, CAGR, etc. Returns annual_data, quarterly_data, yoy_revenue_growth, and cagr_revenue.
Main entry for forecasting next revenue (1-step) using a specified or default strategy (ArimaForecastStrategy). Negative forecasts are preserved to surface declining trends; NaN/Inf results fall back to the last known value.
CLI: Called under the hood by the Orchestrator. Python: python<br/>from edgar_analytics.forecasting import forecast_revenue<br/>fcst = forecast_revenue(rev_dict)
forecasting.ArimaForecastStrategy
Default ARIMA-based strategy that tries ARIMA/SARIMAX model candidates and picks one by AIC.
Builds a final summary of metrics for all tickers, renders rich console output, and optionally saves to CSV.
Internally used by analyze_company(), though you can call it directly with a valid metrics_map.
TickerDetector.validate_ticker_symbol()
Regex-based validation of ticker format.
Used to filter out invalid tickers (e.g., @@@).
Refined FCF Computation
Starting with v0.1.0+, EDGAR Analytics applies a smarter fallback when a direct “capital expenditures” line item is missing from the cash flow statement. Specifically:
Checks for an explicit “capital expenditures” row (via synonyms).
If not found:
Takes the net investing outflow (if negative).
Subtracts intangible purchases and business acquisitions (when detected).
The remainder is treated as approximated “capex.”
This helps avoid over-counting large M&A deals or intangible acquisitions as ongoing capital expenditures. You can see this improvement in:
synonyms_utils.compute_capex_single_period and compute_capex_for_column
metrics.py for single filing snapshots.
multi_period_analysis.py for multi-quarter data.
Disclaimer:
Even with these refinements, certain unusual transactions may still appear in overall investing outflows. Thus, the library’s fallback remains an approximation for investor/analyst guidance only.
Logging & Debugging
EDGAR Analytics provides two parallel logging outputs:
Console (Rich):
Level controlled by --log-level (INFO by default) or --debug
Colorized, minimal, user-friendly log messages
Can be suppressed with --suppress-logs for cleaner output
Ideal for debugging or integration with log management systems
Includes detailed context (file, line number, function name)
Handlers are flushed and closed on process exit via atexit
Library users can opt in via configure_logging(level, enable_file_logging=True)
Test Logging & Ticker Orchestrator
The Orchestrator and ReportingEngine now consistently use loggers named edgar_analytics.orchestrator and edgar_analytics.reporting
This ensures that test fixtures using caplog.at_level(..., logger="edgar_analytics.orchestrator") or "edgar_analytics.reporting" will capture and verify expected log lines
Third-party loggers (edgar, edgartools, httpx) are automatically adjusted based on the chosen log level
Extensibility
EDGAR Analytics is modular, letting you add or override behavior easily:
Synonyms: Extend or override synonyms in synonyms.py for custom labeling.
Alert Thresholds: config.py contains all alert thresholds (negative margins, high leverage, net debt/EBITDA, interest coverage, FCF streaks, inventory/receivables spikes). Override at runtime via ea.analyze("AAPL", alerts_config={"HIGH_LEVERAGE": 5.0}).
Additional Metrics: Add new ratio logic to metrics.py or wherever suitable.
Custom Forecast Strategies:
The library exposes a ForecastStrategy abstract base class in forecasting.py.
By default, we use ArimaForecastStrategy. You can create your own strategy subclass and pass it to forecast_revenue() (or the Orchestrator if you modify its internal logic).
from edgar_analytics.forecasting import ForecastStrategy, forecast_revenue
from edgar_analytics.data_utils import parse_period_label
class MyGrowthStrategy(ForecastStrategy):
def forecast(self, rev_dict: dict, is_quarterly=False) -> float:
# Example: always increase last known revenue by +5%
if not rev_dict:
return 0.0
sorted_periods = sorted(rev_dict.keys(), key=parse_period_label)
last_val = rev_dict[sorted_periods[-1]]
return last_val * 1.05
# Usage:
data_map = {"2020": 100, "2021": 200}
fcst = forecast_revenue(data_map, strategy=MyGrowthStrategy())
print(fcst)
Reporting Formats: ReportingEngine supports rich console output and CSV. Extend it for Excel, JSON, or any other output format.
Testing
We use pytest to ensure reliability and coverage.
From the project root (where pytest can discover tests/):
pytest -v --cov=edgar_analytics --cov-report=term-missing
# To run in parallel threads: pytest --maxfail=1 --disable-warnings -v -n auto tests
The test suite includes fixtures for capturing and verifying log outputs, particularly useful for testing the Orchestrator and ReportingEngine components.
Contributing
We welcome contributions! See CONTRIBUTING.md for the full guide, including development setup, coding standards, and financial accuracy guidelines.
Disclaimer:
This tool extracts data from public SEC filings. Always review official filings directly for investment decisions. The library and its maintainers are not responsible for any inaccuracies or any decisions made based on these outputs.
Happy Analyzing! If you find this useful, please give us a star — it helps others discover the project.
评论