Files
stack/src/lead/settlement.py
kert cb9976e160
All checks were successful
CI / lint (push) Successful in 44s
CI / notebooks-smoke (push) Successful in 1m33s
Deploy / changes (push) Successful in 14s
CI / test (push) Successful in 3m9s
Infra CI / zotero (push) Successful in 14s
Infra CI / notebooks (push) Successful in 55s
Infra CI / api (push) Successful in 1m9s
Infra CI / docs (push) Successful in 1m23s
Infra CI / llm (push) Successful in 1m1s
Infra CI / mc (push) Successful in 16s
Infra CI / bcda (push) Successful in 1m43s
Deploy / notebooks (push) Has been skipped
Deploy / zotero (push) Has been skipped
Deploy / docs (push) Has been skipped
Package Supply Chain / pkg-supply-chain (push) Successful in 1m30s
Deploy / api (push) Successful in 1m17s
Deploy / llm (push) Successful in 1m18s
Deploy / mc (push) Has been skipped
Deploy / bcda (push) Successful in 1m42s
Deploy / report (push) Successful in 1m36s
feat(lead): LEAD PY2027 financial methodology — settlement and benchmark engines
Ports the public CMS "LEAD Model PY 2027 Alignment and Financial
Methodology Paper" v1.2 (bib E4PEU3HV) as generic engines: parameters
come from the paper, everything CMS computes per ACO or per year comes
from the caller. No participant data, no organization-specific rules.

- lead.params: Table 5.2.1 discounts, 3% Quality Withhold, 2% retention
  incentive, Box 5.3.3 Stop-Loss bands, Tables 5.4.1/5.4.3 corridors, 2%
  sequestration, base-year weights, Table 3.5.1 ACPT guardrails,
  risk-score growth caps, REA/PSA shares and caps, voluntary guardrail
  and 500 minimum, Table 2.6.1 base-year alignment minimums.
- lead.settlement: Final Financial Settlement, Table 5.6.1 line by line
  (settle(SettlementInputs) -> SettlementLines).
- lead.stop_loss: Box 5.3.3 charge, banded payout, neutrality factor,
  application to PY expenditure.
- lead.monies_owed: Table 5.5.1 Total Monies Owed, APO reconciliation.
- lead.timing: run-out end, settlement-basis rule, settlement-stage inputs.
- lead.benchmark: §3 formulas — risk standardization, two-/three-way
  trend, base-year weights and sufficiency, voluntary guardrail,
  regional FFS, spending designation, REA, PSA, risk-score cap, hybrid
  alignment dollars, category blend.
- lead.express: the same as narwhals Exprs; express.settlement.settle
  settles a frame of scenarios on any backend.

Rounding: every dollar line rounds to the cent (half away from zero) as
it is produced; PBPMs, rates and factors never do. It is the only rule
under which Tables 3.3.3, 3.5.3.2, 3.5.4, 5.5.1 and 5.6.1 all reproduce
(3.5.4 line 24 sums cent-rounded cells; 3.3.3 carries unrounded PBPMs).
The Expr cents snaps its ÷100 with round(2): polars 2.0 divides a column
by a literal as a reciprocal multiply (k × 0.01), one ulp off k/100 for
~15% of values.

Missing inputs stay missing (None/null or a refused input model); the
only zeros are the paper's own (Professional "N/A" discount, no
Stop-Loss election, sequestration on losses, ineligible REA/PSA).

Paper inconsistencies recorded in tests: Table 5.5.1 line 2 is a cent
below Table 5.6.1 line 28 (.43 vs .44); Box 3.3.2 prints 1.104 then says
1.103; §3.5.1 prose widens the ACPT lower bound a year later than
Table 3.5.1 (the table is followed).

Tests: 283 in tests/lead — every published line to the cent, Expr
builders on polars and DuckDB, bit-for-bit scalar/frame parity over 160
scenarios; 100% of src/lead.
2026-10-27 14:11:10 -04:00

477 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""LEAD Final Financial Settlement: Table 5.6.1, line by line.
The chain is: PY Benchmark (line 1) → Global discount (lines 2–4) →
retention incentive (§5.2.3) → Quality Withhold and Earn Back (lines 5–9)
→ PY expenditure (lines 10–15) → Stop-Loss (lines 16–22) → gross
savings/losses (lines 23–25) → risk corridors (line 26 and its corridor
lines) → sequestration (lines 27–28). :func:`settle` runs it for one
scenario; ``lead.express.settlement.settle`` runs it for a frame of
scenarios on any narwhals backend and returns the same numbers.
Every dollar line is rounded to the cent as it is produced
(:func:`lead.money.cents`); rates and the quality score are not rounded.
The paper prints reductions in parentheses in Table 5.6.1 (lines 5 and 8);
here they are positive amounts that the chain subtracts.
Missing inputs are never silent zeros: :class:`SettlementInputs` refuses
an incomplete scenario. The zeros that do appear are the paper's own: the
Professional option's discount ("N/A", Table 5.6.1 line 3), the Stop-Loss
lines of an ACO that did not elect Stop-Loss (§5.3.3), and sequestration of
Shared Losses (§5.4).
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.2–§5.6 / Table 5.6.1.
"""
from __future__ import annotations
from dataclasses import dataclass
from pydantic import BaseModel, ConfigDict, Field, model_validator
from lead.money import cents
from lead.params import (
DISCOUNT_RATES,
GLOBAL,
PROFESSIONAL,
QUALITY_WITHHOLD_RATE,
RETENTION_INCENTIVE_RATE,
RISK_CORRIDORS,
SEQUESTRATION_RATE,
CorridorScenario,
RiskOption,
SpendingDesignation,
model_year,
)
from lead.stop_loss import apply_stop_loss, without_stop_loss
# ── §5.2 Performance Year Benchmark adjustments ───────────────────────────
def benchmark_discount_rate(
risk_option: RiskOption,
spending_designation: SpendingDesignation | None,
performance_year: int,
) -> float:
"""Return the benchmark discount rate for a risk option, designation and PY.
The Professional option has no discount (0.0). The Global option reads
Table 5.2.1; an unknown designation or a year outside the model raises,
because a Global benchmark with no scheduled discount is not computable.
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.2.1 / Table 5.2.1 /
Table 5.2.2 line 2.
"""
model_year(performance_year)
if risk_option == PROFESSIONAL:
return 0.0
if risk_option != GLOBAL:
raise ValueError(f"unknown risk option {risk_option!r}")
if spending_designation not in DISCOUNT_RATES:
raise ValueError(
"the Global discount needs a spending designation, "
f"got {spending_designation!r}"
)
return DISCOUNT_RATES[spending_designation][performance_year]
@dataclass(frozen=True)
class Discount:
"""Table 5.6.1 lines 2–4."""
discount_rate: float
discount_amount: float
benchmark_after_discount: float
def apply_discount(py_benchmark: float, discount_rate: float | None) -> Discount:
"""Reduce the PY Benchmark by the discount (Table 5.6.1 lines 2–4).
A missing rate (``None``) is the paper's "N/A" — the Professional
option's Total Discount — and removes nothing.
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.2.1 / Table 5.2.2
lines 2–4.
"""
rate = 0.0 if discount_rate is None else discount_rate
amount = cents(py_benchmark * rate)
return Discount(rate, amount, cents(py_benchmark - amount))
def quality_withhold(
py_benchmark: float, withhold_rate: float = QUALITY_WITHHOLD_RATE
) -> float:
"""Return the Quality Withhold: 3 percent of the PY Benchmark before
the discount (Table 5.6.1 line 5).
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.2.2 / Table 5.2.2 line 5.
"""
return cents(py_benchmark * withhold_rate)
def quality_earn_back(withhold: float, quality_score: float) -> float:
"""Return the Earned Quality Withhold: withhold × quality score
(Table 5.6.1 line 7). The score is a share between 0 and 1.
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.2.2 / Table 5.2.2 line 7.
"""
if not 0.0 <= quality_score <= 1.0:
raise ValueError(f"quality score must be within [0, 1], got {quality_score}")
return cents(withhold * quality_score)
def retention_incentive_adjustment(py_benchmark: float, applies: bool) -> float:
"""Return the retention incentive reduction: 2 percent of the PY
Benchmark when the ACO terminated after its first Performance Year,
otherwise zero (the ACO earns it back).
The paper says the PY Benchmark is "reduced by 2 percent" and orders the
reduction after the discount and before the Quality Withhold; like the
Quality Withhold it is taken here on the PY Benchmark before the
discount.
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.2.3.
"""
return cents(py_benchmark * RETENTION_INCENTIVE_RATE) if applies else 0.0
@dataclass(frozen=True)
class BenchmarkAdjustments:
"""Table 5.6.1 lines 1–9 (plus the §5.2.3 retention incentive)."""
py_benchmark: float
discount_rate: float
discount_amount: float
benchmark_after_discount: float
retention_incentive_adjustment: float
quality_withhold: float
quality_score: float
quality_earn_back: float
net_quality_withhold: float
benchmark_after_adjustments: float
def adjust_benchmark(
py_benchmark: float,
discount_rate: float | None,
quality_score: float,
*,
retention_incentive_applies: bool = False,
) -> BenchmarkAdjustments:
"""Apply the discount, retention incentive and net Quality Withhold to
the PY Benchmark (Table 5.6.1 lines 1–9).
Line 9 = line 4 − retention incentive − (line 5 − line 7).
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.2 / Table 5.2.2 /
Table 5.6.1 lines 1–9.
"""
discount = apply_discount(py_benchmark, discount_rate)
retention = retention_incentive_adjustment(
py_benchmark, retention_incentive_applies
)
withhold = quality_withhold(py_benchmark)
earned = quality_earn_back(withhold, quality_score)
net_quality = cents(withhold - earned)
return BenchmarkAdjustments(
py_benchmark=py_benchmark,
discount_rate=discount.discount_rate,
discount_amount=discount.discount_amount,
benchmark_after_discount=discount.benchmark_after_discount,
retention_incentive_adjustment=retention,
quality_withhold=withhold,
quality_score=quality_score,
quality_earn_back=earned,
net_quality_withhold=net_quality,
benchmark_after_adjustments=cents(
discount.benchmark_after_discount - retention - net_quality
),
)
# ── §5.3 Performance Year expenditure ─────────────────────────────────────
@dataclass(frozen=True)
class PYExpenditure:
"""Table 5.6.1 lines 10–15."""
capitation_payments: float
participant_provider_claims: float
preferred_provider_claims: float
non_aco_provider_claims: float
total_ffs_payments: float
py_expenditure: float
def py_expenditure(
capitation_payments: float,
participant_provider_claims: float,
preferred_provider_claims: float,
non_aco_provider_claims: float,
) -> PYExpenditure:
"""Sum capitation and the three FFS claim components into the PY
expenditure, on a pre-sequestration basis (Table 5.6.1 lines 10–15).
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.3 / Table 5.3.2.
"""
total_ffs = cents(
participant_provider_claims
+ preferred_provider_claims
+ non_aco_provider_claims
)
return PYExpenditure(
capitation_payments=capitation_payments,
participant_provider_claims=participant_provider_claims,
preferred_provider_claims=preferred_provider_claims,
non_aco_provider_claims=non_aco_provider_claims,
total_ffs_payments=total_ffs,
py_expenditure=cents(capitation_payments + total_ffs),
)
# ── §5.4 Gross savings/losses, risk corridors, sequestration ──────────────
def gross_savings_losses(
benchmark_after_adjustments: float, py_expenditure_after_stop_loss: float
) -> float:
"""Return gross savings (positive) or losses (negative): benchmark after
adjustments less PY expenditure after Stop-Loss (Table 5.6.1 line 25).
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.4 / Table 5.4.2 line 25.
"""
return cents(benchmark_after_adjustments - py_expenditure_after_stop_loss)
@dataclass(frozen=True)
class SharedSavingsLosses:
"""Table 5.6.1 line 26 and its "Retained ... in Corridor n" lines."""
risk_option: RiskOption
scenario: CorridorScenario
retained_by_corridor: tuple[float, ...]
shared_savings_losses: float
def corridor_exposure(
amount: float, benchmark: float, lower: float, upper: float | None
) -> float:
"""Return the part of ``|amount|`` that falls in one corridor, whose
bounds are shares of ``benchmark``.
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.4 / Table 5.4.1 /
Table 5.4.3.
"""
magnitude = abs(amount)
capped = magnitude if upper is None else min(magnitude, benchmark * upper)
return max(0.0, capped - benchmark * lower)
def shared_savings_losses(
gross: float, benchmark_after_adjustments: float, risk_option: RiskOption
) -> SharedSavingsLosses:
"""Apply the risk corridors to gross savings or losses (Table 5.6.1
line 26).
Corridor bounds are shares of the PY Benchmark after the discount,
Quality Withhold and Earn Back. Each corridor's retained amount keeps
the sign of ``gross`` and is rounded to the cent; line 26 is their sum,
so the printed corridor lines add up to it.
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.4 / Table 5.4.1 /
Table 5.4.3 / Table 5.4.2 / Table 5.4.4.
"""
if risk_option not in (GLOBAL, PROFESSIONAL):
raise ValueError(f"unknown risk option {risk_option!r}")
scenario: CorridorScenario = "savings" if gross >= 0 else "losses"
sign = 1.0 if gross >= 0 else -1.0
retained = tuple(
cents(
sign
* corridor_exposure(gross, benchmark_after_adjustments, c.lower, c.upper)
* c.rate
)
for c in RISK_CORRIDORS[(risk_option, scenario)]
)
return SharedSavingsLosses(risk_option, scenario, retained, cents(sum(retained)))
def sequestration_amount(shared: float, rate: float = SEQUESTRATION_RATE) -> float:
"""Return sequestration: 2 percent of Shared Savings; zero on Shared
Losses, which are not sequestered (Table 5.6.1 line 27).
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.4 / Table 5.4.2 line 27.
"""
return cents(max(shared, 0.0) * rate)
# ── The whole chain ───────────────────────────────────────────────────────
class SettlementInputs(BaseModel):
"""One settlement scenario: the Table 5.6.1 inputs.
``spending_designation`` is required for the Global option (it selects
the discount) and unused for the Professional option. The Stop-Loss
charge and payout are required exactly when Stop-Loss was elected; the
neutrality factor is required unless the payout is zero.
Source: LEAD PY2027 methodology (bib E4PEU3HV) Table 5.6.1 lines 1, 6,
10–13, 17–19; §5.2.3.
"""
model_config = ConfigDict(frozen=True)
py_benchmark: float = Field(description="Line 1: PY Benchmark, all aligned.")
risk_option: RiskOption
spending_designation: SpendingDesignation | None = None
performance_year: int
quality_score: float = Field(ge=0.0, le=1.0, description="Line 6, as a share.")
capitation_payments: float = Field(description="Line 10.")
participant_provider_claims: float = Field(description="Line 11.")
preferred_provider_claims: float = Field(description="Line 12.")
non_aco_provider_claims: float = Field(description="Line 13.")
stop_loss_elected: bool
stop_loss_charge: float | None = Field(default=None, description="Line 17.")
stop_loss_payout: float | None = Field(default=None, description="Line 18.")
stop_loss_neutrality_factor: float | None = Field(
default=None, description="Line 19 (model-wide)."
)
retention_incentive_applies: bool = Field(
default=False,
description="True only when the ACO terminated after its first PY (§5.2.3).",
)
@model_validator(mode="after")
def _complete(self) -> SettlementInputs:
model_year(self.performance_year)
if self.risk_option == GLOBAL and self.spending_designation is None:
raise ValueError("the Global option needs a spending designation")
amounts = (self.stop_loss_charge, self.stop_loss_payout)
if self.stop_loss_elected:
if None in amounts:
raise ValueError(
"Stop-Loss was elected: charge and payout are required"
)
if self.stop_loss_neutrality_factor is None and self.stop_loss_payout:
raise ValueError("a Stop-Loss payout needs the neutrality factor")
elif amounts != (None, None) or self.stop_loss_neutrality_factor is not None:
raise ValueError("Stop-Loss amounts given but Stop-Loss was not elected")
return self
@dataclass(frozen=True)
class SettlementLines:
"""Every line of Table 5.6.1 (line 16 = line 15, line 23 = line 22,
line 24 = line 9), plus the §5.2.3 retention incentive."""
py_benchmark: float # 1
discount_rate: float # 2
discount_amount: float # 3
benchmark_after_discount: float # 4
retention_incentive_adjustment: float # §5.2.3
quality_withhold: float # 5
quality_score: float # 6
quality_earn_back: float # 7
net_quality_withhold: float # 8
benchmark_after_adjustments: float # 9, 24
capitation_payments: float # 10
participant_provider_claims: float # 11
preferred_provider_claims: float # 12
non_aco_provider_claims: float # 13
total_ffs_payments: float # 14
py_expenditure: float # 15, 16
stop_loss_charge: float # 17
stop_loss_payout: float # 18
stop_loss_neutrality_factor: float | None # 19
adjusted_stop_loss_payout: float # 20
net_stop_loss_impact: float # 21
py_expenditure_after_stop_loss: float # 22, 23
gross_savings_losses: float # 25
shared_savings_losses: float # 26
retained_corridor_1: float
retained_corridor_2: float
retained_corridor_3: float
retained_corridor_4: float
sequestration_amount: float # 27
shared_savings_losses_after_sequestration: float # 28
def settle(inputs: SettlementInputs) -> SettlementLines:
"""Run Final Financial Settlement for one scenario (Table 5.6.1).
An ACO that did not elect Stop-Loss has no charge, payout or net
impact: its PY expenditure after Stop-Loss is its PY expenditure.
Source: LEAD PY2027 methodology (bib E4PEU3HV) §5.6 / Table 5.6.1.
"""
rate = benchmark_discount_rate(
inputs.risk_option, inputs.spending_designation, inputs.performance_year
)
benchmark = adjust_benchmark(
inputs.py_benchmark,
rate,
inputs.quality_score,
retention_incentive_applies=inputs.retention_incentive_applies,
)
expenditure = py_expenditure(
inputs.capitation_payments,
inputs.participant_provider_claims,
inputs.preferred_provider_claims,
inputs.non_aco_provider_claims,
)
# SettlementInputs guarantees the charge and payout exist when elected.
stop_loss = (
apply_stop_loss(
expenditure.py_expenditure,
inputs.stop_loss_charge,
inputs.stop_loss_payout,
inputs.stop_loss_neutrality_factor,
)
if inputs.stop_loss_elected
else without_stop_loss(expenditure.py_expenditure)
)
gross = gross_savings_losses(
benchmark.benchmark_after_adjustments,
stop_loss.py_expenditure_after_stop_loss,
)
shared = shared_savings_losses(
gross, benchmark.benchmark_after_adjustments, inputs.risk_option
)
sequestration = sequestration_amount(shared.shared_savings_losses)
c1, c2, c3, c4 = shared.retained_by_corridor
return SettlementLines(
py_benchmark=benchmark.py_benchmark,
discount_rate=benchmark.discount_rate,
discount_amount=benchmark.discount_amount,
benchmark_after_discount=benchmark.benchmark_after_discount,
retention_incentive_adjustment=benchmark.retention_incentive_adjustment,
quality_withhold=benchmark.quality_withhold,
quality_score=benchmark.quality_score,
quality_earn_back=benchmark.quality_earn_back,
net_quality_withhold=benchmark.net_quality_withhold,
benchmark_after_adjustments=benchmark.benchmark_after_adjustments,
capitation_payments=expenditure.capitation_payments,
participant_provider_claims=expenditure.participant_provider_claims,
preferred_provider_claims=expenditure.preferred_provider_claims,
non_aco_provider_claims=expenditure.non_aco_provider_claims,
total_ffs_payments=expenditure.total_ffs_payments,
py_expenditure=expenditure.py_expenditure,
stop_loss_charge=stop_loss.stop_loss_charge,
stop_loss_payout=stop_loss.stop_loss_payout,
stop_loss_neutrality_factor=stop_loss.stop_loss_neutrality_factor,
adjusted_stop_loss_payout=stop_loss.adjusted_stop_loss_payout,
net_stop_loss_impact=stop_loss.net_stop_loss_impact,
py_expenditure_after_stop_loss=stop_loss.py_expenditure_after_stop_loss,
gross_savings_losses=gross,
shared_savings_losses=shared.shared_savings_losses,
retained_corridor_1=c1,
retained_corridor_2=c2,
retained_corridor_3=c3,
retained_corridor_4=c4,
sequestration_amount=sequestration,
shared_savings_losses_after_sequestration=cents(
shared.shared_savings_losses - sequestration
),
)