Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : ORIX Sheet9// File : Packages/FeatureAnalysis/Sources/FinanceStudio/CashFlows/CapitalBudgetingTool.swift10// Module : FinanceStudio11// 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 FinanceModels90import AnalysisKit9192/// Side-by-side comparison of several projects.93enum CapitalBudgetingTool {94 static let descriptor: ToolDescriptor = {95 var t = ToolDescriptor(96 id: "finance.capital-budgeting", title: L("Capital Budgeting Comparison"), group: FinGroup.cashFlows, systemImage: "square.stack.3d.up",97 summary: L("Compares projects (one column of cash flows each) by NPV, IRR, MIRR, payback, profitability index and equivalent annual annuity."),98 fields: [99 .range("data", L("Cash-flow range")),100 .columns("projects", L("Projects"), help: L("One column per project; rows are periods starting at t = 0.")),101 .percent("rate", L("Discount rate"), 0.10, min: -0.99, help: L("Per period.")),102 .toggle("sameRates", L("MIRR finances and reinvests at the discount rate"), true),103 .percent("finance", L("Finance rate (MIRR)"), 0.10, min: -0.99, visible: { !$0.bool("sameRates") }),104 .percent("reinvest", L("Reinvestment rate (MIRR)"), 0.10, min: -0.99, visible: { !$0.bool("sameRates") }),105 ],106 conventions: CashFlowTool.conventions + [107 L("Projects are ranked by NPV (rank 1 = highest). Equivalent annual annuity = NPV·r / (1 − (1+r)^−n), n = periods after t = 0."),108 L("For two projects the crossover (Fisher) rates are the IRRs of the difference of their cash flows."),109 ],110 runTitle: L("Compare"),111 run: run)112 t.demo = { _, v in v.set("data", range: "CashFlows!A1:D8"); v.set("projects", columns: [1, 2, 3]) }113 return t114 }()115116 static func run(_ input: ToolInput) throws -> ToolResult {117 let frame = try input.frame(), loc = input.locale118 let cols = try input.columns("projects")119 let rate = input.values.number("rate")120 let same = input.values.bool("sameRates")121 let projects = cols.map { Project(name: $0.name, cashFlows: $0.present) }122 try Fin.require(projects.allSatisfy { $0.cashFlows.count >= 2 }, L("Every project needs at least two cash flows."))123 let c = CapitalBudgeting.compare(projects, rate: rate, financeRate: same ? nil : input.values.number("finance"),124 reinvestRate: same ? nil : input.values.number("reinvest"))125 typealias Row = (String, (ProjectMetrics) -> Value, CellFormat)126 let never = L("never")127 let rows: [Row] = [128 (L("NPV rank"), { .number(Double($0.npvRank)) }, .integer), (L("Net present value (NPV)"), { .number($0.npv) }, .money),129 (L("Internal rate of return (IRR)"), { m in m.irr.map { .number($0) } ?? .text("—") }, .percent(3)),130 (L("Number of IRRs"), { .number(Double($0.irrCount)) }, .integer),131 (L("Modified IRR (MIRR)"), { .finite($0.mirr) }, .percent(3)),132 (L("Payback (periods)"), { m in m.payback.map { .number($0) } ?? .text(never) }, .fixed(2)),133 (L("Discounted payback (periods)"), { m in m.discountedPayback.map { .number($0) } ?? .text(never) }, .fixed(2)),134 (L("Profitability index"), { .finite($0.profitabilityIndex) }, .fixed(4)),135 (L("Equivalent annual annuity"), { .finite($0.equivalentAnnualAnnuity) }, .money),136 ]137 var table = ReportTable(title: L("Project comparison at %@", Fmt.percent(rate, 2, locale: loc)), rows: [])138 var grid: [[Value]] = [[.text(L("Measure"))] + c.projects.map { .text($0.name) }]139 for (i, r) in rows.enumerated() { grid.append([.text(r.0)] + c.projects.map(r.1)); table.rowFormats[i + 1] = r.2 }140 table.rows = grid141142 var blocks: [ResultBlock] = []143 if let best = c.bestByNPV, let m = c.projects.first(where: { $0.name == best }) {144 blocks.append(.metrics([Metric(L("Highest NPV"), text: best), Metric(L("NPV"), m.npv, .money)]))145 }146 blocks.append(.table(table))147 if !c.crossoverRates.isEmpty {148 blocks.append(.table(.keyValue(title: L("Crossover (Fisher) rates"),149 c.crossoverRates.enumerated().map { (L("Crossover rate %d", $0.offset + 1), .number($0.element), .percent(4)) },150 note: L("Below and above a crossover rate the NPV ranking of the two projects is reversed."))))151 }152 if c.projects.contains(where: { $0.irrCount > 1 }) {153 blocks.append(.warning(L("At least one project has several internal rates of return; its IRR is not a reliable ranking criterion. Use NPV or MIRR.")))154 }155 blocks.append(.chart(CashFlowTool.profileChart(projects.map { ($0.name, $0.cashFlows) }, roots: c.crossoverRates, rate: rate, locale: loc)))156 blocks.append(.interpretation(c.bestByNPV.map { L("At a discount rate of %@, %@ has the highest net present value.", Fmt.percent(rate, 2, locale: loc), $0) }157 ?? L("No project could be ranked.")))158 return ToolResult(title: L("Capital Budgeting Comparison"), subtitle: L("%@ — %d projects", frame.label, projects.count), blocks: blocks, sheetName: L("Projects"))159 }160}161