Compare hospital capacity and patient-service margins in Python
Add report-specific dates, beds and net patient revenue to a hospital roster, then calculate a patient-service margin.
Add financial context to a hospital roster
You have hospital CMS Certification Numbers (CCNs) and want to compare financial scale and capacity. This example adds beds, net patient revenue and report dates, then calculates patient-service income as a percentage of net patient revenue.
The optional input.csv contains three real North Carolina hospital selections. The same CCNs appear in the roster list in the Python code below. The hospital names and financial observations come from CMS; none are invented.
Download reports.csv into your working folder. It is a genuine subset of the purchased file: every report for these three CCNs, with all 226 columns retained. The full $29 reference contains 6,109 reports for 6,026 CCNs, hospital report coverage and source documentation across five CSV tables. Review the complete product and coverage.
Code example
Run the code in a notebook cell, IPython or a script beside reports.csv. It uses Python’s standard library. All matching reports are printed with their dates; it does not pick a preferred filing or drop repeated CCNs.
Paths are relative to your working folder; use from pathlib import Path; print(Path.cwd()) to check it, or supply full paths.
import csv
from decimal import Decimal
from pathlib import Path
# Real hospital selections, also supplied in input.csv.
roster = [
{'facility_ccn': '340030'},
{'facility_ccn': '340040'},
{'facility_ccn': '340069'},
]
def compare_hospitals(roster, directory='.'):
selected = {row['facility_ccn'] for row in roster}
reports = []
seen = set()
with (Path(directory) / 'reports.csv').open(encoding='utf-8', newline='') as file:
for row in csv.DictReader(file):
if row['report_id'] in seen:
raise ValueError('Duplicate report ID')
seen.add(row['report_id'])
if row['facility_ccn'] in selected:
reports.append(row)
results = []
for row in sorted(reports, key=lambda r: (r['facility_ccn'], r['period_start'], r['report_id'])):
result = {key: row[key] for key in [
'facility_ccn', 'report_id', 'hospital_name', 'period_start', 'period_end',
'period_days', 'ccn_report_count', 'beds', 'net_patient_revenue',
'operating_expense', 'patient_service_income']}
result.update(patient_service_margin_pct='', margin_status='unavailable')
if row['net_patient_revenue_status'] == row['patient_service_income_status'] == 'reported':
revenue = Decimal(row['net_patient_revenue'])
result['margin_status'] = 'nonpositive_revenue'
if revenue > 0:
margin = Decimal(row['patient_service_income']) / revenue * 100
result.update(patient_service_margin_pct=f'{margin:.2f}', margin_status='calculated')
margin_text = result['patient_service_margin_pct'] + '%' if result['margin_status'] == 'calculated' else result['margin_status']
beds = row['beds'] if row['beds_status'] == 'reported' else row['beds_status']
revenue_text = f"${Decimal(row['net_patient_revenue']):,.0f}" if row['net_patient_revenue_status'] == 'reported' else row['net_patient_revenue_status']
print(f"{row['facility_ccn']} | {row['hospital_name']} | report {row['report_id']} | {row['period_start']} to {row['period_end']} ({row['period_days']} days) | {beds} beds | {revenue_text} net patient revenue | {margin_text} patient-service margin")
results.append(result)
for ccn in sorted(selected - {row['facility_ccn'] for row in reports}):
print(f'{ccn} | not in this file; no activity inferred')
return results
results = compare_hospitals(roster)
Replace roster with your CCN selections or rows read from a CSV. Preserve identifiers as strings. Set directory when calling compare_hospitals if the data are in another folder.
Analysis of the output
340030 | DUKE UNIVERSITY HOSPITAL | report 818930 | 2024-07-01 to 2025-06-30 (365 days) | 1266 beds | $4,842,220,810 net patient revenue | 4.52% patient-service margin
340040 | PITT COUNTY MEMORIAL HOSPITAL INC | report 827721 | 2023-10-01 to 2024-09-30 (366 days) | 1013 beds | $1,770,994,226 net patient revenue | 6.07% patient-service margin
340069 | WAKEMED RALEIGH CAMPUS | report 798195 | 2023-10-01 to 2024-09-30 (366 days) | 689 beds | $1,442,800,112 net patient revenue | 3.98% patient-service margin
WakeMed Raleigh Campus reports 689 beds and $1.44 billion in net patient revenue for October 2023–September 2024. Its published patient-service income is $57,398,188. Dividing that by $1,442,800,112 in net patient revenue gives 3.98%. This adds capacity and financial context to the original CCN roster.
The dates matter: Duke’s report covers July 2024–June 2025, while the other two cover October 2023–September 2024. These are hospital fiscal reports from the CMS 2024 file edition, not a common calendar-year comparison. Use the dates to choose an appropriate comparison group; the code does not annualize the amounts.
This ratio describes income from patient services relative to net patient revenue. It excludes other income and expenses and is not a total net margin, reimbursement rate or care-quality ranking. Differences in facility scope, services and reporting periods remain. The file also supplies operating_expense, net_income, assets, liabilities and staffing for other analyses.
A numeric blank remains unavailable; the code calculates a margin only when the relevant inputs are reported and revenue is positive. Reported negative income can produce a negative margin. Reported zero remains zero. An absent CCN is printed as not in this file, without inferring zero activity.
Using the full dataset
Extract the purchased ZIP and replace the sample reports.csv with the full file. The code runs unchanged. Its observation key is report_id, the CMS report record number. facility_ccn links reports to a hospital roster but is not unique: 81 CCNs have multiple reports in this edition. All remain in the file.
Use hospital_coverage.csv to identify CCNs with several reports, differing names, short or long periods, and overlapping reporting dates. This edition has no overlapping report pairs, but does contain sequential reports for the same CCN. The source does not supply filing status or acceptance timestamps; the highest report number is not a documented rule for selecting the latest filing.
Every original source field is retained under a documented name. The additional CSVs account for every source row, map the 117 fields to CMS worksheet definitions, and record the source edition and dates. Four original CMS PDFs, complete dictionaries, validation results and this example are included.
The hospital and care-facility selection page links to quality, inpatient DRG and outpatient APC products. They are separate purchases with their own dates and scope. Review CCN identity and periods before joining; financial statements and Medicare claims are not interchangeable.
Sources and versions
Source: CMS Hospital Provider Cost Report, CostReport_2024_Final.csv. CMS’s methodology identifies a September 18, 2026 HCRIS extract; the distribution was modified October 5, 2026. ACD retained the source October 29, 2026 UTC. The 2024 filename is separate from each report’s fiscal period.
The public-use file includes several hospital types and financial, capacity and program-specific fields. It is not a complete HCRIS export, a current directory or independently audited financial statements. Original government data are free; ACD sells preparation, validation, documentation and delivery.
Two dictionary details are documented in the download: the rural/urban prose describes numeric codes while the CSV uses U/R/NA, and the net-patient-revenue prose reverses subtraction. We retain original definitions and values with explicit notes. The example uses the supplied revenue and patient-service income, without recalculating either from that prose.
Read the source and preparation record. Same-source processing improvements are included; genuinely new source editions may be sold separately.
Example checked October 29, 2026 against both these samples and the complete purchased files. Source and processing records, sample checksums · Expected result CSV. Independent preparation; no agency endorsement.