"""ROI and payback: simple and annualized return, payback years (plain and discounted) and net present value of an up-front investment that returns a fixed net benefit every year. Inputs: initial_investment (0.01 to 1e12, default 50000), upfront_benefit (0 to 1e12, default 0, received at year 0), annual_net_benefit (0 to 1e12, default 14000), analysis_years (whole years 1 to 100, default 5), residual_value (0 to 1e12, default 8000, received at the end of the last year), discount_rate_percent (0 to 1000, default 10). Returns simpleRoiPercent, annualizedRoiPercent, paybackYears, discountedPaybackYears (None when not reached), totalNetGain, totalNominalInflow, totalDiscountedInflow, npv; money to cents. mysi, ROI and payback, mysi.dev/roi-payback, version 1, changed 2026-12-04. MIT. """ import math def _roi_payback_num(name, value, low, high, whole=False): if isinstance(value, bool) or not isinstance(value, (int, float)) or not low <= value <= high \ or (whole and value != int(value)): raise ValueError(f"{name} must be a {'whole ' * whole}number from {low} to {high}") return int(value) if whole else float(value) def _roi_payback_r2(x): return math.floor(x * 100 + 0.5) / 100 # to the cent, halves up def _roi_payback_years(cost, cumulative, residual_in_last): # cumulative[y] = inflow received by the end of year y; the benefit arrives evenly through # each year, so payback is interpolated inside the year. The residual comes at the very end. for y, cur in enumerate(cumulative): if cur < cost: continue if y == 0: return 0.0 prev = cumulative[y - 1] if y == len(cumulative) - 1 and residual_in_last > 0: cur -= residual_in_last if cur < cost: return float(y) if cur - prev <= 0: return float(y) return _roi_payback_r2(y - 1 + min(1, max(0, (cost - prev) / (cur - prev)))) return None def roi_payback(initial_investment=50000, upfront_benefit=0, annual_net_benefit=14000, analysis_years=5, residual_value=8000, discount_rate_percent=10): cost = _roi_payback_num("initial_investment", initial_investment, 0.01, 1e12) up = _roi_payback_num("upfront_benefit", upfront_benefit, 0, 1e12) a = _roi_payback_num("annual_net_benefit", annual_net_benefit, 0, 1e12) n = _roi_payback_num("analysis_years", analysis_years, 1, 100, whole=True) res = _roi_payback_num("residual_value", residual_value, 0, 1e12) r = _roi_payback_num("discount_rate_percent", discount_rate_percent, 0, 1000) / 100 nominal = [up + a * y + (res if y == n else 0) for y in range(n + 1)] # each year's benefit is discounted at the end of its year (ordinary annuity), not mid-year disc = [up + sum(a / (1 + r) ** i for i in range(1, y + 1)) for y in range(n + 1)] disc[-1] += res / (1 + r) ** n inflow, r2 = nominal[-1], _roi_payback_r2 gain = inflow - cost annualized = -100.0 if inflow <= 0 else ((inflow / cost) ** (1 / n) - 1) * 100 return { "simpleRoiPercent": r2(gain / cost * 100), "annualizedRoiPercent": r2(annualized), "paybackYears": _roi_payback_years(cost, nominal, res), "discountedPaybackYears": _roi_payback_years(cost, disc, res / (1 + r) ** n), "totalNetGain": r2(gain), "totalNominalInflow": r2(inflow), "totalDiscountedInflow": r2(disc[-1]), "npv": r2(disc[-1] - cost), } ROI_PAYBACK_CASES = [ (dict(initial_investment=50000, upfront_benefit=0, annual_net_benefit=14000, analysis_years=5, residual_value=8000, discount_rate_percent=10), {"simpleRoiPercent": 56.0, "paybackYears": 3.57, "npv": 8038.39}), (dict(initial_investment=1000, upfront_benefit=0, annual_net_benefit=400, analysis_years=3, residual_value=0, discount_rate_percent=10), {"simpleRoiPercent": 20.0, "paybackYears": 2.5, "npv": -5.26}), (dict(initial_investment=1000, upfront_benefit=200, annual_net_benefit=500, analysis_years=2, residual_value=100, discount_rate_percent=0), {"simpleRoiPercent": 30.0, "paybackYears": 1.6, "npv": 300.0}), ] def roi_payback_check(tolerance=1e-3): for given, want in ROI_PAYBACK_CASES: got = roi_payback(**given) for name, value in want.items(): close = abs(got[name] - value) <= tolerance * max(1, abs(value)) assert close, (name, got[name], value) return "ok" if __name__ == "__main__": import json, sys roi_payback_check() given = dict(a.split("=", 1) for a in sys.argv[1:] if "=" in a) js = lambda v: v.lstrip("-")[:1].isdigit() or v[:1] in '[{".' or v in ("true", "false", "null") given = {k: json.loads(v) if js(v) else v for k, v in given.items()} if given: print(json.dumps(roi_payback(**given)))