SPB Git

Repository Public

Amortization.swift 9.7 KB 184 lines swift

1import Foundation2import SheetCore3import Statistics45/// Repayment structure of a loan.6public enum LoanType: Sendable, Hashable, Codable {7    /// Level payment that fully repays the loan (annuity loan).8    case fixedPayment9    /// Equal principal instalments; the payment declines as interest falls.10    case fixedPrincipal11    /// Interest only each period, the whole principal with the last payment (bullet).12    case interestOnly13    /// Level payment sized to leave this balance, due with the last payment.14    case balloon(Decimal)15}1617/// Terms of a loan paid in arrears (payments at the end of each period).18public struct LoanTerms: Sendable, Hashable, Codable {19    public var principal: Decimal20    /// Nominal annual rate as a decimal.21    public var annualRate: Double22    /// Number of scheduled payments.23    public var periods: Int24    public var paymentsPerYear: Double25    /// Compounding of the nominal rate; nil = same as the payment frequency.26    public var compounding: Compounding?27    public var type: LoanType28    /// Extra principal paid with specific payments (1-based period number → amount).29    public var extraPayments: [Int: Decimal]30    /// Extra principal paid with every payment.31    public var recurringExtraPayment: Decimal32    /// Replaces the computed level payment (fixed-payment and balloon loans), e.g. an accelerated or rounded-up payment.33    public var paymentOverride: Decimal?34    public var rounding: MoneyRounding3536    public init(principal: Decimal, annualRate: Double, periods: Int, paymentsPerYear: Double = 12, compounding: Compounding? = nil,37                type: LoanType = .fixedPayment, extraPayments: [Int: Decimal] = [:], recurringExtraPayment: Decimal = 0,38                paymentOverride: Decimal? = nil, rounding: MoneyRounding = .cents) {39        self.principal = principal; self.annualRate = annualRate; self.periods = periods; self.paymentsPerYear = paymentsPerYear40        self.compounding = compounding; self.type = type; self.extraPayments = extraPayments41        self.recurringExtraPayment = recurringExtraPayment; self.paymentOverride = paymentOverride; self.rounding = rounding42    }4344    /// Rate per payment period.45    public var periodicRate: Double {46        TVM.periodicRate(nominal: annualRate, compounding: compounding ?? .perYear(paymentsPerYear), paymentsPerYear: paymentsPerYear)47    }48}4950public struct AmortizationRow: Sendable, Hashable, Codable {51    /// 1-based payment number.52    public var period: Int53    /// Regular payment made this period (interest + scheduled principal, including a balloon on the last row).54    public var payment: Decimal55    public var interest: Decimal56    /// Scheduled principal repaid (excludes `extra`).57    public var principal: Decimal58    /// Extra principal repaid on top of the regular payment.59    public var extra: Decimal60    /// Balance after this payment.61    public var balance: Decimal62}6364public struct AmortizationSchedule: Sendable, Hashable, Codable, TableReport {65    public var rows: [AmortizationRow]66    /// The regular (rounded) payment; for fixed-principal loans the first payment, for interest-only the first interest payment.67    public var scheduledPayment: Decimal68    /// Rate per payment period used for interest.69    public var periodicRate: Double70    public var totalPaid: Decimal71    public var totalInterest: Decimal72    public var totalPrincipal: Decimal73    public var totalExtra: Decimal74    /// Balloon paid with the last payment (0 unless the loan is a balloon loan).75    public var balloonPayment: Decimal76    /// Last regular payment minus the scheduled payment: the cents absorbed by the final payment77    /// (and, with extra payments, the shortfall of the last instalment).78    public var finalPaymentAdjustment: Decimal79    /// Payments actually made (fewer than scheduled when extra payments retire the loan early).80    public var numberOfPayments: Int { rows.count }8182    public func table() -> [[Value]] {83        var out: [[Value]] = [["Period", "Payment", "Interest", "Principal", "Extra", "Balance"].map { Value.text($0) }]84        for r in rows {85            out.append([Report.int(r.period), Money.value(r.payment), Money.value(r.interest), Money.value(r.principal), Money.value(r.extra), Money.value(r.balance)])86        }87        out.append([.text("Total"), Money.value(totalPaid - totalExtra), Money.value(totalInterest), Money.value(totalPrincipal - totalExtra), Money.value(totalExtra), .blank])88        return out89    }90}9192public enum Amortization {93    /// The rounded level payment of a fixed-payment or balloon loan (before any override).94    public static func levelPayment(_ terms: LoanTerms) throws -> Decimal {95        try validate(terms)96        let i = terms.periodicRate, n = Double(terms.periods), p = Money.double(terms.principal)97        var balloon = 0.098        if case .balloon(let b) = terms.type { balloon = Money.double(b) }99        return terms.rounding.round(-TVM.payment(rate: i, periods: n, presentValue: p, futureValue: -balloon))100    }101102    private static func validate(_ t: LoanTerms) throws {103        guard t.principal > 0 else { throw StatError.invalidInput("principal must be positive") }104        guard t.periods > 0 else { throw StatError.invalidInput("the loan needs at least one payment") }105        guard t.paymentsPerYear > 0 else { throw StatError.invalidInput("payments per year must be positive") }106        guard t.periodicRate >= 0, t.periodicRate.isFinite else { throw StatError.invalidInput("the interest rate must be zero or positive") }107        if case .balloon(let b) = t.type, b < 0 || b > t.principal { throw StatError.invalidInput("the balloon must be between 0 and the principal") }108        if t.recurringExtraPayment < 0 || t.extraPayments.values.contains(where: { $0 < 0 }) { throw StatError.invalidInput("extra payments cannot be negative") }109    }110111    /// Builds the payment-by-payment schedule.112    ///113    /// Rounding rules: the level payment is rounded once; each period's interest is114    /// `round(balance × periodic rate)` on the decimal balance; scheduled principal is payment − interest;115    /// the final payment is whatever clears the balance exactly (so the schedule always ends at 0.00 and116    /// the rounding residue shows up in `finalPaymentAdjustment`). Extra payments reduce principal117    /// immediately, never exceed the outstanding balance, and shorten the loan (the payment is not recast).118    public static func schedule(_ terms: LoanTerms) throws -> AmortizationSchedule {119        try validate(terms)120        let rate = Money.decimal(terms.periodicRate)121        let r = terms.rounding122        var balance = r.round(terms.principal)123        let n = terms.periods124        var level = Decimal(0)125        var fixedPrincipal = Decimal(0)126        switch terms.type {127        case .fixedPayment, .balloon:128            level = try terms.paymentOverride ?? levelPayment(terms)129            guard level > 0 else { throw StatError.invalidInput("the payment must be positive") }130        case .fixedPrincipal: fixedPrincipal = r.round(terms.principal / Decimal(n))131        case .interestOnly: break132        }133        var rows = [AmortizationRow]()134        rows.reserveCapacity(n)135        var balloonPaid = Decimal(0)136        var scheduled = level137        for k in 1...n {138            let interest = r.round(balance * rate)139            var principal: Decimal140            let last = k == n141            switch terms.type {142            case .fixedPayment:143                principal = level - interest144                guard principal > 0 || last else { throw StatError.invalidInput("the payment does not cover the interest of period \(k): the loan would never be repaid") }145                if last || principal >= balance { principal = balance }146            case .balloon:147                principal = level - interest148                guard principal >= 0 || last else { throw StatError.invalidInput("the payment does not cover the interest of period \(k)") }149                if principal >= balance { principal = balance } else if last {150                    balloonPaid = balance - max(principal, 0)151                    principal = balance152                }153            case .fixedPrincipal:154                principal = last || fixedPrincipal >= balance ? balance : fixedPrincipal155            case .interestOnly:156                principal = last ? balance : 0157            }158            balance -= principal159            var extra = Decimal(0)160            if balance > 0 {161                extra = min(balance, r.round((terms.extraPayments[k] ?? 0) + terms.recurringExtraPayment))162                balance -= extra163            }164            rows.append(AmortizationRow(period: k, payment: interest + principal, interest: interest, principal: principal, extra: extra, balance: balance))165            if k == 1, level == 0 { scheduled = interest + principal }166            if balance <= 0 { break }167        }168        let totalInterest = rows.reduce(Decimal(0)) { $0 + $1.interest }169        let totalExtra = rows.reduce(Decimal(0)) { $0 + $1.extra }170        let totalPrincipal = rows.reduce(Decimal(0)) { $0 + $1.principal } + totalExtra171        let lastRegular = (rows.last?.payment ?? 0) - balloonPaid172        var adjustment = Decimal(0)173        switch terms.type {174        case .fixedPayment, .balloon: adjustment = lastRegular - level175        case .fixedPrincipal: adjustment = (rows.last?.principal ?? 0) - fixedPrincipal176        case .interestOnly: adjustment = 0177        }178        return AmortizationSchedule(rows: rows, scheduledPayment: scheduled, periodicRate: terms.periodicRate,179                                    totalPaid: totalInterest + totalPrincipal, totalInterest: totalInterest,180                                    totalPrincipal: totalPrincipal, totalExtra: totalExtra, balloonPayment: balloonPaid,181                                    finalPaymentAdjustment: adjustment)182    }183}184
Files main
Menu

Theme