#!/usr/bin/env python3 """ Reproduce the numbers published on amortance.com from the published inputs. python3 verify.py # checks whichever of dental.json / bhph.json is beside it This is a second implementation, written from the specification files rather than shared with the engine that produced them, which is the only thing that makes the exercise worth anything. It re-derives the balances that the event log determines outright: for the dental plan, both branches of the October fork; for the dealer contract, the payoff on the loss date and on the settlement date, and what the waiver leaves standing. It does not re-derive the figures that come from searching a schedule (the repriced instalment, the payoff date under each credit date) — those are stated in the files as expected outputs, not reproduced here. MIT licence, like the engine it checks. Copyright (c) 2026 Amortance. Full text: https://amortance.com/LICENSE """ import json import pathlib import sys from datetime import date from decimal import Decimal, ROUND_HALF_UP CENT = Decimal("0.01") HERE = pathlib.Path(__file__).parent def dec(x) -> Decimal: return Decimal(str(x)) def r2(x: Decimal) -> Decimal: return x.quantize(CENT, rounding=ROUND_HALF_UP) def day(s: str) -> date: y, m, d = (int(p) for p in s.split("-")) return date(y, m, d) def days360(a: date, b: date) -> int: d1, d2 = a.day, b.day if d1 == 31: d1 = 30 if d2 == 31 and d1 == 30: d2 = 30 return (b.year - a.year) * 360 + (b.month - a.month) * 30 + (d2 - d1) def interval(a: date, b: date, conv: str) -> tuple[int, Decimal]: if conv == "30/360": return days360(a, b), dec(360) if conv == "actual/365": return (b - a).days, dec(365) if conv == "actual/360": return (b - a).days, dec(360) raise SystemExit("unknown day count: " + conv) ORDER = {"principal": 0, "fee": 1, "payment": 2} def replay(start: date, apr: Decimal, conv: str, postings: list, through: date) -> dict: """Simple interest on the outstanding principal, rounded half up per interval at posting; a payment settles accrued interest first, then principal; a reduction that takes the balance below zero settles accrued interest first and the rest is a credit.""" bal = accrued = charged = credit = Decimal("0") cursor, closed = start, None for p in sorted(postings, key=lambda p: (p["on"], ORDER[p["kind"]])): if p["on"] > through: break n, basis = interval(cursor, p["on"], conv) if n: i = r2(bal * apr * dec(n) / basis) accrued += i charged += i cursor = p["on"] if p["kind"] in ("principal", "fee"): bal += p["amount"] if bal < 0: excess, bal = -bal, Decimal("0") settled = min(accrued, excess) accrued -= settled credit += excess - settled else: to_i = min(accrued, p["amount"]) accrued -= to_i rest = p["amount"] - to_i to_p = min(bal, rest) bal -= to_p credit += rest - to_p if bal == 0 and closed is None: closed = p["on"] if cursor < through: n, basis = interval(cursor, through, conv) if n: i = r2(bal * apr * dec(n) / basis) accrued += i charged += i return {"balance": bal, "accrued": accrued, "interest": charged, "credit": credit, "closed": closed} def money(x: Decimal) -> str: s = f"{abs(x):,.2f}" return ("−" + s) if x < 0 else s fails = [] def same(label: str, got: Decimal, want: str) -> None: ok = money(got) == want print(f" {'ok ' if ok else 'FAIL'} {label:<52}{money(got):>12} published {want}") if not ok: fails.append(label) def check_dental(spec: dict) -> None: apr = dec(spec["terms"]["apr"]) start = day(spec["order"]["accepted"]) for st in spec["states"]: conv = st["policy"]["day_count"] print(f"\ndental — {conv}, adjudication effective {st['policy']['adjudication_effective']}") log = [{"on": day(p["on"]), "kind": p["kind"], "amount": dec(p["amount"])} for p in st["log"]] for name, branch in st["fork_on_2026-10-05"].items(): eff = day(branch["effective"]) lg = replay(start, apr, conv, log + [{"on": eff, "kind": "principal", "amount": dec(branch["amount"])}], day("2026-10-05")) same(f"{name} — interest charged", lg["interest"], branch["interest_charged"]) same(f"{name} — credit due patient", lg["credit"], branch["credit_due_patient"]) closed = lg["closed"].isoformat() if lg["closed"] else "—" ok = closed == branch["plan_closes"] print(f" {'ok ' if ok else 'FAIL'} {name + ' — plan closes':<52}{closed:>12}" f" published {branch['plan_closes']}") if not ok: fails.append(name + " plan closes") def check_bhph(spec: dict) -> None: apr = dec(spec["terms"]["apr"]) sale = day(spec["deal"]["sold"]) financed = dec(spec["deal"]["amount_financed"]) for st in spec["states"]: conv = st["policy"]["day_count"] print(f"\nbhph — {conv}, refund pro rated on {st['policy']['refund_pro_rated_on']}") pay = st["payments"] skip = {day(e["on"]) for e in pay["exceptions"] if "on" in e} stop = min(day(e["after"]) for e in pay["exceptions"] if "after" in e) first = day(pay["first"]) postings = [{"on": sale, "kind": "principal", "amount": financed}] for i in range(pay["count"]): when = date.fromordinal(first.toordinal() + pay["every_days"] * i) if when in skip or when > stop: continue postings.append({"on": when, "kind": "payment", "amount": dec(pay["amount"])}) acv = loss = settle = None for e in st["events"]: if e["kind"] == "total_loss": acv, loss, settle = dec(e["acv"]), day(e["on"]), day(e["insurer_paid"]) else: postings.append({"on": day(e["on"]), "kind": e["kind"], "amount": dec(e["amount"])}) at_loss = replay(sale, apr, conv, postings, loss) at_settle = replay(sale, apr, conv, postings, settle) payoff_loss = at_loss["balance"] + at_loss["accrued"] payoff_settle = at_settle["balance"] + at_settle["accrued"] waived = payoff_loss - acv - dec(25) # the waiver's stated exclusion same("payoff at the date of loss", payoff_loss, st["expected"]["payoffLoss"]) same("payoff at the insurer's payment", payoff_settle, st["expected"]["payoffSettle"]) same("deficiency at the date of loss", payoff_loss - acv, st["expected"]["deficiencyLoss"]) same("waived by the waiver", waived, st["expected"]["waiverWaives"]) same("left standing on the account", payoff_settle - acv - waived, st["expected"]["remainder"]) if __name__ == "__main__": ran = [] for name, fn in (("dental", check_dental), ("bhph", check_bhph)): path = HERE / f"{name}.json" if not path.exists(): print(f"{name}.json is not beside this script — skipping it. " f"It is at amortance.com/{name}.json if you want it.") continue fn(json.loads(path.read_text())) ran.append(name) if not ran: raise SystemExit("Nothing to check. Put dental.json or bhph.json beside this script; " "either one on its own is enough.") print("\n" + (f"all reproduced ({', '.join(ran)})" if not fails else f"{len(fails)} did not reproduce")) sys.exit(1 if fails else 0)