Skip to content

Commit df41d69

Browse files
joshhheoJoshua Heo
andauthored
Allow statement exports to omit metadata (#2035)
Refs #2019 Co-authored-by: Joshua Heo <jhheo1@uci.edu>
1 parent 8696944 commit df41d69

4 files changed

Lines changed: 104 additions & 40 deletions

File tree

‎changelog.d/2019.added.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
**Statement exports can skip metadata lookups.** `Statement.to_dataframe(include_metadata=False)` omits balance, weight, preferred sign, and both parent columns while preserving statement values. On ExxonMobil's FY2022 income statement, median export time was 14 ms without metadata and 119 ms with metadata. (GH #2019)

‎docs/api/xbrl.md‎

Lines changed: 23 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -419,11 +419,17 @@ Render the statement with rich formatting.
419419
```python
420420
def to_dataframe(
421421
self,
422+
period_filter: Optional[str] = None,
423+
period_view: Optional[str] = None,
424+
standard: bool = True,
422425
view: ViewType = None,
423426
*,
424427
include_unit: bool = False,
425428
include_point_in_time: bool = False,
426-
presentation: bool = False
429+
include_standardization: bool = False,
430+
presentation: bool = True,
431+
matrix: bool = False,
432+
include_metadata: bool = True,
427433
) -> pd.DataFrame
428434
```
429435
Convert statement to pandas DataFrame with optional transformations.
@@ -433,40 +439,44 @@ Convert statement to pandas DataFrame with optional transformations.
433439
`include_dimensions`, which was removed in 6.0 (`True` is `"detailed"`, `False` is `"standard"`)
434440
- `include_unit`: Include unit column (USD, shares, etc.) (default: False)
435441
- `include_point_in_time`: Include point-in-time column for instant facts (default: False)
436-
- `presentation`: Apply HTML-matching transformations using preferred_sign (default: False)
437-
- False (default): Raw instance values from XML
442+
- `presentation`: Apply HTML-matching transformations using preferred_sign (default: True)
438443
- True: Transform values to match SEC filing HTML display
444+
- False: Raw instance values from XML
445+
- `include_metadata`: Include the metadata columns below (default: True). Set to
446+
False to skip metadata lookups while preserving the selected rows and values.
439447

440448
**Returns:** DataFrame with the following columns:
441-
- **Core columns**: `concept`, `label`, period columns (dates)
442-
- **Metadata columns** (always included):
449+
- **Core columns**: `concept`, `label`, period columns (dates), `level` (nesting depth),
450+
and `abstract` (whether the row is a heading)
451+
- **Metadata columns** (with `include_metadata=True`):
443452
- `balance` — debit or credit (from XBRL taxonomy)
444453
- `weight` — calculation tree weight (+1 or -1)
445454
- `preferred_sign` — how the value should be displayed (from presentation linkbase)
446-
- `level` — nesting depth in the presentation tree (0=root, 1=section header, 2=line item, etc.)
447-
- `abstract` — True if this row is a section header, not a data row
448455
- `parent_concept` — calculation tree parent (the metric concept this rolls up to for summation math)
449456
- `parent_abstract_concept` — presentation tree parent (the section header this appears under for display hierarchy)
450457
- **Optional columns**: `dimension`, `unit`, `point_in_time`
451458

452459
**Value Modes:**
453-
- **Raw mode** (default): Preserves values exactly as reported in instance document
454-
- **Presentation mode** (`presentation=True`): Applies transformations to match SEC HTML rendering
460+
- **Raw mode** (`presentation=False`): Preserves values exactly as reported in instance document
461+
- **Presentation mode** (default): Applies transformations to match SEC HTML rendering
455462
- Every statement, parentheticals and statements of equity included: a row with preferred_sign=-1 (a negated label on its presentation arc) has its values negated, as the SEC page shows them
456463
- The result does not depend on how the statement was reached (`income_statement()` or `xbrl.statements[role]`)
457464

458465
**Example:**
459466
```python
460467
statement = xbrl.statements.income_statement()
461468

462-
# Raw values (default)
463-
df_raw = statement.to_dataframe()
469+
# Raw values
470+
df_raw = statement.to_dataframe(presentation=False)
464471
# Returns actual XML values + metadata columns
465472

466473
# Presentation mode (matches SEC HTML)
467-
df_presentation = statement.to_dataframe(presentation=True)
474+
df_presentation = statement.to_dataframe()
468475
# Returns transformed values matching 10-K HTML display
469476

477+
df_lean = statement.to_dataframe(include_metadata=False)
478+
# Returns the same displayed values with fewer columns
479+
470480
# Check metadata
471481
print(df_raw[['concept', 'balance', 'weight', 'preferred_sign']].head())
472482

@@ -1120,4 +1130,4 @@ print(dividends_pres[['concept', '2024-09-30']])
11201130
- **[Company API Reference](company.md)** - Working with company data
11211131
- **[Filing API Reference](filing.md)** - Working with individual filings
11221132
- **[Extract Financial Statements Guide](../guides/extract-statements.md)** - Practical examples
1123-
- **[Working with Filing Guide](../guides/working-with-filing.md)** - Filing workflows
1133+
- **[Working with Filing Guide](../guides/working-with-filing.md)** - Filing workflows

‎edgar/xbrl/statements.py‎

Lines changed: 39 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -1180,7 +1180,8 @@ def to_dataframe(self,
11801180
include_point_in_time: bool = False,
11811181
include_standardization: bool = False,
11821182
presentation: bool = True,
1183-
matrix: bool = False) -> Any:
1183+
matrix: bool = False,
1184+
include_metadata: bool = True) -> Any:
11841185
"""Convert statement to pandas DataFrame.
11851186
11861187
Args:
@@ -1206,9 +1207,12 @@ def to_dataframe(self,
12061207
matrix: If True, return matrix format for Statement of Equity (equity components
12071208
as columns, activities as rows). Ignored for non-equity statements.
12081209
Default: False (standard flat format for backwards compatibility).
1210+
include_metadata: Include balance, weight, preferred_sign, parent_concept,
1211+
and parent_abstract_concept columns. Defaults to True.
1212+
Disabling metadata preserves the requested presentation.
12091213
12101214
Returns:
1211-
DataFrame with raw values + metadata (balance, weight, preferred_sign) by default.
1215+
DataFrame with presented values and metadata by default.
12121216
If matrix=True and this is a Statement of Equity, returns pivoted matrix format.
12131217
12141218
Examples:
@@ -1253,13 +1257,20 @@ def to_dataframe(self,
12531257
if df is None or isinstance(df, str) or df.empty:
12541258
return df
12551259

1256-
# Add metadata columns (balance, weight, preferred_sign) - Issue #463
1257-
df = self._add_metadata_columns(df)
1260+
if include_metadata:
1261+
df = self._add_metadata_columns(df)
1262+
elif presentation:
1263+
df = self._add_metadata_columns(df, include_metadata=False)
1264+
1265+
if not include_metadata:
1266+
df = df.drop(columns=[_ROW_SIGN, _ROW_HAS_VALUES, _ROW_PARENT], errors='ignore')
12581267

12591268
# Apply presentation transformation if requested (Issue #463)
12601269
if presentation:
12611270
df = self._apply_presentation(
12621271
df, numeric_only=self.classified_type in _NUMERIC_VALUE_STATEMENTS)
1272+
if not include_metadata:
1273+
df = df.drop(columns='preferred_sign')
12631274

12641275
# Apply matrix transformation for equity statements (Issue edgartools-uqg7)
12651276
if matrix:
@@ -1643,9 +1654,10 @@ def format_number(x):
16431654
# Return DataFrame with nice __repr__
16441655
return df
16451656

1646-
def _add_metadata_columns(self, df: pd.DataFrame) -> pd.DataFrame:
1657+
def _add_metadata_columns(self, df: pd.DataFrame, *, include_metadata: bool = True) -> pd.DataFrame:
16471658
"""
16481659
Add metadata columns (balance, weight, preferred_sign, parent_concept, parent_abstract_concept) to DataFrame.
1660+
When metadata is disabled, prepare only the sign needed for presentation.
16491661
16501662
Issue #463: Users need access to XBRL metadata to understand value transformations.
16511663
Issue #514: Users need parent_concept to understand hierarchy relationships.
@@ -1673,18 +1685,32 @@ def _add_metadata_columns(self, df: pd.DataFrame) -> pd.DataFrame:
16731685
if concept and concept not in raw_data_by_concept:
16741686
raw_data_by_concept[concept] = item
16751687

1676-
# Create metadata dictionaries to populate
1688+
concepts = [concept for concept in df['concept'].unique() if concept]
1689+
preferred_sign_map = {}
1690+
for concept in concepts:
1691+
preferred_signs = raw_data_by_concept.get(concept, {}).get('preferred_signs')
1692+
if preferred_signs:
1693+
preferred_sign_map[concept] = next(iter(preferred_signs.values()))
1694+
1695+
# GH #1657: a row with values takes its own occurrence's sign; the
1696+
# concept's first occurrence speaks only for rows with nothing to sign.
1697+
preferred_sign = df['concept'].map(preferred_sign_map)
1698+
if _ROW_SIGN in df.columns:
1699+
own_signs = df.pop(_ROW_SIGN)
1700+
has_values = df.pop(_ROW_HAS_VALUES).astype(bool)
1701+
preferred_sign = own_signs.where(has_values, preferred_sign)
1702+
1703+
if not include_metadata:
1704+
df['preferred_sign'] = preferred_sign
1705+
return df
1706+
16771707
balance_map = {}
16781708
weight_map = {}
1679-
preferred_sign_map = {}
16801709
parent_concept_map = {} # Calculation tree parent (metric)
16811710
parent_abstract_concept_map = {} # Presentation tree parent (may be abstract)
16821711

16831712
# For each unique concept in the DataFrame
1684-
for concept in df['concept'].unique():
1685-
if not concept:
1686-
continue
1687-
1713+
for concept in concepts:
16881714
# Get balance and weight from facts (concept-level attributes)
16891715
facts_df = self.xbrl.facts.query().by_concept(concept, exact=True).limit(1).to_dataframe()
16901716

@@ -1693,16 +1719,10 @@ def _add_metadata_columns(self, df: pd.DataFrame) -> pd.DataFrame:
16931719
balance_map[concept] = fact.get('balance')
16941720
weight_map[concept] = fact.get('weight')
16951721

1696-
# Get preferred_sign and parent from statement raw data (presentation linkbase)
1722+
# Get parents from the statement's raw data.
16971723
if concept in raw_data_by_concept:
16981724
item = raw_data_by_concept[concept]
16991725

1700-
# preferred_sign is period-specific, so we take the first available value
1701-
preferred_signs = item.get('preferred_signs', {})
1702-
if preferred_signs:
1703-
# Use first period's preferred_sign as representative value
1704-
preferred_sign_map[concept] = next(iter(preferred_signs.values()))
1705-
17061726
# parent_concept from calculation tree (Issue #514 refinement) - metric parent for math
17071727
parent_concept_map[concept] = item.get('calculation_parent')
17081728

@@ -1712,15 +1732,7 @@ def _add_metadata_columns(self, df: pd.DataFrame) -> pd.DataFrame:
17121732
# Add metadata columns
17131733
df['balance'] = df['concept'].map(balance_map)
17141734
df['weight'] = df['concept'].map(weight_map)
1715-
# GH #1657: a row with values takes its own occurrence's sign; the
1716-
# concept's first occurrence speaks only for rows with nothing to sign.
1717-
concept_signs = df['concept'].map(preferred_sign_map)
1718-
if _ROW_SIGN in df.columns:
1719-
own_signs = df.pop(_ROW_SIGN)
1720-
has_values = df.pop(_ROW_HAS_VALUES).astype(bool)
1721-
df['preferred_sign'] = own_signs.where(has_values, concept_signs)
1722-
else:
1723-
df['preferred_sign'] = concept_signs
1735+
df['preferred_sign'] = preferred_sign
17241736
df['parent_concept'] = df['concept'].map(parent_concept_map)
17251737
# GH #1705: each row's own presentation parent, so a concept presented
17261738
# under two parents keeps both; dimensional rows follow their line.
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
"""GitHub Issue: https://github.com/dgunning/edgartools/issues/2019"""
2+
3+
from pathlib import Path
4+
5+
import pytest
6+
from pandas.testing import assert_frame_equal
7+
8+
from edgar.xbrl import XBRL
9+
10+
pytestmark = pytest.mark.fast
11+
12+
METADATA_COLUMNS = [
13+
"balance", "weight", "preferred_sign", "parent_concept", "parent_abstract_concept",
14+
]
15+
16+
17+
@pytest.fixture(scope="module")
18+
def apple():
19+
# Apple's FY2023 10-K, SEC accession 0000320193-23-000106.
20+
return XBRL.from_directory(Path("tests/fixtures/xbrl/aapl/10k_2023"))
21+
22+
23+
@pytest.mark.parametrize("presentation, capex", [(True, -10_959_000_000), (False, 10_959_000_000)])
24+
def test_omit_metadata_preserves_cash_flow_values(apple, presentation, capex):
25+
statement = apple.statements.cash_flow_statement()
26+
full = statement.to_dataframe(presentation=presentation, include_unit=True)
27+
lean = statement.to_dataframe(presentation=presentation, include_unit=True, include_metadata=False)
28+
29+
assert_frame_equal(lean, full.drop(columns=METADATA_COLUMNS))
30+
capex_rows = lean["concept"] == "us-gaap_PaymentsToAcquirePropertyPlantAndEquipment"
31+
assert lean.loc[capex_rows, "2023-09-30 (FY)"].item() == capex
32+
33+
34+
def test_omit_metadata_preserves_equity_matrix(apple):
35+
statement = apple.statements.statement_of_equity()
36+
full = statement.to_dataframe(matrix=True)
37+
lean = statement.to_dataframe(matrix=True, include_metadata=False)
38+
39+
assert_frame_equal(lean, full)
40+
net_income = lean["concept"] == "us-gaap_NetIncomeLoss"
41+
assert lean.loc[net_income, "Retained earnings/(Accumulated deficit)"].item() == 96_995_000_000

0 commit comments

Comments
 (0)