diff --git a/changelog.d/1824.added.md b/changelog.d/1824.added.md new file mode 100644 index 000000000..254ead40a --- /dev/null +++ b/changelog.d/1824.added.md @@ -0,0 +1 @@ +**Quarterly financials can read untagged 6-K income tables.** A bounded recent-filing search skips monthly notices; TSM's earnings release supplies TWD 763,064 million net income. (GH #1824) diff --git a/docs/api/company.md b/docs/api/company.md index d1cfa6781..fd77b955e 100644 --- a/docs/api/company.md +++ b/docs/api/company.md @@ -330,19 +330,25 @@ if financials: ### get_quarterly_financials() -Get financial statements from the latest 10-Q filing. +Read the latest 10-Q or search recent unamended 6-Ks for quarterly results. ```python -def get_quarterly_financials(self) -> Optional[Financials] +def get_quarterly_financials(self, *, max_6k_filings: int = 10) -> Financials | QuarterlyIncome | None ``` -**Returns:** `Financials` object from latest quarterly report +XBRL returns `Financials`. An eligible HTML earnings exhibit returns +`QuarterlyIncome`, with income getters and an income table. The search +examines at most `max_6k_filings` filings from the last 183 days and returns +`None` if no supported quarterly result is available. **Example:** ```python +from edgar import QuarterlyIncome + quarterly = company.get_quarterly_financials() -if quarterly: - q_income = quarterly.income_statement().to_dataframe() +if quarterly is not None: + income = quarterly if isinstance(quarterly, QuarterlyIncome) else quarterly.income_statement() + q_income = income.to_dataframe() quarterly_revenue = quarterly.get_revenue() ``` diff --git a/docs/guides/financial-data.md b/docs/guides/financial-data.md index 2e25df1a3..dc0bf96c2 100644 --- a/docs/guides/financial-data.md +++ b/docs/guides/financial-data.md @@ -141,16 +141,37 @@ income = quarterly.income_statement() ### Foreign private issuers (6-K) -A foreign private issuer such as TSMC files its annual report on Form 20-F with XBRL, so `get_financials()` works as usual. Its quarterly results arrive on Form 6-K, where the numbers sit in an HTML press release (an EX-99 exhibit) with no XBRL behind it. For those companies `get_quarterly_financials()` returns `None`, because there are no statements to read. +When a company has no 10-Q, `get_quarterly_financials()` checks up to 10 +unamended 6-Ks filed in the last 183 days, newest first. Each filing's XBRL +takes priority. An HTML earnings exhibit with identifiable quarterly columns +and explicit units can supply a `QuarterlyIncome` result. A monthly notice +alone cannot. The search limit can be set with `max_6k_filings`. -To get the quarter's figures, read the press release tables with `EarningsRelease`: +```python +from edgar import Company, Financials, QuarterlyIncome + +quarterly = Company("TSM").get_quarterly_financials() +if isinstance(quarterly, QuarterlyIncome): + print(quarterly.get_net_income()) # Actual currency units + print(quarterly.to_dataframe(include_unit=True)) + print(quarterly.source_url, quarterly.notes) +elif isinstance(quarterly, Financials): + print(quarterly.balance_sheet()) +``` + +The income table preserves the exhibit's period labels. A `period_offset` +of 1 selects the next reported comparison column, which can be a year earlier. +`to_dataframe()` scales monetary amounts to currency units and leaves per-share +values as reported. Generic EPS has no inferred basic or diluted classification. +When no supported filing is found, the method returns `None`. + +To inspect a particular historical release and read the amounts in their +original printed scale, use its accession: ```python -from edgar import Company, find +from edgar import find from edgar.earnings import EarningsRelease -Company("TSM").get_quarterly_financials() # None: TSMC's 6-Ks carry no XBRL - filing = find("0001046179-26-000726") # TSMC's 3Q26 earnings release, filed 2026-10-15 release = EarningsRelease.from_filing(filing) release.income_statement.dataframe diff --git a/docs/guides/sixk-data-object-guide.md b/docs/guides/sixk-data-object-guide.md index a71234709..49740a42e 100644 --- a/docs/guides/sixk-data-object-guide.md +++ b/docs/guides/sixk-data-object-guide.md @@ -151,7 +151,7 @@ if six_k.financials: financials.cash_flow_statement ``` -Most earnings data in 6-K filings is in HTML tables inside EX-99.x exhibits, not in XBRL. To read those tables, use `EarningsRelease.from_filing(filing)` from `edgar.earnings`, which returns the press release's income statement and other tables as DataFrames. This is also why `Company.get_quarterly_financials()` returns `None` for most foreign private issuers. +Most earnings data in 6-K filings is in HTML tables inside EX-99.x exhibits, not in XBRL. To read those tables, use `EarningsRelease.from_filing(filing)` from `edgar.earnings`, which returns the press release's income statement and other tables as DataFrames. For the latest quarterly result, `Company.get_quarterly_financials()` also checks recent 6-K earnings exhibits for an income table. See [Financial data](financial-data.md#foreign-private-issuers-6-k) for its return types. --- diff --git a/docs/upgrade/6.1.md b/docs/upgrade/6.1.md index ffd8b6849..a936b1bdf 100644 --- a/docs/upgrade/6.1.md +++ b/docs/upgrade/6.1.md @@ -13,6 +13,18 @@ see [Getting help](6.0.md#getting-help). --- +## Quarterly income from an untagged 6-K + +`Company.get_quarterly_financials()` can now return `QuarterlyIncome` for a +recent 6-K with a supported HTML income table. In 6.0 this case returned +`None`. The TSMC exhibit in filing `0001046179-26-000726` reports net income +of NT$763,064 million. Call `result.to_dataframe()` on a `QuarterlyIncome` +to read its income table directly. Callers that need a balance sheet or cash flow statement +should first check `isinstance(result, Financials)`. +See the [6-K example](../guides/financial-data.md#foreign-private-issuers-6-k). + +--- + ## `EntityFiling.acceptance_datetime` is deprecated **What changed.** The value `Company(...).get_filings()` gives each filing as diff --git a/edgar/__init__.py b/edgar/__init__.py index 4e1eee26e..d8bc2e6ce 100644 --- a/edgar/__init__.py +++ b/edgar/__init__.py @@ -53,6 +53,7 @@ "get_entity", "get_icon_from_ticker", ), "edgar.filesystem": ("is_cloud_storage_enabled", "sync_to_cloud", "use_cloud_storage"), + "edgar._html_financials": ("QuarterlyIncome",), "edgar.financials": ("Financials", "MultiFinancials"), "edgar.funds": ("Fund", "FundClass", "FundCompany", "FundSeries", "find_fund", "find_funds"), "edgar.funds.ncen": ("NCEN_FORMS", "FundCensus"), @@ -165,7 +166,7 @@ "ValidationError", # -- Financial statements ------------------------------------------------ - "Financials", "MultiFinancials", "XBRL", + "Financials", "MultiFinancials", "QuarterlyIncome", "XBRL", # -- Funds --------------------------------------------------------------- "Fund", "FundCompany", "FundClass", "FundSeries", diff --git a/edgar/_html_financials.py b/edgar/_html_financials.py new file mode 100644 index 000000000..0542a69e3 --- /dev/null +++ b/edgar/_html_financials.py @@ -0,0 +1,380 @@ +"""Conservative, income-statement-only fallback for untagged 6-K exhibits. + +Reuse the earnings parser; do not fabricate an XBRL object or infer missing +statements, currencies, or quarterly periods from the filing date. +""" +import json +import re +from calendar import monthrange +from dataclasses import dataclass, field +from datetime import date, timedelta +from numbers import Real +from typing import TYPE_CHECKING, Optional + +import pandas as pd + +from edgar.earnings import ( + EarningsRelease, + FinancialTable, + RowType, + _currency, + _declared_table_units, + _is_change_column, + _names_currency, + _parse_period_header, + _table_context, + find_earnings_exhibits, +) +from edgar.exceptions import ValidationError +from edgar.xbrl.presentation import ViewType, normalize_view + +if TYPE_CHECKING: + from edgar._filings import Filing + + +_REVENUE = ('total revenue', 'total revenues', 'net sales', 'net revenue', 'revenue', 'revenues') +_NET_INCOME = ('net income attributable to owners of the parent', + 'net income attributable to shareholders of the parent', + 'net income', 'net income (loss)', 'net loss', 'net earnings') +# These are existing standard concept identifiers, not invented source tags. +# Exact labels only: generic "Net income" does not establish parent attribution, +# and generic "EPS" does not establish basic versus diluted earnings per share. +_STANDARD_CONCEPTS = { + **dict.fromkeys(_REVENUE, 'Revenue'), + 'gross profit': 'GrossProfit', + 'gross profit (loss)': 'GrossProfit', + 'income from operations': 'OperatingIncomeLoss', + 'operating income': 'OperatingIncomeLoss', + 'operating loss': 'OperatingIncomeLoss', + 'income before tax': 'PretaxIncomeLoss', + 'income before taxes': 'PretaxIncomeLoss', + 'net income attributable to owners of the parent': 'NetIncome', + 'net income attributable to shareholders of the parent': 'NetIncome', + 'profit (loss)': 'ProfitLoss', +} +_XBRL_METADATA = ( + 'level', 'abstract', 'dimension', 'is_breakdown', 'dimension_axis', + 'dimension_member', 'dimension_member_label', 'dimension_label', 'balance', + 'weight', 'preferred_sign', 'parent_concept', 'parent_abstract_concept', +) + + +def _normalize_label(label): + return ' '.join(str(label).lower().split()) + + +def _standard_concept(label, row_type): + label = _normalize_label(label) + if row_type == RowType.PER_SHARE: + # Do not use an unqualified EPS row or prose elsewhere to guess a type. + match = re.fullmatch(r'(basic|diluted) (?:eps|(?:earnings|loss|earnings \(loss\)) per share)' + r'(?:\s*\((?:nt\$|us\$|hk\$|twd|usd|eur|cny|rmb|jpy|€|¥)\))?', label) + if match: + return {'basic': 'EarningsPerShareBasic', 'diluted': 'EarningsPerShareDiluted'}[match[1]] + return None + if row_type == RowType.AMOUNT: + return _STANDARD_CONCEPTS.get(label) + return None + + +def _unsupported_view(view): + if view is not None: + normalize_view(view) # Preserve the public API's invalid-view diagnostics. + raise NotImplementedError('view requires XBRL dimensions; HTML income tables have no dimensional views') + + +def _row_unit(label, row_type, reporting_currency): + if row_type not in (RowType.AMOUNT, RowType.PER_SHARE): + return {RowType.SHARES: 'shares', RowType.PERCENTAGE: 'percent'}.get(row_type) + code = _currency(label) + if code is None: + if _names_currency(label) or re.search(r'\((?:[A-Z]{3}|\$)\)', label): + return None + code = reporting_currency + currency = code.lower() + return f'{currency}PerShare' if row_type == RowType.PER_SHARE else currency + + +def _quarter(header, filing_year, fiscal_year_end='1231'): + if _is_change_column(header) or re.search(r'\b(?:YTD|TTM|FY|annual|year.to.date)\b', header, re.I): + return None + info = _parse_period_header(header) + if info['duration_months'] == 3: + end = info['period_end'] + # The same fiscal quarter must have one key regardless of header style. + # This is an identity/sort key, never a fabricated source date. + fiscal_month = int(fiscal_year_end[:2]) + quarter = ((end.month - fiscal_month - 1) % 12) // 3 + 1 + year = end.year + (end.month > fiscal_month) + return year, quarter + if info['duration_months'] is not None: + return None + # Compact fiscal-quarter labels need not imply calendar-quarter dates. + match = re.search(r'\b(?:([1-4])Q\s*(\d{4}|\d{2})|Q([1-4])\s*(\d{4}|\d{2}))\b', header, re.I) + if match: + quarter, year = int(match[1] or match[3]), match[2] or match[4] + year = int(year) if len(year) == 4 else filing_year // 100 * 100 + int(year) + if year > filing_year + 1: + year -= 100 + return year, quarter + return None + + +@dataclass +class QuarterlyIncome(FinancialTable): + """Reported quarterly income table from a 6-K exhibit, with its source and units. + + to_dataframe() returns actual currency amounts. period_offset in the income + getters selects a reported comparison column, starting with the most recent. + """ + + source_filing: Optional['Filing'] = None + source_url: str = '' + notes: tuple = field(default_factory=tuple) + + def __post_init__(self): + self.dataframe = self.dataframe.copy() + # An explicit loss label carries the sign when a release prints a + # positive magnitude. Already-negative values must not flip twice. + for i, label in enumerate(self.dataframe.index): + if _normalize_label(label) not in ('net loss', 'operating loss'): + continue + for j in range(len(self.dataframe.columns)): + value = self.dataframe.iloc[i, j] + if isinstance(value, Real) and pd.notna(value) and value > 0: + self.dataframe.iloc[i, j] = -value + + def to_dataframe(self, + period_filter: Optional[str] = None, + period_view: Optional[str] = None, + standard: bool = True, + view: ViewType = None, + *, + include_unit: bool = False, + include_point_in_time: bool = False, + include_standardization: bool = False, + presentation: bool = True, + matrix: bool = False) -> pd.DataFrame: + """Statement-compatible columns with honest HTML provenance. + + Amounts use actual currency units and EPS stays unscaled. Source XBRL + concepts and linkbase metadata are null. ``standard`` adds conservative + exact-label mappings without changing labels; the deprecated + ``include_standardization`` flag does not override it, as in Statement. + ``period_filter`` selects an exact source column from ``periods``. + XBRL period/dimensional views, raw-instance signs and equity matrices + are unavailable and raise rather than being silently ignored. + """ + for name, value in (('standard', standard), ('include_unit', include_unit), + ('include_point_in_time', include_point_in_time), + ('include_standardization', include_standardization), + ('presentation', presentation), ('matrix', matrix)): + if not isinstance(value, bool): + raise ValidationError(f'{name} must be a boolean', parameter=name, invalid_value=value) + _unsupported_view(view) + if period_view is not None: + if not isinstance(period_view, str): + raise ValidationError('period_view must be a string', parameter='period_view', invalid_value=period_view) + raise NotImplementedError('period_view requires XBRL periods; use period_filter with a source column') + if not presentation: + raise NotImplementedError('presentation=False requires raw XBRL signs; HTML preserves reported signs') + if matrix: + raise NotImplementedError('matrix=True is unavailable for HTML income tables') + + columns = list(self.periods) + if period_filter is not None: + if not isinstance(period_filter, str) or period_filter not in columns: + raise ValidationError(f'period_filter must be one of the reported columns: {columns}', + parameter='period_filter', invalid_value=period_filter) + columns = [period_filter] + frame = self.scaled_dataframe.loc[:, columns].reset_index(names='label') + row_types = [self.get_row_type(str(label), pos) for pos, label in enumerate(frame['label'])] + frame.insert(0, 'concept', None) + frame.insert(2, 'standard_concept', [ + _standard_concept(label, row_type) if standard else None + for label, row_type in zip(frame['label'], row_types, strict=True) + ]) + if include_unit: + frame['unit'] = [_row_unit(str(label), row_type, self.currency) + for label, row_type in zip(frame['label'], row_types, strict=True)] + if include_point_in_time: + frame['point_in_time'] = False # Explicit quarterly durations, never instants. + for name in _XBRL_METADATA: + frame[name] = None + frame.attrs.update(source='HTML', currency=self.currency, reported_scale=self.scale.value, + source_url=self.source_url, notes=self.notes, period_columns=columns, + standardization_source='HTML exact labels' if standard else None) + return frame + + def to_json(self, include_metadata=True): + result = json.loads(super().to_json(include_metadata=include_metadata)) + if include_metadata: + result['metadata'].update(source='HTML', currency=self.currency, + source_url=self.source_url, notes=self.notes) + return json.dumps(result, indent=2, default=str) + + def to_facts_dataframe(self): + raise NotImplementedError('HTML financials do not synthesize XBRL facts; use to_dataframe()') + + def __rich__(self): + from rich.console import Group + from rich.text import Text + return Group(Text(f'HTML income statement | {self.currency} {self.scale} | {self.source_url}'), + super().__rich__(), *(Text(note) for note in self.notes)) + + def _value(self, labels, period_offset): + if isinstance(period_offset, bool) or not isinstance(period_offset, int) or period_offset < 0: + raise ValidationError('period_offset must be a non-negative integer', + parameter='period_offset', invalid_value=period_offset) + if period_offset >= len(self.periods): + return None + frame = self.dataframe + for label in labels: + positions = [i for i, name in enumerate(frame.index) if _normalize_label(name) == label] + if len(positions) == 1: + value = frame.iloc[positions[0], period_offset] + if isinstance(value, Real) and pd.notna(value): + return value * self.scale.value + return None + + def get_revenue(self, period_offset=0): + return self._value(_REVENUE, period_offset) + + def get_net_income(self, period_offset=0): + return self._value(_NET_INCOME, period_offset) + + def get_operating_income(self, period_offset=0): + return self._value(('income from operations', 'operating income', 'operating loss'), period_offset) + + def get_gross_profit(self, period_offset=0): + return self._value(('gross profit', 'gross profit (loss)'), period_offset) + + +def _quarter_column_positions(table, filing_year, fiscal_year_end=None): + """Keep unique quarterly amount columns, newest comparison first.""" + headers = [str(col) for col in table.dataframe.columns] + compact = any(re.search(r'\b(?:[1-4]Q|Q[1-4])\s*\d{2,4}\b', h, re.I) for h in headers) + dated = any(_parse_period_header(h)['duration_months'] == 3 for h in headers) + if compact and dated and fiscal_year_end is None: + return [] # Compact fiscal labels cannot establish calendar identity alone. + if fiscal_year_end is not None and ( + not isinstance(fiscal_year_end, str) + or not re.fullmatch(r'(?:0[1-9]|1[0-2])(?:0[1-9]|[12]\d|3[01])', fiscal_year_end) + ): + return [] + if fiscal_year_end is not None: + month, day = int(fiscal_year_end[:2]), int(fiscal_year_end[2:]) + if day > monthrange(filing_year, month)[1]: + return [] + columns = {} + for i, header in enumerate(headers): + key = _quarter(header, filing_year, fiscal_year_end or '1231') + if key is None: + continue + if key in columns: + if not table.dataframe.iloc[:, columns[key]].equals(table.dataframe.iloc[:, i]): + return [] # Conflicting amounts/currencies/segments, never pick arbitrarily. + else: + columns[key] = i + return [columns[key] for key in sorted(columns, reverse=True)] + + +def _has_income_totals(table): + labels = {_normalize_label(label) for label in table.dataframe.index} + if not labels.intersection(_REVENUE) or not labels.intersection(_NET_INCOME): + return False + # A grouped/NCI table needs explicit parent attribution; do not return + # consolidated income as the owners' income via a loose label match. + has_nci = any('noncontrolling' in label or 'non-controlling' in label for label in labels) + return not has_nci or bool(labels.intersection(_NET_INCOME[:2])) + + +def _extract_6k_income_statement(filing, *, exhibits=None, fiscal_year_end=None) -> Optional[QuarterlyIncome]: + """Return only an explicitly quarterly, currency-qualified income table. + + Absence is None; downloads and parser failures are not hidden. EX-99 exhibits + are discovered from filing attachments, never guessed from document names. + """ + if filing.form != '6-K': + return None + filing_year = int(str(filing.filing_date)[:4]) + for attachment in (find_earnings_exhibits(filing.attachments) if exhibits is None else exhibits): + release = EarningsRelease(attachment) + if release.document is None: + continue + table = release.income_statement + if table is None: + continue + positions = _quarter_column_positions(table, filing_year, fiscal_year_end) + if not positions or not _has_income_totals(table): + continue + nodes = release.document.tables + if not 0 <= table.raw_index < len(nodes): + continue + context, notes = _table_context(nodes[table.raw_index], table.title) + units = _declared_table_units(context) + if units is None: + continue + declaration, currency, scale = units + # FinancialTable supports a default USD display. A filing-level income + # result requires explicit units and consistent table-local currency. + if scale is None or _currency(declaration) is None or table.currency != currency: + continue + frame = table.dataframe.iloc[:, positions].copy() + row_types = list(table.row_types) + source_url = attachment.url + result = QuarterlyIncome( + dataframe=frame, scale=scale, title=table.title, + statement_type=table.statement_type, periods=list(frame.columns), + raw_index=table.raw_index, row_types=row_types, currency=currency, + source_filing=filing, source_url=source_url, notes=tuple([declaration, *notes]), + ) + if result.get_revenue() is not None and result.get_net_income() is not None: + return result + return None + + +def _latest_candidates(filings, limit): + """Try the newest filing first. Sort a larger window only on a miss.""" + newest = filings.latest() + if newest is None: + return + yield newest + if limit > 1: + recent = filings.latest(limit) + # EntityFilings.latest returns a single filing for a one-element result. + if recent is not None and not hasattr(recent, 'accession_no'): + yield from (filing for filing in recent if filing.accession_no != newest.accession_no) + + +def _recent_quarterly_income(filings, limit, fiscal_year_end): + from edgar.financials import Financials + + today = date.today() + cutoff = today - timedelta(days=183) + for filing in _latest_candidates(filings, limit): + filed = getattr(filing, 'filing_date', None) + if filed is None: + # Without a date we can still read the newest filing's XBRL, but + # cannot establish the recency of an HTML fallback search. + return Financials.extract(filing) + filed = date.fromisoformat(str(filed)) + if filed < cutoff: + break + if filed > today: + continue + exhibits = None + if getattr(filing, 'is_xbrl', None) in (False, 0, '0'): + homepage = getattr(filing, 'homepage', None) + attachments = homepage.attachments if homepage is not None else filing.attachments + exhibits = find_earnings_exhibits(attachments) + if not exhibits and not getattr(attachments, 'data_files', None): + continue + + financials = Financials.extract(filing) + if financials is not None: + return financials + income = _extract_6k_income_statement(filing, exhibits=exhibits, fiscal_year_end=fiscal_year_end) + if income is not None: + return income + return None diff --git a/edgar/entity/core.py b/edgar/entity/core.py index c4eeb1d1d..908821458 100644 --- a/edgar/entity/core.py +++ b/edgar/entity/core.py @@ -14,6 +14,7 @@ if TYPE_CHECKING: import pandas as pd + from edgar._html_financials import QuarterlyIncome from edgar.entity.enhanced_statement import MultiPeriodStatement, StructuredStatement from edgar.entity.filings import EntityFilings from edgar.enums import FilerCategory, FormType, PeriodType @@ -31,7 +32,7 @@ from edgar.display.styles import get_style, SYMBOLS from edgar.entity.data import Address, CompanyData, EntityData from edgar.entity.entity_facts import EntityFacts, get_company_facts -from edgar.exceptions import CompanyFactsNotFoundError, CompanyNotFoundError +from edgar.exceptions import CompanyFactsNotFoundError, CompanyNotFoundError, ValidationError from edgar.entity.tickers import get_icon_from_ticker from edgar.financials import Financials from edgar.display.formatting import cik_text, datefmt, reverse_name @@ -673,38 +674,26 @@ def get_financials(self) -> Optional[Financials]: self._warn_history_with_predecessor("has filed no annual report yet", "get_financials") return None - def get_quarterly_financials(self) -> Optional[Financials]: - """ - Get financial statements from this company's latest quarterly report. - - Checks 10-Q first, then falls back to 6-K (foreign private issuers). - Returns a Financials object with the same interface as get_financials(), - but with quarterly data instead of annual. - - Returns: - Financials object, or None when there are no statements to read: - this company has filed no 10-Q or 6-K, or the latest one carries no - XBRL (most 6-Ks don't). It is never how a failure is reported; a - transport or parsing failure raises. + def get_quarterly_financials(self, *, max_6k_filings: int = 10) -> Optional[Union[Financials, 'QuarterlyIncome']]: + """Read the latest 10-Q, or search recent unamended 6-Ks newest first. - A 6-K filer's quarterly figures are usually in an HTML press - release instead; read them with - ``edgar.earnings.EarningsRelease.from_filing(filing)``. + XBRL yields Financials. An HTML exhibit with explicit quarterly amounts + and units yields QuarterlyIncome, which exposes the income statement. + Returns None if neither is available. For a particular historical 6-K + use edgar.earnings.EarningsRelease.from_filing(filing). - Example:: - - quarterly = Company("AAPL").get_quarterly_financials() - quarterly.income_statement() - quarterly.balance_sheet() + max_6k_filings bounds the number examined within the last 183 days. """ + if isinstance(max_6k_filings, bool) or not isinstance(max_6k_filings, int) or max_6k_filings < 1: + raise ValidationError('max_6k_filings must be a positive integer', + parameter='max_6k_filings', invalid_value=max_6k_filings) tenq_filing = self.latest_tenq if tenq_filing is not None: return tenq_filing.financials - # Fall back to 6-K (foreign private issuers) - filing = self.get_filings(form='6-K', amendments=False, trigger_full_load=False).latest() - if filing is not None: - return Financials.extract(filing) - return None + from edgar._html_financials import _recent_quarterly_income + + filings = self.get_filings(form='6-K', amendments=False, trigger_full_load=False) + return _recent_quarterly_income(filings, max_6k_filings, getattr(self, 'fiscal_year_end', None)) @property def fiscal_year_end(self): diff --git a/tests/fixtures/html/issue1824/README.md b/tests/fixtures/html/issue1824/README.md index 1cca175b2..a7f87b7fb 100644 --- a/tests/fixtures/html/issue1824/README.md +++ b/tests/fixtures/html/issue1824/README.md @@ -25,8 +25,14 @@ The EPS footnote is a smaller font positioned above the baseline, not a plain magnitude suffix. Footnote a says the 3Q2026 figures have not been approved by the Board of Directors. -The primary and month-end 6-K fixtures belong to the Company fallback tests in -PR #1825 and are intentionally absent from this standalone parser change. +The accompanying 6-K documents were saved on 2026-11-01. The primary +filing links the earnings exhibit. The later month-end notice has no +quarterly income statement. + +| Document | Accession | SHA-256 | +| --- | --- | --- | +| [tsm-20261015x6k.htm](https://www.sec.gov/Archives/edgar/data/1046179/000104617926000726/tsm-20261015x6k.htm) | 0001046179-26-000726 | `43a0be1d03e92a19e49e8e55b18a0165811a5a7a105a5a89f731b53022bc664f` | +| [tsm-monthend6kx20261022.htm](https://www.sec.gov/Archives/edgar/data/1046179/000104617926000728/tsm-monthend6kx20261022.htm) | 0001046179-26-000728 | `9183c7d03daf67fd0efa4547cdc7e37fbcaaf33a593e71f37d27dba7dbc24878` | ## Cardlytics currency regression diff --git a/tests/fixtures/html/issue1824/tsm-20261015x6k.htm b/tests/fixtures/html/issue1824/tsm-20261015x6k.htm new file mode 100644 index 000000000..4a5d8991d --- /dev/null +++ b/tests/fixtures/html/issue1824/tsm-20261015x6k.htm @@ -0,0 +1,12 @@ + +6-K +1 +tsm-20261015x6k.htm +6-K + + + + +Document

1934 Act Registration No. 1-14700
UNITED STATES
SECURITIES AND EXCHANGE COMMISSION
Washington, D.C. 20549
_____________________________
FORM 6-K
_____________________________
REPORT OF FOREIGN PRIVATE ISSUER
PURSUANT TO RULE 13a-16 OR 15d-16 UNDER
THE SECURITIES EXCHANGE ACT OF 1934
For the month of October 2026
(Commission File Number: 001-14700)
_____________________________
Taiwan Semiconductor Manufacturing Company Limited
(Translation of Registrant’s Name Into English)
_____________________________
No. 8, Li-Hsin Road 6
Hsinchu Science Park
Hsinchu 300-096, Taiwan
Republic of China
(Address of Principal Executive Offices)
_____________________________
Indicate by check mark whether the registrant files or will file annual reports under cover of Form 20-F or Form 40-F.
Form 20-F  x            Form 40-F  o
Indicate by check mark if the registrant is submitting the Form 6-K in papers as permitted by Regulation S-T Rule 101(b)(1):o
Indicate by check mark if the registrant is submitting the Form 6-K in papers as permitted by Regulation S-T Rule 101(b)(7):o



SIGNATURES
Pursuant to the requirements of the Securities Exchange Act of 1934, the registrant has duly caused this report to be signed on its behalf by the undersigned, thereunto duly authorized.


Taiwan Semiconductor Manufacturing Company Limited
Date: October 15, 2026By   /s/ Wendell Huang
  Wendell Huang
   Senior Vice President & Chief Financial Officer




Exhibits

+
+
diff --git a/tests/fixtures/html/issue1824/tsm-monthend6kx20261022.htm b/tests/fixtures/html/issue1824/tsm-monthend6kx20261022.htm new file mode 100644 index 000000000..6aa34936c --- /dev/null +++ b/tests/fixtures/html/issue1824/tsm-monthend6kx20261022.htm @@ -0,0 +1,12 @@ + +6-K +1 +tsm-monthend6kx20261022.htm +6-K + + + + +Document

1934 Act Registration No. 1-14700
UNITED STATES
SECURITIES AND EXCHANGE COMMISSION
Washington, D.C. 20549
_____________________________
FORM 6-K
_____________________________
REPORT OF FOREIGN PRIVATE ISSUER
PURSUANT TO RULE 13a-16 OR 15d-16 UNDER
THE SECURITIES EXCHANGE ACT OF 1934
For the month of October 2026
(Commission File Number: 001-14700)
_____________________________
Taiwan Semiconductor Manufacturing Company Limited
(Translation of Registrant’s Name Into English)
_____________________________
No. 8, Li-Hsin Road 6
Hsinchu Science Park
Hsinchu 300-096, Taiwan
Republic of China
(Address of Principal Executive Offices)
_____________________________
Indicate by check mark whether the registrant files or will file annual reports under cover of Form 20-F or Form 40-F.
Form 20-F  x            Form 40-F  o
Indicate by check mark if the registrant is submitting the Form 6-K in papers as permitted by Regulation S-T Rule 101(b)(1):o
Indicate by check mark if the registrant is submitting the Form 6-K in papers as permitted by Regulation S-T Rule 101(b)(7):o



SIGNATURES
Pursuant to the requirements of the Securities Exchange Act of 1934, the registrant has duly caused this report to be signed on its behalf by the undersigned, thereunto duly authorized.


Taiwan Semiconductor Manufacturing Company Limited
Date: October 22, 2026By/s/ Wendell Huang
Wendell Huang
Senior Vice President and Chief Financial Officer
   




Taiwan Semiconductor Manufacturing Company Limited
("TSMC"; NYSE: TSM)
This is to report 1) the changes in the shareholdings of TSMC board of directors, executive officers and shareholders who own more than 10% of total outstanding common shares of TSMC; 2) the changes in the pledge of TSMC common shares by TSMC board of directors, executive officers and shareholders who own more than 10% of total outstanding common shares of TSMC; 3) the acquisition and disposition of assets by TSMC and its subsidiaries; 4) the capital appropriations approved by TSMC board of directors; 5) the unsecured bonds issued by TSMC and its subsidiaries and 6) the cancellation of TSMC common shares for the month of September 2026.
1.The changes in the shareholdings of TSMC board of directors, executive officers and shareholders who own more than 10% of total outstanding common shares of TSMC:
TitleNameNumber of shares held as ofChanges
8/31/20269/30/2026
Chairman & Chief Executive OfficerC.C. Wei8,152,6108,356,985204,375 
Executive Vice President and Co-Chief Operating OfficerY.P. Chyn9,362,0429,394,24632,204 
Executive Vice President and Co-Chief Operating OfficerY.J. Mii1,254,0571,286,26132,204 
Senior Vice President and Deputy Co-Chief Operating Officer / Chief Information Security OfficerCliff Hou723,205771,22948,024 
Senior Vice President and Deputy Co-Chief Operating OfficerKevin Zhang329,663349,97620,313 
Senior Vice President, General Counsel and Corporate Governance OfficerSylvia Fang1,310,2981,350,80140,503 
Senior Vice President and Chief Financial OfficerWendell Huang1,811,5431,831,85620,313 
Senior Vice PresidentY.L. Wang1,497,9211,510,80212,881 
Senior Vice PresidentT.S. Chang317,638346,58028,942 
Senior Vice PresidentMichael Wu829,171842,05212,881 
Senior Vice PresidentGeoffrey Yeap213,375243,38330,008 
Senior Vice PresidentJonathan Lee512,032524,91312,881 
Vice PresidentMin Cao542,349555,23012,881 
Vice PresidentSimon Jang445,879454,0548,175 
Vice PresidentC.S. Yoo2,869,4462,877,6218,175 
Vice PresidentJun He120,119140,73520,616 
Vice President and Chief Information OfficerChris Horng-Dar Lin143,184164,37221,188 



TitleNameNumber of shares held as ofChanges
8/31/20269/30/2026
Vice PresidentArthur Chuang3,488,3053,509,36821,063 
Vice PresidentL.C. Lu291,716299,8918,175 
Vice PresidentK.C. Hsu190,924199,0998,175 
Vice PresidentRay Chuang345,738365,23919,501 

Note: Shareholdings include shares held by the related parties.
2.The changes in the pledge of TSMC common shares by TSMC board of directors, executive officers and shareholders who own more than 10% of total outstanding common shares of TSMC:
None.
3.The acquisition and disposition of assets by TSMC and its subsidiaries:
None.
4.The capital appropriations approved by TSMC board of directors:
None.
5.The unsecured bonds issued by TSMC and its subsidiaries:
None.
6.The cancellation of TSMC common shares:
None.

+
+
diff --git a/tests/issues/regression/test_issue_1824.py b/tests/issues/regression/test_issue_1824.py new file mode 100644 index 000000000..08fa67b36 --- /dev/null +++ b/tests/issues/regression/test_issue_1824.py @@ -0,0 +1,570 @@ +"""Bounded 6-K HTML income-statement fallback, with the reported TSM amounts. + +GitHub Issue: https://github.com/dgunning/edgartools/issues/1824 + +SEC originals downloaded unchanged on 2026-11-01, before the implementation: +TSM 6-K 0001046179-26-000726, a3q26e_withguidancexfinal.htm (2026-10-15): +net income TWD 763,064 million, net sales TWD 1,494,243 million, EPS NT$29.43. +Comparison amounts: 2Q26 net income 706,562 million, 3Q25 452,302 million. +The latest 6-K 0001046179-26-000728 is a monthly notice, not this release. +""" +import inspect +import json +from datetime import date, timedelta +from pathlib import Path +from types import SimpleNamespace + +import pandas as pd +import pytest +from lxml import html + +from edgar import QuarterlyIncome +from edgar._html_financials import ( + _extract_6k_income_statement, + _quarter_column_positions, +) +from edgar.earnings import FinancialTable, RowType, Scale +from edgar.entity import Company +from edgar.financials import Financials +from edgar.xbrl import XBRL +from edgar.xbrl.presentation import StatementView +from edgar.xbrl.statements import Statement + +FIXTURES = Path(__file__).parents[2] / 'fixtures' / 'html' / 'issue1824' +EARNINGS = '0001046179-26-000726' +MONTHLY = '0001046179-26-000728' + + +class Attachment: + def __init__(self, name, content, accession=EARNINGS): + self.document = name + self.document_type = 'EX-99.1' + self.description = 'Press release' + self.content = content + self.url = f'https://www.sec.gov/Archives/edgar/data/1046179/{accession.replace("-", "")}/{name}' + + def is_html(self): + return True + + +class Filings(list): + def latest(self, count=1): + recent = sorted(self, key=lambda f: f.filing_date, reverse=True)[:count] + return recent[0] if len(recent) == 1 else recent or None + + +class SearchDate(date): + @classmethod + def today(cls): + return cls(2026, 11, 3) + + +@pytest.fixture(autouse=True) +def stable_search_date(monkeypatch): + monkeypatch.setattr('edgar._html_financials.date', SearchDate) + + +def filing(accession, attachments, filed=date(2026, 10, 22)): + return SimpleNamespace(form='6-K', accession_no=accession, filing_date=filed, + attachments=attachments) + + +def company(filings): + class ForeignCompany: + latest_tenq = None + + def get_filings(self, **kwargs): + assert kwargs == dict(form='6-K', amendments=False, trigger_full_load=False) + return Filings(filings) + + return ForeignCompany() + + +@pytest.fixture +def release(): + # Discover the exhibit through the actual primary document's links. + primary = html.fromstring((FIXTURES / 'tsm-20261015x6k.htm').read_bytes()) + links = set(primary.xpath('//a/@href')) + exhibit = 'a3q26e_withguidancexfinal.htm' + assert exhibit in links + return filing(EARNINGS, [Attachment(exhibit, (FIXTURES / exhibit).read_text())], date(2026, 10, 15)) + + +@pytest.fixture +def monthly(): + name = 'tsm-monthend6kx20261022.htm' + # Even treating the whole monthly notice as an exhibit must not accept it. + return filing(MONTHLY, [Attachment(name, (FIXTURES / name).read_text(), MONTHLY)]) + + +@pytest.fixture +def no_xbrl(monkeypatch): + monkeypatch.setattr(XBRL, 'from_filing', lambda f: None) + + +def test_tsm_reported_values_periods_units_and_caveat(release): + result = _extract_6k_income_statement(release) + assert isinstance(result, QuarterlyIncome) + assert not isinstance(result, Financials) + assert result.source_filing.accession_no == EARNINGS + assert result.currency == 'TWD' + assert result.get_net_income() == 763_064_000_000 + assert result.get_net_income(1) == 706_562_000_000 + assert result.get_net_income(2) == 452_302_000_000 + assert result.get_net_income(3) is None + assert result.get_revenue() == 1_494_243_000_000 + assert result.get_gross_profit() == 992_379_000_000 + assert result.get_operating_income() == 876_445_000_000 + statement = result + assert statement.scale is Scale.MILLIONS + assert list(statement.dataframe.columns) == ['3Q26\nAmounta', '2Q26\nAmount', '3Q25\nAmount'] + assert statement.dataframe.loc['EPS (NT$)'].tolist() == [29.43, 27.25, 17.44] + assert statement.get_row_type('EPS (NT$)', 5) is RowType.PER_SHARE + frame = statement.to_dataframe().set_index('label') + assert frame.loc['EPS (NT$)', statement.periods].tolist() == [29.43, 27.25, 17.44] + assert frame.loc['Net income', statement.periods].tolist() == [763_064_000_000, 706_562_000_000, 452_302_000_000] + assert frame.attrs['currency'] == 'TWD' + exported = json.loads(statement.to_json()) + assert exported['metadata']['currency'] == 'TWD' + assert exported['metadata']['source'] == 'HTML' + assert any('Board of Directors' in note for note in exported['metadata']['notes']) + with pytest.raises(NotImplementedError, match='do not synthesize XBRL facts'): + statement.to_facts_dataframe() + assert any('not been approved by Board of Directors' in note for note in result.notes) + assert any('25,932 million' in note for note in result.notes) + assert 'actual USD' not in statement.to_context() + assert 'TWD' in statement.to_context() + assert result.source_url.endswith('a3q26e_withguidancexfinal.htm') + assert isinstance(result, FinancialTable) + assert not hasattr(result, 'balance_sheet') + assert not hasattr(result, 'cash_flow_statement') + + +def test_monthly_notice_is_not_a_quarterly_income_statement(monthly): + assert _extract_6k_income_statement(monthly) is None + + +def test_company_passes_monthly_to_reach_real_earnings_release(release, monthly, no_xbrl): + result = Company.get_quarterly_financials(company([monthly, release])) + assert result.source_filing.accession_no == EARNINGS + assert result.get_net_income() == 763_064_000_000 + + +def test_search_is_bounded(release, monthly, no_xbrl): + assert Company.get_quarterly_financials(company([monthly, release]), max_6k_filings=1) is None + assert Company.get_quarterly_financials(company([])) is None + + +def test_xbrl_still_wins_and_does_not_download_html(release, monkeypatch): + expected = Financials(object()) + monkeypatch.setattr(Financials, 'extract', lambda f: expected) + release.attachments = None # Access would fail if the HTML fallback runs. + assert Company.get_quarterly_financials(company([release])) is expected + + +def test_tenq_still_wins(): + expected = object() + c = SimpleNamespace(latest_tenq=SimpleNamespace(financials=expected)) + assert Company.get_quarterly_financials(c) is expected + + +@pytest.mark.parametrize('bound', [0, -1, True, 1.5, '10']) +def test_invalid_search_bound_raises(bound): + with pytest.raises(ValueError, match='positive integer'): + Company.get_quarterly_financials(company([]), max_6k_filings=bound) + + +def test_transport_failure_is_not_swallowed(release, monkeypatch): + def fail(f): + raise ConnectionError('SEC unavailable') + + monkeypatch.setattr(XBRL, 'from_filing', fail) + with pytest.raises(ConnectionError, match='SEC unavailable'): + Company.get_quarterly_financials(company([release])) + + +def test_unknown_currency_remains_unsupported(release): + content = release.attachments[0].content + release.attachments[0].content = content.replace('NT$ million', 'million') + assert _extract_6k_income_statement(release) is None + + +def test_annual_or_ambiguous_periods_are_not_presented_as_quarterly(release): + content = release.attachments[0].content + # No quarter labels remains an annual/unknown-period table. + release.attachments[0].content = content.replace('3Q26', '2026').replace('3Q25', '2025').replace('2Q26', '2026') + assert _extract_6k_income_statement(release) is None + # Two amount columns for the same quarter could be separate segments or currencies. + release.attachments[0].content = content.replace('2Q26', '3Q26') + assert _extract_6k_income_statement(release) is None + + +def test_compact_ytd_headers_are_not_quarters(release): + content = release.attachments[0].content + for label in ['3Q26', '3Q25', '2Q26']: + content = content.replace(label, 'YTD ' + label) + release.attachments[0].content = content + assert _extract_6k_income_statement(release) is None + + +def test_narrative_currency_is_not_a_table_unit_declaration(release): + original = release.attachments[0].content + release.attachments[0].content = original.replace( + '(Unit: NT$ million, except for EPS)', 'Forecast profit in NT$ million') + assert release.attachments[0].content != original + assert _extract_6k_income_statement(release) is None + + +def test_exhibit_download_failure_is_not_swallowed(release): + class UnavailableAttachment(Attachment): + @property + def content(self): + raise ConnectionError('exhibit download failed') + + attachment = object.__new__(UnavailableAttachment) + attachment.document = 'ex99.htm' + attachment.document_type = 'EX-99.1' + attachment.description = 'earnings' + release.attachments = [attachment] + with pytest.raises(ConnectionError, match='exhibit download failed'): + _extract_6k_income_statement(release) + + +@pytest.mark.parametrize('offset', [-1, 1.5, True, '1', None]) +def test_invalid_period_offset_raises(release, offset): + result = _extract_6k_income_statement(release) + with pytest.raises(ValueError, match='non-negative integer'): + result.get_net_income(offset) + + +@pytest.fixture(scope='module') +def nvda_statement(): + # Existing, unmodified SEC XBRL fixture: 0001045810-26-000021. This pins + # the public Statement schema, not a claim of matching TSM's fiscal dates. + return XBRL.from_directory(Path('tests/fixtures/xbrl/nvda/10k_2026')).statements.income_statement() + + +def test_html_and_xbrl_share_dataframe_parameters(release): + statement = _extract_6k_income_statement(release) + html_params = inspect.signature(type(statement).to_dataframe).parameters + xbrl_params = inspect.signature(Statement.to_dataframe).parameters + assert list(html_params) == list(xbrl_params) + assert [(p.kind, p.default) for p in html_params.values()] == [ + (p.kind, p.default) for p in xbrl_params.values() + ] + + +@pytest.mark.parametrize('options', [ + {}, {'include_unit': True}, {'include_point_in_time': True}, + {'include_unit': True, 'include_point_in_time': True}, + {'standard': False}, {'include_standardization': True}, + {'standard': False, 'include_standardization': True}, +]) +def test_real_tsm_and_nvda_share_columns_and_standard_flag(release, nvda_statement, options): + statement = _extract_6k_income_statement(release) + html = statement.to_dataframe(**options) + xbrl = nvda_statement.to_dataframe(**options) + html_periods = set(statement.periods) + xbrl_periods = {col for col in xbrl if col.startswith(('2026-', '2025-', '2024-'))} + assert [col for col in html if col not in html_periods] == [col for col in xbrl if col not in xbrl_periods] + # Source identity remains XBRL only; HTML label mappings are not source tags. + assert html['concept'].isna().all() + assert 'us-gaap_Revenues' in xbrl['concept'].to_numpy() + if options.get('standard', True): + assert set(html['standard_concept'].dropna()) <= set(xbrl['standard_concept'].dropna()) + for frame, label in [(html, 'Net sales'), (xbrl, 'Revenue')]: + revenue = frame.loc[frame['label'] == label].iloc[0] + if options.get('standard', True): + assert revenue['standard_concept'] == 'Revenue' + else: + assert pd.isna(revenue['standard_concept']) + + +def test_html_units_provenance_and_missing_xbrl_metadata(release): + statement = _extract_6k_income_statement(release) + frame = statement.to_dataframe(include_unit=True, include_point_in_time=True).set_index('label') + assert frame['unit'].tolist() == ['twd'] * 5 + ['twdPerShare'] + assert frame['point_in_time'].tolist() == [False] * 6 + assert frame['standard_concept'].iloc[:4].tolist() == [ + 'Revenue', 'GrossProfit', 'OperatingIncomeLoss', 'PretaxIncomeLoss', + ] + assert frame['standard_concept'].iloc[4:].isna().all() + # Generic net income does not establish attribution, nor EPS basic/diluted. + assert frame.loc['Net income', '3Q26\nAmounta'] == 763_064_000_000 + assert frame.loc['EPS (NT$)', '3Q26\nAmounta'] == 29.43 + for column in ('concept', 'level', 'abstract', 'dimension', 'is_breakdown', + 'dimension_axis', 'dimension_member', 'dimension_member_label', + 'dimension_label', 'balance', 'weight', 'preferred_sign', + 'parent_concept', 'parent_abstract_concept'): + assert frame[column].isna().all(), column + assert frame.attrs['source'] == 'HTML' + assert frame.attrs['standardization_source'] == 'HTML exact labels' + assert frame.attrs['period_columns'] == statement.periods + assert frame.attrs['reported_scale'] == 1_000_000 + assert frame.attrs['source_url'].endswith('a3q26e_withguidancexfinal.htm') + assert any('Board of Directors' in note for note in frame.attrs['notes']) + + +def test_period_filter_selects_reported_comparative_column_without_mutation(release): + statement = _extract_6k_income_statement(release) + original = statement.dataframe.copy(deep=True) + periods = list(statement.periods) + frame = statement.to_dataframe(period_filter='3Q25\nAmount', include_unit=True).set_index('label') + assert frame.attrs['period_columns'] == ['3Q25\nAmount'] + assert not set(periods[:2]).intersection(frame.columns) + assert frame.loc['Net income', '3Q25\nAmount'] == 452_302_000_000 + assert frame.loc['EPS (NT$)', '3Q25\nAmount'] == 17.44 + frame.loc['Net income', '3Q25\nAmount'] = 0 + pd.testing.assert_frame_equal(statement.dataframe, original) + assert statement.periods == periods + assert statement.to_dataframe().attrs['period_columns'] == periods + + +@pytest.mark.parametrize('value', ['', 'Q3 2025', 'duration_2025-07-01_2025-09-30', 1, True]) +def test_invalid_html_period_filter_is_not_silently_ignored(release, value): + statement = _extract_6k_income_statement(release) + with pytest.raises(ValueError, match='period_filter.*reported columns'): + statement.to_dataframe(period_filter=value) + + +@pytest.mark.parametrize('options, message', [ + ({'period_view': 'Quarterly Comparison'}, 'period_view'), + ({'view': 'summary'}, 'view.*XBRL dimensions'), + ({'view': StatementView.STANDARD}, 'view.*XBRL dimensions'), + ({'presentation': False}, 'presentation=False'), + ({'matrix': True}, 'matrix=True'), +]) +def test_unavailable_xbrl_operations_raise_explicitly(release, options, message): + statement = _extract_6k_income_statement(release) + with pytest.raises(NotImplementedError, match=message): + statement.to_dataframe(**options) + + +def test_html_table_rejects_misspelled_view(release): + result = _extract_6k_income_statement(release) + with pytest.raises(ValueError, match='Invalid view'): + result.to_dataframe(view='misspelled') + + +@pytest.mark.parametrize('name', [ + 'standard', 'include_unit', 'include_point_in_time', + 'include_standardization', 'presentation', 'matrix', +]) +def test_html_boolean_parameters_reject_non_booleans(release, name): + statement = _extract_6k_income_statement(release) + with pytest.raises(ValueError, match=f'{name} must be a boolean'): + statement.to_dataframe(**{name: 1}) + + +def test_html_period_view_type_and_unknown_keywords_raise(release): + statement = _extract_6k_income_statement(release) + with pytest.raises(ValueError, match='period_view must be a string'): + statement.to_dataframe(period_view=1) + with pytest.raises(TypeError, match='unexpected keyword argument.*include_unt'): + statement.to_dataframe(include_unt=True) + + +def test_explicit_concept_labels_map_but_ambiguous_and_adjusted_labels_do_not(release): + # In-memory mutations test the inference boundary; SEC fixture bytes stay intact. + statement = _extract_6k_income_statement(release) + statement.dataframe.index = [ + 'Adjusted revenue', 'Revenue growth', 'Net income attributable to owners of the parent', + 'Unrecognized income', 'Profit (loss)', 'Diluted EPS (NT$)', + ] + frame = statement.to_dataframe() + assert frame['standard_concept'].iloc[[0, 1, 3]].isna().all() + assert frame['standard_concept'].iloc[[2, 4, 5]].tolist() == ['NetIncome', 'ProfitLoss', 'EarningsPerShareDiluted'] + assert frame['concept'].isna().all() + statement.dataframe.index = [*statement.dataframe.index[:-1], 'Basic earnings per share (NT$)'] + assert statement.to_dataframe()['standard_concept'].iloc[-1] == 'EarningsPerShareBasic' + assert frame['label'].iloc[-1] == 'Diluted EPS (NT$)' + + +def test_row_types_and_explicit_row_currency_determine_units(release): + statement = _extract_6k_income_statement(release) + statement.row_types = [RowType.AMOUNT, RowType.SHARES, RowType.PERCENTAGE, + RowType.OTHER, RowType.AMOUNT, RowType.PER_SHARE] + statement.dataframe.index = [*statement.dataframe.index[:-1], 'EPS (US$)'] + frame = statement.to_dataframe(include_unit=True) + assert frame['unit'].iloc[[0, 1, 2, 4, 5]].tolist() == ['twd', 'shares', 'percent', 'twd', 'usdPerShare'] + assert pd.isna(frame['unit'].iloc[3]) + assert frame['3Q26\nAmounta'].tolist() == [1_494_243_000_000, 992_379, 876_445, 911_039, 763_064_000_000, 29.43] + + +@pytest.mark.parametrize('label', ['Basic EPS (non-GAAP)', 'Diluted EPS (adjusted)', 'Adjusted diluted EPS (NT$)']) +def test_adjusted_eps_qualifiers_do_not_become_standard_gaap_eps(release, label): + statement = _extract_6k_income_statement(release) + statement.dataframe.index = [*statement.dataframe.index[:-1], label] + frame = statement.to_dataframe() + assert pd.isna(frame['standard_concept'].iloc[-1]) + assert frame['3Q26\nAmounta'].iloc[-1] == 29.43 + + +@pytest.mark.parametrize('label', ['EPS (NT$ / US$)', 'EPS (GBP)', 'EPS ($)']) +def test_uncertain_row_currency_stays_null(release, label): + statement = _extract_6k_income_statement(release) + statement.dataframe.index = [*statement.dataframe.index[:-1], label] + frame = statement.to_dataframe(include_unit=True) + assert pd.isna(frame['unit'].iloc[-1]) + assert frame['3Q26\nAmounta'].iloc[-1] == 29.43 + + +def test_newest_earnings_wins_even_when_filings_are_unsorted(release, monkeypatch): + older = filing('older', [], date(2026, 9, 1)) + probed = [] + + def extract(candidate): + probed.append(candidate.accession_no) + return Financials(object()) + + monkeypatch.setattr(Financials, 'extract', extract) + assert Company.get_quarterly_financials(company([older, release]), max_6k_filings=1) is not None + assert probed == [EARNINGS] + + +def test_single_filing_return_from_latest_is_supported(release, no_xbrl): + c = company([]) + c.get_filings = lambda **kwargs: SimpleNamespace(latest=lambda n=1: release) + assert Company.get_quarterly_financials(c, max_6k_filings=1).get_net_income() == 763_064_000_000 + + +@pytest.mark.parametrize('age, expected_probes', [(183, 1), (184, 0), (550, 0), (-1, 0)]) +def test_search_age_boundary_before_any_download(release, monkeypatch, age, expected_probes): + release.filing_date = SearchDate.today() - timedelta(days=age) + probed = [] + monkeypatch.setattr(Financials, 'extract', lambda candidate: probed.append(candidate)) + # No attachments can be inspected for expired/future filings. + release.attachments = [] if expected_probes else None + assert Company.get_quarterly_financials(company([release])) is None + assert len(probed) == expected_probes + + +def test_known_untagged_monthly_notice_is_screened_using_index(release, monthly, monkeypatch): + monthly.is_xbrl = False + monthly.attachments = [] + probed = [] + + def extract(candidate): + probed.append(candidate.accession_no) + return None + + monkeypatch.setattr(Financials, 'extract', extract) + result = Company.get_quarterly_financials(company([release, monthly])) + assert result.get_net_income() == 763_064_000_000 + assert probed == [EARNINGS] + + +def test_attachment_index_can_skip_monthly_notice_without_loading_submission(release, monkeypatch): + class IndexedNotice: + form = '6-K' + accession_no = MONTHLY + filing_date = date(2026, 10, 22) + is_xbrl = False + homepage = SimpleNamespace(attachments=[]) + + @property + def attachments(self): + raise AssertionError('Monthly notice must not download the full SGML submission') + + probed = [] + monkeypatch.setattr(Financials, 'extract', lambda candidate: probed.append(candidate.accession_no)) + result = Company.get_quarterly_financials(company([release, IndexedNotice()])) + assert result.get_net_income() == 763_064_000_000 + assert probed == [EARNINGS] + + +def test_attachment_index_download_error_is_not_swallowed(): + class UnavailableIndex: + accession_no = MONTHLY + filing_date = date(2026, 10, 22) + is_xbrl = False + + @property + def homepage(self): + raise ConnectionError('attachment index unavailable') + + with pytest.raises(ConnectionError, match='attachment index unavailable'): + Company.get_quarterly_financials(company([UnavailableIndex()])) + + +def test_xbrl_data_files_are_not_screened_out_by_negative_flag(release, monkeypatch): + class Index(list): + data_files = ['instance.xml'] + + release.is_xbrl = '0' + release.attachments = Index() + expected = Financials(object()) + monkeypatch.setattr(Financials, 'extract', lambda candidate: expected) + assert Company.get_quarterly_financials(company([release])) is expected + + +@pytest.mark.parametrize('flag', [False, True, None]) +def test_earnings_exhibit_still_probes_xbrl_before_html(release, monkeypatch, flag): + release.is_xbrl = flag + expected = Financials(object()) + monkeypatch.setattr(Financials, 'extract', lambda candidate: expected) + assert Company.get_quarterly_financials(company([release])) is expected + + +@pytest.mark.parametrize('printed', [5000, -5000]) +def test_explicit_losses_have_negative_values_in_every_view(release, printed): + original = pd.DataFrame({'3Q26': [10000, printed, printed]}, + index=['Revenue', 'Operating loss', 'Net loss']) + before = original.copy(deep=True) + statement = QuarterlyIncome( + source_filing=release, dataframe=original, scale=Scale.MILLIONS, currency='TWD', periods=['3Q26'], + row_types=[RowType.AMOUNT] * 3) + assert statement.get_operating_income() == -5_000_000_000 + assert statement.get_net_income() == -5_000_000_000 + assert statement.dataframe['3Q26'].tolist() == [10000, -5000, -5000] + exported = statement.to_dataframe().set_index('label') + assert exported.loc['Operating loss', '3Q26'] == -5_000_000_000 + assert exported.loc['Operating loss', 'standard_concept'] == 'OperatingIncomeLoss' + pd.testing.assert_frame_equal(original, before) + + +def test_income_loss_label_does_not_imply_negative_sign(release): + table = QuarterlyIncome(pd.DataFrame({'3Q26': [50]}, index=['Net income (loss)']), periods=['3Q26']) + assert table.get_net_income() == 50 + + +def test_whitespace_normalization_is_shared_by_getters_and_mapping(release): + original = release.attachments[0].content + release.attachments[0].content = original.replace('Net sales', 'Net  sales').replace( + 'Gross profit', 'Gross  profit') + result = _extract_6k_income_statement(release) + assert result.get_revenue() == 1_494_243_000_000 + assert result.get_gross_profit() == 992_379_000_000 + frame = result.to_dataframe() + assert frame['standard_concept'].iloc[:2].tolist() == ['Revenue', 'GrossProfit'] + + +@pytest.mark.parametrize('fiscal_end, compact', [('1231', '3Q26'), ('0630', '1Q27')]) +def test_dated_and_compact_headers_for_one_quarter_are_deduplicated(fiscal_end, compact): + table = FinancialTable(pd.DataFrame( + [[10, 10, 8], [2, 2, 1]], index=['Revenue', 'Net income'], + columns=['Three Months Ended September 30, 2026', compact, '2Q26'])) + assert _quarter_column_positions(table, 2026, fiscal_end) == [0, 2] + table.dataframe.iloc[1, 1] = 3 + assert _quarter_column_positions(table, 2026, fiscal_end) == [] + + +def test_mixed_headers_without_fiscal_calendar_are_not_guessed(): + table = FinancialTable(pd.DataFrame([[10, 10]], columns=[ + 'Three Months Ended September 30, 2026', '3Q26'])) + assert _quarter_column_positions(table, 2026) == [] + + +@pytest.mark.parametrize('fiscal_end', ['', 1231, '1331', '0230', '123']) +def test_malformed_fiscal_calendar_does_not_abort_search(fiscal_end): + table = FinancialTable(pd.DataFrame([[10]], columns=['3Q26'])) + assert _quarter_column_positions(table, 2026, fiscal_end) == [] + + +def test_missing_table_index_is_not_a_search_error(release, monkeypatch): + from edgar.earnings import EarningsRelease + + real = EarningsRelease(release.attachments[0]).income_statement + real.raw_index = 10000 + monkeypatch.setattr(EarningsRelease, 'income_statement', property(lambda self: real)) + assert _extract_6k_income_statement(release) is None diff --git a/tests/issues/regression/test_issue_1824_6k_quarterly_docs.py b/tests/issues/regression/test_issue_1824_6k_quarterly_docs.py index 323c59f4c..999dce430 100644 --- a/tests/issues/regression/test_issue_1824_6k_quarterly_docs.py +++ b/tests/issues/regression/test_issue_1824_6k_quarterly_docs.py @@ -1,30 +1,23 @@ -"""get_quarterly_financials() returns None for TSM, and the docs did not say why. +"""Read a particular historical 6-K through the documented EarningsRelease API. GitHub Issue: https://github.com/dgunning/edgartools/issues/1824 -TSMC files its quarterly results on Form 6-K as an HTML press release (EX-99) -with no XBRL, so ``get_quarterly_financials()`` has no statements to read and -returns ``None``, which is the 6.0 contract (docs/upgrade/6.0.md). The guide now -says so and points to ``EarningsRelease``. This runs the documented example as -written in docs/guides/financial-data.md. - Ground truth: TSMC 6-K 0001046179-26-000726 (filed 2026-10-15), exhibit a3q26e_withguidancexfinal.htm, unit "NT$ million": 3Q26 net income 763,064 and 3Q25 net income 452,302. """ import pytest -from edgar import Company, find +from edgar import find from edgar.earnings import EarningsRelease from tests.paths import REPO_ROOT @pytest.mark.vcr def test_documented_6k_quarterly_example(): - assert Company("TSM").get_quarterly_financials() is None - filing = find("0001046179-26-000726") release = EarningsRelease.from_filing(filing) + assert release.income_statement.currency == "TWD" df = release.income_statement.dataframe net_income = df.loc["Net income"] diff --git a/tests/meta/test_documented_api_exists.py b/tests/meta/test_documented_api_exists.py index 4aa3f22a5..c38f11449 100644 --- a/tests/meta/test_documented_api_exists.py +++ b/tests/meta/test_documented_api_exists.py @@ -343,5 +343,5 @@ def test_names_the_checker_cannot_see_are_not_reported(snippet): @pytest.mark.fast def test_a_local_binding_is_still_checked(): """A name the snippet assigns is checked as the type of its right-hand side.""" - problems, _ = check("```python\nquarterly = company.get_quarterly_financials()\nq = quarterly.income\n```\n") - assert problems == ["quarterly.income: Financials has no 'income'"] + problems, _ = check("```python\nannual = company.get_financials()\nq = annual.income\n```\n") + assert problems == ["annual.income: Financials has no 'income'"]