Skip to content

Commit 1ca9a1f

Browse files
MiusHuvdgunning
andauthored
fix(mcp): prevent YTD figures from overwriting quarterly revenue in edgar_trends (#2018)
Co-authored-by: Dwight Gunning <dgunning@gmail.com>
1 parent 75222fd commit 1ca9a1f

3 files changed

Lines changed: 180 additions & 6 deletions

File tree

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
**`edgar_trends(..., period="quarterly")` no longer overwrites quarterly revenue with 6M/9M YTD cumulative figures.** `_prefer_consolidated_totals` now compares only within the period-filtered window so Apple Q3 FY2026 (`0000320193-26-000020`) returns $109.4B instead of $364.4B (9M YTD) while MetLife Q3 2026 (`0001099219-26-000062`) still upgrades its $728M ASC-606 slice to $20.5B consolidated quarterly revenue.

‎edgar/ai/mcp/tools/trends.py‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@
7575
_CONSOLIDATED_TOTAL_CONCEPTS = frozenset({"revenue"})
7676

7777

78-
def _prefer_consolidated_totals(all_rows, chosen):
78+
def _prefer_consolidated_totals(period_rows, chosen):
7979
"""Replace a ranked pick with the same-period total it is a slice of.
8080
8181
The variant list orders *names*; it cannot tell that one name measures a
@@ -85,13 +85,17 @@ def _prefer_consolidated_totals(all_rows, chosen):
8585
the $77.1B its own income statement reports, and disagreed with
8686
`get_revenue()` for the same company and year.
8787
88+
`period_rows` must already be filtered to the caller's period window
89+
(`_of_period_type`): passing the unfiltered series lets 6M/9M YTD or annual
90+
rows on the same `period_end` dwarf and overwrite discrete quarterly picks.
91+
8892
Uses the same threshold as the standardized getters
8993
(`is_consolidated_total_over`) rather than a second copy of the rule, which
9094
is what let the two surfaces drift apart in the first place.
9195
"""
9296
from edgar.entity.utils import is_consolidated_total_over
9397

94-
largest = all_rows.groupby('period_end')['numeric_value'].max()
98+
largest = period_rows.groupby('period_end')['numeric_value'].max()
9599

96100
def _total_for(row):
97101
candidate = largest.get(row.period_end)
@@ -237,19 +241,21 @@ async def edgar_trends(
237241
# 10-Q pushed the correct annual row out of the window, which is
238242
# why the same call returned different concepts for different
239243
# values of `periods` (GH #1138).
240-
filtered = _of_period_type(ts, period)
244+
period_rows = _of_period_type(ts, period)
241245

242246
# One row per period: the highest-ranked concept present, then
243247
# the largest value, which drops segment-level facts reported
244248
# under the same concept as the consolidated figure.
245-
if not filtered.empty:
246-
filtered = (filtered
249+
if not period_rows.empty:
250+
filtered = (period_rows
247251
.sort_values(['period_end', '_concept_rank', 'numeric_value'],
248252
ascending=[False, True, False])
249253
.drop_duplicates(subset=['period_end'], keep='first'))
250254

251255
if concept_name in _CONSOLIDATED_TOTAL_CONCEPTS:
252-
filtered = _prefer_consolidated_totals(ts, filtered)
256+
filtered = _prefer_consolidated_totals(period_rows, filtered)
257+
else:
258+
filtered = period_rows
253259

254260
# Limit to requested periods
255261
filtered = filtered.head(periods)
Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
"""Regression: edgar_trends(period="quarterly") replaced quarterly revenue with 6M/9M YTD totals.
2+
3+
GitHub PR: https://github.com/dgunning/edgartools/pull/1168
4+
5+
PR #1168 added `_prefer_consolidated_totals` so an insurer's small ASC-606
6+
contract-revenue slice would yield to consolidated `Revenues` for the same
7+
period. However, `edgar_trends` passed the *unfiltered* time-series frame `ts`
8+
(which still holds 6-month, 9-month YTD, and 12-month FY rows on the same
9+
`period_end`) instead of the period-type-filtered rows.
10+
11+
Because `_CONSOLIDATED_TOTAL_FACTOR = 2.0`, 9M YTD (~3x a single quarter) and
12+
6M YTD (>= 2x a single quarter) silently overwrote discrete 3-month quarterly
13+
revenue on every company that files YTD figures:
14+
15+
AAPL Q3 FY2026 (0000320193-26-000020): reported $364.357B (9M YTD) vs $109.417B (3M)
16+
AAPL Q2 FY2026 (0000320193-26-000013): reported $254.940B (6M YTD) vs $111.184B (3M)
17+
TSLA Q3 2026 (0001628280-26-066775): reported $78.669B (9M YTD) vs $28.046B (3M)
18+
MET Q3 2026 (0001099219-26-000062): reported $58.750B (9M YTD) vs $20.522B (3M consolidated)
19+
20+
Passing the period-filtered frame to `_prefer_consolidated_totals` preserves the
21+
same-window consolidated-over-slice upgrade (MetLife Q3 upgrades $728M -> $20.522B)
22+
while preventing YTD/annual rows from bleeding into quarterly series.
23+
"""
24+
25+
import asyncio
26+
from datetime import date
27+
from types import SimpleNamespace
28+
from unittest.mock import patch
29+
30+
import pandas as pd
31+
import pytest
32+
33+
34+
def _make_fake_company(name: str, cik: str, series_by_concept: dict[str, pd.DataFrame]):
35+
class _FakeFacts:
36+
def time_series(self, concept: str, periods: int = 500):
37+
return series_by_concept.get(concept)
38+
39+
return SimpleNamespace(name=name, cik=cik, get_facts=lambda: _FakeFacts())
40+
41+
42+
def _trend_values(result, concept: str = "revenue") -> dict[str, float]:
43+
data = result.data if hasattr(result, "data") else result
44+
trend = data["trends"][concept]
45+
assert "error" not in trend, trend
46+
return {entry["period"]: entry["value"] for entry in trend["values"]}
47+
48+
49+
# --- Offline end-to-end regression tests ------------------------------------
50+
51+
52+
def test_quarterly_revenue_ignores_ytd_and_annual_rows_on_same_period_end():
53+
"""6M/9M YTD rows sharing a period_end must never overwrite 3M quarterly revenue."""
54+
from edgar.ai.mcp.tools.trends import edgar_trends
55+
56+
aapl_contract_rev = pd.DataFrame([
57+
# Q3 FY26: 3M discrete ($109.417B) alongside 9M YTD ($364.357B) on 2026-06-27
58+
{"fiscal_period": "Q3", "period_end": date(2026, 6, 27), "duration_days": 90, "numeric_value": 109_417_000_000.0},
59+
{"fiscal_period": "Q3", "period_end": date(2026, 6, 27), "duration_days": 272, "numeric_value": 364_357_000_000.0},
60+
# Q2 FY26: 3M discrete ($111.184B) alongside 6M YTD ($254.940B) on 2026-03-28
61+
{"fiscal_period": "Q2", "period_end": date(2026, 3, 28), "duration_days": 90, "numeric_value": 111_184_000_000.0},
62+
{"fiscal_period": "Q2", "period_end": date(2026, 3, 28), "duration_days": 181, "numeric_value": 254_940_000_000.0},
63+
# Q1 FY26: 3M discrete ($143.756B)
64+
{"fiscal_period": "Q1", "period_end": date(2025, 12, 27), "duration_days": 90, "numeric_value": 143_756_000_000.0},
65+
])
66+
fake = _make_fake_company(
67+
"Apple Inc.",
68+
"320193",
69+
{"us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax": aapl_contract_rev},
70+
)
71+
72+
with patch("edgar.ai.mcp.tools.trends.resolve_company", return_value=fake):
73+
result = asyncio.run(edgar_trends("AAPL", concepts=["revenue"], period="quarterly", periods=3))
74+
75+
values = _trend_values(result)
76+
assert values == {
77+
"2026-Q3": 109_417_000_000.0,
78+
"2026-Q2": 111_184_000_000.0,
79+
"2025-Q1": 143_756_000_000.0,
80+
}
81+
82+
83+
def test_quarterly_insurer_upgrades_slice_to_3m_total_without_jumping_to_ytd():
84+
"""MetLife Q3 must upgrade its 91d ASC-606 slice ($728M) to 91d Revenues ($20.522B), not 9M YTD ($58.75B)."""
85+
from edgar.ai.mcp.tools.trends import edgar_trends
86+
87+
asc606_slice = pd.DataFrame([
88+
{"fiscal_period": "Q3", "period_end": date(2026, 9, 30), "duration_days": 91, "numeric_value": 728_000_000.0},
89+
{"fiscal_period": "Q3", "period_end": date(2026, 9, 30), "duration_days": 272, "numeric_value": 2_186_000_000.0},
90+
{"fiscal_period": "Q2", "period_end": date(2026, 6, 30), "duration_days": 90, "numeric_value": 724_000_000.0},
91+
{"fiscal_period": "Q2", "period_end": date(2026, 6, 30), "duration_days": 180, "numeric_value": 1_458_000_000.0},
92+
])
93+
consolidated = pd.DataFrame([
94+
{"fiscal_period": "Q3", "period_end": date(2026, 9, 30), "duration_days": 91, "numeric_value": 20_522_000_000.0},
95+
{"fiscal_period": "Q3", "period_end": date(2026, 9, 30), "duration_days": 272, "numeric_value": 58_750_000_000.0},
96+
{"fiscal_period": "Q2", "period_end": date(2026, 6, 30), "duration_days": 90, "numeric_value": 19_154_000_000.0},
97+
{"fiscal_period": "Q2", "period_end": date(2026, 6, 30), "duration_days": 180, "numeric_value": 38_228_000_000.0},
98+
])
99+
fake = _make_fake_company(
100+
"METLIFE INC",
101+
"1099219",
102+
{
103+
"us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax": asc606_slice,
104+
"us-gaap:Revenues": consolidated,
105+
},
106+
)
107+
108+
with patch("edgar.ai.mcp.tools.trends.resolve_company", return_value=fake):
109+
result = asyncio.run(edgar_trends("MET", concepts=["revenue"], period="quarterly", periods=2))
110+
111+
values = _trend_values(result)
112+
assert values == {
113+
"2026-Q3": 20_522_000_000.0,
114+
"2026-Q2": 19_154_000_000.0,
115+
}
116+
117+
118+
def test_annual_insurer_still_upgrades_slice_to_fy_total():
119+
"""Annual mode continues to prefer same-year consolidated Revenues over ASC-606 slice."""
120+
from edgar.ai.mcp.tools.trends import edgar_trends
121+
122+
asc606_slice = pd.DataFrame([
123+
{"fiscal_period": "FY", "period_end": date(2025, 12, 31), "duration_days": 364, "numeric_value": 2_436_000_000.0},
124+
])
125+
consolidated = pd.DataFrame([
126+
{"fiscal_period": "FY", "period_end": date(2025, 12, 31), "duration_days": 364, "numeric_value": 77_084_000_000.0},
127+
# A stray multi-year row should not leak into annual either
128+
{"fiscal_period": "FY", "period_end": date(2025, 12, 31), "duration_days": 730, "numeric_value": 200_000_000_000.0},
129+
])
130+
fake = _make_fake_company(
131+
"METLIFE INC",
132+
"1099219",
133+
{
134+
"us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax": asc606_slice,
135+
"us-gaap:Revenues": consolidated,
136+
},
137+
)
138+
139+
with patch("edgar.ai.mcp.tools.trends.resolve_company", return_value=fake):
140+
result = asyncio.run(edgar_trends("MET", concepts=["revenue"], period="annual", periods=1))
141+
142+
assert _trend_values(result) == {"2025": 77_084_000_000.0}
143+
144+
145+
# --- Network regression against verified SEC 10-Q filings -------------------
146+
147+
148+
@pytest.mark.network
149+
@pytest.mark.regression
150+
@pytest.mark.parametrize("ticker,period_key,expected", [
151+
# Apple Q3 FY2026 10-Q (0000320193-26-000020): 3M $109.417B vs 9M YTD $364.357B
152+
("AAPL", "2026-Q3", 109_417_000_000),
153+
# Apple Q2 FY2026 10-Q (0000320193-26-000013): 3M $111.184B vs 6M YTD $254.940B
154+
("AAPL", "2026-Q2", 111_184_000_000),
155+
# Tesla Q3 2026 10-Q (0001628280-26-066775): 3M $28.046B vs 9M YTD $78.669B
156+
("TSLA", "2026-Q3", 28_046_000_000),
157+
# MetLife Q3 2026 10-Q (0001099219-26-000062): 3M consolidated $20.522B (vs $728M slice & $58.75B 9M YTD)
158+
("MET", "2026-Q3", 20_522_000_000),
159+
])
160+
def test_quarterly_revenue_matches_discrete_10q_filings(ticker, period_key, expected):
161+
from edgar.ai.mcp.tools.trends import edgar_trends
162+
163+
result = asyncio.run(
164+
edgar_trends(ticker, concepts=["revenue"], period="quarterly", periods=6)
165+
)
166+
values = _trend_values(result)
167+
assert values[period_key] == expected

0 commit comments

Comments
 (0)