SPB Git

Repository Public MIT

generate_reference.py 28.0 KB 513 lines python

1#!/usr/bin/env python32# ORIX Calc3# File: Packages/ORIXFinancial/Reference/generate_reference.py4# Description: Independent reference values for the ORIXFinancial test suite (brute force / high precision, no Swift code involved).5#6# Author: Simon-Pierre Boucher7# Contact: contact@spboucher.ai8#9# Usage:  python3 Reference/generate_reference.py10# Writes: Reference/reference.json  and a copy in Tests/ORIXFinancialTests/Resources/reference.json11#12# Method: every value is obtained by a route different from the Swift implementation —13#   * TVM: period-by-period compounding of the balance in 50-digit arithmetic (mpmath), never the closed form;14#   * cash flows: term-by-term discounting; IRRs from the polynomial roots (mpmath.polyroots / findroot);15#   * loans: closed forms in 50 digits; schedules simulated with Python's decimal module (exact cents, ROUND_HALF_UP);16#   * bonds: term-by-term discounting with dates from the standard library; durations/convexity by high-precision17#     numerical differentiation of the price function (mpmath.diff), not by the analytic sums;18#   * options: Black-Scholes-Merton with mpmath.ncdf; Greeks by mpmath.diff of the price; implied volatility by19#     scipy.optimize.brentq; CRR trees with numpy.20import calendar21import datetime as dt22import json23import os24import shutil25from decimal import Decimal, ROUND_HALF_UP, getcontext2627import mpmath as mp28import numpy as np29import scipy30from scipy.optimize import brentq31from scipy.stats import norm3233mp.mp.dps = 5034getcontext().prec = 6035F = float36out = {"_meta": {"generator": "generate_reference.py", "mpmath_dps": 50, "scipy": scipy.__version__, "numpy": np.__version__}}3738# ---------------------------------------------------------------- TVM39def tvm_fv(n, iy, pv, pmt, py, cy, begin):40    i = (1 + mp.mpf(iy) / 100 / cy) ** (mp.mpf(cy) / py) - 141    bal = mp.mpf(pv)42    for _ in range(n):43        bal = (bal + pmt) * (1 + i) if begin else bal * (1 + i) + pmt44    return -bal, i4546tvm_cases = [47    dict(name="us_mortgage", n=360, iy="6", pv="200000", pmt="-1199.10", py=12, cy=12, begin=False),48    dict(name="lump_sum", n=10, iy="5", pv="-1000", pmt="0", py=1, cy=1, begin=False),49    dict(name="annuity_due", n=20, iy="7", pv="0", pmt="-500", py=1, cy=1, begin=True),50    dict(name="canadian_py12_cy2", n=300, iy="5", pv="300000", pmt="-1744.81", py=12, cy=2, begin=False),51    dict(name="zero_rate", n=48, iy="0", pv="12000", pmt="-250", py=12, cy=12, begin=False),52    dict(name="negative_rate", n=10, iy="-2", pv="-1000", pmt="-100", py=1, cy=1, begin=False),53    dict(name="quarterly_pay_monthly_comp_begin", n=40, iy="8", pv="-5000", pmt="-200", py=4, cy=12, begin=True),54    dict(name="daily_compounding", n=24, iy="3.5", pv="10000", pmt="-300", py=12, cy=365, begin=False),55    dict(name="tiny_rate", n=120, iy="0.0000001", pv="-100", pmt="-10", py=12, cy=12, begin=False),56    dict(name="savings_begin_semiannual_comp", n=180, iy="4.25", pv="-2500", pmt="-150", py=12, cy=2, begin=True),57    dict(name="lease_with_residual", n=48, iy="3.9", pv="35000", pmt="-450", py=12, cy=12, begin=True),58]59out["tvm"] = []60for c in tvm_cases:61    fv, i = tvm_fv(c["n"], c["iy"], mp.mpf(c["pv"]), mp.mpf(c["pmt"]), c["py"], c["cy"], c["begin"])62    out["tvm"].append(dict(name=c["name"], n=c["n"], iy=F(c["iy"]), pv=F(c["pv"]), pmt=F(c["pmt"]), fv=F(fv),63                           py=c["py"], cy=c["cy"], begin=c["begin"], periodic_rate=F(i)))6465# rate conversions66out["rates"] = dict(67    eff_6_monthly=F((1 + mp.mpf("0.06") / 12) ** 12 - 1),68    eff_6_continuous=F(mp.e ** mp.mpf("0.06") - 1),69    nom_semi_from_eff_5=F(2 * ((1 + mp.mpf("0.05")) ** (mp.mpf(1) / 2) - 1)),70    nom_cont_from_eff_5=F(mp.log(1 + mp.mpf("0.05"))),71    monthly_from_semi_5=F(12 * ((1 + mp.mpf("0.05") / 2) ** (mp.mpf(1) / 6) - 1)),72)7374# ---------------------------------------------------------------- Cash flows75def npv(flows, r):76    return sum(mp.mpf(c) / (1 + mp.mpf(r)) ** k for k, c in enumerate(flows))7778def real_irrs(flows):79    # roots of sum c_k x^k in x = 1/(1+r), x > 080    coeffs = [mp.mpf(c) for c in reversed(flows)]  # highest degree first81    while coeffs and coeffs[0] == 0:82        coeffs.pop(0)83    roots = mp.polyroots(coeffs, maxsteps=2000, extraprec=400)84    rs = []85    for x in roots:86        if abs(mp.im(x)) < mp.mpf(10) ** -25 and mp.re(x) > 0:87            rs.append(1 / mp.re(x) - 1)88    return sorted(F(r) for r in rs)8990def payback(flows):91    cum = mp.mpf(flows[0])92    if cum >= 0:93        return 0.094    for k in range(1, len(flows)):95        nxt = cum + flows[k]96        if nxt >= 0:97            return F(k - 1 + (-cum) / flows[k])98        cum = nxt99    return None100101def mirr(flows, fin, re):102    n = len(flows) - 1103    pvneg = sum(mp.mpf(c) / (1 + mp.mpf(fin)) ** k for k, c in enumerate(flows) if c < 0)104    fvpos = sum(mp.mpf(c) * (1 + mp.mpf(re)) ** (n - k) for k, c in enumerate(flows) if c > 0)105    return F((fvpos / -pvneg) ** (mp.mpf(1) / n) - 1)106107cf_cases = [108    dict(name="conventional", flows=[-10000, 3000, 4200, 6800], rate="0.10"),109    dict(name="two_irrs", flows=[-1000, 2300, -1320], rate="0.15"),110    dict(name="no_real_irr", flows=[1000, -3000, 2500], rate="0.10"),111    dict(name="grouped", flows=[-50000] + [12000] * 5 + [20000], rate="0.08"),112    dict(name="negative_irr", flows=[-1000, 200, 300, 300], rate="0.05"),113    dict(name="three_irrs", flows=[-1000, 3600, -4310, 1716], rate="0.25"),114    dict(name="mine_with_cleanup", flows=[-100, 50, 50, 50, 50, -150], rate="0.07"),115    dict(name="negative_discount_rate", flows=[-500, 100, 150, 200, 120], rate="-0.03"),116]117out["cashflows"] = []118for c in cf_cases:119    fl, r = c["flows"], mp.mpf(c["rate"])120    n = len(fl) - 1121    v = npv(fl, r)122    disc = [mp.mpf(x) / (1 + r) ** k for k, x in enumerate(fl)]123    entry = dict(name=c["name"], flows=fl, rate=F(r), npv=F(v), nfv=F(v * (1 + r) ** n), irrs=real_irrs(fl),124                 payback=payback(fl), discounted_payback=payback(disc))125    if any(x < 0 for x in fl) and any(x > 0 for x in fl):126        entry["mirr_fin"], entry["mirr_re"] = 0.06, 0.09127        entry["mirr"] = mirr(fl, "0.06", "0.09")128    if fl[0] < 0:129        entry["pi"] = F((v - fl[0]) / -fl[0])130    out["cashflows"].append(entry)131# long series: one IRR, found by a high-precision root search132long_flows = [-100000] + [599.55] * 360133r_long = mp.findroot(lambda r: npv(long_flows, r), mp.mpf("0.005"))134out["cashflow_long"] = dict(initial=-100000, amount=599.55, count=360, irr=F(r_long), npv_at_0004=F(npv(long_flows, "0.004")))135136# ---------------------------------------------------------------- Loans137PPY = dict(monthly=12, semiMonthly=24, biweekly=26, acceleratedBiweekly=26, weekly=52, acceleratedWeekly=52)138CY = dict(usMonthly=12, canadianFixed=2, canadianVariable=12)139140def periodic(rate, comp, ppy):141    rate = mp.mpf(rate)142    if comp == "continuous":143        return mp.e ** (rate / ppy) - 1144    m = CY[comp] if comp in CY else int(comp)145    return (1 + rate / m) ** (mp.mpf(m) / ppy) - 1146147def level(P, i, n):148    return P / n if i == 0 else P * i / (1 - (1 + i) ** (-n))149150def raw_payment(P, rate, comp, freq, remaining):151    ppy = PPY[freq]152    if freq.startswith("accelerated"):153        im = periodic(rate, comp, 12)154        return level(mp.mpf(P), im, mp.mpf(remaining) * 12 / ppy) / (2 if freq == "acceleratedBiweekly" else 4)155    return level(mp.mpf(P), periodic(rate, comp, ppy), remaining)156157def cents(x):158    return Decimal(mp.nstr(x, 40)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)159160pay_cases = [161    dict(name="canadian_300k_5_25", P="300000", rate="0.05", years=25, freq="monthly", comp="canadianFixed"),162    dict(name="us_250k_65_30", P="250000", rate="0.065", years=30, freq="monthly", comp="usMonthly"),163    dict(name="cdn_var_semi_monthly", P="425000", rate="0.0595", years=25, freq="semiMonthly", comp="canadianVariable"),164    dict(name="cdn_biweekly", P="400000", rate="0.0479", years=25, freq="biweekly", comp="canadianFixed"),165    dict(name="cdn_acc_biweekly", P="400000", rate="0.0479", years=25, freq="acceleratedBiweekly", comp="canadianFixed"),166    dict(name="cdn_weekly", P="400000", rate="0.0479", years=25, freq="weekly", comp="canadianFixed"),167    dict(name="cdn_acc_weekly", P="400000", rate="0.0479", years=25, freq="acceleratedWeekly", comp="canadianFixed"),168    dict(name="quarterly_comp", P="80000", rate="0.072", years=7, freq="monthly", comp="4"),169    dict(name="continuous", P="80000", rate="0.072", years=7, freq="monthly", comp="continuous"),170    dict(name="zero_rate", P="12000", rate="0", years=4, freq="monthly", comp="usMonthly"),171]172out["loan_payments"] = []173for c in pay_cases:174    ppy = PPY[c["freq"]]175    raw = raw_payment(c["P"], c["rate"], c["comp"], c["freq"], c["years"] * ppy)176    out["loan_payments"].append(dict(c, payment_unrounded=F(raw), payment=F(cents(raw)), periodic_rate=F(periodic(c["rate"], c["comp"], ppy))))177178def schedule(P, rate, comp, freq, years, lumps=None, recurring=None, changes=None, override=None, stop=None):179    """Cent-exact simulation with the decimal module. changes: {period: (rate, comp_or_None, 'recalc'|'keep')}."""180    ppy = PPY[freq]181    n = years * ppy182    lumps, recurring, changes = lumps or {}, recurring or [], changes or {}183    accelerated = freq.startswith("accelerated")184    i = periodic(rate, comp, ppy)185    if override is not None:186        pmt, forced = cents(mp.mpf(override)), None187    else:188        pmt, forced = cents(raw_payment(P, rate, comp, freq, n)), (None if accelerated else n)189    bal = Decimal(P)190    rows, k = [], 0191    first_payment = pmt192    while bal > 0:193        k += 1194        if k in changes:195            rate, newcomp, policy = changes[k]196            comp = newcomp or comp197            i = periodic(rate, comp, ppy)198            if policy == "recalc":199                pmt = cents(raw_payment(mp.mpf(str(bal)), rate, comp, freq, max(1, n - k + 1)))200                forced = None if accelerated else max(n, k)201            else:202                forced = None203        interest = cents(mp.mpf(str(bal)) * i)204        if k == forced or bal + interest <= pmt:205            principal, paid, bal = bal, bal + interest, Decimal(0)206        else:207            assert pmt > interest208            principal, paid = pmt - interest, pmt209            bal -= principal210        extra = Decimal(0)211        if k in lumps:212            extra += Decimal(lumps[k])213        for (start, end, every, amount) in recurring:214            if k >= start and (end is None or k <= end) and (k - start) % every == 0:215                extra += Decimal(amount)216        extra = min(extra, bal)217        bal -= extra218        rows.append((k, paid, interest, principal, extra, bal))219        if stop is not None and k == stop:220            break221    return rows, first_payment222223def summarize(rows, first_payment, probes=()):224    return dict(225        payments=len(rows), payment=F(first_payment), final_payment=F(rows[-1][1]),226        total_interest=F(sum(r[2] for r in rows)), total_principal=F(sum(r[3] for r in rows)),227        total_prepayments=F(sum(r[4] for r in rows)), total_paid=F(sum(r[1] + r[4] for r in rows)),228        ending_balance=F(rows[-1][5]),229        probes=[dict(period=p, interest=F(rows[p - 1][2]), principal=F(rows[p - 1][3]), balance=F(rows[p - 1][5])) for p in probes if p <= len(rows)],230    )231232sched_cases = [233    dict(name="canadian_300k", args=dict(P="300000", rate="0.05", comp="canadianFixed", freq="monthly", years=25), probes=(1, 2, 60, 150, 299, 300)),234    dict(name="us_250k", args=dict(P="250000", rate="0.065", comp="usMonthly", freq="monthly", years=30), probes=(1, 12, 180, 359, 360)),235    dict(name="acc_biweekly", args=dict(P="400000", rate="0.0479", comp="canadianFixed", freq="acceleratedBiweekly", years=25), probes=(1, 26, 260)),236    dict(name="weekly", args=dict(P="150000", rate="0.039", comp="usMonthly", freq="weekly", years=10), probes=(1, 52, 519, 520)),237    dict(name="semi_monthly_quarterly_comp", args=dict(P="95000", rate="0.0825", comp="4", freq="semiMonthly", years=5), probes=(1, 60, 120)),238    dict(name="zero_rate", args=dict(P="12000", rate="0", comp="usMonthly", freq="monthly", years=4), probes=(1, 48)),239    dict(name="prepayments", args=dict(P="250000", rate="0.065", comp="usMonthly", freq="monthly", years=30,240                                       lumps={24: "10000"}, recurring=[(1, None, 1, "200"), (12, 120, 12, "1500")]), probes=(1, 24, 25, 120)),241    dict(name="rate_changes", args=dict(P="300000", rate="0.05", comp="canadianFixed", freq="monthly", years=25,242                                        changes={61: ("0.065", None, "recalc"), 121: ("0.04", None, "keep")}), probes=(60, 61, 120, 121, 200)),243    dict(name="rate_up_keep_payment", args=dict(P="200000", rate="0.03", comp="canadianVariable", freq="monthly", years=25,244                                                changes={13: ("0.045", None, "keep")}), probes=(12, 13, 300)),245    dict(name="payment_override", args=dict(P="20000", rate="0.0699", comp="usMonthly", freq="monthly", years=5, override="500"), probes=(1, 12)),246    dict(name="term_5y", args=dict(P="300000", rate="0.05", comp="canadianFixed", freq="monthly", years=25, stop=60), probes=(60,)),247]248out["loan_schedules"] = []249for c in sched_cases:250    rows, pmt = schedule(**c["args"])251    a = dict(c["args"])252    a["lumps"] = [[k, F(v)] for k, v in (a.get("lumps") or {}).items()]253    a["recurring"] = [[s, e if e is not None else -1, ev, F(am)] for (s, e, ev, am) in (a.get("recurring") or [])]254    a["changes"] = [[k, F(v[0]), v[2]] for k, v in (a.get("changes") or {}).items()]255    out["loan_schedules"].append(dict(name=c["name"], args=a, **summarize(rows, pmt, c["probes"])))256257# refinancing: 240k left at 6.5% US over 25 years, new 5.25% over 25 years, 3000 costs + 1500 penalty paid in cash258def refi(financed):259    costs = Decimal("4500")260    old, pold = schedule("240000", "0.065", "usMonthly", "monthly", 25)261    new, pnew = schedule(str(Decimal("240000") + (costs if financed else 0)), "0.0525", "usMonthly", "monthly", 25)262    cash = Decimal(0) if financed else costs263    savings = pold - pnew264    be = None265    po = pn = Decimal(0)266    for k in range(1, max(len(old), len(new)) + 1):267        if k <= len(old): po += old[k - 1][1]268        if k <= len(new): pn += new[k - 1][1]269        bo = old[k - 1][5] if k <= len(old) else Decimal(0)270        bn = new[k - 1][5] if k <= len(new) else Decimal(0)271        if pn + bn + cash <= po + bo:272            be = k273            break274    return dict(financed=financed, current_payment=F(pold), new_payment=F(pnew), savings=F(savings),275                simple_break_even=F(costs / savings), net_break_even=be,276                current_interest=F(sum(r[2] for r in old)), new_interest=F(sum(r[2] for r in new)),277                lifetime_savings=F(sum(r[1] for r in old) - sum(r[1] for r in new) - cash))278out["refinance"] = [refi(False), refi(True)]279280# affordability: income 120k, tax 4200, heat 1500, condo 300 (50%), debts 650, limits 39% / 44%, 5.25% Canadian fixed, 25 years281inc = mp.mpf(120000) / 12282other = mp.mpf(4200) / 12 + mp.mpf(1500) / 12 + 300 * mp.mpf("0.5")283by_h, by_t = mp.mpf("0.39") * inc - other, mp.mpf("0.44") * inc - other - 650284i_aff = periodic("0.0525", "canadianFixed", 12)285pm = min(by_h, by_t)286out["affordability"] = dict(by_housing=F(by_h), by_total=F(by_t), max_payment=F(pm), max_loan=F(pm * (1 - (1 + i_aff) ** -300) / i_aff))287288# ---------------------------------------------------------------- Day counts and bonds289def eom(d):290    return d.day == calendar.monthrange(d.year, d.month)[1]291292def days_30_360_us(a, b):293    d1, d2 = a.day, b.day294    fa, fb = (a.month == 2 and eom(a)), (b.month == 2 and eom(b))295    if fa and fb: d2 = 30296    if fa: d1 = 30297    if d2 == 31 and d1 >= 30: d2 = 30298    if d1 == 31: d1 = 30299    return 360 * (b.year - a.year) + 30 * (b.month - a.month) + (d2 - d1)300301def days_30e_360(a, b):302    return 360 * (b.year - a.year) + 30 * (b.month - a.month) + (min(b.day, 30) - min(a.day, 30))303304def daycount(conv, a, b):305    if conv == "thirty360US": return days_30_360_us(a, b)306    if conv == "thirtyE360": return days_30e_360(a, b)307    return (b - a).days308309D = dt.date310pairs = [(D(2024, 1, 31), D(2024, 2, 29)), (D(2023, 2, 28), D(2024, 2, 29)), (D(2024, 2, 29), D(2024, 8, 31)),311         (D(2025, 1, 30), D(2025, 3, 31)), (D(2025, 1, 31), D(2025, 3, 31)), (D(2024, 12, 15), D(2025, 6, 15)),312         (D(2023, 8, 31), D(2024, 2, 28)), (D(2020, 2, 29), D(2021, 2, 28)), (D(1999, 12, 31), D(2000, 3, 1)),313         (D(2024, 5, 31), D(2024, 6, 30))]314CONVS = ["thirty360US", "thirtyE360", "actual360", "actual365Fixed", "actualActualICMA"]315out["daycounts"] = [dict(a=a.isoformat(), b=b.isoformat(), **{c: daycount(c, a, b) for c in CONVS}) for a, b in pairs]316317def add_months(d, n, eom_rule):318    t = d.year * 12 + d.month - 1 + n319    y, m = divmod(t, 12)320    m += 1321    dim = calendar.monthrange(y, m)[1]322    return D(y, m, dim if (eom_rule and eom(d)) else min(d.day, dim))323324def coupon_dates(settle, maturity, f, eom_rule=True):325    rem, k = [], 0326    while True:327        d = add_months(maturity, -k * (12 // f), eom_rule)328        if d <= settle:329            return d, list(reversed(rem))330        rem.append(d)331        k += 1332333def bond_setup(face, cpn, f, redemption, conv, settle, maturity):334    prev, rem = coupon_dates(settle, maturity, f)335    nxt = rem[0]336    C = mp.mpf(face) * mp.mpf(cpn) / f337    A = mp.mpf(daycount(conv, prev, settle))338    if conv == "actualActualICMA":339        E = mp.mpf((nxt - prev).days); w = mp.mpf((nxt - settle).days) / E340    elif conv in ("thirty360US", "thirtyE360"):341        E = mp.mpf(360) / f; w = (E - A) / E342    elif conv == "actual360":343        E = mp.mpf(360) / f; w = mp.mpf((nxt - settle).days) / E344    else:345        E = mp.mpf(365) / f; w = mp.mpf((nxt - settle).days) / E346    flows = [(w + k, C + (mp.mpf(redemption) if k == len(rem) - 1 else 0)) for k in range(len(rem))]347    return flows, C * A / E, A, E, w, rem348349def dirty(flows, y, f):350    return sum(a / (1 + mp.mpf(y) / f) ** t for t, a in flows)351352def bond_metrics(flows, accrued, y, f):353    y = mp.mpf(y)354    P = dirty(flows, y, f)355    dP = mp.diff(lambda x: dirty(flows, x, f), y)356    d2P = mp.diff(lambda x: dirty(flows, x, f), y, 2)357    mod = -dP / P358    return dict(dirty=F(P), clean=F(P - accrued), accrued=F(accrued), modified=F(mod), macaulay=F(mod * (1 + y / f)), convexity=F(d2P / P),359                ytm_from_clean=F(brentq(lambda x: float(dirty(flows, x, f) - P), -0.5, 5.0, xtol=1e-15, rtol=8.9e-16, maxiter=500)))360361bond_cases = [362    dict(name="excel_price_example", face=100, cpn="0.0575", f=2, red=100, conv="thirty360US", settle=D(2008, 2, 15), mat=D(2017, 11, 15), y="0.065"),363    dict(name="icma_semi", face=100, cpn="0.04375", f=2, red=100, conv="actualActualICMA", settle=D(2025, 3, 10), mat=D(2034, 11, 15), y="0.0412"),364    dict(name="e30_annual", face=1000, cpn="0.03", f=1, red=1000, conv="thirtyE360", settle=D(2024, 7, 31), mat=D(2031, 1, 31), y="0.0355"),365    dict(name="act360_quarterly", face=100, cpn="0.06", f=4, red=100, conv="actual360", settle=D(2025, 1, 20), mat=D(2027, 12, 15), y="0.052"),366    dict(name="act365_monthly", face=100, cpn="0.048", f=12, red=100, conv="actual365Fixed", settle=D(2025, 5, 7), mat=D(2026, 9, 30), y="0.07"),367    dict(name="eom_feb_maturity", face=100, cpn="0.05", f=2, red=100, conv="thirty360US", settle=D(2024, 10, 15), mat=D(2029, 2, 28), y="0.045"),368    dict(name="zero_coupon", face=100, cpn="0", f=2, red=100, conv="actualActualICMA", settle=D(2025, 6, 1), mat=D(2035, 6, 1), y="0.04"),369    dict(name="negative_yield", face=100, cpn="0.005", f=1, red=100, conv="actualActualICMA", settle=D(2021, 4, 12), mat=D(2026, 8, 15), y="-0.004"),370    dict(name="on_coupon_date", face=100, cpn="0.06", f=2, red=100, conv="thirty360US", settle=D(2025, 6, 15), mat=D(2030, 6, 15), y="0.05"),371    dict(name="premium_redemption", face=100, cpn="0.07", f=2, red=103, conv="thirty360US", settle=D(2025, 2, 3), mat=D(2028, 9, 1), y="0.058"),372]373out["bonds"] = []374for c in bond_cases:375    flows, acc, A, E, w, rem = bond_setup(c["face"], c["cpn"], c["f"], c["red"], c["conv"], c["settle"], c["mat"])376    m = bond_metrics(flows, acc, c["y"], c["f"])377    out["bonds"].append(dict(name=c["name"], face=c["face"], coupon=F(c["cpn"]), frequency=c["f"], redemption=c["red"], convention=c["conv"],378                             settlement=c["settle"].isoformat(), maturity=c["mat"].isoformat(), y=F(c["y"]),379                             accrued_days=F(A), period_days=F(E), w=F(w), remaining=len(rem),380                             first_coupon=rem[0].isoformat(), **m))381382out["bonds_simple"] = []383for (face, cpn, f, n, y) in [(100, "0.08", 2, 20, "0.10"), (1000, "0.05", 1, 10, "0.05"), (100, "0.03", 4, 37, "0.021"), (100, "0.09", 12, 60, "0.12")]:384    C = mp.mpf(face) * mp.mpf(cpn) / f385    flows = [(mp.mpf(k), C + (face if k == n else 0)) for k in range(1, n + 1)]386    out["bonds_simple"].append(dict(face=face, coupon=F(cpn), frequency=f, periods=n, y=F(y), **bond_metrics(flows, mp.mpf(0), y, f)))387388# yield to call: 8% semi-annual, callable 2029-06-15 at 104, clean price 106.50, settlement 2025-09-02, 30/360 US389flows, acc, *_ = bond_setup(100, "0.08", 2, 104, "thirty360US", D(2025, 9, 2), D(2029, 6, 15))390out["yield_to_call"] = dict(clean=106.5, call_price=104, accrued=F(acc),391                            ytc=F(mp.findroot(lambda x: dirty(flows, x, 2) - (mp.mpf("106.5") + acc), mp.mpf("0.06"))))392393# ---------------------------------------------------------------- Investment394def xirr(flows):395    d0 = min(d for d, _ in flows)396    f = lambda r: sum(mp.mpf(a) / (1 + mp.mpf(r)) ** (mp.mpf((d - d0).days) / 365) for d, a in flows)397    guess = brentq(lambda r: float(f(r)), -0.99, 10)398    return F(mp.findroot(f, mp.mpf(guess)))399400xirr_cases = [401    dict(name="excel_xirr_example", flows=[(D(2008, 1, 1), -10000), (D(2008, 3, 1), 2750), (D(2008, 10, 30), 4250), (D(2009, 2, 15), 3250), (D(2009, 4, 1), 2750)]),402    dict(name="portfolio_with_contributions", flows=[(D(2022, 1, 3), -25000), (D(2022, 6, 15), -5000), (D(2023, 2, 1), 3000), (D(2023, 9, 30), -4000), (D(2024, 12, 31), 36250.75)]),403    dict(name="loss", flows=[(D(2023, 5, 1), -10000), (D(2024, 5, 1), 400), (D(2025, 5, 1), 8200)]),404]405out["xirr"] = [dict(name=c["name"], flows=[[d.isoformat(), a] for d, a in c["flows"]], rate=xirr(c["flows"])) for c in xirr_cases]406407def growing_pv(c, r, g, n, due):408    r, g = mp.mpf(r), mp.mpf(g)409    if due:410        return sum(mp.mpf(c) * (1 + g) ** k / (1 + r) ** k for k in range(n))411    return sum(mp.mpf(c) * (1 + g) ** (k - 1) / (1 + r) ** k for k in range(1, n + 1))412413out["growing_annuities"] = []414for (c, r, g, n, due) in [(1000, "0.08", "0.03", 25, False), (1000, "0.05", "0.05", 30, False), (1000, "0.05", "0.0500000001", 30, False),415                          (500, "0.04", "0.07", 15, True), (250, "0.06", "-0.02", 40, False), (1000, "0.05", "0.05", 12, True)]:416    pv = growing_pv(c, r, g, n, due)417    out["growing_annuities"].append(dict(c=c, r=F(r), g=F(g), n=n, due=due, pv=F(pv), fv=F(pv * (1 + mp.mpf(r)) ** n)))418419rets = ["0.12", "-0.08", "0.25", "0.03", "-0.15", "0.19"]420prod = mp.mpf(1)421for x in rets: prod *= 1 + mp.mpf(x)422out["returns"] = dict(423    series=[F(x) for x in rets], arithmetic=F(sum(mp.mpf(x) for x in rets) / len(rets)), geometric=F(prod ** (mp.mpf(1) / len(rets)) - 1),424    cagr_10000_18500_7y=F((mp.mpf(18500) / 10000) ** (mp.mpf(1) / 7) - 1),425    annualized_35pct_2_5y=F(mp.mpf("1.35") ** (1 / mp.mpf("2.5")) - 1),426    real_7_nominal_3_inflation=F(mp.mpf("1.07") / mp.mpf("1.03") - 1),427    deflate_1000_25y_2pct=F(1000 / mp.mpf("1.02") ** 25),428    twr=F((mp.mpf(105000) / 100000) * (mp.mpf(118000) / 115000) * (mp.mpf(102000) / 108000) - 1),429    pv_annuity_due_500_6pct_15=F(sum(500 / mp.mpf("1.06") ** k for k in range(15))),430    fv_annuity_ord_500_6pct_15=F(sum(500 * mp.mpf("1.06") ** k for k in range(15))),431    pv_annuity_tiny_rate=F(sum(100 / (1 + mp.mpf("1e-10")) ** k for k in range(1, 361))),432)433434# ---------------------------------------------------------------- Options435def bsm(kind, S, K, r, q, s, T):436    S, K, r, q, s, T = map(mp.mpf, (S, K, r, q, s, T))437    d1 = (mp.log(S / K) + (r - q + s * s / 2) * T) / (s * mp.sqrt(T))438    d2 = d1 - s * mp.sqrt(T)439    if kind == "call":440        return S * mp.e ** (-q * T) * mp.ncdf(d1) - K * mp.e ** (-r * T) * mp.ncdf(d2)441    return K * mp.e ** (-r * T) * mp.ncdf(-d2) - S * mp.e ** (-q * T) * mp.ncdf(-d1)442443def bsm_float(kind, S, K, r, q, s, T):   # second route: scipy.stats.norm in double precision444    d1 = (np.log(S / K) + (r - q + s * s / 2) * T) / (s * np.sqrt(T))445    d2 = d1 - s * np.sqrt(T)446    if kind == "call":447        return S * np.exp(-q * T) * norm.cdf(d1) - K * np.exp(-r * T) * norm.cdf(d2)448    return K * np.exp(-r * T) * norm.cdf(-d2) - S * np.exp(-q * T) * norm.cdf(-d1)449450opt_cases = [("42", "40", "0.10", "0", "0.20", "0.5"), ("100", "100", "0.05", "0.02", "0.25", "1"), ("100", "130", "0.03", "0.01", "0.35", "0.25"),451             ("100", "70", "0.03", "0.04", "0.15", "2"), ("50", "50", "-0.01", "0", "0.6", "0.08"), ("3500", "3600", "0.045", "0.015", "0.18", "1.5"),452             ("10", "25", "0.02", "0", "0.4", "0.5"), ("100", "100", "0.05", "0", "0.01", "1")]453out["bsm"] = []454for (S, K, r, q, s, T) in opt_cases:455    for kind in ("call", "put"):456        args = (S, K, r, q, s, T)457        p = bsm(kind, *args)458        g = dict(459            delta=mp.diff(lambda x: bsm(kind, x, K, r, q, s, T), mp.mpf(S)),460            gamma=mp.diff(lambda x: bsm(kind, x, K, r, q, s, T), mp.mpf(S), 2),461            vega=mp.diff(lambda x: bsm(kind, S, K, r, q, x, T), mp.mpf(s)),462            theta=-mp.diff(lambda x: bsm(kind, S, K, r, q, s, x), mp.mpf(T)),463            rho=mp.diff(lambda x: bsm(kind, S, K, x, q, s, T), mp.mpf(r)),464        )465        fl = tuple(map(float, args))466        pf = bsm_float(kind, *fl)467        assert abs(pf - F(p)) < 1e-9 * max(1.0, F(p)), (kind, args)468        lo = max((fl[0] * np.exp(-fl[3] * fl[5]) - fl[1] * np.exp(-fl[2] * fl[5])) * (1 if kind == "call" else -1), 0)469        iv = None470        if F(p) - lo > 1e-6:   # implied volatility is only well conditioned away from the intrinsic bound471            iv = brentq(lambda v: bsm_float(kind, fl[0], fl[1], fl[2], fl[3], v, fl[5]) - F(p), 1e-6, 10, xtol=1e-15, rtol=8.9e-16)472        out["bsm"].append(dict(kind=kind, S=F(S), K=F(K), r=F(r), q=F(q), sigma=F(s), T=F(T), price=F(p), implied_vol=iv,473                               **{k: F(v) for k, v in g.items()}))474475def crr(kind, american, S, K, r, q, s, T, n):476    dt_ = T / n477    u = np.exp(s * np.sqrt(dt_)); d = 1 / u478    p = (np.exp((r - q) * dt_) - d) / (u - d)479    disc = np.exp(-r * dt_)480    sign = 1 if kind == "call" else -1481    j = np.arange(n + 1)482    v = np.maximum(sign * (S * u ** (2.0 * j - n) - K), 0)483    for step in range(n - 1, -1, -1):484        v = disc * (p * v[1:step + 2] + (1 - p) * v[0:step + 1])485        if american:486            jj = np.arange(step + 1)487            v = np.maximum(v, sign * (S * u ** (2.0 * jj - step) - K))488    return float(v[0])489490out["crr"] = []491for (S, K, r, q, s, T, n) in [(50, 50, 0.10, 0.0, 0.40, 5 / 12, 5), (50, 50, 0.10, 0.0, 0.40, 5 / 12, 500), (42, 40, 0.10, 0.0, 0.20, 0.5, 1000),492                              (100, 110, 0.03, 0.06, 0.30, 1.0, 400), (100, 95, 0.05, 0.02, 0.25, 0.75, 250), (36, 40, 0.06, 0.0, 0.20, 1.0, 2000)]:493    for kind in ("call", "put"):494        out["crr"].append(dict(kind=kind, S=S, K=K, r=r, q=q, sigma=s, T=T, steps=n,495                               european=crr(kind, False, S, K, r, q, s, T, n), american=crr(kind, True, S, K, r, q, s, T, n),496                               bsm=float(bsm_float(kind, S, K, r, q, s, T))))497498# ---------------------------------------------------------------- write499here = os.path.dirname(os.path.abspath(__file__))500path = os.path.join(here, "reference.json")501with open(path, "w") as fh:502    json.dump(out, fh, indent=1, sort_keys=True)503    fh.write("\n")504shutil.copyfile(path, os.path.join(here, "..", "Tests", "ORIXFinancialTests", "Resources", "reference.json"))505506# Human-readable spot checks of the textbook figures quoted in VALIDATION.md.507print("Canadian mortgage 300000 @5% semi-annual, 25y monthly:", out["loan_payments"][0]["payment"])508print("Hull BSM S=42 K=40 r=10%% sigma=20%% T=0.5: call %.4f put %.4f" % (out["bsm"][0]["price"], out["bsm"][1]["price"]))509print("Hull CRR American put 5 steps:", out["crr"][1]["american"])510print("Excel PRICE example:", out["bonds"][0]["clean"], " Excel XIRR example:", out["xirr"][0]["rate"])511print("IRRs two_irrs:", out["cashflows"][1]["irrs"], " three_irrs:", out["cashflows"][5]["irrs"], " none:", out["cashflows"][2]["irrs"])512print("cases:", {k: (len(v) if isinstance(v, list) else 1) for k, v in out.items() if k != "_meta"})513
Files main
Menu

Theme