SPB Git

Repository Public

TVMTool.swift 5.9 KB 82 lines swift

1import Foundation2import SheetCore3import FinanceModels4import AnalysisKit56/// Time value of money: solve for N, I/Y, PV, PMT or FV.7enum TVMTool {8    static let descriptor: ToolDescriptor = {9        func unless(_ id: String) -> @Sendable (FormValues) -> Bool { { $0.choice("solve") != id } }10        var t = ToolDescriptor(11            id: "finance.tvm", title: L("Time Value of Money"), group: FinGroup.timeValue, systemImage: "clock.arrow.circlepath",12            summary: L("Solves for the number of periods, the interest rate, the present value, the payment or the future value from the other four."),13            fields: [14                .choice("solve", L("Solve for"), [FieldOption("periods", L("Number of periods (N)")), FieldOption("rate", L("Annual rate (I/Y)")),15                                                  FieldOption("presentValue", L("Present value (PV)")), FieldOption("payment", L("Payment (PMT)")),16                                                  FieldOption("futureValue", L("Future value (FV)"))], default: "payment"),17                .number("n", L("Number of periods (N)"), 300, min: 0, unit: L("payments"), visible: unless("periods")),18                .percent("rate", L("Annual rate (I/Y)"), 0.06, min: -0.99, visible: unless("rate")),19                .number("pv", L("Present value (PV)"), 200_000, visible: unless("presentValue")),20                .number("pmt", L("Payment (PMT)"), -1_288.60, visible: unless("payment")),21                .number("fv", L("Future value (FV)"), 0, visible: unless("futureValue")),22                .integer("ppy", L("Payments per year"), 12, min: 1, max: 365),23            ] + Fin.compoundingFields + [24                .choice("timing", L("Payment timing"), [FieldOption("end", L("End of period")), FieldOption("begin", L("Beginning of period"))]),25            ],26            conventions: [27                L("Sign convention: money received is positive, money paid is negative (as in Excel and HP/TI calculators)."),28                L("Equation: PV·(1+i)^N + PMT·(1+i·k)·((1+i)^N − 1)/i + FV = 0, with i the rate per payment period and k = 1 for payments at the beginning, 0 at the end."),29                L("When compounding differs from the payment frequency: i = (1 + r/m)^(m/p) − 1; continuous compounding: i = e^(r/p) − 1."),30                L("The effective annual rate is (1+i)^p − 1. The nominal rate is reported in the chosen compounding."),31                L("The rate is found by Brent's method on the sign change nearest the guess; an error is reported when the cash flows cannot balance."),32            ],33            runTitle: L("Solve"),34            run: run)35        t.demo = { _, _ in }36        return t37    }()3839    static func run(_ input: ToolInput) throws -> ToolResult {40        let v = input.values41        guard let variable = TVMVariable(rawValue: v.choice("solve")) else { throw ToolError(L("Choose the variable to solve for.")) }42        let ppy = Double(max(v.int("ppy"), 1))43        let comp = Fin.compounding(v)44        let inputs = TVMInputs(periods: variable == .periods ? nil : v.number("n"), annualRate: variable == .rate ? nil : v.number("rate"),45                               presentValue: variable == .presentValue ? nil : v.number("pv"), payment: variable == .payment ? nil : v.number("pmt"),46                               futureValue: variable == .futureValue ? nil : v.number("fv"), paymentsPerYear: ppy, compounding: comp,47                               timing: v.choice("timing") == "begin" ? .begin : .end)48        let s = try TVM.solve(inputs, for: variable)4950        let solved: Metric51        switch variable {52        case .periods: solved = Metric(L("Number of periods (N)"), s.periods, .fixed(4), detail: L("payments"))53        case .rate: solved = Metric(L("Annual rate (I/Y)"), s.annualRate, .percent(4))54        case .presentValue: solved = Metric(L("Present value (PV)"), s.presentValue, .money)55        case .payment: solved = Metric(L("Payment (PMT)"), s.payment, .money)56        case .futureValue: solved = Metric(L("Future value (FV)"), s.futureValue, .money)57        }58        let metrics = [solved, Metric(L("Rate per period"), s.periodicRate, .percent(5)), Metric(L("Effective annual rate"), s.effectiveAnnualRate, .percent(4))]59        func mark(_ label: String, _ x: TVMVariable) -> String { x == variable ? label + " — " + L("solved") : label }60        let table = ReportTable.keyValue(title: L("Solution"), header: (L("Quantity"), L("Value")), [61            (mark(L("Number of periods (N)"), .periods), .finite(s.periods), .fixed(4)),62            (mark(L("Annual rate (I/Y)"), .rate), .finite(s.annualRate), .percent(4)),63            (mark(L("Present value (PV)"), .presentValue), .finite(s.presentValue), .money),64            (mark(L("Payment (PMT)"), .payment), .finite(s.payment), .money),65            (mark(L("Future value (FV)"), .futureValue), .finite(s.futureValue), .money),66            (L("Payments per year"), .number(ppy), .integer),67            (L("Compounding"), .text(Fin.compoundingLabel(comp, paymentsPerYear: ppy)), .auto),68            (L("Payment timing"), .text(s.timing == .begin ? L("Beginning of period") : L("End of period")), .auto),69            (L("Rate per period"), .finite(s.periodicRate), .percent(5)),70            (L("Effective annual rate"), .finite(s.effectiveAnnualRate), .percent(4)),71            (L("Term in years"), .finite(s.periods / ppy), .fixed(2)),72        ])73        let total = s.payment * s.periods74        var notes = [L("Signs follow the cash-flow convention: amounts received are positive, amounts paid are negative.")]75        if s.payment != 0, s.periods.isFinite {76            notes.append(L("Sum of the payments over the term: %@ (not discounted).", Fmt.money(total, locale: input.locale)))77        }78        return ToolResult(title: L("Time Value of Money"), subtitle: L("Solved for: %@", solved.label),79                          blocks: [.metrics(metrics), .table(table), .note(notes)], sheetName: L("TVM"))80    }81}82
Files main
Menu

Theme