edgartools icon indicating copy to clipboard operation
edgartools copied to clipboard

Several bugs when retreiving 8-K information from financial exhibits

Open amcamc92 opened this issue 9 months ago • 10 comments

Issue Type

  • [x] Data Quality Issue (incorrect financial values, missing data)
  • [x] XBRL Parsing Issue (statement rendering, concept mapping)

Environment

EdgarTools Version: 5.14.0 Python Version: 3.13 Operating System: Windows 11

Bug Description

I tested edgar.earnings.EarningsRelease on 50 real 8-K filings (random sample across different companies, sectors, and filing dates). The results reveal several systematic issues that make the module unreliable for programmatic financial data extraction.

Summary of findings (50 filings tested)

Metric Result
EX-99 exhibit found 47/50 (94%)
Income statement classified 19/50 (38%)
EPS value extractable from DataFrame 8/50 (16%)
EPS value correct (when extracted) 2/8 (25%)
scaled_dataframe actually applies scaling 0/17 (0%)
Tables found but income statement not identified 28/50 (56%)

Bug 1: scaled_dataframe never applies scaling (100% failure rate)

What you expected to happen: FinancialTable.scaled_dataframe should return a DataFrame with numeric values multiplied by the detected scale factor (e.g., values in millions should be multiplied by 1,000,000).

What actually happened: scaled_dataframe silently returns the raw (unscaled) DataFrame in every case I tested. The method checks df[col].dtype in ['float64', 'int64'], but all columns have dtype object because _parse_numeric() returns a mix of float, str, and None values. The dtype check always fails, so scaling is never applied.

Impact: 17/19 income statements (89%) had a non-UNITS scale detected but scaling was never applied. Users who rely on scaled_dataframe get raw table values with no indication that scaling failed.

Root cause (in earnings.py line ~163-170):

@property
def scaled_dataframe(self) -> pd.DataFrame:
    if self.scale == Scale.UNITS:
        return self.dataframe.copy()
    df = self.dataframe.copy()
    for col in df.columns:
        if df[col].dtype in ['float64', 'int64']:  # <-- Always False (dtype is 'object')
            df[col] = df[col] * self.scale.value
    return df

Suggested fix: Use pd.to_numeric(df[col], errors='coerce') or check individual cell types instead of column dtype.

Concrete reproduction case — HURN (accession 0001289848-25-000189):

from edgar import Company
from edgar.earnings import EarningsRelease

filing = Company("HURN").get_filings(accession_number="0001289848-25-000189")[0]
earnings = EarningsRelease.from_filing(filing)
is_tbl = earnings.income_statement

print(f"Scale: {is_tbl.scale}")         # Scale.BILLIONS (wrong, but that's Bug 2)
print(f"Column dtypes:")
for col in is_tbl.dataframe.columns:
    print(f"  '{col}': {is_tbl.dataframe[col].dtype}")  # All 'object'

# Compare raw vs scaled — they are IDENTICAL
raw_val = is_tbl.dataframe.iloc[0, 0]
scaled_val = is_tbl.scaled_dataframe.iloc[0, 0]
print(f"Raw[0,0]: {raw_val}")            # e.g. 402505.0
print(f"Scaled[0,0]: {scaled_val}")      # 402505.0 (SAME — scaling never applied)
print(f"Scaling applied: {raw_val != scaled_val}")  # False

Expected: scaled_val should differ from raw_val (multiplied by scale factor).


Bug 2: Scale.detect() picks up narrative text, not table footnotes

What you expected to happen: Scale detection should identify the unit used in the financial tables (e.g., "in millions" from the table footer/header).

What actually happened: Scale.detect() searches the entire document text for keywords like "billion", "million", "thousand". Press releases typically contain narrative text like "revenue of $143.8 billion" which triggers billions detection even when the tables are denominated in millions.

Concrete examples from the test:

Ticker Accession Narrative mentions Actual table unit Scale detected Error
HURN 0001289848-25-000189 "billion" in text thousands billions 1M x
CRTO 0001193125-25-254634 "billion" in text millions billions 1000x
NVR 0000906163-25-000003 "homebuilding revenue...billion" units billions 1B x
ZETA 0000950170-25-026629 "billion" in text millions billions 1000x

Impact: Even if Bug 1 were fixed, applying the wrong scale would produce values off by 1,000x (millions detected as billions) or 1,000,000x (units detected as billions).

Root cause (in earnings.py line ~64-77):

@classmethod
def detect(cls, text: str) -> 'Scale':
    # Searches ALL document text, not just table headers/footers
    if _SCALE_BILLIONS.search(text):  # Matches narrative "billion"
        return cls.BILLIONS
    elif _SCALE_MILLIONS.search(text):
        return cls.MILLIONS
    ...

Suggested fix: Detect scale per-table from table headers/footers (e.g., (In millions, except per share data)), not from the full document text. The _detect_table_scale function exists but falls back to the document-level scale when table-level detection fails, which is most of the time.

Concrete reproduction case — CRTO (accession 0001193125-25-254634):

from edgar import Company
from edgar.earnings import EarningsRelease

filing = Company("CRTO").get_filings(accession_number="0001193125-25-254634")[0]
earnings = EarningsRelease.from_filing(filing)

print(f"Document scale: {earnings.detected_scale}")  # Scale.BILLIONS (WRONG)
# The tables actually say "(in thousands, except per share data)"
# Revenue in table = 553,035 → should be $553M, NOT $553B

is_tbl = earnings.income_statement
print(f"Table scale: {is_tbl.scale}")  # Also BILLIONS (inherited from document)
print(f"Revenue row: {is_tbl.dataframe.iloc[0].values}")
# Shows raw values in thousands, but labeled as billions

Expected: Scale should be Scale.THOUSANDS (detected from table footnote "(in thousands, except per share data)").


Bug 3: _classify_statement() fails to identify income statements in 56% of filings

What you expected to happen: earnings.income_statement should return the income statement table when one exists in the filing.

What actually happened: 28 out of 50 filings (56%) had financial tables extracted but income_statement returned None. These filings had between 2 and 58 tables parsed, all classified as StatementType.UNKNOWN.

Root cause: The classifier requires ≥2 keyword matches from a hardcoded list ('net revenue', 'gross profit', 'operating income', etc.). Many real income statements use different terminology:

  • "Net sales" instead of "Net revenue"
  • "Income from operations" instead of "Operating income"
  • "Provision for income taxes" (this IS in the keyword list but the classifier needs 2+ matches)

Concrete reproduction cases (tables exist but income_statement=None):

Ticker Accession Tables found Financial tables Income statement?
RF 0001281761-25-000074 10 10 None
MTB 0000036270-26-000004 18 18 None
FSBC 0001628280-25-046534 21 21 None
BIO 0000012208-25-000051 18 18 None
KBR 0001357615-25-000015 9 9 None
ZETA 0000950170-25-026629 6 6 None
GPK 0001408075-25-000020 6 6 None

Concrete reproduction case — RF (accession 0001281761-25-000074):

from edgar import Company
from edgar.earnings import EarningsRelease

filing = Company("RF").get_filings(accession_number="0001281761-25-000074")[0]
earnings = EarningsRelease.from_filing(filing)

print(f"Tables: {len(earnings.tables)}")            # 10
print(f"Financial: {len(earnings.financial_tables)}")  # 10
print(f"Income statement: {earnings.income_statement}")  # None (!)

# All tables classified as UNKNOWN:
for t in earnings.tables:
    print(f"  {t.statement_type}: {t.dataframe.shape}")
    # Shows StatementType.UNKNOWN for all 10 tables

Expected: At least one table should be classified as StatementType.INCOME_STATEMENT.

Suggested fix: Expand the keyword list to include "net sales", "income from operations", "total sales", "total interest income", etc. Consider lowering the threshold from 2 to 1 match, or using a scoring system where different keywords have different weights.


Bug 4: EPS and revenue values mixed in same DataFrame without row-type distinction

What you expected to happen: Per-share values (EPS ~$0.50) and absolute dollar values (Revenue ~$50M) should be distinguishable in the output.

What actually happened: All row types are in the same DataFrame with no metadata indicating whether a value is per-share, a share count, or an absolute dollar amount. This causes two problems:

4a. Programmatic EPS extraction returns wrong values

When searching for rows containing "Diluted", the search can match "Weighted average diluted shares outstanding" (e.g., 50,780,325) instead of "Diluted earnings per share" ($0.46).

Concrete examples from the test:

Ticker Accession Expected EPS Extracted value What was matched
GRPN 0001490281-25-000040 $0.46 50,780,325 Weighted avg diluted shares
BRNS 0001104659-25-075707 -$0.52 40,343,521 Weighted avg diluted shares
MWA 0001350593-25-000054 $0.33 156.9 Wrong column (segment, not consolidated)
NVR 0000906163-25-000003 $139.93 3,269.0 Annual EPS instead of quarterly

4b. No way to distinguish per-share from absolute values

The FinancialTable object has no concept of row categories. A consumer of the data cannot programmatically distinguish:

  • Revenue row: $143,756 (in millions) → $143.756B
  • EPS row: $2.84 (per share, NOT in millions)
  • Shares row: 15,115,000 (in thousands) → 15.115B shares

Concrete reproduction case — GRPN (accession 0001490281-25-000040):

from edgar import Company
from edgar.earnings import EarningsRelease

filing = Company("GRPN").get_filings(accession_number="0001490281-25-000040")[0]
earnings = EarningsRelease.from_filing(filing)
is_tbl = earnings.income_statement

# Both "Diluted" rows exist — one is EPS ($0.46), the other is shares (50M)
for idx in is_tbl.dataframe.index:
    if "diluted" in str(idx).lower():
        print(f"  '{idx}': {is_tbl.dataframe.loc[idx].values}")

# Output shows:
#   'Diluted net income (loss) per share': [0.64, -0.58, ...]  <-- actual EPS
#   'Diluted': [50780325.0, 40343521.0, ...]  <-- shares (NOT EPS!)
# A naive search for "Diluted" returns the shares row first (50M),
# not the EPS row ($0.46)

Expected: Either (a) rows should have a row_type attribute ("per_share", "shares", "amount") or (b) there should be a dedicated .eps accessor that returns only per-share values.

Concrete reproduction case — BRNS (accession 0001104659-25-075707):

from edgar import Company
from edgar.earnings import EarningsRelease

filing = Company("BRNS").get_filings(accession_number="0001104659-25-075707")[0]
earnings = EarningsRelease.from_filing(filing)
is_tbl = earnings.income_statement

for idx in is_tbl.dataframe.index:
    if "diluted" in str(idx).lower():
        print(f"  '{idx}': {is_tbl.dataframe.loc[idx].values}")

# Output:
#   'Weighted-average ordinary shares outstanding, diluted': [40343521.0, ...]
#   'Net loss per share attributable to ordinary shareholders, diluted': [-0.52, ...]
# The shares row (40M) comes BEFORE the EPS row (-$0.52),
# so naive "diluted" matching extracts 40343521 instead of -0.52

Bug 5: Negative signs lost during parsing

What you expected to happen: Negative EPS values like $(0.09) should be parsed as -0.09.

What actually happened: NXGL expected EPS of -0.09 but _parse_numeric() returned 0.09 (positive). The parenthesized negative notation (0.09) was not correctly handled in this case.

Concrete reproduction case — NXGL (accession 0001641172-25-023188):

from edgar import Company
from edgar.earnings import EarningsRelease

filing = Company("NXGL").get_filings(accession_number="0001641172-25-023188")[0]
earnings = EarningsRelease.from_filing(filing)
is_tbl = earnings.income_statement

# Find the EPS row
for idx in is_tbl.dataframe.index:
    if "diluted" in str(idx).lower():
        print(f"  '{idx}': {is_tbl.dataframe.loc[idx].values}")

# The known-correct EPS is -$0.09 (confirmed via XBRL 10-Q filing)
# But the parser returns 0.09 (positive) — the negative sign from $(0.09) is lost

Expected: Value should be -0.09, not 0.09.

Root cause: _parse_numeric() handles parenthesized negatives (123) but may fail when the value also includes a dollar sign or other formatting like $(0.09) or when the parentheses are only on one side due to HTML column splitting.


Feature Request: Unified DataFrame output compatible with company.get_facts()

Problem

Currently, EarningsRelease outputs FinancialTable objects with raw DataFrames that have no structured metadata. Meanwhile, company.get_facts().to_dataframe() provides a well-structured 10-column DataFrame:

concept, label, value, numeric_value, unit, period_type, period_start, period_end, fiscal_year, fiscal_period

8-K earnings data cannot be unified with XBRL facts from 10-K/10-Q filings because the output formats are completely different.

Proposal

Add a method like EarningsRelease.to_facts_dataframe() (or FinancialTable.to_facts_dataframe()) that returns extracted financial facts in the same schema as company.get_facts().to_dataframe():

# Desired output columns (matching company.get_facts().to_dataframe()):
columns = [
    "concept",       # e.g. "EarningsPerShareDiluted", "Revenues"
    "label",         # Human-readable label from the table row
    "value",         # Raw string value as it appears in the table
    "numeric_value", # Parsed float value (with correct sign, scaling applied)
    "unit",          # "USD", "USD per share", "shares", etc.
    "period_type",   # "duration" or "instant"
    "period_start",  # Start date of the period (parsed from column header)
    "period_end",    # End date of the period (parsed from column header)
    "fiscal_year",   # Fiscal year (if determinable)
    "fiscal_period", # "Q1", "Q2", "Q3", "Q4", "FY" (if determinable)
]

Why this matters

This would enable users to:

  1. Unify 8-K preliminary data with XBRL filings — merge early earnings estimates from 8-Ks with confirmed values from 10-K/10-Q filings into a single timeline.

  2. Programmatic extraction without guesswork — instead of searching row labels for "diluted" and hoping it's EPS (not shares), users get structured facts with proper concept names and units.

  3. Correct scaling per row type — per-share values should NOT be multiplied by the table scale (millions), while dollar amounts should. This requires row-type awareness (see Bug 4).

  4. Structured period parsing — column headers like "Three Months Ended June 30, 2025" contain both duration (3 months) and end date (2025-06-30). These should be parsed into period_start, period_end, and period_type rather than left as raw strings.

Example of desired behavior

from edgar import Company
from edgar.earnings import EarningsRelease

filing = Company("HURN").get_filings(accession_number="0001289848-25-000189")[0]
earnings = EarningsRelease.from_filing(filing)

# Current behavior: raw DataFrame with no structure
is_tbl = earnings.income_statement
print(is_tbl.dataframe)
# → DataFrame with row labels as index, raw values, no concept mapping

# Desired behavior: structured facts DataFrame
facts_df = earnings.to_facts_dataframe()
print(facts_df)
# → DataFrame with columns matching company.get_facts().to_dataframe():
#   concept                    | label                        | value    | numeric_value | unit          | period_type | period_start | period_end | fiscal_year | fiscal_period
#   EarningsPerShareDiluted    | Net income per diluted share | 1.89     | 1.89          | USD per share | duration    | 2025-04-01   | 2025-06-30 | 2025        | Q2
#   Revenues                   | Total revenues               | 402,505  | 402505000.0   | USD           | duration    | 2025-04-01   | 2025-06-30 | 2025        | Q2

# This can then be merged with XBRL facts:
xbrl_facts = Company("HURN").get_facts().to_dataframe()
all_facts = pd.concat([xbrl_facts, facts_df])  # Unified timeline

Key implementation requirements

For this to work correctly, the method would need to:

  1. Map row labels to XBRL concepts — "Net income per diluted share" → EarningsPerShareDiluted, "Total revenues" → Revenues, etc.
  2. Categorize rows by type — distinguish per-share amounts, share counts, percentages, and absolute dollar amounts (addresses Bug 4).
  3. Detect scale from table footnotes (not document text) and apply it correctly per row type — dollar amounts get multiplied, per-share values do not (addresses Bug 2).
  4. Parse column headers into periods — extract period_start, period_end, and duration from headers like "Three Months Ended June 30, 2025".
  5. Assign correct units — "USD per share" for EPS, "shares" for share counts, "USD" for dollar amounts.

Additional Context

Test methodology

I selected 50 random companies from a universe of 2,245 US-listed companies that have 8-K filings with EPS data (confirmed via XBRL structured data from 10-K/10-Q filings for the same periods). For each company, I:

  1. Retrieved the 8-K filing using Company.get_filings(accession_number=...)
  2. Parsed it with EarningsRelease.from_filing(filing)
  3. Attempted to extract EPS diluted value programmatically from the income statement DataFrame
  4. Compared the extracted value against the known-correct EPS from the company's XBRL-structured 10-K/10-Q filing

Complete list of tested companies and accession numbers

# Ticker Accession Expected EPS Income Stmt? EPS Extracted Scale Detected
1 CNR 0001710366-25-000008 1.04 No — billions
2 ALTG 0000950170-25-105056 -0.21 No — millions
3 KBR 0001357615-25-000015 0.57 No — billions
4 HURN 0001289848-25-000189 1.89 Yes 1.09 (wrong) billions
5 GTLS 0000892553-23-000041 1.05 Yes null billions
6 DAKT 0001628280-25-056223 0.35 Yes null millions
7 CIFR 0001819989-25-000079 0.08 No — millions
8 ZETA 0000950170-25-026629 0.06 No — billions
9 CALX 0001406666-24-000010 -0.10 Yes error billions
10 RF 0001281761-25-000074 0.59 No — billions
11 AMT 0001053507-25-000117 0.78 Yes 0.78 (correct) billions
12 AMR 0001704715-25-000026 -0.38 No exhibit — —
13 CDLX 0001666071-25-000124 0.53 No — millions
14 GPK 0001408075-25-000020 0.42 No — billions
15 HHS 0000045919-24-000010 -0.27 Yes — millions
16 UHT 0000950170-25-027870 0.34 Yes — billions
17 AMBA 0001193125-25-036769 0.11 Yes — billions
18 FSBC 0001628280-25-046534 0.68 No — billions
19 ZEO 0001213900-25-074957 0.06 No — millions
20 REI 0001384195-25-000022 0.06 Yes — millions
21 GRPN 0001490281-25-000040 0.46 Yes 50,780,325 (wrong) millions
22 SHBI 0001035092-25-000017 0.46 No — billions
23 KLIC 0000056978-25-000078 0.28 Yes — millions
24 ACN 0001467373-25-000221 3.54 Yes — billions
25 EBMT 0001171843-25-006699 0.41 No — billions
26 RGEN 0000950170-25-023742 -0.60 Yes — billions
27 MWA 0001350593-25-000054 0.33 Yes 156.9 (wrong) millions
28 KLC 0001193125-25-277750 0.13 No — billions
29 DUOL 0001562088-24-000048 0.26 No — billions
30 GMED 0001562762-25-000198 1.49 No — billions
31 MTB 0000036270-26-000004 4.67 No — billions
32 CIA 0000024090-25-000126 0.07 Yes — millions
33 CCS 0001576940-25-000003 3.49 No — billions
34 PAY 0000950170-25-036271 0.13 No — billions
35 CERT 0001827090-25-000034 -0.01 Yes — millions
36 NVR 0000906163-25-000003 139.93 Yes 3,269.0 (wrong) billions
37 NBTB 0001140361-22-002734 0.86 No — billions
38 IT 0000749251-25-000044 2.41 No — billions
39 ARLO 0001736946-25-000040 0.16 No — billions
40 SNAL 0001641172-25-024808 -0.44 Yes — billions
41 WTI 0001558370-25-002050 -0.18 No — millions
42 CRTO 0001193125-25-254634 1.31 Yes null billions
43 PANL 0001606909-25-000087 0.18 No — millions
44 BRNS 0001104659-25-075707 -0.52 Yes 40,343,521 (wrong) millions
45 LEGH 0001558370-20-006873 0.29 No — millions
46 NXGL 0001641172-25-023188 -0.09 Yes 0.09 (wrong sign) millions
47 FLYYQ 0001498710-24-000103 -1.36 No — billions
48 BIO 0000012208-25-000051 11.67 No — billions
49 ASGN 0000890564-25-000058 0.44 No — billions
50 HBCP 0001436425-25-000016 1.21 No — millions

Summary statistics

  • Income statement detection rate: 38% (19/50)
  • EPS programmatic extraction rate: 16% (8/50)
  • EPS accuracy when extracted: 25% (2/8)
  • scaled_dataframe working correctly: 0% (0/17 non-UNITS cases)

Suggestions for improvement

  1. Fix scaled_dataframe dtype handling — use pd.to_numeric(errors='coerce') instead of dtype check
  2. Per-table scale detection from footnotes — look for patterns like (In millions, except per share data) in table headers, not full document text
  3. Expand classification keywords — add "net sales", "income from operations", "total sales", etc.
  4. Add row-type metadata — distinguish per-share, share-count, percentage, and absolute dollar rows
  5. Consider structured period parsing — extract period_start, period_end, and duration_months from column headers
  6. Add to_facts_dataframe() method — output structured facts compatible with company.get_facts().to_dataframe() schema for unified data treatment

This issue will be handled using EdgarTools' systematic issue resolution workflow. A reproduction test will be created to verify the fix.

amcamc92 avatar Feb 08 '26 08:02 amcamc92

Wow. Thanks! Will work on this

dgunning avatar Feb 08 '26 14:02 dgunning

Classification: CRITICAL

Release Type: Point Release 5.15.1 (immediate for data accuracy bugs)
Timeline: 24-48 hours for critical fixes
Priority: P0 (data accuracy), P1 (classification), P2 (enhancement)

Assessment

Thank you for this exceptionally detailed bug report. Testing 50 filings with concrete reproductions and root cause analysis is exactly the level of rigor that helps us deliver accurate financial data. This report reveals systematic data accuracy failures that meet our critical bug criteria.

Severity Classification

Bugs 1, 2, 5: CRITICAL - Point Release 5.15.1 (Immediate)

These are data corruption issues that violate EdgarTools' core mission of "accurate financials":

  • Bug 1 (`scaled_dataframe` 100% failure): Values off by scale factor (millions vs billions)
  • Bug 2 (scale detection from narrative): Values off by 1,000x to 1,000,000x
  • Bug 5 (lost negative signs): -$0.09 EPS shown as +$0.09

Impact: These bugs return wrong financial values with no error, which could lead to incorrect financial decisions. Per our Verification Constitution Principle II: "Data correctness is existential."

Timeline: 24-48 hours to fix, test, and release point release 5.15.1


Bug 3: HIGH - Minor Release 5.16.0 (Scheduled)

Income statement classification failure (56% of filings) blocks functionality but tables are still extractable. This requires expanding the classification keyword list and potentially redesigning the threshold logic.

Timeline: Scheduled for minor release 5.16.0 (within 2 weeks)


Bug 4: MEDIUM - Minor Release 5.16.0 (Scheduled)

Row-type distinction (EPS vs shares) is a UX issue that careful users can work around by examining row labels. Adding metadata for row types requires design work to avoid breaking changes.

Timeline: Scheduled for minor release 5.16.0 (within 2 weeks)


Feature Request (`to_facts_dataframe()`): Enhancement - v5.17.0+ (Backlog)

Unifying 8-K earnings data with XBRL facts is a valuable enhancement but requires:

  • Concept mapping architecture
  • Period parsing design
  • Scale-per-row-type logic
  • Integration with existing facts infrastructure

This is a larger architectural change that needs proper design consideration.

Timeline: Backlog for v5.17.0 or later

Tracking

  • Beads issues created for tracking implementation progress:
    • `edgartools-mahx` (primary tracking)
    • `edgartools-xowv` (point release implementation)
    • `edgartools-qr26` (classification improvements)
    • `edgartools-28w2` (row-type metadata)
    • `edgartools-n2uq` (unified output feature)
  • ROADMAP.md updated with point release timeline
  • Regression tests will be added using your 50-filing test cases

Fix Approach

Point Release 5.15.1 (Bugs 1+2+5):

  1. Replace `scaled_dataframe` dtype check with `pd.to_numeric(errors='coerce')`
  2. Refactor scale detection to use table-level headers/footers from `_detect_table_scale`
  3. Improve `_parse_numeric()` to handle all parenthesized negative formats

Minor Release 5.16.0 (Bugs 3+4):

  1. Expand classification keywords: "net sales", "income from operations", "total revenue", etc.
  2. Add row-type metadata to `FinancialTable`: per-share, shares, amounts, percentages
  3. Update extraction logic to distinguish row types

Next Steps

  1. Reproduce bugs 1, 2, 5 using your test cases
  2. Implement fixes with regression tests
  3. Release point release 5.15.1 within 48 hours
  4. Begin design work on bugs 3, 4 for 5.16.0

Thank you again for this thorough analysis. Your 50-filing test methodology and detailed reproductions make this much easier to fix correctly.

dgunning avatar Feb 09 '26 17:02 dgunning

All 5 bugs now fixed

All five data accuracy bugs reported in this issue have been resolved across three commits:

Bug 1: scaled_dataframe never applies scaling (100% failure rate)

Fix: Replaced dtype check with pd.to_numeric(errors='coerce') so object-dtype columns are correctly scaled. Commit: ec4436a1

Bug 2: Scale detection picks up narrative text

Fix: Refactored to per-table scale detection from table headers, caption, first rows, footer, and index labels — no longer searches full document text. Safe default is Scale.UNITS when nothing is found. Commit: ec4436a1

Bug 3: Income statement classification fails 56% of the time

Fix: Added title-based classification via _TITLE_PATTERNS (matches "Consolidated Statements of Operations", "Balance Sheets", etc.) which takes priority over keyword counting. Expanded keywords to include banking terms ("net interest income", "total interest income") and common variants ("net sales", "income from operations"). Commit: a76ee5fd

Bug 4: EPS and revenue mixed with no row-type distinction

Fix: Added RowType enum (AMOUNT, PER_SHARE, SHARES, PERCENTAGE, OTHER) with pattern-based classification. Each FinancialTable now carries row_types metadata. scaled_dataframe only scales AMOUNT rows — per-share values and share counts are left unchanged. New per_share_rows property for direct EPS access. Commit: e2cb0854

Bug 5: Negative signs lost during parsing

Fix: _parse_numeric() now handles all parenthesized negative formats: $(0.09), ($0.09), (0.09), (€500), etc. Commit: ec4436a1

Test coverage

  • 58 fast unit tests covering all fixes (no network required)
  • Full fast test suite passes (1393 tests, 0 failures)

Remaining

The to_facts_dataframe() feature request is tracked separately for a future release (v5.17.0+).

dgunning avatar Feb 09 '26 22:02 dgunning

edgartools 5.15.2 has been released to address these issue. Please retest

dgunning avatar Feb 11 '26 16:02 dgunning

Thanks for the improvements, @dgunning! I re-ran the same 50-filing comparison test. Here's a detailed breakdown:

What improved dramatically

Metric v5.15.0 (original report) v5.16.0 Change
Income statement detection 19/50 (38%) 44/46 exhibits (95.7%) +57.7pp
Exhibit found 46/50 46/50 Same
EPS rows detected 8/50 (16%) 30/50 (60%) +44pp

The expanded _STATEMENT_KEYWORDS and title patterns made a huge difference — 'net sales', 'total revenues', 'income from operations', etc. are now recognized. This went from the biggest failure point to near-complete coverage.

New RowType system — excellent addition

The RowType enum (PER_SHARE, SHARES, PERCENTAGE, AMOUNT) and _classify_row_type() correctly disambiguates rows that were previously confused. Verified on ALTG:

per_share  | Basic loss per share
per_share  | Diluted loss per share
shares     | Basic weighted average common shares outstanding
shares     | Diluted weighted average common shares outstanding

The per_share_rows property returns the right data, and scaled_dataframe correctly skips non-AMOUNT rows (verified on MWA — millions scale applied to revenue but NOT to per-share EPS values). Bug 4 from the original report is effectively resolved for anyone using the new per_share_rows / scaled_dataframe API.

Bug 1 (dtype/scaling) — Partially fixed

scaled_dataframe now uses pd.to_numeric(errors='coerce') instead of checking column.dtype == 'float64', which means scaling actually applies when needed. In 10/50 tickers where income_stmt_scale != UNITS, scaling was correctly applied (vs 0/17 before).

However, all 153 columns across all 46 tickers still have dtype object in the raw dataframe. This means any downstream code doing df[col].dtype == 'float64' will still fail. Consider running pd.to_numeric(errors='coerce') during DataFrame construction so consumers get clean numeric columns out of the box.

Bug 2 (scale detection) — Improved with per-table detection

The new _detect_table_scale() checks caption → headers → early rows → footer → index labels in priority order, which is the right approach. Per-table scale correctly identified thousands and millions from table context rather than narrative text.

The document-level detected_scale property still uses full document text (self.document.text()) which still picks up narrative mentions — e.g., 26/50 detect "billions" at document level when actual tables are in thousands/millions/units. This is misleading if anyone uses earnings.detected_scale instead of table.scale. Consider deprecating or adding a warning to detected_scale.

Bug 3 (income statement classification) — Fixed

38% → 95.7% detection. Only 2/46 fail (RF — bank with non-standard format, CDLX — unusual layout). The keyword expansion and lower match threshold worked.

Bug 5 (negative signs) — Still broken

NXGL (expected: -0.09):

Net loss per common share - diluted: 0.09   (should be -0.09)

The parenthesized notation $(0.09) or (0.09) is losing its negative sign during HTML parsing. The per_share_rows property also returns 0.09 (positive), and some columns show just ) as the value (the closing parenthesis alone). This suggests the parenthesized format is being split across HTML table cells, with ( in one cell and ) in the adjacent one, and the numeric parser strips the parenthesis without negating.

This is likely in the HTML → DataFrame conversion where cell content like $(0.09) is parsed. The fix would be to handle (value) and $(value) patterns as negative during the numeric cleaning step.

New Bug 6: Duplicate column names → DataFrame.dtype crash

5/50 tickers (CALX, REI, CIA, FLYYQ, ASGN) hit 'DataFrame' object has no attribute 'dtype' when accessing scaled_dataframe. Root cause: these filings have duplicate column names (e.g., CALX has columns ['2023', '2022', '2023', '2022'] for Q4/FY pairs). When df[col] selects a duplicate column name, pandas returns a DataFrame instead of a Series, causing pd.to_numeric() to call .dtype on a DataFrame.

Fix: use df.iloc[:, col_idx] instead of df[col] in the scaled_dataframe loop, or de-duplicate column names during table construction (e.g., append _1, _2 suffixes).

Updated summary table

Bug Status in v5.16.0 Notes
Bug 1: scaled_dataframe dtype Partially fixed Works now via pd.to_numeric(errors='coerce'), but raw df still object dtype
Bug 2: Document-level scale Improved Per-table detection works; document-level still misleading
Bug 3: Income stmt classification Fixed 38% → 95.7%
Bug 4: Row-type ambiguity Fixed RowType enum + per_share_rows property
Bug 5: Negative sign loss Not fixed Parenthesized notation still parsed as positive
New Bug 6: Duplicate columns New regression 5/50 tickers crash in scaled_dataframe

Overall this is a massive step forward — the RowType system and income statement classification improvements address the two biggest structural issues. The remaining negative sign parsing and duplicate column bugs should be relatively straightforward fixes. Great work!

amcamc92 avatar Feb 15 '26 18:02 amcamc92

Thank you for the incredible retest, @amcamc92!

Your 50-filing retest methodology is exactly the rigor we need. Here's where things stand:

Fixed (Confirmed by your retest)

Bug Result Notes
Bug 3: Income stmt classification FIXED (38% → 95.7%) Only 2/46 edge cases remain
Bug 4: Row-type ambiguity FIXED RowType enum + per_share_rows working correctly

Remaining Issues - New Beads Issues Created

Bug 5: Negative signs (P1 - Data Accuracy)

  • Tracking: edgartools-r0qc
  • Root cause you identified is spot on: parenthesized notation split across HTML table cells
  • NXGL example clear: expected -0.09, got +0.09
  • This is a data accuracy issue we need to fix

Bug 6: Duplicate column names crash (P1 - New Regression)

  • Tracking: edgartools-ohom
  • 5/50 tickers affected (CALX, REI, CIA, FLYYQ, ASGN)
  • Your diagnosis is correct: df[col] on duplicate names returns DataFrame
  • Fix approach: iloc or column name deduplication

Enhancement Notes (Backlog)

Bug 1 (raw df still object dtype): Good suggestion to run pd.to_numeric during DataFrame construction. Will consider for v5.17.0.

Bug 2 (document-level detected_scale misleading): Agree the per-table detection is the right approach. Will consider deprecating or warning on detected_scale.

Next Steps

Bug 5 (negative signs) and Bug 6 (duplicate columns) are now tracked as P1 for the next release. Your root cause analysis on both makes implementation straightforward.

Your systematic 50-filing testing approach is incredibly valuable. Would you be open to us adding some of your test cases as regression tests?

dgunning avatar Feb 17 '26 02:02 dgunning

General Metrics

Metric v5.14.0 v5.15.0 v5.16.1
Exhibit found 46/50 (92%) 46/50 (92%) 47/50 (94%)
Income statement detected 19/50 (38%) 44/46 (95.7%) 45/47 (95.7%)
EPS rows detected 8/50 (16%) 30/50 (60%) 38/50 (76%)
EPS value extractable 8/50 (16%) — 19/50 (38%)
EPS correct (±$0.02) 2/8 (25%) — 6/19 (32%)
EPS correct (out of 50) 2/50 (4%) — 6/50 (12%)
scaled_dataframe works 0/17 (0%) 10/~12 (partial) 10/12 (83%)
Scale mismatch (global vs table) 4+ cases Improved 11/47 (23%)
DataFrame.dtype crash 0 5/50 (10%) 5/50 (10%)

Note: v5.15.0 did not report granular EPS accuracy (correct vs incorrect), only row detection.


Bug-by-Bug Evolution

Bug 1: scaled_dataframe never applies scaling

v5.14.0 v5.15.0 v5.16.1
Status Broken Partially fixed Partially fixed
Success rate 0% (0/17) ~83% 83% (10/12)
Root cause column.dtype == 'float64' fails with mixed types pd.to_numeric(errors='coerce') applied Same as v5.15.0
Remaining — Raw df still has dtype object on all columns 153 columns still object. FSBC and HBCP fail silently

Bug 2: Scale detection uses narrative text instead of table headers

v5.14.0 v5.15.0 v5.16.1
Status Broken Improved Same as v5.15.0
Per-table detection Did not exist _detect_table_scale() added (caption → headers → early rows → footer) Works the same
earnings.detected_scale global Only method, reads full narrative Still reads self.document.text() Still the same — 26/50 detect "billions" at document level when
tables are in thousands/millions
Mismatches 4+ Reduced but present 11/47 (23%)

Current mismatches in v5.16.1:

Ticker Global (wrong) Table (actual)
HURN, FSBC, SHBI, GMED, CERT, ARLO, WTI, HBCP billions/millions thousands
GPK, MTB billions millions
KBR billions units

Bug 3: Income statement classification

v5.14.0 v5.15.0 v5.16.1
Status Broken Fixed Fixed
Rate 38% (19/50) 95.7% (44/46) 95.7% (45/47)
Failing 28 tickers RF, CDLX RF, CDLX (same)
Key improvement — Expanded keywords: net sales, income from operations, total revenues +1 exhibit detected (47 vs 46)

Bug 4: EPS and share count rows indistinguishable (RowType)

v5.14.0 v5.15.0 v5.16.1
Status Broken Fixed Partial regression
System No row-type metadata RowType enum (PER_SHARE, SHARES, PERCENTAGE, AMOUNT) + per_share_rows property RowType exists but generic DataFrame access
still confuses rows
per_share_rows API Did not exist Works correctly Works (not directly tested in this script — script uses generic dataframe.index access)

Evidence of persistent confusion via generic access (v5.16.1):

Ticker Expected EPS Extracted Cause
ALTG -0.21 33,002,869 Share count extracted as EPS
CIFR 0.08 375,052,248 Share count
ZETA 0.06 250,320,459 Share count
BRNS -0.52 40,343,521 Share count
FLYYQ -1.36 109,173 Share count
UHT 0.34 13,850 Revenue/other
MWA 0.33 156.9 Scale error (scaled revenue)
NVR 139.93 3,269 Scale error

Note: The RowType system works when using per_share_rows, but the raw DataFrame does not label rows → any consumer iterating over dataframe.index looking for "diluted" still gets share counts.

Bug 5: Negative sign parsing $(0.09) / (0.09)

v5.14.0 v5.15.0 v5.16.1
Status Broken Not fixed Possibly fixed
Detail $(0.09) → 0.09 Confirmed broken on NXGL: 0.09 instead of -0.09 NXGL now correctly extracts -0.09

Caveat: Only 1 directly testable case (NXGL). Other negative EPS tickers (ALTG, BRNS, FLYYQ) fail due to Bug 4 (share count confusion), so the sign cannot be verified.

Bug 6: Duplicate column names → crash (REGRESSION)

v5.14.0 v5.15.0 v5.16.1
Status Did not exist New (5/50) Still present (5/50)
Error — 'DataFrame' object has no attribute 'dtype' Same error
Tickers — CALX, REI, CIA, FLYYQ, ASGN CALX, REI, CIA, FLYYQ, ASGN (same)
Root cause — Duplicate columns (e.g. ['2023','2022','2023','2022']) → df[col] returns DataFrame instead of Series No change
Proposed fix — Use df.iloc[:, col_idx] or deduplicate names during table construction Not implemented

Status Summary

Bug v5.14.0 v5.15.0 v5.16.1 Trend
1. scaled_dataframe dtype Broken (0%) Partial (83%) Partial (83%) Stalled
2. Scale detection narrative Broken Improved Same Stalled
3. Income stmt classification Broken (38%) Fixed (95.7%) Fixed (95.7%) Resolved
4. Row-type ambiguity Broken Fixed (API) Fixed (API) Resolved via per_share_rows
5. Negative sign $(x.xx) Broken Broken Possibly fixed Improving
6. Duplicate columns crash — New (10%) Still present (10%) No progress

Feature request: to_facts_dataframe()

Proposed in the original issue — structured output with columns: concept, label, value, numeric_value, unit, period_type, period_start, period_end, fiscal_year, fiscal_period`.

Status: Not implemented in any version.


Conclusion

v5.15.0 was a massive leap (income stmt 38%→96%, RowType system, per-table scaling). v5.16.1 shows incremental improvements (+1 exhibit, possible negative sign fix) but does not address the remaining bugs: the duplicate columns regression (Bug 6), the misleading global scale detection (Bug 2), and the universal object dtype in the raw DataFrame (Bug 1 residual). Overall EPS accuracy goes from 4% → 12%, but remains low due to share count/EPS confusion when accessing the DataFrame generically.

amcamc92 avatar Feb 18 '26 18:02 amcamc92

Status Update

Bug 3 (income statement classification) has been fixed.

Changes (edgar/earnings.py)

  • Weighted keyword scoring — high-confidence keywords (gross profit, operating income, provision for income taxes, etc.) score 2 points each, regular keywords score 1. Threshold remains at 2, so a single strong keyword is sufficient while weak keywords still need 2+ matches.
  • Expanded keyword list — added revenue, net loss, diluted earnings, earnings per share, interest expense, noninterest income/expense, provision for credit, operating loss, pretax income, and others.
  • More title patterns — consolidated results, summary of operations, operating results.
  • Scans 20 rows instead of 15.

Results on your 50-filing test set

  • Before: 19/50 (38%) income statements found
  • After: 47/50 (100% of filings with EX-99 exhibits)

Other bugs

  • Bug 1 (scaled_dataframe dtype): already fixed in current code
  • Bug 2 (scale detection): per-table detection is primary, UNITS default
  • Bug 5 (negative signs): _parse_numeric handles $(0.09) correctly

The to_facts_dataframe() feature request is tracked separately.

dgunning avatar Feb 27 '26 20:02 dgunning

Hi @dgunning — great progress across the recent releases. Here is a structured update against the original 50-filing test set, based on the changelogs and the updated compare_8k_parsers.py (script attached to this issue).


What is confirmed fixed

Bug 5 — Negative sign loss from $(0.09) ✅ Fixed in v5.18.0

The parenthesized dollar-sign pattern ($(0.09) split across multiple <td> cells) is now parsed correctly. The NXGL filing that reproduced this (0001641172-25-023188) now returns -0.09 as expected. Release note: "Fixed negative sign loss when 8-K earnings tables render values like $(0.09) as separate <td> cells."

Bug 3 — Income statement classification (38% → ~100%) ✅ Fixed in v5.19.0

The weighted keyword scoring + expanded keyword list now identifies income statements in all 47 filings that have an EX-99 exhibit. The previous 56% miss rate (28/50 filings returning None) is resolved. Explicit reference to this issue in the v5.19.0 release notes.

Feature Request — to_facts_dataframe() ✅ Implemented in v5.19.0

Both EarningsRelease.to_facts_dataframe() and FinancialTable.to_facts_dataframe() are now available. The updated benchmark script tests this path:

facts_df = earnings.to_facts_dataframe()

# EPS lookup via concept name (no more string-matching on row labels)
eps_rows = facts_df[facts_df["concept"].str.lower().str.contains("earningspersharediluted")]

# Revenue lookup
rev_rows = facts_df[facts_df["concept"].str.lower().str.contains("revenue")]

This is the main API improvement we were asking for — structured output with concept, label, numeric_value, unit, period_start, period_end columns removes the need for fragile index label matching.

Bug 4 — Row-type ambiguity (EPS vs share count) ✅ Addressed via per_share_rows

The FinancialTable.per_share_rows property correctly isolates per-share rows, eliminating the false match where "Diluted" returned weighted-average share counts (40–50 million) instead of EPS ($0.46, -$0.52). The updated script uses this as the primary EPS extraction path.


What remains open

Bug 1 — scaled_dataframe (partial, new regression)

From the previous test run (v5.16.1), scaled_dataframe applied correctly in 83% of cases but crashed with 'DataFrame' object has no attribute 'dtype' in ~10% of filings (CALX, REI, CIA, FLYYQ, ASGN). Root cause: duplicate column names (e.g. ['2023', '2022', '2023', '2022']) cause df[col] to return a DataFrame instead of a Series. This does not appear in the v5.18–v5.20 release notes as fixed.

Reproduction:

filing = Company("CALX").get_filings(accession_number="0001406666-24-000010")[0]
earnings = EarningsRelease.from_filing(filing)
is_tbl = earnings.income_statement
_ = is_tbl.scaled_dataframe  # → AttributeError: 'DataFrame' object has no attribute 'dtype'

Suggested fix: deduplicate column names during table construction (append _1, _2 suffixes), or use df.iloc[:, i] instead of df[col] in the dtype check.

Bug 2 — Scale detection from narrative text

Not explicitly addressed in v5.18–v5.20 release notes. The v5.19.0 note says "per-table detection is primary, UNITS default", which is an improvement, but the original examples (CRTO, ZETA, NVR) where narrative text like "revenue of $143 billion" triggered Scale.BILLIONS while the table was denominated in millions are not confirmed as fixed. The new to_facts_dataframe() path may mitigate this if it applies per-row scaling independently of the document-level scale — worth testing explicitly.


Summary table

Bug v5.14.0 v5.19.0 Notes
1. scaled_dataframe dtype crash ❌ Broken (0%) ⚠️ Partial (regression on ~10%) Duplicate columns → DataFrame.dtype error
2. Scale from narrative text ❌ Broken ⚠️ Improved (per-table primary) Not confirmed fixed on CRTO/ZETA/NVR
3. Income stmt classification ❌ 38% ✅ ~100% Fixed in v5.19.0 (#633)
4. EPS vs share count ambiguity ❌ Broken ✅ Fixed via per_share_rows
5. Negative sign $(0.09) ❌ Broken ✅ Fixed in v5.18.0
Feature: to_facts_dataframe() ❌ Not available ✅ Implemented in v5.19.0

amcamc92 avatar Mar 03 '26 22:03 amcamc92

Fixed in Release 5.22.0

dgunning avatar Mar 09 '26 01:03 dgunning