Repository Public
1"""Independent Python reference implementations of the financial functions.23Deliberately written differently from the Swift engine: plain powers instead of log1p/expm1,4amortization schedules simulated period by period, bonds priced by discounting an explicit list of5cash flows, every equation solved with scipy.optimize.brentq.6"""7import calendar8import math9from datetime import date, timedelta1011from scipy.optimize import brentq1213EPOCH = date(1899, 12, 30)141516def to_date(serial): return EPOCH + timedelta(days=int(math.floor(serial)))17def to_serial(d): return (d - EPOCH).days18def S(y, m, d): return to_serial(date(y, m, d))192021# ---- time value of money --------------------------------------------------------------------22def pmt(rate, nper, pv, fv=0, typ=0):23 if rate == 0: return -(pv + fv) / nper24 q = (1 + rate) ** nper25 return -(pv * q + fv) * rate / ((1 + rate * typ) * (q - 1))262728def fv(rate, nper, pmt_, pv=0, typ=0):29 """Simulates the account period by period when nper is a whole number, else the closed form."""30 if float(nper).is_integer() and 0 <= nper <= 5000:31 bal = pv32 for _ in range(int(nper)):33 if typ: bal = (bal + pmt_) * (1 + rate)34 else: bal = bal * (1 + rate) + pmt_35 return -bal36 if rate == 0: return -(pv + pmt_ * nper)37 q = (1 + rate) ** nper38 return -(pv * q + pmt_ * (1 + rate * typ) * (q - 1) / rate)394041def pv(rate, nper, pmt_, fv_=0, typ=0):42 if rate == 0: return -(fv_ + pmt_ * nper)43 q = (1 + rate) ** nper44 return -(fv_ + pmt_ * (1 + rate * typ) * (q - 1) / rate) / q454647def tvm_residual(rate, nper, pmt_, pv_, fv_, typ):48 if rate == 0: return pv_ + pmt_ * nper + fv_49 q = (1 + rate) ** nper50 return pv_ * q + pmt_ * (1 + rate * typ) * (q - 1) / rate + fv_515253def nper(rate, pmt_, pv_, fv_=0, typ=0):54 if rate == 0: return -(pv_ + fv_) / pmt_55 return brentq(lambda n: tvm_residual(rate, n, pmt_, pv_, fv_, typ), 1e-9, 3000, xtol=1e-13, rtol=1e-15)565758def rate(nper_, pmt_, pv_, fv_=0, typ=0, lo=-0.99, hi=10.0):59 return brentq(lambda r: tvm_residual(r, nper_, pmt_, pv_, fv_, typ), lo, hi, xtol=1e-15, rtol=1e-15, maxiter=500)606162def schedule(rate, nper, pv_, fv_=0, typ=0):63 """Amortization table: list of (interest, principal) for periods 1…nper (whole nper)."""64 p = pmt(rate, nper, pv_, fv_, typ)65 bal = pv_66 out = []67 for k in range(1, int(nper) + 1):68 if typ == 1:69 interest = 0.0 if k == 1 else -(bal) * rate70 # payment at the beginning: interest of period k accrues on the balance after the previous payment71 else:72 interest = -bal * rate73 principal = p - interest74 bal = bal + principal75 out.append((interest, principal))76 return out777879# ---- cash flows -------------------------------------------------------------------------------80def npv(rate, values): return sum(v / (1 + rate) ** (i + 1) for i, v in enumerate(values))81def irr_fn(values): return lambda r: sum(v / (1 + r) ** i for i, v in enumerate(values))82def irr(values, lo=-0.99, hi=10.0): return brentq(irr_fn(values), lo, hi, xtol=1e-15, rtol=1e-15, maxiter=1000)83def xnpv(rate, values, dates): return sum(v / (1 + rate) ** ((d - dates[0]) / 365.0) for v, d in zip(values, dates))84def xirr(values, dates, lo=-0.99, hi=10.0): return brentq(lambda r: xnpv(r, values, dates), lo, hi, xtol=1e-15, rtol=1e-15, maxiter=1000)858687def mirr(values, finance, reinvest):88 n = len(values)89 fv_pos = sum(v * (1 + reinvest) ** (n - 1 - i) for i, v in enumerate(values) if v > 0)90 pv_neg = sum(v / (1 + finance) ** i for i, v in enumerate(values) if v < 0)91 return (fv_pos / -pv_neg) ** (1.0 / (n - 1)) - 1929394# ---- depreciation (book-value simulations) ----------------------------------------------------95def syd(cost, salvage, life, per): return (cost - salvage) * (life - per + 1) / (life * (life + 1) / 2)969798def db(cost, salvage, life, period, month=12):99 r = round(1 - (salvage / cost) ** (1.0 / life) + 1e-12, 3)100 book = cost101 dep = 0102 for p in range(1, int(period) + 1):103 if p == 1: dep = cost * r * month / 12104 elif p == life + 1: dep = book * r * (12 - month) / 12105 else: dep = book * r106 book -= dep107 return dep108109110def ddb(cost, salvage, life, period, factor=2):111 book = cost112 dep = 0113 for _ in range(int(period)):114 dep = min(book * min(factor / life, 1), max(book - salvage, 0))115 book -= dep116 return dep117118119def vdb_whole(cost, salvage, life, start, end, factor=2, no_switch=False):120 """Whole periods only: declining balance with a switch to straight line when larger."""121 book = cost122 total = 0123 switched = False124 for p in range(1, int(end) + 1):125 d = min(book * min(factor / life, 1), max(book - salvage, 0))126 sl = (book - salvage) / (life - p + 1)127 if not no_switch and (switched or sl > d):128 switched = True129 d = sl130 book -= d131 if p > start: total += d132 return total133134135# ---- day counts -------------------------------------------------------------------------------136def last_day(y, m): return calendar.monthrange(y, m)[1]137def is_eom(d): return d.day == last_day(d.year, d.month)138139140def days360(a, b, european, both=False):141 """30/360 day count. US rules as Excel applies them (Wheeler, "YEARFRAC incompatibilities between142 Excel 2007 and OOXML"; same rules in ExcelFinancialFunctions' dateDiff360Us). `both` is the143 variant used for whole coupon periods, where the end date is adjusted unconditionally."""144 d1, d2 = a.day, b.day145 if european:146 d1, d2 = min(d1, 30), min(d2, 30)147 else:148 feb1 = a.month == 2 and is_eom(a)149 feb2 = b.month == 2 and is_eom(b)150 if feb2 and (feb1 or both): d2 = 30151 if d2 == 31 and (a.day >= 30 or both): d2 = 30152 if d1 == 31: d1 = 30153 if feb1: d1 = 30154 return 360 * (b.year - a.year) + 30 * (b.month - a.month) + (d2 - d1)155156157def daycount(a, b, basis):158 if basis == 0: return days360(a, b, False)159 if basis == 4: return days360(a, b, True)160 return (b - a).days161162163def year_length(a, b, basis):164 if basis in (0, 2, 4): return 360.0165 if basis == 3: return 365.0166 le_year = a.year == b.year or (a.year + 1 == b.year and (a.month, a.day) >= (b.month, b.day))167 if le_year:168 if a.year == b.year: return 366.0 if calendar.isleap(a.year) else 365.0169 for y in (a.year, b.year):170 if calendar.isleap(y) and a <= date(y, 2, 29) <= b: return 366.0171 return 365.0172 return (date(b.year + 1, 1, 1) - date(a.year, 1, 1)).days / float(b.year - a.year + 1)173174175def yearfrac(a, b, basis):176 if a > b: a, b = b, a177 return daycount(a, b, basis) / year_length(a, b, basis)178179180# ---- coupons ----------------------------------------------------------------------------------181def shift(d, months, eom):182 total = d.year * 12 + d.month - 1 + months183 y, m = divmod(total, 12)184 m += 1185 return date(y, m, last_day(y, m) if eom else min(d.day, last_day(y, m)))186187188def coupons(settle, maturity, freq):189 """(previous coupon date, next coupon date, number of coupons remaining)."""190 step = 12 // freq191 eom = is_eom(maturity)192 k = 0193 while shift(maturity, -k * step, eom) > settle: k += 1194 return shift(maturity, -k * step, eom), shift(maturity, -(k - 1) * step, eom), k195196197def coup(settle, maturity, freq, basis):198 """dict of the six COUP* results, plus x = (E − A)/E, the time to the next coupon used in pricing."""199 pcd, ncd, n = coupons(settle, maturity, freq)200 a = daycount(pcd, settle, basis)201 if basis == 1: e = (ncd - pcd).days202 elif basis == 3: e = 365.0 / freq203 else: e = 360.0 / freq204 if basis == 0: dsc = days360(pcd, ncd, False, both=True) - a205 elif basis == 4: dsc = days360(settle, ncd, True)206 else: dsc = (ncd - settle).days207 return dict(pcd=pcd, ncd=ncd, n=n, a=float(a), e=float(e), dsc=float(dsc), x=(e - a) / e)208209210def price(settle, maturity, rate_, yld, redemption, freq, basis):211 c = coup(settle, maturity, freq, basis)212 cpn = 100.0 * rate_ / freq213 x = c["x"]214 accrued = cpn * c["a"] / c["e"]215 if c["n"] == 1:216 return (redemption + cpn) / (1 + yld / freq * x) - accrued217 flows = [(x + k, cpn) for k in range(c["n"])]218 flows[-1] = (flows[-1][0], cpn + redemption)219 return sum(cash / (1 + yld / freq) ** t for t, cash in flows) - accrued220221222def bond_yield(settle, maturity, rate_, pr, redemption, freq, basis):223 return brentq(lambda y: price(settle, maturity, rate_, y, redemption, freq, basis) - pr, -0.9 * freq, 50.0, xtol=1e-15, rtol=1e-15, maxiter=1000)224225226def duration(settle, maturity, cpn_rate, yld, freq, basis):227 c = coup(settle, maturity, freq, basis)228 cpn = 100.0 * cpn_rate / freq229 x = c["x"]230 flows = [(x + k, cpn) for k in range(c["n"])]231 flows[-1] = (flows[-1][0], cpn + 100.0)232 pvs = [(t, cash / (1 + yld / freq) ** t) for t, cash in flows]233 return sum(t * v for t, v in pvs) / sum(v for _, v in pvs) / freq234235236def mat_terms(settle, maturity, issue, basis):237 """B, DIM, A, DSM of PRICEMAT / YIELDMAT."""238 b = year_length(issue, settle, basis)239 dim = daycount(issue, maturity, basis)240 a = daycount(issue, settle, basis)241 return b, float(dim), float(a), float(dim - a)242243244def pricemat(settle, maturity, issue, rate_, yld, basis):245 b, dim, a, dsm = mat_terms(settle, maturity, issue, basis)246 return (100 + dim / b * rate_ * 100) / (1 + dsm / b * yld) - a / b * rate_ * 100247248249def yieldmat(settle, maturity, issue, rate_, pr, basis):250 b, dim, a, dsm = mat_terms(settle, maturity, issue, basis)251 dirty = pr / 100.0 + a / b * rate_252 return (dim / b * rate_ + 1 - dirty) / dirty * b / dsm253254255def accrint(issue, first, settle, rate_, par, freq, basis, from_issue=True):256 """Σ Aᵢ/NLᵢ over quasi-coupon periods, written period by period going forward in time257 (the Swift engine walks backwards from the period containing settlement)."""258 step = 12 // freq259 eom = is_eom(first)260 q = lambda k: shift(first, k * step, eom)261 start = first if (not from_issue and settle > first) else issue262 k_end = 0263 while q(k_end) < settle: k_end += 1 # settlement lies in (q(k_end−1), q(k_end)]264 k = k_end265 while q(k - 1) > start: k -= 1 # accrual starts in [q(k−1), q(k))266 total = 0.0267 for j in range(k, k_end + 1):268 q0, q1 = q(j - 1), q(j)269 if j == k_end: # period containing settlement270 e = (q1 - q0).days if basis == 1 else (365.0 if basis == 3 else 360.0) / freq271 total += daycount(max(start, q0), settle, basis) / e272 elif start <= q0:273 total += 1.0274 else: # period containing the start of accrual275 if basis == 0: total += days360(start, q1, False) / float(days360(q0, q1, False, both=True))276 elif basis == 4: total += days360(start, q1, True) / float(days360(q0, q1, True))277 elif basis == 1: total += (q1 - start).days / float((q1 - q0).days)278 elif basis == 2: total += (q1 - start).days / float(days360(q0, q1, False))279 else: total += (q1 - start).days / (365.0 / freq)280 return par * rate_ / freq * total281282283def tbilleq(settle, maturity, discount):284 dsm = (maturity - settle).days285 if dsm <= 182: return 365 * discount / (360 - discount * dsm)286 p = 1 - discount * dsm / 360.0287 x = dsm / (366.0 if dsm == 366 else 365.0)288 # bond-equivalent yield of a bill longer than half a year: p·(1 + y/2)·(1 + (2x − 1)·y/2) = 1289 return brentq(lambda y: p * (1 + y / 2) * (1 + (2 * x - 1) * y / 2) - 1, 0, 5, xtol=1e-15, rtol=1e-15)290