AI Analytics

Technical writing

IRS Exempt Organizations: The Recognition and Form 990 Record

· AI Analytics
IRSNonprofits501(c)(3)Tax-ExemptFederal Data

The Internal Revenue Service publishes two different records that must not be conflated. The Exempt Organizations Business Master File (EO BMF) is a monthly account/status extract; only a documented STATUS-filtered cohort can support a bounded recognition statement. It is not a census of every tax-exempt organization. The Form 990 files contain electronically filed returns from organizations required or choosing to file. Churches that were not required to apply and did not apply can be absent from the BMF, and churches generally fall within an annual-return filing exception. A missing BMF row or Form 990 is therefore not evidence of misconduct.

Scale and composition of the tax-exempt sector

The exempt sector spans many IRC subsection categories and several source systems. A dated BMF snapshot can report the recognized rows carried under each subsection, while the IRS Statistics of Income extracts can report filing-derived finances for specified calendar years. Neither source should be presented as a timeless count or a census of every tax-exempt organization.

Section 501(c)(3) includes public charities and private foundations; 501(c)(4) covers social-welfare organizations; 501(c)(6) covers business leagues; and 501(c)(7) covers social clubs. Counts must come from the acquired source version and retain the IRS subsection code. Presence in the EO-BMF account/status extract does not by itself establish recognition or current operation; the STATUS value must be retained.

Religious organizations create a major gap in the public data. Churches, certain integrated auxiliaries, and conventions or associations of churches generally are not required to file annual Form 990 returns. Churches that meet the requirements of IRC § 501(c)(3) are automatically considered tax-exempt and are not required to apply for IRS recognition. IRC § 7611 separately establishes procedures and approvals for church tax inquiries; it is not a substitute filing or a finding about any institution. The result is a lawful disclosure gap: BMF and Form 990 counts cannot establish the size of the religious sector, and absence from either file cannot be treated as evasion.

The EO BMF: structure and field layout

The IRS publishes the EO BMF at https://www.irs.gov/charities-non-profits/exempt-organizations-business-master-file-extract-eo-bmf as four comma-separated-value region files updated monthly: eo1.csvthrough eo4.csv. Together they cover the states, territories, international organizations, and rows without a state code. Each row represents one EO-BMF account/status record. A recognition cohort requires an explicit STATUS filter; the whole extract is not a uniform list of recognized exempt organizations. The extract explicitly omits self-declared organizations and churches or other organizations that were not required to apply and did not apply. Key fields:

  • EIN: the nine-digit Employer Identification Number, zero-padded, no hyphens. It is the primary stable identifier across IRS recognition and filing records that carry it. USAspending recipient search does not expose EIN; it uses name, UEI, and legacy DUNS, so cross-system publication requires a separately verified exact EIN-to-UEI mapping. Organization names alone cannot close that join.
  • SUBSECTION: a two-digit code for the IRC exemption subsection. 03 = 501(c)(3), 04 = 501(c)(4), 06 = 501(c)(6), 07 = 501(c)(7), and 27 = 501(c)(27). Values 01 through 29 map to IRC subsections 501(c)(1) through 501(c)(29).
  • STATUS: the EO-account posture, which must be preserved before describing any recognition cohort. In the August 11, 2026 files, STATUS 01 has 1,949,212 rows, STATUS 12 has 6,640, STATUS 25 has 847, and STATUS 02 has 641. STATUS 01/02 can support a bounded recognition cohort; STATUS 12 includes return-filing accounts without a favorable exemption determination, and STATUS 25 records a private-foundation status termination process. Current IRS descriptions and the observed file do not fully agree about STATUS 12 inclusion, so the source version and observed distribution belong in the acquisition receipt.
  • FOUNDATION: a two-digit code distinguishing types within 501(c)(3). Codes 02 and 03 identify private operating foundations, and code 04 identifies a private non-operating foundation. Code 10 is church under 170(b)(1)(A)(i); code 15 is a publicly supported organization under 170(b)(1)(A)(vi); and codes 16–18 and 21–24 identify other public-charity support types. Preserve the source code rather than collapsing these categories.
  • RULING: a six-digit YYYYMM IRS ruling or determination month. It is not the organization's founding date. Cohort analysis must label it as an IRS administrative date and separately reconcile later revocation and reinstatement records.
  • DEDUCTIBILITY: code 1 means contributions to the organization are deductible for donors as charitable contributions under IRC § 170; code 2 means they are not. Preserve and decode this source field independently rather than inferring deductibility from the subsection alone.
  • ORGANIZATION: type code 1 = corporation, 2 = trust, 3 = cooperative, 4 = partnership, 5 = association. The organizational form matters for governance: corporations have boards; trusts have trustees; the distinction affects state law obligations and IRS treatment of certain transactions.
  • ASSET_CD / INCOME_CD: range codes (0–9) giving bucketed asset and income amounts. Code 0 is the source-coded $0 band; an absent exact amount is retained separately as missing. Code 9 = $50M or more. These are coarse but sufficient for stratified sampling: a researcher wanting to study mid-size nonprofits can filter to ASSET_CD = 6 or 7 ($1M–$10M) without downloading all 990 XML.
  • NTEE_CD: the documented National Taxonomy of Exempt Entities shape is three or four alphanumeric characters. In a valid value, the first character is the major group letter (A through Z), the next two characters specify a subdivision, and an optional fourth character further defines the classification. An organization assigned NTEE code E22 is in major group E (Health) subdivision 22 (Hospitals). B82 is Education—Scholarships. P20 is Human Services—Multipurpose. NTEE major group X is religion-related and is broader than “church.” The August 11, 2026 four-file snapshot contains 1,235,239 three-character values, 147,447 four-character values, 207 malformed two-character values, and 574,447 blanks. Blank and malformed values must be reported as unclassified; a short value such as X2 must not enter the NTEE-X total merely because it starts with X. Organizations absent from the BMF have no BMF NTEE value at all. NTEE X therefore supports a religion-related discovery cohort, not a definitive church classification.

NTEE: the nonprofit classification system

The National Taxonomy of Exempt Entities was developed by the National Center for Charitable Statistics (NCCS) at the Urban Institute in partnership with the IRS. It provides a hierarchical classification of nonprofit organizational purposes across 26 major categories designated by letters A through Z. Within each major group, two-character alphanumeric subclassifications identify specific activity types; the IRS can append an optional fourth character that further defines the classification. The taxonomy is more granular than it appears from the major category list—the Education (B) category alone contains over 30 distinct subdivision codes covering everything from preschools (B21) to graduate and professional schools (B50) to libraries (B70) to student financial aid (B82) to educational services (B90).

NTEE category counts depend on the acquisition snapshot, exemption-subsection filter, source status code, and handling of blank or unclassified values. This article does not publish a prose ranking without a pinned acquisition date, explicit denominator, and a separately reported Z/blank/malformed/unclassified count; the sample first validates the full ^[A-Z][A-Z0-9]{2,3}$ shape and computes the distribution from all four validated region files instead.

NTEE codes are assigned by the IRS based on information submitted during the exemption application process (Form 1023 for 501(c)(3)s, Form 1024 for most others). They are not always accurate—organizations that change their primary purpose do not automatically receive updated codes, and the IRS assignment process has historically applied codes inconsistently across regions and time periods. NCCS has developed a supplementary “NTEE-CC” (Core Code) system that regularizes codes and provides cleaner data for longitudinal research; this cleaned version is distributed through the NCCS data archive at Urban Institute and through Candid's GuideStar platform.

Current IRS Form 990 e-file XML distribution

The current official bulk distribution is the IRS Tax Exempt Organization Search XML directory at https://apps.irs.gov/pub/epostcard/990/xml/{year}/. As reviewed on August 21, 2026, the IRS download surface exposes annual indexes and XML ZIP batches for 2019 through 2026. That current distribution window must not be described as the complete history of electronically filed returns.

Each annual index_{year}.csv inventory includes anOBJECT_ID and XML_BATCH_ID. The batch identifier selects the ZIP file in that year's directory, and the object identifier selects the exact{OBJECT_ID}_public.xml member inside that archive. Preserve the annual index, acquisition timestamp, response validators, and archive/member hashes; resolve amendments or superseding returns before making institution-level claims.

The Form 990 XML follows an IRS-defined schema that has evolved across tax years. The XML namespace for recent filings is http://www.irs.gov/efile; older filings use variants of this namespace with year-specific suffixes. Any production parser must handle namespace variation. The top-level structure is a Return element containing a ReturnHeader (EIN, organization name, tax year, preparer information) and one or more ReturnData elements containing the substantive financial data organized by form part.

Key financial fields accessible in 990 XML by XPath (within the IRS efile namespace):

  • Part I summary totals: CYTotalRevenueAmt, CYTotalExpensesAmt, TotalAssetsEOYAmt, TotalLiabilitiesEOYAmt, NetAssetsOrFundBalancesEOYAmt. These provide a balance-sheet snapshot sufficient for most financial screening.
  • Institution-only boundary: Form 990 can contain natural-person names, titles, compensation, preparer details, and other human fields. This project does not ingest or republish those fields; the financial analysis remains at the institution level.
  • Part IX functional expenses: TotalFunctionalExpensesGrp contains TotalAmt, ProgramServicesAmt, ManagementAndGeneralAmt, and FundraisingAmt. These are reported allocations, not an automatic efficiency or misconduct score.
  • Schedule C political and lobbying activity: PoliticalCampaignActyInd (yes/no flag for any participation in political campaign activity), LobbyingActivitiesInd, and, in the reviewed TY2025 schema, TotalDirectLobbyingGrp/FilingOrganizationsTotalAmt. Amount paths vary across schema versions and must be pinned to the return's schema. A reported “yes” is a source lead, not a violation finding: review the schedule, organization type, tax period, and any identified IRS or court disposition before drawing an adverse conclusion.
  • Schedule L related-party transactions: loans to or from officers, directors, or key employees; business transactions with interested persons. The schedule reports transactions and relationships; it does not itself establish prohibited self-dealing. Any adverse claim requires the transaction facts, governing rule, tax period, and an identified official action or adjudicated outcome.

The Form 990-PF (private foundation return) has a different schema from the standard 990. It is required for all private foundations regardless of size—even a small family foundation with $500,000 in assets must file. Part I line 1 reports contributions, gifts, and grants received—not total investment income. Grants paid or approved are itemized in a supplementary grant list whose part number changes across form years (Part XIV on the 2025 form and Part XV on older forms). A durable parser must pin the tax year and follow that year's official form, instructions, and XML schema rather than hard-coding one part number.

ProPublica Nonprofit Explorer and the search API

ProPublica's Nonprofit Explorer at projects.propublica.org/nonprofits provides a public-facing search interface over parsed 990 data, and more importantly exposes a JSON API that developers can query programmatically without the overhead of downloading and parsing raw IRS XML. The API base URL is https://projects.propublica.org/nonprofits/api/v2/.

The organization detail endpoint at /organizations/{ein}.json separates anorganization profile derived from BMF fields fromfilings_with_data summary rows. The filing summaries expose selected form totals and a pdf_url field, which can be null. They do not expose an XML URL. Use the current official IRS annual index and XML batch identifiers when an exact source filing is required; do not infer a complete filing history from this convenience response.

The search endpoint at /search.json accepts query parameters including q (text search against organization name), state[id] (two-letter state code), ntee[id] (an integer category from 1 through 10; Religion Related is 8), c_code[id] (subsection code, e.g., 3 for 501(c)(3)), and sort options including revenue and name. The documented endpoint uses unauthenticated GET requests. Clients should still cache responses, preserve acquisition evidence, and handle HTTP errors without inventing an undocumented quota or completeness guarantee.

Candid (formerly GuideStar) and the Urban Institute's NCCS Data Archive provide separate nonprofit-data products and transformations. Their coverage, licensing, update cadence, and field provenance must be evaluated directly before use; this article does not rank them or substitute either one for the official IRS filing.

Schedule A and the public support test

IRC § 509(a) divides 501(c)(3) organizations into public charities and private foundations. A 501(c)(3) is presumed to be a private foundation unless an exception applies. Section 509(a)(1) incorporates the institutional categories in § 170(b)(1)(A), including § 170(b)(1)(A)(i) for a church, § 170(b)(1)(A)(ii) for a school, § 170(b)(1)(A)(iii) for a hospital, and § 170(b)(1)(A)(vi) for the publicly supported route. Section 509(a)(2) supplies a separate support route. Schedule A records the organization's claimed public-charity category and any computation that category requires.

The 33.3-percent support test and the separate 10-percent facts-and-circumstances route belong specifically to § 170(b)(1)(A)(vi), generally using a rolling five-year computation period. Contributions from one person generally count in the public-support numerator only up to 2 percent of total support for that computation. A qualifying church described in § 170(b)(1)(A)(i) does not have to pass the clause (vi) support fraction merely to qualify as a public charity.

Under the § 509(a)(2) test, used primarily by membership organizations and social service agencies that earn fees for services, more than one-third of support must come from fees for exempt function services plus government and public contributions, while gross investment income plus net unrelated-business income must not exceed one-third of total support. The exact Schedule A computation and exclusions must be read for the return's tax year.

Public-support status uses a multi-year computation and transition rules. A single ratio or one return should not be converted into an automatic reclassification or compliance finding.

Private foundations: the excise tax regime

Private foundations in the BMF use foundation codes 02, 03, or 04; code 15 instead identifies a publicly supported organization under 170(b)(1)(A)(vi). Private foundations are typically funded by a single donor, family, or corporation rather than by broad public support. Congress subjected private foundations to a strict excise tax regime in the Tax Reform Act of 1969 in response to abuses by foundations used primarily to maintain family control of businesses or to engage in self-dealing.

The current private-foundation excise-tax structure includes the § 4940 net investment income tax plus five Chapter 42 regimes under §§ 4941–4945:

  • Net investment income tax (IRC § 4940): a 1.39 percent excise tax on net investment income (interest, dividends, capital gains, rents, and royalties less investment expenses) for most domestic tax-exempt private foundations. An exempt operating foundation that qualifies under § 4940(d) is exempt from this tax, so the rule is not universal. Before 2020 a two-tiered rate (2 percent standard, 1 percent if distributions exceeded historical average) applied; the Taxpayer Certainty and Disaster Tax Relief Act of 2019 simplified this to a flat 1.39 percent.
  • Self-dealing rules (IRC § 4941): specified direct or indirect acts between a private foundation and disqualified persons can be taxable self-dealing unless a statutory exception applies. Covered categories include sales, exchanges, leases, lending, transfers, and certain compensation or service arrangements. Penalties can include an initial excise tax of 10 percent of the transaction amount on the disqualified person, plus 5 percent on the foundation manager who approved it; if the violation is not corrected, additional taxes of 200 percent and 50 percent respectively apply.
  • Distributable amount (IRC § 4942): a nonoperating private foundation generally must make qualifying distributions equal to its distributable amount. The starting minimum-investment-return calculation is approximately 5 percent of the fair-market value of noncharitable-use assets, less acquisition indebtedness, with statutory and form adjustments; it is not 5 percent of total net asset value. Undistributed income can trigger a 30 percent first-tier excise tax. “Qualifying distributions” include grants to public charities, reasonable administrative expenses, and direct charitable expenditures; program-related investments (PRIs) such as below-market loans to charitable projects also count. The calculation can shape grantmaking and cash management, but it is not a blanket requirement that every private foundation liquidate 5 percent of all assets.
  • Excess business holdings (IRC § 4943): a private foundation generally may hold 20 percent of a business enterprise's voting stock, reduced by the percentage held by disqualified persons; a 35-percent limit can apply when effective control rests with unrelated persons. A separate de minimis rule can permit holdings of no more than 2 percent of both voting power and value. Additional transition and disposition rules require source-specific review.
  • Jeopardizing investments (IRC § 4944): a private foundation may not make investments that jeopardize its charitable purpose—speculative ventures that could impair the foundation's ability to carry out its exempt purposes. The initial excise tax is 10 percent of the investment amount on the foundation; 10 percent on the foundation manager who approved it.
  • Taxable expenditures (IRC § 4945): expenditures for lobbying, political campaign activity, certain grants to individuals for travel, study, or similar purposes unless the grant procedure has advance IRS approval under § 4945(g), and certain grants to organizations other than those described in § 509(a)(1)–(3) or qualifying exempt operating foundations unless the private foundation exercises “expenditure responsibility.” Ordinary grants for poverty or distress relief are not treated as travel-or-study grants merely because an individual receives them. Other non-charitable expenditures can also fall within § 4945. The applicable foundation and manager taxes have their own statutory rates and correction rules.

Form 990-PF publicly reports selected financial and grant information, including the foundation's assets at fair market value, its net investment income, excise tax paid, distributable amount, actual qualifying distributions, grants paid (by recipient organization and purpose), and some excise-tax corrections. It is a filed disclosure for a tax period, not a complete record of conduct or a compliance verdict.

501(c)(3) vs. 501(c)(4): political activity rules

The most consequential distinction in nonprofit law for purposes of political transparency is between 501(c)(3) public charities and 501(c)(4) social welfare organizations. These categories have different political-activity and annual-return rules, and any institution-level claim must be tied to the applicable tax period and an identified official action.

A 501(c)(3) organization is absolutely prohibited from participating in any political campaign activity on behalf of or in opposition to any candidate for public office under IRC § 501(c)(3)'s direct statutory language. This prohibition is categorical. Prohibited campaign intervention may result in denial or revocation of exempt status, and IRC § 4955 excise taxes may also apply. The initial organization-level tax is 10 percent of the political expenditure; if the expenditure is not timely corrected, a second-tier 100 percent tax can apply. Separate manager taxes may apply under the statutory conditions. A 501(c)(3) may engage in non-partisan voter education, candidate forums, and legislative advocacy, but a filed indicator is not itself an IRS finding that prohibited intervention occurred.

Lobbying by 501(c)(3) organizations is permitted but regulated. Eligible public charities may elect the expenditure test under IRC § 501(h), but churches, integrated auxiliaries, conventions or associations of churches, members of an affiliated group that includes one of those church organizations, and private foundations are ineligible for that election. For eligible electing organizations, the total lobbying nontaxable amount follows a sliding scale: 20 percent of the first $500,000 of exempt-purpose expenditures, then 15, 10, and 5 percent across the statutory bands, capped at $1 million. The grassroots lobbying nontaxable amount is 25 percent of the total lobbying nontaxable amount. Organizations outside the election remain subject to the substantial-part test.

A 501(c)(4) social welfare organization operates under the standard that its primary purpose must be the promotion of the common good and general welfare of the community—but political activity may be a secondary activity so long as it is not the organization's primary activity. Federal election reporting or registration duties depend on the organization's actual conduct and the applicable election law; 501(c)(4) status does not itself resolve those duties. Contributor identities generally are not publicly disclosed through the organization's IRS annual return, but another governing law or filing can create a separate disclosure duty.

The 2013 IRS “targeting controversy”—commonly associated with IRS official Lois Lerner—involved the use of Be On the Lookout (BOLO) lists that disproportionately flagged applications from Tea Party-affiliated 501(c)(4) organizations for additional scrutiny. The Treasury Inspector General for Tax Administration (TIGTA) documented the improper use of political criteria in the exemption application process. Separately, section 405 of the Protecting Americans from Tax Hikes Act of 2015, Public Law 114-113, division Q, created IRC § 506. Effective December 18, 2015, the provision generally requires a new 501(c)(4) organization to submit Form 8976 notice within 60 days of formation.

Section 527 organizations operate under separate IRS and election-law filing regimes. Which disclosure system applies depends on the entity and activity. This project does not ingest or republish contributor identities from either system.

Schedule B and the donor disclosure debate

Schedule B is the contribution schedule attached to Forms 990, 990-EZ, and 990-PF when its filing tests apply. Section 501(c)(3) and section 527 filers generally report the required contributor names and addresses to the IRS; other exempt organizations generally do not report those identities on Schedule B, although contribution amounts and other non-identifying information remain reportable. Public-inspection treatment also differs: Schedule B is open for Form 990-PF and section 527 filings, while contributor names and addresses generally are withheld from public Form 990 and 990-EZ copies for other filers. This project does not ingest or republish contributor identities, including where another source may make them public.

The confidentiality of Schedule B has been the subject of sustained litigation. The fundamental tension is between donor privacy (the First Amendment right of association, which the Supreme Court in NAACP v. Alabama (1958) recognized as protecting donor identities from disclosure when disclosure would chill protected association) and public accountability for organizations receiving significant tax subsidies. For 501(c)(3) charities, the balance has traditionally favored privacy. For 501(c)(4) organizations engaged in substantial political activity, critics argue that Schedule B confidentiality enables anonymous political spending that undermines democratic accountability.

California's Attorney General historically required 501(c)(4) organizations soliciting donations in California to file Schedule B with the state registry. The Supreme Court struck down this requirement in Americans for Prosperity Foundation v. Bonta (2021), holding it facially unconstitutional under the First Amendment because the state could not demonstrate that its across-the-board disclosure requirement was narrowly tailored to its interest in investigating charitable misconduct. The decision makes state-level Schedule B disclosure requirements constitutionally precarious going forward.

Accessing the data programmatically

The IRS EO BMF is available at the URL above as four regional CSV files,eo1.csv through eo4.csv. No API key or registration is required. The files are updated monthly; researchers building databases should implement a differential ingestion process comparing the current month's BMF against prior snapshots to detect new organizations, revocations, and address changes. The IRS does not publish a delta file; full snapshots must be compared.

For Form 990 XML, fetch the year's official https://apps.irs.gov/pub/epostcard/990/xml/{year}/index_{year}.csv, validate its schema, and use XML_BATCH_ID to select the referenced ZIP. Use OBJECT_ID to select the exact {OBJECT_ID}_public.xml member. Downloading a batch or using bounded HTTP range requests are both possible acquisition strategies, but either path should enforce archive-size, member-size, CRC, decompression-ratio, and hash checks before XML parsing. No AWS credential or retired bucket workflow is part of the current contract.

The ProPublica API can reduce parsing work when its documented summary fields are sufficient. When a claim depends on a specific schedule or exact filing field, retrieve the corresponding official IRS XML ZIP batch, select the indexed object, validate the member, and parse the tax-year-specific schema. Third-party convenience data should be reconciled to that filing; this article makes no comparative completeness or fitness claim for academic, journalistic, compliance, or due-diligence use.

Python example: BMF coverage and a religion-related cohort

The script downloads all four current EO BMF region files, counts source-status 01 501(c)(3) recognition rows by NTEE major category, and produces an aggregate asset-band distribution for NTEE X. It labels NTEE X as a religion-related discovery cohort, not a church determination, and does not publish borrower, donor, or street-address data.

import requests
import pandas as pd
import csv
import io
import re
from collections import defaultdict

# ---------------------------------------------------------------------------
# IRS Exempt Organizations: BMF Aggregate Analysis
#
# Part 1: Download all four IRS EO BMF region files and count recognized 501(c)(3)
#         rows by NTEE major category (A through Z). This is not a census.
# Part 2: Isolate the source-native NTEE X religion-related cohort.
# Part 3: Print aggregate distributions without publishing street addresses or
#         treating an IRS category, missing filing, or asset value as misconduct.
#
# IRS BMF landing page (four comma-separated region files, updated monthly):
#   https://www.irs.gov/charities-non-profits/exempt-organizations-business-master-file-extract-eo-bmf
# ---------------------------------------------------------------------------

BMF_BASE = "https://www.irs.gov/pub/irs-soi"
BMF_FILES = ["eo1.csv", "eo2.csv", "eo3.csv", "eo4.csv"]
# Retain only the four source fields used by this aggregate analysis.
ANALYSIS_FIELDS = ("SUBSECTION", "STATUS", "NTEE_CD", "ASSET_CD")
EXPECTED_STATUS_CODES = {"01", "02", "12", "25"}

# NTEE major category names (26 groups, A through Z)
NTEE_LABELS: dict[str, str] = {
    "A": "Arts, Culture, Humanities",
    "B": "Education",
    "C": "Environment",
    "D": "Animal Services",
    "E": "Health",
    "F": "Mental Health",
    "G": "Disease / Disorder Research",
    "H": "Medical Research",
    "I": "Crime & Legal",
    "J": "Employment",
    "K": "Food, Agriculture & Nutrition",
    "L": "Housing & Shelter",
    "M": "Public Safety, Disaster",
    "N": "Recreation & Sports",
    "O": "Youth Development",
    "P": "Human Services",
    "Q": "International / Foreign Affairs",
    "R": "Civil Rights / Advocacy",
    "S": "Community Improvement",
    "T": "Philanthropy / Voluntarism",
    "U": "Science & Technology",
    "V": "Social Science Research",
    "W": "Public / Society Benefit",
    "X": "Religion-Related",
    "Y": "Mutual / Membership Benefit",
    "Z": "Unknown / Unclassified",
}
NTEE_PATTERN = re.compile(r"^[A-Z][A-Z0-9]{2,3}$")


def fetch_bmf_regions() -> list[dict[str, str]]:
    """
    Download all four current IRS EO BMF region CSVs and return row dicts.
    Filters to SUBSECTION == '03' (501c3) and exact source STATUS 01.

    The result is a STATUS 01 recognition cohort from the broader account/status
    extract. It excludes churches and other organizations that were not required
    to apply and did not apply.

    Column names are on the first row. EIN is a 9-digit string (no hyphens).
    The documented NTEE_CD shape is three or four alphanumeric characters, but
    source files can also contain blanks and malformed short values. Those
    values remain unclassified rather than inheriting a major-group letter.
    Preserve a source manifest and hashes in production.
    """
    rows = []
    status_counts: dict[str, int] = defaultdict(int)
    for filename in BMF_FILES:
        url = BMF_BASE + "/" + filename
        print("Downloading " + url + " ...")
        resp = requests.get(url, timeout=180)
        resp.raise_for_status()
        reader = csv.DictReader(io.StringIO(resp.content.decode("latin-1")))
        if not set(ANALYSIS_FIELDS).issubset(reader.fieldnames or []):
            raise RuntimeError(filename + " does not match the expected EO BMF schema")
        for row in reader:
            status = row.get("STATUS", "").strip()
            if not re.fullmatch(r"\d{2}", status) or status not in EXPECTED_STATUS_CODES:
                raise RuntimeError(filename + " contains an unreviewed STATUS value: " + repr(status))
            status_counts[status] += 1
            asset_code = row.get("ASSET_CD", "").strip()
            if asset_code not in {str(value) for value in range(10)}:
                raise RuntimeError(filename + " contains an invalid ASSET_CD value")
            # STATUS 01 = source unconditional-exemption code; SUBSECTION 03 = 501(c)(3).
            if row.get("SUBSECTION", "").strip().zfill(2) == "03" and status == "01":
                rows.append({field: row.get(field, "") for field in ANALYSIS_FIELDS})
    print("Observed EO-BMF STATUS distribution:")
    for status in sorted(status_counts):
        print("  STATUS " + status + ": " + str(status_counts[status]))
    if not rows:
        raise RuntimeError("EO BMF returned an empty STATUS 01 / SUBSECTION 03 cohort")
    print(f"Recognized 501(c)(3) rows in downloaded BMF: {len(rows):,}")
    return rows


def count_by_ntee_major(
    rows: list[dict[str, str]],
) -> tuple[pd.DataFrame, dict[str, int]]:
    """
    Count valid NTEE codes by major group. Blank and malformed values are
    reported separately and included in the Z/unclassified denominator.
    """
    counts: dict[str, int] = defaultdict(int)
    quality = {"blank": 0, "malformed": 0}
    for row in rows:
        ntee = row.get("NTEE_CD", "").strip().upper()
        if not ntee:
            quality["blank"] += 1
            major = "Z"
        elif not NTEE_PATTERN.fullmatch(ntee):
            quality["malformed"] += 1
            major = "Z"
        else:
            major = ntee[0]
            if major not in NTEE_LABELS:
                quality["malformed"] += 1
                major = "Z"
        counts[major] += 1

    records = [
        {
            "major": k,
            "label": NTEE_LABELS[k],
            "count": counts.get(k, 0),
        }
        for k in sorted(NTEE_LABELS.keys())
    ]
    df = pd.DataFrame(records)
    df["pct"] = 100.0 * df["count"] / df["count"].sum()
    return df.sort_values("count", ascending=False).reset_index(drop=True), quality


def print_ntee_table(df: pd.DataFrame, quality: dict[str, int]) -> None:
    total = df["count"].sum()
    print()
    print(f"Recognized 501(c)(3) BMF Rows by NTEE Major Category  (n={total:,})")
    print()
    print(f"  {'#':>3}  {'Cat':>3}  {'Label':<38}  {'Count':>8}  {'Share':>7}")
    print("  " + "-" * 68)
    for i, row in df.iterrows():
        print(
            f"  {i+1:>3}  {row['major']:>3}  {row['label']:<38}"
            f"  {int(row['count']):>8,}  {row['pct']:>6.1f}%"
        )
    print()
    print("NTEE source quality: blank=" + str(quality["blank"])
          + " malformed=" + str(quality["malformed"]))
    print("Blank/malformed values are included in Z/unclassified, never in X.")
    print()


def main() -> None:
    # --- Part 1: BMF subsector count ---
    bmf_rows = fetch_bmf_regions()
    ntee_df, ntee_quality = count_by_ntee_major(bmf_rows)
    print_ntee_table(ntee_df, ntee_quality)

    # --- Part 2: Aggregate asset ranges for the NTEE X discovery cohort ---
    # ASSET_CD codes: 0=$0, 1=$1-$9,999, 2=$10,000-$24,999,
    #                 3=$25,000-$99,999, 4=$100,000-$499,999,
    #                 5=$500,000-$999,999, 6=$1,000,000-$4,999,999,
    #                 7=$5,000,000-$9,999,999, 8=$10,000,000-$49,999,999,
    #                 9=$50,000,000 and greater.
    ASSET_LABELS = {
        "0": "$0", "1": "$1-$9,999", "2": "$10,000-$24,999",
        "3": "$25,000-$99,999", "4": "$100,000-$499,999",
        "5": "$500,000-$999,999", "6": "$1,000,000-$4,999,999",
        "7": "$5,000,000-$9,999,999", "8": "$10,000,000-$49,999,999",
        "9": "$50,000,000 and greater",
    }
    x_rows = []
    for row in bmf_rows:
        ntee = (row.get("NTEE_CD") or "").strip().upper()
        if NTEE_PATTERN.fullmatch(ntee) and ntee.startswith("X"):
            x_rows.append(row)
    asset_counts: dict[str, int] = defaultdict(int)
    for r in x_rows:
        cd = r["ASSET_CD"].strip()
        asset_counts[cd] += 1

    print(f"Religion-Related discovery cohort (NTEE X)  (n={len(x_rows):,})")
    print("NTEE X is broader than church and covers only rows carried in the BMF.")
    print()
    print(f"  {'Asset Range':<20}  {'Count':>8}  {'Share':>7}")
    print("  " + "-" * 42)
    for cd in sorted(ASSET_LABELS.keys()):
        ct = asset_counts.get(cd, 0)
        pct = 100.0 * ct / len(x_rows) if x_rows else 0
        print(f"  {ASSET_LABELS[cd]:<20}  {ct:>8,}  {pct:>6.1f}%")
    print()


if __name__ == "__main__":
    main()

The output must be read as a measurement of the downloaded EO-BMF account/status extract after filtering to STATUS 01 and subsection 03. NTEE distributions and asset bands can describe that bounded cohort, but they cannot estimate the number or wealth of all churches because non-applying churches are absent and NTEE X includes religion-related entities that are not churches.

For organizations that file, exact financial analysis belongs in the dated Form 990, 990-EZ, or 990-PF record. Keep return period, form type, amendment status, and source URL with every value; do not turn a large asset or revenue amount into a misconduct finding.

For the federal foreign assistance database where many large US nonprofits—including Catholic Relief Services, Save the Children, World Vision, and the International Rescue Committee—appear as implementing partners receiving USAID contracts and grants, with award-level data on obligation amounts, recipient countries, DAC sector codes, and year-over-year disbursement trends, see USAID Foreign Aid Data: The Federal Database Behind $40 Billion in Annual US Development Assistance (2026-12-04).

For the Social Security Administration's OASDI dataset covering 70 million beneficiaries and $1.4 trillion in annual benefit payments—and the connection between nonprofit-sector employment and Form SSA-1099 Social Security contributions, including how nonprofit employees with 401(k)-equivalent 403(b) plans interact with Social Security benefit calculations through the Windfall Elimination Provision and Government Pension Offset—see Social Security OASDI: The Federal Data Behind $1.4 Trillion in Annual Benefits and 70 Million Recipients.