Skip to content
Open
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
5 changes: 5 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@ heading here; `tests/test_repo_hygiene.py` asserts that they do.

## [Unreleased]

### `obr_shock`: household lever no longer fails on a shock shorter than the solve window

- **Bug.** `obr_shock(var="HHDI_ADDFACTOR", ...)` with `periods` below 12 raised `TypeError: float() argument must be a string or a real number, not 'NoneType'` after both solves had run, locally and on the hosted server. The model solves to 2027Q4 at least and leaves the GDP-per-pound ratio undefined in the quarters after the shock ends; the adapter tried to round those. In place since the ratio was added on 16 Nov 2026 (`9b2c8e1d`).
- **Fix.** `gdp_per_revenue_current_price`, `gdp_per_revenue_real` and `cpi_pct_delta` keep `null` for an undefined quarter, so each list still lines up with `results` row for row. No published number changes: the site's figures use 12 shocked quarters, where every ratio is defined.

### BoE SVAR re-pin to `17f5d82`

- **Pin.** BoE SVAR `c827ab86` → `17f5d824` (boe-var-model #34, world CPI seasonal adjustment; #35, November 2026 MPR comparator and 2026Q3 scoring). After a redeploy the hosted `forecast_uk` and `latest_shocks` run this pin.
Expand Down
29 changes: 25 additions & 4 deletions integration/src/policyengine_macro/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

from __future__ import annotations

import math
import os
import re
import time
Expand Down Expand Up @@ -334,6 +335,23 @@ def _obr_result_rows(df) -> list[dict]:
]


def _rounded_or_none(values, n: int, digits: int = 4) -> list:
"""The first ``n`` per-quarter values, rounded; undefined ones stay None.

The model marks a quarter where a ratio is undefined with None (or NaN).
Neither may become a number: JSON has no NaN, and a 0.0 would read as a
measured zero.
"""
out = []
for v in list(values)[:n]:
if v is None:
out.append(None)
continue
f = float(v)
out.append(round(f, digits) if math.isfinite(f) else None)
return out


def obr_shock(
var: str,
shock: float,
Expand Down Expand Up @@ -462,11 +480,16 @@ def obr_shock(
# bases on the frame (obr #63/#66); without them an MCP caller can only
# form -delta_gdp/shock, the real-GDP ratio, and compare it with the
# OBR's current-price 0.3.
# The model leaves the ratio undefined (None) in every quarter after the
# shock ends, where there is no revenue to divide by. Those quarters stay
# None here so the list lines up with `results` row for row; before 25
# Nov 2026 float(None) raised, so every household-lever call with fewer
# shocked quarters than solved ones (periods < 12) failed after the solve.
attrs = getattr(df, "attrs", {}) or {}
for key in ("gdp_per_revenue_current_price", "gdp_per_revenue_real"):
values = attrs.get(key)
if values is not None:
result[key] = [round(float(v), 4) for v in list(values)[: len(rows)]]
result[key] = _rounded_or_none(values, len(rows))
if attrs.get("gdp_per_revenue_basis_note"):
result["gdp_per_revenue_basis_note"] = str(attrs["gdp_per_revenue_basis_note"])
# The model's own labels (obr #70). They live on the frame's attrs, which
Expand All @@ -487,9 +510,7 @@ def obr_shock(
result["price_passthrough_note"] = str(attrs["price_passthrough_note"])
cpi = (attrs.get("price_passthrough_detail") or {}).get("cpi_pct_delta")
if cpi is not None:
result["cpi_pct_delta"] = [
round(float(v), 4) for v in list(cpi)[: len(rows)]
]
result["cpi_pct_delta"] = _rounded_or_none(cpi, len(rows))
return result


Expand Down
2 changes: 2 additions & 0 deletions integration/src/policyengine_macro/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -263,6 +263,8 @@ def obr_shock(
the peak percent-of-GDP effect, plus a caveat for levers whose channel is
partial and, for HHDI_ADDFACTOR, the GDP-per-pound ratio on both bases
(gdp_per_revenue_current_price is the one to compare with the OBR's 0.3).
The ratio lists line up with the rows and are null in the quarters after
the shock ends, where there is no revenue to divide by.
Identity-passthrough and overlay runs are labelled in the payload
(mechanical_passthrough, transmission_note, price_passthrough_note).
Takes about one to two minutes (two solves); on a cold hosted server use
Expand Down
58 changes: 58 additions & 0 deletions integration/tests/test_wiring.py
Original file line number Diff line number Diff line change
Expand Up @@ -485,6 +485,64 @@ def fake_run_reform(**kw):
assert "current_price" in out["caveat"]


def test_obr_shock_household_ratio_is_none_after_the_shock_ends(monkeypatch):
"""A household shock shorter than the solve window must not crash.

The model solves to 2027Q4 at least (12 quarters) and leaves the
GDP-per-pound ratio None in every quarter after the shock ends. Before
25 Nov 2026 obr_shock did float(None) on those, so every HHDI_ADDFACTOR
call with periods < 12 raised TypeError after both solves had run; the
earlier test missed it by patching the window down to the shocked
quarters. The window is the real one here.
"""
import pandas as pd
from policyengine_macro import core

quarters = [str(p) for p in pd.period_range("2025Q1", "2027Q4", freq="Q")]
shocked = 8

def fake_run_reform(**kw):
assert kw["end"] == "2027Q4" and kw["periods"] == shocked
df = pd.DataFrame({
"period": quarters,
"delta_gdp_bn": [-0.1] * 12, "pct_gdp": [-0.01] * 12,
"delta_cons_m": [-100.0] * 12, "delta_if_m": [0.0] * 12,
})
tail = [None] * (12 - shocked)
df.attrs.update(
gdp_per_revenue_current_price=[0.1] * shocked + tail,
# NaN is the other way a model marks "undefined"; JSON has none.
gdp_per_revenue_real=[0.09] * shocked + [float("nan")] * len(tail),
solver_converged=True, solver_nonconverged_periods=[],
)
return df

monkeypatch.setattr(core, "_import_obr", lambda: fake_run_reform)
out = core.obr_shock("HHDI_ADDFACTOR", 1000, periods=shocked)
for key in ("gdp_per_revenue_current_price", "gdp_per_revenue_real"):
assert len(out[key]) == len(out["results"]) == 12
assert all(v is not None for v in out[key][:shocked])
assert out[key][shocked:] == [None] * 4
# Strict JSON: what the MCP transport has to serialise.
import json
json.dumps(out, allow_nan=False)


@pytest.mark.slow
def test_obr_shock_household_lever_real_solve_shorter_than_window():
"""The same path against the installed model, not a mocked frame."""
pytest.importorskip("obr_macro")
import json
from policyengine_macro import core

out = core.obr_shock("HHDI_ADDFACTOR", 1000, periods=4)
ratio = out["gdp_per_revenue_current_price"]
assert len(ratio) == len(out["results"])
assert all(isinstance(v, float) for v in ratio[:4])
assert all(v is None for v in ratio[4:])
json.dumps(out, allow_nan=False)


def _obr_frame(attrs=None):
import pandas as pd

Expand Down