Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -178,12 +178,19 @@ All entities must have consistent member lists.

### Marginal tax savings

Calculated using numpy's gradient on the backend:
The curve's rate, which the marginal chart plots, uses numpy's gradient:
```python
df["marginal_savings"] = -np.gradient(df.income_tax_after_donations) / \
np.gradient(df[donation_column])
```

The "Average savings per extra dollar" card shows `/api/calculate`'s
`marginal_savings_rate`, which for the US is `next_dollar_rate` in
`api/main.py`. This averages net tax savings per dollar over a window
above the gift ($100, wider for large absolute net taxes to reduce float32
rounding). A central difference averages the rates on either side of a
kink, such as the $1,000 non-itemizer cap.

## Household wizard

The US form uses `policyengine-household-wizard`'s primitives and US draft, and
Expand Down
56 changes: 50 additions & 6 deletions api/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -388,17 +388,53 @@ def sample_curve(df, donation_column: str, point_type) -> list:
def marginal_rate_at(df, donation_column: str, donation: float) -> float:
"""The sweep's marginal savings rate at the grid point nearest
``donation``. It is a central difference over the grid, so at a kink
it averages the rates on either side."""
it averages the rates on either side. The US rate comes from
``next_dollar_rate`` instead."""
idx = np.abs(df[donation_column].values - donation).argmin()
return float(df["marginal_savings"].iloc[idx])


# The US card averages net tax savings per dollar over a window of
# NEXT_DOLLARS or more above the gift. policyengine-us returns
# taxes as float32, whose spacing grows with the tax (about $0.002 at
# $17,000, $4 at $40 million), and the two runs' difference carries a
# spacing or so of rounding, which the window divides. Measured at
# policyengine-us 2.156.4: a $1 window read a $75,000 earner's 5% as 5.08%,
# and a $100 window read a $100 million earner's 35% as 32%. So the window
# is NEXT_DOLLARS, or SPACINGS_PER_WINDOW float32 spacings of the net tax
# when that is wider, which keeps each spacing of rounding to 0.05 point.
# The model's intermediate rounding can still affect the displayed rate.
# A gift less than one window below a kink gets a blend of the rates on
# either side.
NEXT_DOLLARS = 100
SPACINGS_PER_WINDOW = 2_000


def next_dollar_window(net_tax: float) -> float:
"""The window above the gift that the next-dollar rate averages over:
``NEXT_DOLLARS``, or ``SPACINGS_PER_WINDOW`` float32 spacings of
``net_tax`` when that is wider ($125 from $524,288 of net tax, doubling
with each doubling of the tax: $8,000 at $40 million)."""
spacing = float(np.spacing(np.float32(abs(net_tax))))
return max(float(NEXT_DOLLARS), SPACINGS_PER_WINDOW * spacing)


def next_dollar_rate(
at_donation: PointMetrics, after_window: PointMetrics, window: float
) -> float:
"""Average net tax savings per dollar over the window above the gift."""
return (at_donation.net_tax - after_window.net_tax) / window


@app.post("/api/calculate", response_model=CalculateResponse)
def calculate_donation(request: CalculateRequest):
"""Calculate tax impact of a charitable donation.

Returns tax savings, marginal rates, and full donation curve data.
Runs three simulations: $0, the donation, and the donation sweep.
Runs four simulations: $0, the donation, the donation plus
``NEXT_DOLLARS`` (for the next-dollar rate), and the donation sweep.
When the net tax calls for a wider window (``next_dollar_window``), a
fifth runs at the donation plus that window, alongside the sweep.
"""
try:
gift = request.donation_amount
Expand All @@ -408,13 +444,21 @@ def calculate_donation(request: CalculateRequest):
curve = None
if request.household is None:
curve = start_curve("us", situation)
baseline, at_donation = point_metrics_many(
"us", [(situation, 0), (situation, gift)]
baseline, at_donation, after_window = point_metrics_many(
"us",
[
(situation, 0),
(situation, gift),
(situation, gift + NEXT_DOLLARS),
],
)
if curve is None:
curve = start_curve(
"us", with_curve_top(request, situation, baseline, gift)
)
window = next_dollar_window(at_donation.net_tax)
if window > NEXT_DOLLARS:
after_window = point_metrics("us", situation, gift + window)
df = add_net_income_columns(
curve_result(curve), baseline_metrics_dict(baseline)
)
Expand All @@ -424,8 +468,8 @@ def calculate_donation(request: CalculateRequest):
baseline_net_tax=baseline.net_tax,
net_tax_at_donation=at_donation.net_tax,
tax_savings=baseline.net_tax - at_donation.net_tax,
marginal_savings_rate=marginal_rate_at(
df, "charitable_cash_donations", request.donation_amount
marginal_savings_rate=next_dollar_rate(
at_donation, after_window, window
),
baseline_net_income=baseline.household_net_income,
net_income_after_donation=at_donation.household_net_income
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -293,8 +293,8 @@ function Calculator() {

if (!cached?.headline) setPublished(null);
setCurveStatus(null);
// The headline first, from two simulations; then the curve and the
// marginal rate, from the donation sweep.
// The headline first, from two simulations; then the curve, from the
// donation sweep, and the next-dollar rate, from a run above the gift.
await fetchHeadlineFirst({
cachedHeadline: cached?.headline,
fetchHeadline: () => savingsMutation.mutateAsync(request),
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/components/Results.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -280,9 +280,9 @@ export default function Results({
description="Federal, state and local"
/>
<MetricCard
label="Saved on the next $1"
label="Average savings per extra dollar"
value={marginalRate}
description="Tax saved if you gave a little more"
description="Change in net taxes if you give a little more"
/>
</>
)}
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/__tests__/Faq.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ describe("FAQ", () => {
"If you itemize, the federal deduction for cash gifts to qualifying public charities is generally limited to 60% of your adjusted gross income for the year. Giving more than the limit adds no deduction for that year. From 2026, itemizers then subtract 0.5% of that income from the gifts the percentage limits allow.",
);
expect(answer("Why did my gift save little or nothing?")).toContain(
"“Saved on the next $1” estimates the tax savings per dollar near your gift.",
"“Average savings per extra dollar” is the reduction in net taxes per dollar over the next $100 above your gift. The range widens when the gap between your taxes and benefits at your gift is about $500,000 or more. A negative rate means giving more increases net taxes.",
);
expect(answer("What does GiveCalc leave out?")).toContain(
"For itemizers, federal law lets you carry eligible gifts above the annual deduction limit forward for up to five years;",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ describe("Results - headline before the curve", () => {
it("fills in the marginal rate and charts when the curve arrives", () => {
render(<Results headline={HEADLINE} result={FULL} year={2026} />);
expect(screen.getByText("$1,589")).toBeInTheDocument();
expect(screen.getByText("Average savings per extra dollar")).toBeInTheDocument();
expect(screen.getByText("28.4%")).toBeInTheDocument();
expect(screen.getByTestId("tax-chart")).toBeInTheDocument();
expect(screen.getByTestId("marginal-chart")).toBeInTheDocument();
Expand Down
8 changes: 6 additions & 2 deletions frontend/src/components/faq/questions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -142,8 +142,12 @@ export const FAQ_ITEMS: FaqItem[] = [
limit adds no deduction for that year. From {us.year}, itemizers
then subtract{" "}
{formatPercent(us.itemizer_floor_share_of_agi, 1)} of that income
from the gifts the percentage limits allow. In your results, “Saved on
the next $1” estimates the tax savings per dollar near your gift.
from the gifts the percentage limits allow. In your results,
“Average savings per extra dollar” is the reduction in net taxes per
dollar over the next {usd(us.next_dollars)} above your gift. The range
widens when the gap between your taxes and benefits at your gift is
about $500,000 or more. A negative rate means giving more increases
net taxes.
{/* 26 U.S.C. 170(b)(1)(G) and (H) define the cash limit and
contribution base; (b)(1)(I), the floor on gifts otherwise
allowable. */}
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/lib/faqRules.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,8 @@
"itemizer_floor_share_of_agi": 0.005,
"cash_gift_limit_share_of_agi": 0.6,
"top_bracket_rate": 0.37,
"top_bracket_limit": { "numerator": 2, "denominator": 37 }
"top_bracket_limit": { "numerator": 2, "denominator": 37 },
"next_dollars": 100
},
"uk": {
"year": 2026,
Expand Down
3 changes: 2 additions & 1 deletion frontend/src/lib/headlineFirst.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
* Fetch the headline, show it, then fetch the full result with the curve.
*
* The headline (/api/savings) runs two simulations; the full result
* (/api/calculate) adds the donation sweep. Showing the headline first puts
* (/api/calculate) adds the donation sweep and a run above the gift for the
* next-dollar rate. Showing the headline first puts
* the answer on screen while the charts load.
*/

Expand Down
13 changes: 11 additions & 2 deletions tests/test_faq_numbers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
- The file records the model versions modal_app.py deploys, which are the
ones installed here.
- Each rule the FAQ states equals its PolicyEngine parameter in the year
the FAQ names.
the FAQ names, and the next-dollar window it states equals the API's,
widening from about $500,000 of net tax as it says.
- The Florida example's reasons hold in the model: no state or local income
tax, adjusted gross income equal to wages, each $10,000 step saving at the
rate of the bracket its taxable income stays in, and a deduction that stops
Expand All @@ -31,7 +32,7 @@
import pytest
from fastapi.testclient import TestClient

from api.main import app, us_situation
from api.main import NEXT_DOLLARS, app, next_dollar_window, us_situation
from api.schemas import SavingsRequest
from api.simulations import clear_caches
from givecalc.core.simulation import create_donation_simulation
Expand Down Expand Up @@ -118,6 +119,14 @@ def test_us_rules_match_policyengine_us():
assert not before.deductions.itemized.limitation.obbb.applies


def test_next_dollar_window_matches_the_api():
"""The FAQ's $100 window widens for large net taxes or net benefits."""
assert RULES["us"]["next_dollars"] == NEXT_DOLLARS
assert next_dollar_window(500_000) == NEXT_DOLLARS
assert next_dollar_window(550_000) > NEXT_DOLLARS
assert next_dollar_window(-550_000) > NEXT_DOLLARS


def test_uk_rules_match_policyengine_uk():
from policyengine_uk.system import system
from policyengine_uk.utils.income_tax import (
Expand Down
8 changes: 4 additions & 4 deletions tests/test_household_payload.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
from policyengine_us import Simulation # noqa: E402
from policyengine_us.system import system # noqa: E402

from api.main import _printable, app # noqa: E402
from api.main import NEXT_DOLLARS, _printable, app # noqa: E402
from api.simulations import clear_caches # noqa: E402
from givecalc import create_situation # noqa: E402
from givecalc.calculations.tax import calculate_donation_metrics # noqa: E402
Expand Down Expand Up @@ -145,10 +145,10 @@ def test_both_request_shapes_agree_at_the_endpoint(fixture):
assert new.json()[key] == pytest.approx(
old.json()[key], abs=TOLERANCE
), key
# The curves' grids differ when benefits raise the top, so the rate is
# compared loosely: the same bracket, not the same grid point.
# The next-dollar rate is the difference of two point runs, the gift
# and NEXT_DOLLARS above it, each within TOLERANCE as above.
assert new.json()["marginal_savings_rate"] == pytest.approx(
old.json()["marginal_savings_rate"], abs=0.02
old.json()["marginal_savings_rate"], abs=2 * TOLERANCE / NEXT_DOLLARS
)


Expand Down
154 changes: 154 additions & 0 deletions tests/test_next_dollar_rate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,154 @@
"""The US card shows average net tax savings per extra dollar.

/api/calculate's ``marginal_savings_rate`` is the reduction in net taxes
per dollar over a window above the gift: (net tax at the gift - net tax a
window above it) / the window, from two point runs. The window is
``NEXT_DOLLARS``, wider for a net tax large enough that float32 rounding
would show (``next_dollar_window``).

The rate used to be the donation sweep's central difference at the
nearest grid point, which averages the rates on either side of a kink. A
gift that sits on a kink, such as $1,000 for a single filer who takes the
standard deduction (the 26 U.S.C. 170(p) cap), then showed a rate it gets
on neither side.

The households are those of GiveCalc's Giving Tuesday 2026 posts: a single
30-year-old with $75,000 in wages, built as the wizard builds it, giving
$1,000 in 2026. In Texas the next dollar saves nothing: the 170(p)
deduction is used up, and Texas has no income tax. In Massachusetts it
saves 5%, the Part B charitable deduction. The live site showed 14.7% and
19.7% (2026-12-01).

Invariants:
- A window starting at the non-itemizer cap sees only the rates above the
cap: TX 0%, MA 5% for a single filer at $1,000 and a joint filer at
$2,000.
- A window starting at $500 in Texas sees only the 22% federal rate.
- A window that crosses the cap averages the rates on either side, as the
card and FAQ say: TX at $925 saves 22% on $75 and 0% on $25, 16.5%.
- Identity: the rate equals the change in /api/savings' tax savings from
the gift to the gift plus ``NEXT_DOLLARS``, divided by ``NEXT_DOLLARS``.
- Rounding: the window is at least ``SPACINGS_PER_WINDOW`` float32 spacings
of the net tax, so a $100 million earner's 35% (37% less the 2/37
limit) reads 35%, not the 32% a $100 window gave.
"""

import copy

import numpy as np
import pytest
from fastapi.testclient import TestClient

from api.main import (
NEXT_DOLLARS,
SPACINGS_PER_WINDOW,
app,
next_dollar_window,
)
from api.simulations import clear_caches

client = TestClient(app)


def wizard_body(state, gift, wages=75_000, married=False, year=2026):
"""The request the wizard sends for a 30-year-old earner (and spouse)."""
y = str(year)
members = ["adult-1", "adult-2"] if married else ["adult-1"]
people = {
member: {"age": {y: 30}, "is_tax_unit_dependent": {y: False}}
for member in members
}
people["adult-1"]["employment_income"] = {y: wages}
return {
"donation_amount": gift,
"year": year,
"household": {
"people": people,
"families": {"family": {"members": members}},
"marital_units": (
{"marital_unit": {"members": members}} if married else {}
),
"tax_units": {"tax_unit": {"members": members}},
"spm_units": {"spm_unit": {"members": members}},
"households": {
"household": {"members": members, "state_name": {y: state}}
},
},
}


def post(path, body):
response = client.post(path, json=body)
assert response.status_code == 200, response.text
return response.json()


def rate(body):
clear_caches()
return post("/api/calculate", body)["marginal_savings_rate"]


@pytest.mark.parametrize(
"state,married,gift,expected",
[
# On the 170(p) cap ($1,000 single, $2,000 joint): federal 0%.
("TX", False, 1_000, 0.0),
("MA", False, 1_000, 0.05),
("TX", True, 2_000, 0.0),
("MA", True, 2_000, 0.05),
# Below the cap: the 22% bracket, and no Texas income tax.
("TX", False, 500, 0.22),
# A window across the cap: $75 at 22%, $25 at 0%.
("TX", False, 925, 0.165),
],
ids=[
"TX single at the $1,000 cap",
"MA single at the $1,000 cap",
"TX joint at the $2,000 cap",
"MA joint at the $2,000 cap",
"TX single below the cap",
"TX single with the cap inside the window",
],
)
def test_next_dollar_rate_is_the_forward_rate(state, married, gift, expected):
wages = 120_000 if married else 75_000
body = wizard_body(state, gift, wages=wages, married=married)
assert rate(body) == pytest.approx(expected, abs=0.001)


@pytest.mark.parametrize("state", ["TX", "MA"])
def test_next_dollar_rate_matches_the_savings_endpoint(state):
body = wizard_body(state, 1_000)
more = copy.deepcopy(body)
more["donation_amount"] += NEXT_DOLLARS
clear_caches()
savings = post("/api/savings", body)["tax_savings"]
savings_more = post("/api/savings", more)["tax_savings"]
assert rate(body) == pytest.approx(
(savings_more - savings) / NEXT_DOLLARS, abs=1e-6
)


@pytest.mark.parametrize(
"net_tax,window",
[
(13_187.50, 100),
(-5_000, 100),
(524_287, 100),
(524_288, 125),
(3_800_000, 500),
(39_000_000, 8_000),
],
)
def test_window_grows_with_the_float32_spacing(net_tax, window):
assert next_dollar_window(net_tax) == window
spacing = float(np.spacing(np.float32(abs(net_tax))))
assert next_dollar_window(net_tax) >= SPACINGS_PER_WINDOW * spacing


def test_a_large_tax_bill_gets_a_wider_window():
"""Net tax near $39 million: float32 spacing is $4, so a $100 window
read 32%. The top bracket's 37%, less the 2/37 limit on itemized
deductions, is 35%."""
body = wizard_body("TX", 1_000_000, wages=100_000_000)
assert rate(body) == pytest.approx(0.35, abs=0.002)