SPB Git

Repository Public

CanadianMortgage.swift 10.8 KB 219 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetAnalytics/Sources/FinanceModels/Loans/CanadianMortgage.swift10// Module           : FinanceModels11// Repository       : https://git.spboucher.ai/orix-sheet12// Created          : 2026-11-2113// Last Modified    : 2026-11-2114//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : None specified (no license file in this repository)80// Maintainer       : Simon-Pierre Boucher81// Technical Contact: dev@spboucher.ai82//83// =============================================================================84// END OF SP BOUCHER SOURCE HEADER85// =============================================================================8687import Foundation88import SheetCore89import Statistics9091/// Payment frequencies offered on Canadian mortgages.92public enum CanadianPaymentFrequency: String, Sendable, Codable, CaseIterable {93    case monthly, semiMonthly, biWeekly, weekly94    /// Half of the monthly payment every two weeks (26 a year, i.e. one extra monthly payment per year).95    case acceleratedBiWeekly96    /// A quarter of the monthly payment every week (52 a year).97    case acceleratedWeekly9899    public var paymentsPerYear: Double {100        switch self {101        case .monthly: 12102        case .semiMonthly: 24103        case .biWeekly, .acceleratedBiWeekly: 26104        case .weekly, .acceleratedWeekly: 52105        }106    }107    public var isAccelerated: Bool { self == .acceleratedBiWeekly || self == .acceleratedWeekly }108}109110/// A Canadian fixed-rate mortgage. By law (Interest Act, s. 6) the quoted rate of a fixed-rate111/// mortgage compounds semi-annually, not in advance, so the rate per payment period is112/// `i_f = (1 + j/2)^(2/f) − 1` for f payments a year (j = quoted nominal rate).113public struct CanadianMortgage: Sendable, Hashable, Codable {114    public var principal: Decimal115    /// Quoted nominal annual rate (decimal), compounded semi-annually.116    public var annualRate: Double117    /// Amortization period in months (300 = 25 years).118    public var amortizationMonths: Int119    /// Term in months (60 = 5-year term); nil = no term analysis.120    public var termMonths: Int?121    public var frequency: CanadianPaymentFrequency122    public var rounding: MoneyRounding123    /// Compounding of the quoted rate. Semi-annual for fixed-rate mortgages; variable-rate mortgages124    /// usually compound monthly (`.perYear(12)`).125    public var compounding: Compounding126127    public init(principal: Decimal, annualRate: Double, amortizationMonths: Int, termMonths: Int? = nil,128                frequency: CanadianPaymentFrequency = .monthly, rounding: MoneyRounding = .cents, compounding: Compounding = .perYear(2)) {129        self.principal = principal; self.annualRate = annualRate; self.amortizationMonths = amortizationMonths130        self.termMonths = termMonths; self.frequency = frequency; self.rounding = rounding; self.compounding = compounding131    }132133    public struct Result: Sendable, Hashable, Codable, TableReport {134        public var frequency: CanadianPaymentFrequency135        public var payment: Decimal136        /// The monthly payment the accelerated payments are derived from (equals `payment` for monthly).137        public var monthlyPayment: Decimal138        public var paymentsPerYear: Double139        public var periodicRate: Double140        /// (1 + j/2)² − 1 for semi-annual compounding.141        public var effectiveAnnualRate: Double142        /// Payments scheduled over the contractual amortization.143        public var scheduledPayments: Int144        /// Payments actually needed (fewer for accelerated frequencies).145        public var actualPayments: Int146        public var actualAmortizationYears: Double147        public var totalInterest: Decimal148        /// Balance outstanding at the end of the term (nil without a term).149        public var balanceAtTermEnd: Decimal?150        public var interestPaidDuringTerm: Decimal?151        public var principalPaidDuringTerm: Decimal?152        public var schedule: AmortizationSchedule153154        public func table() -> [[Value]] {155            var out: [[Value]] = [156                [.text("Canadian mortgage"), .text(frequency.rawValue)],157                [.text("Payment"), Money.value(payment)],158                [.text("Equivalent monthly payment"), Money.value(monthlyPayment)],159                Report.row("Payments per year", paymentsPerYear),160                Report.row("Rate per payment", periodicRate),161                Report.row("Effective annual rate", effectiveAnnualRate),162                Report.row("Scheduled payments", scheduledPayments),163                Report.row("Payments to pay off", actualPayments),164                Report.row("Actual amortization (years)", actualAmortizationYears),165                [.text("Total interest"), Money.value(totalInterest)],166            ]167            if let b = balanceAtTermEnd, let ip = interestPaidDuringTerm, let pp = principalPaidDuringTerm {168                out.append([.text("Balance at end of term"), Money.value(b)])169                out.append([.text("Interest paid during term"), Money.value(ip)])170                out.append([.text("Principal paid during term"), Money.value(pp)])171            }172            return out173        }174    }175176    /// Rate per payment for a given number of payments a year.177    public func periodicRate(paymentsPerYear f: Double) -> Double {178        TVM.periodicRate(nominal: annualRate, compounding: compounding, paymentsPerYear: f)179    }180181    /// Computes the payment, the full schedule and the term summary.182    ///183    /// Regular frequencies: payment = P·i_f / (1 − (1+i_f)^−n) with n = f × amortization years.184    /// Accelerated frequencies: payment = monthly payment ÷ 2 (bi-weekly) or ÷ 4 (weekly), rounded;185    /// interest still accrues at i_26 / i_52, so the loan is repaid before the contractual amortization.186    public func solve() throws -> Result {187        guard amortizationMonths > 0 else { throw StatError.invalidInput("amortization must be at least one month") }188        let f = frequency.paymentsPerYear189        let monthlyTerms = LoanTerms(principal: principal, annualRate: annualRate, periods: amortizationMonths, paymentsPerYear: 12,190                                     compounding: compounding, rounding: rounding)191        let monthly = try Amortization.levelPayment(monthlyTerms)192        let n = Int((Double(amortizationMonths) * f / 12).rounded())193        var terms = LoanTerms(principal: principal, annualRate: annualRate, periods: max(n, 1), paymentsPerYear: f,194                              compounding: compounding, rounding: rounding)195        switch frequency {196        case .acceleratedBiWeekly: terms.paymentOverride = rounding.round(monthly / 2)197        case .acceleratedWeekly: terms.paymentOverride = rounding.round(monthly / 4)198        default: break199        }200        let schedule = try Amortization.schedule(terms)201        let payment = try terms.paymentOverride ?? Amortization.levelPayment(terms)202        var balance: Decimal?, interestInTerm: Decimal?, principalInTerm: Decimal?203        if let termMonths {204            let k = min(schedule.rows.count, Int((Double(termMonths) * f / 12).rounded()))205            let slice = schedule.rows.prefix(k)206            balance = slice.last?.balance ?? rounding.round(principal)207            interestInTerm = slice.reduce(Decimal(0)) { $0 + $1.interest }208            principalInTerm = slice.reduce(Decimal(0)) { $0 + $1.principal + $1.extra }209        }210        return Result(frequency: frequency, payment: payment, monthlyPayment: monthly, paymentsPerYear: f,211                      periodicRate: terms.periodicRate,212                      effectiveAnnualRate: TVM.effectiveAnnualRate(nominal: annualRate, compounding: compounding),213                      scheduledPayments: n, actualPayments: schedule.rows.count,214                      actualAmortizationYears: Double(schedule.rows.count) / f, totalInterest: schedule.totalInterest,215                      balanceAtTermEnd: balance, interestPaidDuringTerm: interestInTerm, principalPaidDuringTerm: principalInTerm,216                      schedule: schedule)217    }218}219
Files main
Menu

Theme