SPB Git

Repository Public

gen_finance.py 29.8 KB 658 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : ORIX Sheet9# File             : Packages/SheetAnalytics/Tests/FinanceModelsTests/Generators/gen_finance.py10# Description      : Reference values for FinanceModels.11# Module           : FinanceModelsTests12# Repository       : https://git.spboucher.ai/orix-sheet13# Created          : 2026-11-2114# Last Modified    : 2026-11-2115#16# =============================================================================17# AUTHOR & PROFESSIONAL AFFILIATION18# =============================================================================19#20# Author           : Simon-Pierre Boucher21# Position         : Professor of Finance22# Institution      : Université du Québec en Outaouais (UQO)23# Department       : Département des sciences administratives24# Organization     : SP Boucher25#26# Website          : https://spboucher.ai27# Git              : https://git.spboucher.ai28#29# =============================================================================30# OFFICIAL CONTACT DIRECTORY31# =============================================================================32#33# General          : info@spboucher.ai34# Professional     : contact@spboucher.ai35# Direct           : simon@spboucher.ai36# Research         : research@spboucher.ai37# Development      : dev@spboucher.ai38# Support          : support@spboucher.ai39# Security/Admin   : admin@spboucher.ai40# Notifications    : notifications@spboucher.ai41#42# Preferred Contact: support@spboucher.ai43#44# =============================================================================45# COPYRIGHT & INTELLECTUAL PROPERTY46# =============================================================================47#48# Copyright (c) 202649# Simon-Pierre Boucher50#51# All rights reserved where applicable.52#53# This file is governed by the applicable project license,54# copyright notices, institutional agreements and relevant law.55#56# Unless expressly authorized by the applicable license or57# rights holder, copying, redistribution, sublicensing,58# publication and commercial exploitation are not permitted.59#60# Existing third-party rights and notices remain unaffected.61#62# =============================================================================63# CONFIDENTIALITY & SECURITY64# =============================================================================65#66# Classification   : Public67# Distribution     : Public repository; use is governed by the project license68# Security Contact : admin@spboucher.ai69#70# Access to this source does not independently grant permission71# to redistribute or disclose confidential materials.72#73# Do not embed credentials, private keys, access tokens,74# certificates or confidential personal information.75#76# =============================================================================77# LICENSE & MAINTENANCE78# =============================================================================79#80# License          : None specified (no license file in this repository)81# Maintainer       : Simon-Pierre Boucher82# Technical Contact: dev@spboucher.ai83#84# =============================================================================85# END OF SP BOUCHER SOURCE HEADER86# =============================================================================8788"""Reference values for FinanceModels. Every block is an independent implementation written from the89textbook definitions (plain Python / decimal / numpy / scipy / statsmodels), not a port of the Swift code."""90import datetime as dt91import math92from decimal import Decimal, ROUND_HALF_UP, ROUND_HALF_EVEN, getcontext9394import numpy as np95import statsmodels.api as sm96from dateutil.relativedelta import relativedelta97from scipy import optimize, stats9899from gen_common import dump100101getcontext().prec = 60102out = {}103104105# ---------------------------------------------------------------------------------------------106# Time value of money107# ---------------------------------------------------------------------------------------------108def periodic(r, m, p):109    """rate per payment period; m = compounding per year (None = continuous), p = payments per year"""110    if m is None:111        return math.exp(r / p) - 1112    return (1 + r / m) ** (m / p) - 1113114115def tvm_residual(i, n, pv, pmt, fv, begin):116    if i == 0:117        return pv + pmt * n + fv118    k = 1 + i if begin else 1119    return pv * (1 + i) ** n + pmt * k * ((1 + i) ** n - 1) / i + fv120121122tvm = []123cases = [124    # n, annual rate, pv, pmt, payments/yr, compounding/yr (None = continuous, 0 = same as payments), begin125    (360, 0.06, 200000.0, -1199.10, 12, 0, False),126    (60, 0.0499, 25000.0, -500.0, 12, 0, True),127    (300, 0.0549, 450000.0, -2744.0, 12, 2, False),        # Canadian: semi-annual compounding, monthly payments128    (40, 0.08, -10000.0, -250.0, 4, 12, False),            # saving: deposits quarterly, monthly compounding129    (10, 0.035, -1000.0, 0.0, 1, None, False),             # continuous compounding, lump sum130    (120, 0.0, 12000.0, -100.0, 12, 0, False),             # zero rate131    (26 * 5, 0.045, 30000.0, -260.0, 26, 2, True),132    (18, 0.12, 5000.0, -350.0, 12, 1, False),133]134for n, r, pv, pmt, p, m, begin in cases:135    mm = p if m == 0 else m136    i = periodic(r, mm, p)137    k = 1 + i if begin else 1138    ann = n if i == 0 else ((1 + i) ** n - 1) / i139    fv = -(pv * (1 + i) ** n + pmt * k * ann)140    rec = {"n": n, "rate": r, "pv": pv, "pmt": pmt, "fv": fv, "ppy": p, "cpy": ("cont" if m is None else mm), "begin": begin,141           "periodic": i, "ear": (1 + i) ** p - 1}142    # independent re-solves143    rec["pv_solved"] = -(fv + pmt * k * ann) / (1 + i) ** n144    rec["pmt_solved"] = -(pv * (1 + i) ** n + fv) / (k * ann)145    if pmt != 0 or i != 0:146        rec["n_solved"] = optimize.brentq(lambda x: tvm_residual(i, x, pv, pmt, fv, begin), 0.5, 5000, xtol=1e-13) if abs(tvm_residual(i, 0.5, pv, pmt, fv, begin)) > 0 else None147    if i != 0:148        lo, hi = i * 0.2, i * 5149        rec["i_solved"] = optimize.brentq(lambda x: tvm_residual(x, n, pv, pmt, fv, begin), lo, hi, xtol=1e-16)150    else:151        rec["i_solved"] = 0.0152    tvm.append(rec)153out["tvm"] = tvm154out["rates"] = {155    "ear_6_semi": (1 + 0.06 / 2) ** 2 - 1, "ear_6_monthly": (1 + 0.06 / 12) ** 12 - 1, "ear_6_cont": math.exp(0.06) - 1,156    "nominal_monthly_from_ear_8": 12 * (1.08 ** (1 / 12) - 1), "nominal_cont_from_ear_8": math.log(1.08),157}158159160# ---------------------------------------------------------------------------------------------161# Amortization (decimal arithmetic, round half up to cents)162# ---------------------------------------------------------------------------------------------163def q(x, mode=ROUND_HALF_UP):164    return Decimal(x).quantize(Decimal("0.01"), rounding=mode)165166167def level_payment(P, i, n, balloon=0.0):168    if i == 0:169        return (P - balloon) / n170    return (P - balloon * (1 + i) ** -n) * i / (1 - (1 + i) ** -n)171172173def schedule(P, i, n, kind="fixed", balloon=Decimal(0), extras=None, recurring=Decimal(0), override=None, mode=ROUND_HALF_UP):174    extras = extras or {}175    rate = Decimal(repr(i))176    bal = q(P, mode)177    pay = None178    if kind in ("fixed", "balloon"):179        pay = override if override is not None else q(Decimal(repr(level_payment(float(P), i, n, float(balloon)))), mode)180    fixed_principal = q(Decimal(P) / n, mode) if kind == "fixedPrincipal" else None181    rows, balloon_paid = [], Decimal(0)182    for k in range(1, n + 1):183        interest = q(bal * rate, mode)184        last = k == n185        if kind == "fixed":186            principal = pay - interest187            if last or principal >= bal:188                principal = bal189        elif kind == "balloon":190            principal = pay - interest191            if principal >= bal:192                principal = bal193            elif last:194                balloon_paid = bal - max(principal, Decimal(0))195                principal = bal196        elif kind == "fixedPrincipal":197            principal = bal if (last or fixed_principal >= bal) else fixed_principal198        else:199            principal = bal if last else Decimal(0)200        bal -= principal201        extra = Decimal(0)202        if bal > 0:203            extra = min(bal, q(Decimal(extras.get(k, 0)) + recurring, mode))204            bal -= extra205        rows.append([k, str(interest + principal), str(interest), str(principal), str(extra), str(bal)])206        if bal <= 0:207            break208    total_interest = sum(Decimal(r[2]) for r in rows)209    total_extra = sum(Decimal(r[4]) for r in rows)210    return {"rows": rows, "payment": str(pay) if pay is not None else rows[0][1], "total_interest": str(total_interest),211            "total_extra": str(total_extra), "balloon": str(balloon_paid), "count": len(rows)}212213214am = {}215am["fixed_12"] = schedule(Decimal("10000"), 0.075 / 12, 12)216am["fixed_360"] = schedule(Decimal("200000"), 0.06 / 12, 360)217am["fixed_360"]["rows"] = am["fixed_360"]["rows"][:3] + am["fixed_360"]["rows"][-3:]218am["fixed_principal_8"] = schedule(Decimal("25000"), 0.09 / 4, 8, kind="fixedPrincipal")219am["interest_only_6"] = schedule(Decimal("50000"), 0.048 / 12, 6, kind="interestOnly")220am["balloon_24"] = schedule(Decimal("80000"), 0.0625 / 12, 24, kind="balloon", balloon=Decimal("60000"))221am["extra_36"] = schedule(Decimal("15000.55"), 0.0899 / 12, 36, extras={3: "500", 10: "1250.25"}, recurring=Decimal("50"))222am["bankers_10"] = schedule(Decimal("1234.56"), 0.2 / 12, 10, mode=ROUND_HALF_EVEN)223am["zero_rate_5"] = schedule(Decimal("1000"), 0.0, 5)224i_sa = (1 + 0.0725 / 2) ** (2 / 12) - 1225am["semiannual_comp_18"] = schedule(Decimal("42000"), i_sa, 18)226am["semiannual_comp_18"]["periodic"] = i_sa227out["amort"] = am228229# ---------------------------------------------------------------------------------------------230# Canadian mortgage: j compounded semi-annually → i_f = (1 + j/2)^(2/f) − 1231# ---------------------------------------------------------------------------------------------232can = []233for P, j, months, term in [(Decimal("100000"), 0.06, 300, 60), (Decimal("523450.75"), 0.0489, 300, 60), (Decimal("350000"), 0.0719, 240, 36)]:234    i12 = (1 + j / 2) ** (2 / 12) - 1235    monthly = q(Decimal(repr(level_payment(float(P), i12, months))))236    rec = {"principal": str(P), "rate": j, "months": months, "term": term, "ear": (1 + j / 2) ** 2 - 1, "monthly": str(monthly), "freq": {}}237    for name, f, accel in [("monthly", 12, None), ("semiMonthly", 24, None), ("biWeekly", 26, None), ("weekly", 52, None),238                           ("acceleratedBiWeekly", 26, 2), ("acceleratedWeekly", 52, 4)]:239        i_f = (1 + j / 2) ** (2 / f) - 1240        n = round(months * f / 12)241        override = q(monthly / accel) if accel else None242        s = schedule(P, i_f, n, override=override)243        kterm = min(s["count"], round(term * f / 12))244        rows = s["rows"][:kterm]245        rec["freq"][name] = {246            "periodic": i_f, "payment": s["payment"], "scheduled": n, "actual": s["count"], "total_interest": s["total_interest"],247            "balance_at_term": rows[-1][5], "interest_in_term": str(sum(Decimal(r[2]) for r in rows)),248            "principal_in_term": str(sum(Decimal(r[3]) + Decimal(r[4]) for r in rows)),249        }250    can.append(rec)251out["canadian"] = can252253254# ---------------------------------------------------------------------------------------------255# Day counts (definitions: ISDA 2006 §4.16, SIFMA 30U/360, ICMA rule 251)256# ---------------------------------------------------------------------------------------------257def eom(d):258    return (d + dt.timedelta(days=1)).month != d.month259260261def d30u(a, b):262    d1, d2 = a.day, b.day263    if a.month == 2 and eom(a):264        if b.month == 2 and eom(b):265            d2 = 30266        d1 = 30267    if d2 == 31 and d1 >= 30:268        d2 = 30269    if d1 == 31:270        d1 = 30271    return 360 * (b.year - a.year) + 30 * (b.month - a.month) + (d2 - d1)272273274def d30e(a, b):275    return 360 * (b.year - a.year) + 30 * (b.month - a.month) + (min(b.day, 30) - min(a.day, 30))276277278def leap(y):279    return y % 4 == 0 and (y % 100 != 0 or y % 400 == 0)280281282def act_act_isda(a, b):283    total = 0.0284    cur = a285    while cur.year < b.year:286        nxt = dt.date(cur.year + 1, 1, 1)287        total += (nxt - cur).days / (366 if leap(cur.year) else 365)288        cur = nxt289    return total + (b - cur).days / (366 if leap(cur.year) else 365)290291292pairs = [((2007, 1, 15), (2007, 7, 30)), ((2008, 2, 29), (2008, 8, 31)), ((2007, 2, 28), (2008, 2, 29)), ((2011, 1, 31), (2011, 3, 31)),293         ((2011, 1, 30), (2011, 3, 31)), ((2010, 8, 31), (2011, 2, 28)), ((2003, 11, 1), (2004, 5, 1)), ((1999, 12, 30), (2001, 1, 2)),294         ((2012, 2, 29), (2012, 3, 1)), ((2019, 5, 31), (2019, 6, 30)), ((2020, 12, 31), (2024, 2, 29)), ((2023, 3, 15), (2023, 3, 15))]295dc = []296for a, b in pairs:297    da, db = dt.date(*a), dt.date(*b)298    dc.append({"a": list(a), "b": list(b), "d30u": d30u(da, db), "d30e": d30e(da, db), "act": (db - da).days,299               "yf_30u": d30u(da, db) / 360, "yf_30e": d30e(da, db) / 360, "yf_a360": (db - da).days / 360,300               "yf_a365": (db - da).days / 365, "yf_isda": act_act_isda(da, db)})301out["daycount"] = dc302303304# ---------------------------------------------------------------------------------------------305# Bonds: street convention, cash flows discounted at (1 + y/f)^-(k − 1 + w)306# ---------------------------------------------------------------------------------------------307def coupon_dates(settle, maturity, f):308    step = 12 // f309    sticky = eom(maturity)310    k = 0311    dates = [maturity]312    while True:313        k += 1314        d = maturity - relativedelta(months=step * k)315        if sticky:316            d = (d.replace(day=1) + relativedelta(months=1)) - dt.timedelta(days=1)317        dates.append(d)318        if d <= settle:319            break320    return dates[::-1]          # previous coupon first321322323def bond_numbers(settle, maturity, c, y, f, red, basis):324    ds = coupon_dates(settle, maturity, f)325    prev, nxt = ds[0], ds[1]326    n = len(ds) - 1327    if basis in ("30u", "30e"):328        fn = d30u if basis == "30u" else d30e329        A = fn(prev, settle); E = 360 / f; DSC = E - A330    elif basis == "a360":331        A = (settle - prev).days; E = 360 / f; DSC = (nxt - settle).days332    elif basis == "a365":333        A = (settle - prev).days; E = 365 / f; DSC = (nxt - settle).days334    else:335        A = (settle - prev).days; E = (nxt - prev).days; DSC = (nxt - settle).days336    w = DSC / E337    cpn = 100 * c / f338    accrued = cpn * A / E339340    def dirty(yy):341        if n == 1:342            return (red + cpn) / (1 + w * yy / f)343        return sum(cpn / (1 + yy / f) ** (k - 1 + w) for k in range(1, n + 1)) + red / (1 + yy / f) ** (n - 1 + w)344345    def dirty_compound(yy):346        return sum(cpn / (1 + yy / f) ** (k - 1 + w) for k in range(1, n + 1)) + red / (1 + yy / f) ** (n - 1 + w)347348    p = dirty(y)349    pc = dirty_compound(y)350    times = [(k - 1 + w) / f for k in range(1, n + 1)]351    flows = [cpn] * n352    flows[-1] += red353    pvs = [cf / (1 + y / f) ** (t * f) for cf, t in zip(flows, times)]354    mac = sum(t * v for t, v in zip(times, pvs)) / sum(pvs)355    mod = mac / (1 + y / f)356    h = 1e-5357    conv_fd = (dirty_compound(y + h) - 2 * pc + dirty_compound(y - h)) / (h * h) / pc358    mod_fd = -(dirty_compound(y + h) - dirty_compound(y - h)) / (2 * h) / pc359    clean = p - accrued360    y_back = optimize.brentq(lambda yy: dirty(yy) - p, -0.5, 3, xtol=1e-15) if n > 1 else y361    return {"prev": [prev.year, prev.month, prev.day], "next": [nxt.year, nxt.month, nxt.day], "n": n, "A": A, "E": E, "DSC": DSC,362            "accrued": accrued, "dirty": p, "clean": clean, "macaulay": mac, "modified": mod, "modified_fd": mod_fd,363            "convexity_fd": conv_fd, "dv01": mod * p * 1e-4, "yield_back": y_back, "current_yield": 100 * c / clean}364365366bonds = []367specs = [((2008, 2, 15), (2017, 11, 15), 0.0575, 0.065, 2, 100, "30u"),368         ((2018, 7, 1), (2048, 1, 1), 0.08, 0.09, 2, 100, "icma"),369         ((2008, 1, 1), (2016, 1, 1), 0.08, 0.09, 2, 100, "icma"),370         ((2024, 3, 11), (2031, 8, 31), 0.04125, 0.0387, 2, 100, "icma"),371         ((2023, 10, 17), (2029, 6, 30), 0.025, 0.051, 4, 100, "a360"),372         ((2022, 5, 5), (2027, 12, 1), 0.07, 0.032, 1, 102.5, "30e"),373         ((2025, 1, 20), (2025, 6, 15), 0.05, 0.047, 2, 100, "a365"),          # last coupon period374         ((2020, 9, 9), (2040, 9, 15), 0.0, 0.03, 2, 100, "30u"),             # zero coupon375         ((2021, 2, 28), (2026, 8, 31), 0.0333, 0.012, 12, 100, "30u"),376         ((2024, 6, 3), (2034, 6, 1), 0.03, -0.004, 1, 100, "icma")]          # negative yield377for s, mtr, c, y, f, red, basis in specs:378    rec = {"settle": list(s), "maturity": list(mtr), "coupon": c, "yield": y, "freq": f, "redemption": red, "basis": basis}379    rec.update(bond_numbers(dt.date(*s), dt.date(*mtr), c, y, f, red, basis))380    bonds.append(rec)381out["bonds"] = bonds382383384# ---------------------------------------------------------------------------------------------385# NPV / IRR / XIRR / MIRR386# ---------------------------------------------------------------------------------------------387def real_rate_roots(flows, lo=-0.99, hi=10.0):388    """IRRs via the polynomial in x = 1/(1+r): numpy.roots, real positive roots, polished by Newton."""389    coefs = np.array(flows[::-1], dtype=float)           # highest power first for sum cf_t x^t390    roots = np.roots(coefs)391    res = []392    for z in roots:393        if abs(z.imag) < 1e-7 * max(1, abs(z)) and z.real > 0:394            x = z.real395            for _ in range(50):                          # Newton polish on the polynomial396                p = np.polyval(coefs, x)397                d = np.polyval(np.polyder(coefs), x)398                if d == 0:399                    break400                x_new = x - p / d401                if abs(x_new - x) < 1e-16 * abs(x):402                    x = x_new403                    break404                x = x_new405            r = 1 / x - 1406            if lo < r <= hi:407                res.append(r)408    res = sorted(res)409    merged = []410    for r in res:411        if not merged or abs(r - merged[-1]) > 1e-7:412            merged.append(r)413    return merged414415416irr_cases = {417    "simple": [-1000, 300, 420, 680],418    "excel_doc": [-70000, 12000, 15000, 18000, 21000, 26000],419    "two_roots": [-1600, 10000, -10000],420    "three_roots": [-1000, 3600, -4310, 1716],          # (1+r) = 1.1, 1.2, 1.3421    "no_sign_change": [100, 200, 300],422    "no_real_root": [-100, 100, -100],423    "negative_irr": [-1000, 200, 300, 250],424    "long": [-50000] + [450] * 180,425    "late_outflow": [-5000, 2500, 2500, 2500, -1500, 800],426}427irr = {}428for name, flows in irr_cases.items():429    irr[name] = {"flows": flows, "roots": real_rate_roots(flows), "npv10": sum(cf / 1.1 ** t for t, cf in enumerate(flows)),430                 "sign_changes": int(np.sum(np.diff(np.sign([f for f in flows if f != 0])) != 0))}431out["irr"] = irr432433xflows = [-10000, 2750, 4250, 3250, 2750]434xdates = [(2008, 1, 1), (2008, 3, 1), (2008, 10, 30), (2009, 2, 15), (2009, 4, 1)]435436437def xnpv(r, flows, dates):438    d0 = dt.date(*dates[0])439    return sum(cf / (1 + r) ** ((dt.date(*d) - d0).days / 365) for cf, d in zip(flows, dates))440441442x2flows = [-25000, 4000, -3000, 9000, 12000, 8500]443x2dates = [(2020, 6, 15), (2020, 12, 31), (2021, 3, 1), (2022, 2, 28), (2023, 7, 4), (2024, 2, 29)]444out["xirr"] = [445    {"flows": xflows, "dates": [list(d) for d in xdates], "xirr": optimize.brentq(lambda r: xnpv(r, xflows, xdates), -0.9, 5, xtol=1e-15), "xnpv9": xnpv(0.09, xflows, xdates)},446    {"flows": x2flows, "dates": [list(d) for d in x2dates], "xirr": optimize.brentq(lambda r: xnpv(r, x2flows, x2dates), -0.9, 5, xtol=1e-15), "xnpv9": xnpv(0.09, x2flows, x2dates)},447]448449450def mirr(flows, fin, re):451    n = len(flows)452    pv_neg = sum(cf / (1 + fin) ** t for t, cf in enumerate(flows) if cf < 0)453    fv_pos = sum(cf * (1 + re) ** (n - 1 - t) for t, cf in enumerate(flows) if cf > 0)454    return (fv_pos / -pv_neg) ** (1 / (n - 1)) - 1455456457mflows = [-120000, 39000, 30000, 21000, 37000, 46000]458out["mirr"] = {"flows": mflows, "fin": 0.10, "re": 0.12, "mirr": mirr(mflows, 0.10, 0.12), "mirr2": mirr(irr_cases["late_outflow"], 0.07, 0.05)}459460# capital budgeting461A = [-10000, 6500, 3000, 3000, 1000]462B = [-10000, 3500, 3500, 3500, 3500]463rate = 0.12464465466def payback(flows):467    cum = 0.0468    for t, cf in enumerate(flows):469        before = cum470        cum += cf471        if cum >= 0:472            return float(t) if (t == 0 or cf <= 0) else (t - 1) + (-before) / cf473    return None474475476def npv(r, flows):477    return sum(cf / (1 + r) ** t for t, cf in enumerate(flows))478479480cb = {}481for name, fl in [("A", A), ("B", B)]:482    disc = [cf / (1 + rate) ** t for t, cf in enumerate(fl)]483    n = len(fl) - 1484    cb[name] = {"flows": fl, "npv": npv(rate, fl), "irr": real_rate_roots(fl)[0], "payback": payback(fl), "dpayback": payback(disc),485                "pi": (npv(rate, fl) - fl[0]) / -fl[0], "eaa": npv(rate, fl) * rate / (1 - (1 + rate) ** -n), "mirr": mirr(fl, rate, rate)}486cb["crossover"] = real_rate_roots([a - b for a, b in zip(A, B)])487cb["rate"] = rate488out["capbudget"] = cb489490# ---------------------------------------------------------------------------------------------491# Portfolio analytics492# ---------------------------------------------------------------------------------------------493rng = np.random.default_rng(20261121)494T, N = 250, 4495L = np.array([[0.012, 0, 0, 0], [0.004, 0.009, 0, 0], [0.002, -0.003, 0.015, 0], [0.001, 0.002, 0.004, 0.006]])496R = rng.standard_t(6, size=(T, N)) @ L.T + np.array([0.0006, 0.0003, 0.0009, 0.0002])497prices = 100 * np.cumprod(1 + R[:, 0])498prices = np.concatenate([[100.0], prices])499r0, bench = R[:, 0], R[:, 1]500ppy = 252.0501rf = 0.02 / 252502ex = r0 - rf503wealth = np.concatenate([[1.0], np.cumprod(1 + r0)])504peak = np.maximum.accumulate(wealth)505dd = (peak - wealth) / peak506trough = int(np.argmax(dd))507peak_idx = int(np.argmax(wealth[: trough + 1]))508rec_idx = next((i for i in range(trough + 1, len(wealth)) if wealth[i] >= wealth[peak_idx]), None)509exb = bench - rf510beta = np.cov(ex, exb, ddof=1)[0, 1] / np.var(exb, ddof=1)511alpha = ex.mean() - beta * exb.mean()512ols = sm.OLS(ex, sm.add_constant(exb)).fit()513active = r0 - bench514c = 0.95515qh = np.quantile(r0, 1 - c)516mu_, sd_ = r0.mean(), r0.std(ddof=1)517z = stats.norm.ppf(1 - c)518cov = np.cov(R.T, ddof=1)519mu = R.mean(axis=0)520w = np.array([0.4, 0.3, 0.2, 0.1])521port = {522    "R": R.T, "prices": prices, "simple": prices[1:] / prices[:-1] - 1, "log": np.log(prices[1:] / prices[:-1]),523    "ppy": ppy, "rf": rf,524    "cumulative": np.prod(1 + r0) - 1, "ann_return": np.prod(1 + r0) ** (ppy / T) - 1, "ann_mean": r0.mean() * ppy,525    "ann_vol": r0.std(ddof=1) * np.sqrt(ppy),526    "sharpe": ex.mean() / ex.std(ddof=1) * np.sqrt(ppy),527    "downside_dev": np.sqrt(np.mean(np.minimum(r0 - rf, 0) ** 2)),528    "sortino": (r0.mean() - rf) / np.sqrt(np.mean(np.minimum(r0 - rf, 0) ** 2)) * np.sqrt(ppy),529    "max_dd": dd.max(), "dd_peak": peak_idx, "dd_trough": trough, "dd_recovery": rec_idx,530    "beta": beta, "alpha": alpha, "beta_ols": ols.params[1], "alpha_ols": ols.params[0], "r2": ols.rsquared,531    "corr": np.corrcoef(ex, exb)[0, 1], "tracking_error": active.std(ddof=1) * np.sqrt(ppy),532    "info_ratio": active.mean() * ppy / (active.std(ddof=1) * np.sqrt(ppy)),533    "var_hist": -qh, "cvar_hist": -r0[r0 <= qh].mean(),534    "var_hist_99": -np.quantile(r0, 0.01), "cvar_hist_99": -r0[r0 <= np.quantile(r0, 0.01)].mean(),535    "var_norm": -(mu_ + sd_ * z), "cvar_norm": -mu_ + sd_ * stats.norm.pdf(z) / (1 - c),536    "cov": cov, "corrmat": np.corrcoef(R.T), "mu": mu, "w": w, "port_var": w @ cov @ w, "port_ret": w @ mu,537    "port_returns_head": (R @ w)[:5],538}539540# closed-form frontier (independent: Lagrangian via a bordered linear system)541ones = np.ones(N)542543544def eq_min_var(target=None):545    if target is None:546        K = np.block([[2 * cov, ones[:, None]], [ones[None, :], np.zeros((1, 1))]])547        rhs = np.concatenate([np.zeros(N), [1.0]])548    else:549        K = np.block([[2 * cov, ones[:, None], mu[:, None]], [ones[None, :], np.zeros((1, 2))], [mu[None, :], np.zeros((1, 2))]])550        rhs = np.concatenate([np.zeros(N), [1.0, target]])551    return np.linalg.solve(K, rhs)[:N]552553554gmv = eq_min_var()555targets = [float(gmv @ mu) + k * 0.0002 for k in range(1, 5)]556port["gmv_w"] = gmv557port["gmv_var"] = gmv @ cov @ gmv558port["eff"] = [{"target": t, "w": eq_min_var(t), "var": eq_min_var(t) @ cov @ eq_min_var(t)} for t in targets]559rf_t = float(gmv @ mu) - 0.0003          # below the minimum-variance return, so the tangency portfolio exists560zt = np.linalg.solve(cov, mu - rf_t)561port["tangency_rf"] = rf_t562port["tangency_w"] = zt / zt.sum()563tw = zt / zt.sum()564port["tangency_sharpe"] = (tw @ mu - rf_t) / np.sqrt(tw @ cov @ tw)565566# long-only via SLSQP on a harder 6-asset problem (several bounds bind)567mu6 = np.array([0.062, 0.081, 0.045, 0.104, 0.073, 0.038])568sd6 = np.array([0.11, 0.18, 0.07, 0.27, 0.16, 0.05])569C6 = np.array([[1, .55, .3, .45, .6, .1], [.55, 1, .2, .65, .5, .05], [.3, .2, 1, .15, .25, .4],570               [.45, .65, .15, 1, .55, -.05], [.6, .5, .25, .55, 1, .1], [.1, .05, .4, -.05, .1, 1]])571cov6 = np.outer(sd6, sd6) * C6572573574def slsqp(target=None):575    cons = [{"type": "eq", "fun": lambda x: x.sum() - 1, "jac": lambda x: np.ones(6)}]576    if target is not None:577        cons.append({"type": "eq", "fun": lambda x: x @ mu6 - target, "jac": lambda x: mu6})578    best = None579    for start in [np.ones(6) / 6, np.eye(6)[3] * 0.5 + np.ones(6) / 12, np.array([.3, .1, .2, .1, .1, .2])]:580        res = optimize.minimize(lambda x: 1e4 * x @ cov6 @ x, start, jac=lambda x: 2e4 * cov6 @ x, bounds=[(0, 1)] * 6,581                                constraints=cons, method="SLSQP", options={"ftol": 1e-15, "maxiter": 2000})582        x = res.x583        feasible = abs(x.sum() - 1) < 1e-10 and x.min() > -1e-12 and (target is None or abs(x @ mu6 - target) < 1e-10)584        if feasible and (best is None or res.fun < best.fun):     # SLSQP may stop with a line-search status at the optimum585            best = res586    return np.clip(best.x, 0, None)587588589lo_gmv = slsqp()590lo_targets = [0.045, 0.055, 0.065, 0.075, 0.085, 0.095, 0.10]591port["lo"] = {"mu": mu6, "cov": cov6, "gmv_w": lo_gmv, "gmv_var": lo_gmv @ cov6 @ lo_gmv,592              "points": [{"target": t, "w": slsqp(t), "var": slsqp(t) @ cov6 @ slsqp(t)} for t in lo_targets]}593out["portfolio"] = port594595# ---------------------------------------------------------------------------------------------596# Forecasting597# ---------------------------------------------------------------------------------------------598y = np.array([112.0, 118, 132, 129, 121, 135, 148, 148, 136, 119, 104, 118, 115, 126, 141, 135, 125, 149, 170, 170, 158, 133, 114, 140])599t = np.arange(1, len(y) + 1)600fit = sm.OLS(y, sm.add_constant(t)).fit()601new_t = np.arange(len(y) + 1, len(y) + 7)602pred = fit.get_prediction(sm.add_constant(new_t, has_constant="add")).summary_frame(alpha=0.05)603out["forecast"] = {"y": y, "slope": fit.params[1], "intercept": fit.params[0], "r2": fit.rsquared, "se": np.sqrt(fit.mse_resid),604                   "fitted": fit.fittedvalues, "forecast": pred["mean"].values, "pi_low": pred["obs_ci_lower"].values,605                   "pi_high": pred["obs_ci_upper"].values, "pi_low_80": fit.get_prediction(sm.add_constant(new_t, has_constant="add")).summary_frame(alpha=0.2)["obs_ci_lower"].values,606                   "seasonal_naive_12_h18": [float(y[len(y) - 12 + (h - 1) % 12]) for h in range(1, 19)],607                   "drift_h4": [float(y[-1] + h * (y[-1] - y[0]) / (len(y) - 1)) for h in range(1, 5)],608                   "cagr": (y[-1] / y[0]) ** (1 / (len(y) - 1)) - 1}609610611# ---------------------------------------------------------------------------------------------612# DCF (independent spreadsheet-style calculation)613# ---------------------------------------------------------------------------------------------614def dcf(base, growth, margin, da, capex, nwc, tax, w, terminal, mid, debt, cash, minority, pref, other, shares):615    rev, fcfs, ebitdas, pvs, dfs = base, [], [], [], []616    revs = []617    for k, g in enumerate(growth, start=1):618        new = rev * (1 + g)619        ebit = new * margin[k - 1]620        d = new * da[k - 1]621        f = ebit * (1 - tax) + d - new * capex[k - 1] - nwc * (new - rev)622        tt = k - 0.5 if mid else k623        df = (1 + w) ** -tt624        revs.append(new); fcfs.append(f); ebitdas.append(ebit + d); dfs.append(df); pvs.append(f * df)625        rev = new626    n = len(growth)627    if terminal[0] == "gordon":628        tv = fcfs[-1] * (1 + terminal[1]) / (w - terminal[1])629        pv_tv = tv * (1 + w) ** -(n - 0.5 if mid else n)630    else:631        tv = ebitdas[-1] * terminal[1]632        pv_tv = tv * (1 + w) ** -n633    ev = sum(pvs) + pv_tv634    eq = ev - debt + cash - minority - pref + other635    return {"revenue": revs, "fcf": fcfs, "ebitda": ebitdas, "df": dfs, "pv": pvs, "tv": tv, "pv_tv": pv_tv, "sum_pv": sum(pvs), "ev": ev,636            "equity": eq, "per_share": eq / shares, "tv_share": pv_tv / ev, "implied_multiple": tv / ebitdas[-1],637            "implied_growth": (tv * w - fcfs[-1]) / (tv + fcfs[-1])}638639640rf_, beta_, erp_, extra_, kd_, wtax_, E_, D_ = 0.035, 1.15, 0.055, 0.01, 0.062, 0.265, 820.0, 240.0641ke = rf_ + beta_ * erp_ + extra_642wacc = E_ / (E_ + D_) * ke + D_ / (E_ + D_) * kd_ * (1 - wtax_)643g5 = [0.12, 0.10, 0.08, 0.06, 0.04]644m5 = [0.18, 0.19, 0.20, 0.20, 0.21]645da5 = [0.04, 0.04, 0.038, 0.036, 0.035]646cx5 = [0.06, 0.055, 0.05, 0.045, 0.04]647out["dcf"] = {648    "wacc_inputs": {"rf": rf_, "beta": beta_, "erp": erp_, "extra": extra_, "kd": kd_, "tax": wtax_, "E": E_, "D": D_, "ke": ke, "wacc": wacc},649    "drivers": {"base": 500.0, "growth": g5, "margin": m5, "da": da5, "capex": cx5, "nwc": 0.12, "tax": 0.25,650                "debt": 240.0, "cash": 65.0, "minority": 12.0, "pref": 8.0, "other": 20.0, "shares": 48.5},651    "gordon_end": dcf(500.0, g5, m5, da5, cx5, 0.12, 0.25, wacc, ("gordon", 0.025), False, 240, 65, 12, 8, 20, 48.5),652    "gordon_mid": dcf(500.0, g5, m5, da5, cx5, 0.12, 0.25, wacc, ("gordon", 0.025), True, 240, 65, 12, 8, 20, 48.5),653    "multiple_end": dcf(500.0, g5, m5, da5, cx5, 0.12, 0.25, 0.09, ("multiple", 9.5), False, 240, 65, 12, 8, 20, 48.5),654    "multiple_mid": dcf(500.0, g5, m5, da5, cx5, 0.12, 0.25, 0.09, ("multiple", 9.5), True, 240, 65, 12, 8, 20, 48.5),655}656657dump("finance", out)658
Files main
Menu

Theme