SPB Git

Repository Public

CapitalBudgeting.swift 14.6 KB 296 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/CashFlows/CapitalBudgeting.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/// A project described by its periodic cash flows (t = 0 first).92public struct Project: Sendable, Hashable, Codable {93    public var name: String94    public var cashFlows: [Double]95    public init(name: String, cashFlows: [Double]) { self.name = name; self.cashFlows = cashFlows }96}9798public struct ProjectMetrics: Sendable, Hashable, Codable {99    public var name: String100    public var npv: Double101    /// nil when no IRR exists in range.102    public var irr: Double?103    public var irrCount: Int104    public var mirr: Double?105    /// Periods until cumulative cash flow turns non-negative (fractional, linear within the period); nil if never.106    public var payback: Double?107    public var discountedPayback: Double?108    public var profitabilityIndex: Double?109    /// Level annual amount with the same NPV over the project's life (for unequal lives).110    public var equivalentAnnualAnnuity: Double?111    /// 1 = highest NPV.112    public var npvRank: Int113}114115public struct CapitalBudgetComparison: Sendable, Hashable, Codable, TableReport {116    public var discountRate: Double117    public var projects: [ProjectMetrics]118    /// Name of the project with the highest NPV.119    public var bestByNPV: String?120    /// For exactly two projects: the discount rate(s) at which their NPVs are equal (Fisher crossover).121    public var crossoverRates: [Double]122123    public func table() -> [[Value]] {124        var out: [[Value]] = [["Project", "NPV", "IRR", "IRRs found", "MIRR", "Payback", "Discounted payback", "Profitability index", "Equivalent annual annuity", "NPV rank"].map { Value.text($0) }]125        for p in projects {126            out.append([.text(p.name), Report.num(p.npv), Report.num(p.irr), Report.int(p.irrCount), Report.num(p.mirr), Report.num(p.payback),127                        Report.num(p.discountedPayback), Report.num(p.profitabilityIndex), Report.num(p.equivalentAnnualAnnuity), Report.int(p.npvRank)])128        }129        out.append(Report.row("Discount rate", discountRate))130        if !crossoverRates.isEmpty { out.append([.text("Crossover rate(s)")] + crossoverRates.map { Report.num($0) }) }131        return Report.rectangular(out)132    }133}134135public enum CapitalBudgeting {136    /// Payback period in periods: the time at which the cumulative cash flow first reaches zero, with137    /// linear interpolation inside the recovering period (cash assumed to arrive evenly). `nil` when the138    /// investment is never recovered; 0 when the first flow is already non-negative.139    public static func payback(cashFlows: [Double]) -> Double? {140        var cumulative = 0.0141        for (t, cf) in cashFlows.enumerated() {142            let before = cumulative143            cumulative += cf144            if cumulative >= 0 {145                if t == 0 || cf <= 0 { return Double(t) }146                return Double(t - 1) + (-before) / cf147            }148        }149        return nil150    }151152    /// Payback computed on flows discounted to t = 0 at `rate`.153    public static func discountedPayback(cashFlows: [Double], rate: Double) -> Double? {154        payback(cashFlows: cashFlows.enumerated().map { $1 / pow(1 + rate, Double($0)) })155    }156157    /// Profitability index: PV of the flows after t = 0 divided by the initial outlay,158    /// PI = (NPV − CF₀) / (−CF₀) = 1 + NPV / |CF₀|. nil unless CF₀ < 0.159    public static func profitabilityIndex(cashFlows: [Double], rate: Double) -> Double? {160        guard let first = cashFlows.first, first < 0 else { return nil }161        return (CashFlowAnalysis.npv(rate: rate, cashFlows: cashFlows) - first) / -first162    }163164    /// Equivalent annual annuity: NPV · r / (1 − (1+r)^−n) over n = number of periods after t = 0.165    public static func equivalentAnnualAnnuity(cashFlows: [Double], rate: Double) -> Double? {166        let n = Double(cashFlows.count - 1)167        guard n >= 1 else { return nil }168        let npv = CashFlowAnalysis.npv(rate: rate, cashFlows: cashFlows)169        return rate == 0 ? npv / n : npv * rate / (1 - pow(1 + rate, -n))170    }171172    /// Metrics of one project at a discount rate (MIRR finances and reinvests at that same rate unless given).173    public static func metrics(_ project: Project, rate: Double, financeRate: Double? = nil, reinvestRate: Double? = nil) -> ProjectMetrics {174        let cf = project.cashFlows175        let irr = try? CashFlowAnalysis.irr(cashFlows: cf, guess: rate)176        return ProjectMetrics(name: project.name, npv: CashFlowAnalysis.npv(rate: rate, cashFlows: cf), irr: irr?.irr, irrCount: irr?.allRoots.count ?? 0,177                              mirr: try? CashFlowAnalysis.mirr(cashFlows: cf, financeRate: financeRate ?? rate, reinvestRate: reinvestRate ?? rate),178                              payback: payback(cashFlows: cf), discountedPayback: discountedPayback(cashFlows: cf, rate: rate),179                              profitabilityIndex: profitabilityIndex(cashFlows: cf, rate: rate),180                              equivalentAnnualAnnuity: equivalentAnnualAnnuity(cashFlows: cf, rate: rate), npvRank: 0)181    }182183    /// Side-by-side comparison of projects at one discount rate, ranked by NPV.184    public static func compare(_ projects: [Project], rate: Double, financeRate: Double? = nil, reinvestRate: Double? = nil) -> CapitalBudgetComparison {185        var ms = projects.map { metrics($0, rate: rate, financeRate: financeRate, reinvestRate: reinvestRate) }186        let order = ms.indices.sorted { ms[$0].npv > ms[$1].npv }187        for (rank, i) in order.enumerated() { ms[i].npvRank = rank + 1 }188        var crossover = [Double]()189        if projects.count == 2 { crossover = crossoverRates(projects[0].cashFlows, projects[1].cashFlows) }190        return CapitalBudgetComparison(discountRate: rate, projects: ms, bestByNPV: order.first.map { ms[$0].name }, crossoverRates: crossover)191    }192193    /// Discount rates at which two projects have the same NPV: the IRRs of the difference of their flows.194    public static func crossoverRates(_ a: [Double], _ b: [Double]) -> [Double] {195        let n = max(a.count, b.count)196        let diff = (0..<n).map { ($0 < a.count ? a[$0] : 0) - ($0 < b.count ? b[$0] : 0) }197        return (try? CashFlowAnalysis.irr(cashFlows: diff))?.allRoots ?? []198    }199}200201/// Cost–volume–profit (break-even) analysis for a single product or a fixed sales mix.202public struct BreakEvenAnalysis: Sendable, Hashable, Codable, TableReport {203    public var fixedCosts: Double204    public var pricePerUnit: Double205    public var variableCostPerUnit: Double206    /// Price − variable cost.207    public var contributionMargin: Double208    /// Contribution margin ÷ price.209    public var contributionMarginRatio: Double210    /// Fixed costs ÷ contribution margin; nil when the margin is not positive (no break-even).211    public var breakEvenUnits: Double?212    /// Break-even units × price = fixed costs ÷ contribution-margin ratio.213    public var breakEvenRevenue: Double?214    /// Units needed for the target profit (nil without a target or a positive margin).215    public var unitsForTargetProfit: Double?216    /// (Actual − break-even units) ÷ actual units, when actual units are supplied.217    public var marginOfSafety: Double?218    /// Total contribution ÷ operating profit at the actual volume (degree of operating leverage).219    public var operatingLeverage: Double?220221    public func table() -> [[Value]] {222        [223            Report.row("Fixed costs", fixedCosts),224            Report.row("Price per unit", pricePerUnit),225            Report.row("Variable cost per unit", variableCostPerUnit),226            Report.row("Contribution margin per unit", contributionMargin),227            Report.row("Contribution margin ratio", contributionMarginRatio),228            [.text("Break-even units"), Report.num(breakEvenUnits)],229            [.text("Break-even revenue"), Report.num(breakEvenRevenue)],230            [.text("Units for target profit"), Report.num(unitsForTargetProfit)],231            [.text("Margin of safety"), Report.num(marginOfSafety)],232            [.text("Degree of operating leverage"), Report.num(operatingLeverage)],233        ]234    }235236    public struct ChartPoint: Sendable, Hashable, Codable {237        public var units: Double238        public var revenue: Double239        public var totalCost: Double240        public var profit: Double241    }242243    /// Revenue, total cost and profit on an even grid of volumes from 0 to `maxUnits` (for the break-even chart).244    public func chartData(maxUnits: Double, steps: Int = 20) -> [ChartPoint] {245        (0...max(1, steps)).map { k in246            let u = maxUnits * Double(k) / Double(max(1, steps))247            let rev = u * pricePerUnit, cost = fixedCosts + u * variableCostPerUnit248            return ChartPoint(units: u, revenue: rev, totalCost: cost, profit: rev - cost)249        }250    }251}252253public enum BreakEven {254    /// Single-product break-even.255    public static func analyze(fixedCosts: Double, pricePerUnit: Double, variableCostPerUnit: Double,256                               targetProfit: Double? = nil, actualUnits: Double? = nil) -> BreakEvenAnalysis {257        let cm = pricePerUnit - variableCostPerUnit258        let ratio = pricePerUnit != 0 ? cm / pricePerUnit : .nan259        let be: Double? = cm > 0 ? fixedCosts / cm : nil260        var safety: Double?, leverage: Double?261        if let actualUnits, actualUnits != 0 {262            if let be { safety = (actualUnits - be) / actualUnits }263            let profit = actualUnits * cm - fixedCosts264            if profit != 0 { leverage = actualUnits * cm / profit }265        }266        return BreakEvenAnalysis(fixedCosts: fixedCosts, pricePerUnit: pricePerUnit, variableCostPerUnit: variableCostPerUnit,267                                 contributionMargin: cm, contributionMarginRatio: ratio, breakEvenUnits: be,268                                 breakEvenRevenue: be.map { $0 * pricePerUnit },269                                 unitsForTargetProfit: cm > 0 ? targetProfit.map { (fixedCosts + $0) / cm } : nil,270                                 marginOfSafety: safety, operatingLeverage: leverage)271    }272273    public struct MixProduct: Sendable, Hashable, Codable {274        public var name: String275        public var price: Double276        public var variableCost: Double277        /// Share of total units (any positive weights; normalised).278        public var mixWeight: Double279        public init(name: String, price: Double, variableCost: Double, mixWeight: Double) {280            self.name = name; self.price = price; self.variableCost = variableCost; self.mixWeight = mixWeight281        }282    }283284    /// Multi-product break-even at a constant sales mix: total units = fixed costs ÷ weighted-average285    /// contribution margin, split by the mix. Returns nil when the weighted margin is not positive.286    public static func salesMix(fixedCosts: Double, products: [MixProduct]) -> (totalUnits: Double, unitsByProduct: [Double], revenue: Double)? {287        let total = products.reduce(0) { $0 + $1.mixWeight }288        guard total > 0 else { return nil }289        let wcm = products.reduce(0) { $0 + ($1.price - $1.variableCost) * $1.mixWeight / total }290        guard wcm > 0 else { return nil }291        let units = fixedCosts / wcm292        let split = products.map { units * $0.mixWeight / total }293        return (units, split, zip(split, products).reduce(0) { $0 + $1.0 * $1.1.price })294    }295}296
Files main
Menu

Theme