Compare Medicare Part B spending and billing units in Python
Compare annual spending with billed drug quantities using HCPCS codes, a free product sample and copyable notebook code.
Compare spending with billed drug quantities
You have a list of HCPCS drug billing codes and want to understand how spending changed. Comparing total spending with billed quantities helps distinguish a change in utilization from a change in spending per billing unit. The prepared annual table supplies both measures, without reshaping CMS’s year-suffixed columns.
This example selects J0178 (Eylea) and J9271 (Keytruda). The optional input.csv lists those two real codes; the identical portfolio list appears in the Python code below. These are research selections, with no invented claims or patients.
drug_years.csv below is a sample of the paid product’s main table, containing all five annual records for these two codes and every product column. The full download covers 799 HCPCS codes and includes code attributes, published trends, a separate payment-benchmark table and documentation.
Save the sample into your working folder. For these two codes, the HCPCS description defines a billing unit as 1 mg. That is a billing quantity, not a patient dose or a treatment course.
Code example
Copy this into one notebook cell or a Python script. It compares 2023 with 2024 and prints the results using Python’s standard library. Missing numbers and zero starting values produce “not available.” The output also carries CMS’s unit-spending outlier warning when either year is flagged.
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
# Selected real HCPCS billing codes, also supplied in input.csv.
# Replace this list with your own codes after inspecting drugs.csv.
portfolio = [{"hcpcs_code": "J0178"}, {"hcpcs_code": "J9271"}]
with open("drug_years.csv", newline="", encoding="utf-8-sig") as file:
observations = {}
for row in csv.DictReader(file):
key = (row["hcpcs_code"], row["year"])
if key in observations:
raise ValueError(f"Duplicate code/year: {key}")
observations[key] = row
def percent_change(before, after):
if before == "" or after == "" or Decimal(before) == 0:
return None
return (Decimal(after) / Decimal(before) - 1) * 100
def display_change(value):
return "not available" if value is None else f"{value:+.1f}%"
results = []
for drug in portfolio:
code = drug["hcpcs_code"]
before = observations.get((code, "2023"))
after = observations.get((code, "2024"))
if before is None or after is None:
raise ValueError(f"Code absent from this sample/edition: {code}")
flags = [before["outlier_flag"], after["outlier_flag"]]
warning = ("CMS outlier flag: review unit spending" if "1" in flags else
"Outlier status unavailable" if "" in flags else "No CMS outlier flag")
results.append({
"hcpcs_code": code,
"brand_name": after["brand_name"],
"spending_change_2023_2024": display_change(percent_change(before["total_spending_usd"], after["total_spending_usd"])),
"billing_units_change_2023_2024": display_change(percent_change(before["total_dosage_units"], after["total_dosage_units"])),
"unit_spending_change_2023_2024": display_change(percent_change(before["spending_per_dosage_unit_usd"], after["spending_per_dosage_unit_usd"])),
"outlier_review": warning,
})
print("2023–2024 change | spending | HCPCS billing units | spending per billing unit")
for row in results:
print(f'{row["hcpcs_code"]} {row["brand_name"]}: {row["spending_change_2023_2024"]} | '
f'{row["billing_units_change_2023_2024"]} | {row["unit_spending_change_2023_2024"]} | '
f'{row["outlier_review"]}')
Analysis of the output
2023–2024 change | spending | HCPCS billing units | spending per billing unit
J0178 Eylea: -24.9% | -21.0% | -4.9% | No CMS outlier flag
J9271 Keytruda: +10.2% | +6.7% | +3.3% | No CMS outlier flag
For J0178, spending fell 24.9%, while billed units fell 21.0% and spending per billing unit fell 4.9%. For J9271, spending rose 10.2%, alongside a 6.7% increase in billed units and a 3.3% increase in spending per billing unit.
Those comparisons give a spending brief more useful context than a total alone. The percentages combine multiplicatively, so they should not simply be added. They describe the source’s annual aggregates; they do not establish a causal price change, clinical effectiveness or a change in disease prevalence. Neither selected comparison has a CMS outlier flag, which does not certify that the claims are error-free.
Spending, billing units and payment benchmarks
Spending includes Medicare payments plus beneficiary deductible and coinsurance, in nominal dollars. It is not Medicare payments alone, an acquisition cost or a manufacturer’s net revenue. Claims count Part B claims, not prescription fills. Beneficiaries cannot be summed across codes or years to obtain unique people.
Each code defines its own billing unit. Do not sum unlike units across drugs or interpret a milligram comparison as a comparison of treatment costs. Unlike the weighted average in CMS’s Part D product, Part B’s reported spending per unit is total spending divided by billed units.
The separate payment_benchmarks.csv contains CMS’s average 2024 quarterly payment amount, including the applicable add-on. Although the source calls the field Avg_DY24_ASP_Price, it is not raw Average Sales Price or a current payment quote. Keep it separate from observed spending per unit.
Using the full dataset
After purchase, replace the sample drug_years.csv with the full file of the same name. The code runs unchanged. Inspect drugs.csv for identifiers and billing descriptions, then replace the portfolio list or load your own one-column HCPCS CSV. Keep codes as text, including codes that contain only digits. Matching by code alone returns five annual slots; include year when you need one observation.
drug_trends.csv preserves CMS’s published change and CAGR as percentages. Check the annual outlier flags before interpreting those measures. A single asterisk in a brand or generic label indicates multiple names for that code; a starred label does not identify spending exclusively for one brand. The source’s missing generic labels remain blank.
Coverage and missing values
This is fee-for-service Part B, excluding Medicare Advantage. CMS selects its latest-year ASP-file reporting cohort with at least 11 claims in 2024. The historical records therefore cover that cohort, not every drug billed in earlier years. Missing annual slots remain in the table; a blank value is not_reported, never an assumed zero or discontinuation.
The package accounts for all 799 source rows. It retains CMS flags for 277 annual observations and records four name differences between the CSV and companion workbook, preserving the CSV labels. All 34,357 numeric source cells reconcile with the workbook within source-rounding tolerance.
For help choosing a source, see Choosing drug-cost data: NADAC, Medicare and Medicaid.
Sources and versions
CMS Medicare Part B Spending by Drug, annual 2024 edition, with service years 2020–2024. CMS metadata and dictionary are dated June 25, 2026. CMS currently links a January 2023 methodology document; that date is retained. ACD prepared this package on 2026-10-20. Preliminary quarterly releases are not included.
Raw inputs, lossless staging, preparation and publication have separate retained identities. Same-source processing improvements are included for purchasers; later source editions may be sold separately. No scheduled refresh is promised. Original CMS data are free; ACD sells preparation, validation and documentation, without CMS endorsement.
Example checked October 20, 2026 against both these samples and the complete purchased files. Source and processing records, sample checksums · Expected result CSV. Independent preparation; no agency endorsement.
For prescription-drug spending and manufacturer detail, see the Part D history and its guide. For NDC-level pharmacy acquisition benchmarks, see NADAC. These products use different identifiers and measures; this Part B package contains no automatic NDC or Part D crosswalk.