Repository Public
1import Foundation2import SheetCore3import Statistics45/// Cost-of-capital inputs (CAPM cost of equity, after-tax cost of debt, market-value weights).6public struct WACCInputs: Sendable, Hashable, Codable {7 public var riskFreeRate: Double8 public var beta: Double9 /// Expected market return minus the risk-free rate.10 public var equityRiskPremium: Double11 /// Additional premium added to the CAPM cost of equity (size, country…); 0 by default.12 public var additionalPremium: Double13 public var preTaxCostOfDebt: Double14 /// Marginal tax rate applied to the interest tax shield.15 public var taxRate: Double16 /// Market value of equity and of debt (only their proportions matter).17 public var equityValue: Double18 public var debtValue: Double1920 public init(riskFreeRate: Double, beta: Double, equityRiskPremium: Double, additionalPremium: Double = 0,21 preTaxCostOfDebt: Double, taxRate: Double, equityValue: Double, debtValue: Double) {22 self.riskFreeRate = riskFreeRate; self.beta = beta; self.equityRiskPremium = equityRiskPremium23 self.additionalPremium = additionalPremium; self.preTaxCostOfDebt = preTaxCostOfDebt; self.taxRate = taxRate24 self.equityValue = equityValue; self.debtValue = debtValue25 }2627 /// CAPM: r_f + β·ERP + additional premium.28 public var costOfEquity: Double { riskFreeRate + beta * equityRiskPremium + additionalPremium }29 public var afterTaxCostOfDebt: Double { preTaxCostOfDebt * (1 - taxRate) }30 public var equityWeight: Double { equityValue / (equityValue + debtValue) }31 public var debtWeight: Double { debtValue / (equityValue + debtValue) }32 /// E/(D+E)·k_e + D/(D+E)·k_d·(1 − t).33 public var wacc: Double { equityWeight * costOfEquity + debtWeight * afterTaxCostOfDebt }34}3536public enum DiscountRateSource: Sendable, Hashable, Codable {37 case fixed(Double)38 case wacc(WACCInputs)39 public var rate: Double {40 switch self {41 case .fixed(let r): r42 case .wacc(let w): w.wacc43 }44 }45}4647public enum TerminalValueMethod: Sendable, Hashable, Codable {48 /// Gordon growth: TV = FCF_N·(1 + g) / (WACC − g).49 case gordonGrowth(Double)50 /// Exit multiple: TV = EBITDA_N × multiple.51 case exitMultiple(Double)52}5354/// Driver-based assumptions of a discounted-cash-flow valuation. All per-year arrays have one entry55/// per projection year (year 1 … N).56public struct DCFAssumptions: Sendable, Hashable, Codable {57 /// Revenue of the last historical year (year 0).58 public var baseRevenue: Double59 public var revenueGrowth: [Double]60 /// EBIT ÷ revenue.61 public var ebitMargin: [Double]62 /// Depreciation & amortisation ÷ revenue.63 public var depreciationPercentOfRevenue: [Double]64 /// Capital expenditure ÷ revenue.65 public var capexPercentOfRevenue: [Double]66 /// Net working capital ÷ revenue; the yearly investment is this share of the revenue increase.67 public var nwcPercentOfRevenue: Double68 /// Cash tax rate on EBIT.69 public var taxRate: Double70 public var discountRate: DiscountRateSource71 public var terminal: TerminalValueMethod72 /// Mid-year convention: flows are discounted at t − 0.5 (cash arrives evenly through the year).73 public var midYearConvention: Bool74 public var debt: Double75 public var cash: Double76 public var minorityInterest: Double77 public var preferredEquity: Double78 public var nonOperatingAssets: Double79 public var dilutedShares: Double8081 public init(baseRevenue: Double, revenueGrowth: [Double], ebitMargin: [Double], depreciationPercentOfRevenue: [Double],82 capexPercentOfRevenue: [Double], nwcPercentOfRevenue: Double, taxRate: Double, discountRate: DiscountRateSource,83 terminal: TerminalValueMethod, midYearConvention: Bool = false, debt: Double = 0, cash: Double = 0,84 minorityInterest: Double = 0, preferredEquity: Double = 0, nonOperatingAssets: Double = 0, dilutedShares: Double) {85 self.baseRevenue = baseRevenue; self.revenueGrowth = revenueGrowth; self.ebitMargin = ebitMargin86 self.depreciationPercentOfRevenue = depreciationPercentOfRevenue; self.capexPercentOfRevenue = capexPercentOfRevenue87 self.nwcPercentOfRevenue = nwcPercentOfRevenue; self.taxRate = taxRate; self.discountRate = discountRate88 self.terminal = terminal; self.midYearConvention = midYearConvention; self.debt = debt; self.cash = cash89 self.minorityInterest = minorityInterest; self.preferredEquity = preferredEquity90 self.nonOperatingAssets = nonOperatingAssets; self.dilutedShares = dilutedShares91 }9293 /// Constant drivers over `years` projection years.94 public init(baseRevenue: Double, years: Int, revenueGrowth: Double, ebitMargin: Double, depreciationPercentOfRevenue: Double,95 capexPercentOfRevenue: Double, nwcPercentOfRevenue: Double, taxRate: Double, discountRate: DiscountRateSource,96 terminal: TerminalValueMethod, midYearConvention: Bool = false, debt: Double = 0, cash: Double = 0, dilutedShares: Double) {97 func rep(_ v: Double) -> [Double] { Array(repeating: v, count: max(0, years)) }98 self.init(baseRevenue: baseRevenue, revenueGrowth: rep(revenueGrowth), ebitMargin: rep(ebitMargin),99 depreciationPercentOfRevenue: rep(depreciationPercentOfRevenue), capexPercentOfRevenue: rep(capexPercentOfRevenue),100 nwcPercentOfRevenue: nwcPercentOfRevenue, taxRate: taxRate, discountRate: discountRate, terminal: terminal,101 midYearConvention: midYearConvention, debt: debt, cash: cash, dilutedShares: dilutedShares)102 }103104 public var years: Int { revenueGrowth.count }105}106107public struct DCFResult: Sendable, Hashable, Codable, TableReport {108 /// Per projection year (index 0 = year 1).109 public var revenue: [Double]110 public var ebit: [Double]111 public var taxes: [Double]112 public var nopat: [Double]113 public var depreciation: [Double]114 public var capex: [Double]115 public var changeInNWC: [Double]116 public var ebitda: [Double]117 /// Unlevered free cash flow: NOPAT + D&A − capex − ΔNWC.118 public var freeCashFlow: [Double]119 /// Discounting time of each year's flow (t, or t − 0.5 with the mid-year convention).120 public var discountPeriods: [Double]121 public var discountFactors: [Double]122 public var presentValues: [Double]123 public var discountRate: Double124 public var costOfEquity: Double?125 public var terminalValue: Double126 public var presentValueOfTerminal: Double127 public var sumOfPresentValues: Double128 public var enterpriseValue: Double129 public var equityValue: Double130 public var valuePerShare: Double131 /// PV of terminal value ÷ enterprise value.132 public var terminalShareOfValue: Double133 /// Terminal value ÷ final-year EBITDA.134 public var impliedExitMultiple: Double135 /// Growth rate g such that FCF_N(1+g)/(WACC − g) equals the terminal value.136 public var impliedPerpetualGrowth: Double137138 public func table() -> [[Value]] {139 let n = revenue.count140 func line(_ label: String, _ v: [Double]) -> [Value] { [.text(label)] + v.map { Report.num($0) } }141 var out: [[Value]] = [[.text("Year")] + (1...max(n, 1)).prefix(n).map { Report.int($0) }]142 out.append(line("Revenue", revenue))143 out.append(line("EBIT", ebit))144 out.append(line("Taxes on EBIT", taxes))145 out.append(line("NOPAT", nopat))146 out.append(line("Depreciation & amortisation", depreciation))147 out.append(line("Capital expenditure", capex))148 out.append(line("Change in net working capital", changeInNWC))149 out.append(line("Free cash flow", freeCashFlow))150 out.append(line("Discount factor", discountFactors))151 out.append(line("Present value of FCF", presentValues))152 out.append([])153 out.append(Report.row("Discount rate (WACC)", discountRate))154 out.append(Report.row("Sum of PV of FCF", sumOfPresentValues))155 out.append(Report.row("Terminal value", terminalValue))156 out.append(Report.row("PV of terminal value", presentValueOfTerminal))157 out.append(Report.row("Enterprise value", enterpriseValue))158 out.append(Report.row("Equity value", equityValue))159 out.append(Report.row("Value per share", valuePerShare))160 out.append(Report.row("Terminal value share of EV", terminalShareOfValue))161 out.append(Report.row("Implied exit multiple (EV/EBITDA)", impliedExitMultiple))162 out.append(Report.row("Implied perpetual growth", impliedPerpetualGrowth))163 return Report.rectangular(out)164 }165}166167public enum DCFModel {168 static func validate(_ a: DCFAssumptions) throws {169 let n = a.years170 guard n >= 1 else { throw StatError.invalidInput("the DCF needs at least one projection year") }171 guard a.ebitMargin.count == n, a.depreciationPercentOfRevenue.count == n, a.capexPercentOfRevenue.count == n else {172 throw StatError.invalidInput("every per-year driver needs one value per projection year (\(n))")173 }174 let w = a.discountRate.rate175 guard w > -1, w.isFinite else { throw StatError.invalidInput("the discount rate must be greater than −100 %") }176 if case .gordonGrowth(let g) = a.terminal, !(g < w) { throw StatError.invalidInput("terminal growth must be below the discount rate") }177 guard a.dilutedShares > 0 else { throw StatError.invalidInput("diluted shares must be positive") }178 }179180 /// Runs the valuation.181 ///182 /// Conventions: FCF_t = EBIT_t(1 − tax) + D&A_t − capex_t − nwc%·(Rev_t − Rev_{t−1}); flows are183 /// discounted at t (year-end) or t − 0.5 (mid-year). The Gordon terminal value is discounted with the184 /// same timing as the final-year flow (N, or N − 0.5 under the mid-year convention); an exit-multiple185 /// terminal value is a year-end price and is always discounted at N. Equity = EV − debt + cash −186 /// minority interest − preferred equity + non-operating assets.187 public static func value(_ a: DCFAssumptions) throws -> DCFResult {188 try validate(a)189 let n = a.years, w = a.discountRate.rate190 var revenue = [Double](), ebit = [Double](), taxes = [Double](), nopat = [Double](), da = [Double](), capex = [Double]()191 var dnwc = [Double](), fcf = [Double](), ebitda = [Double](), periods = [Double](), dfs = [Double](), pvs = [Double]()192 var prev = a.baseRevenue193 let offset = a.midYearConvention ? 0.5 : 0.0194 for t in 0..<n {195 let rev = prev * (1 + a.revenueGrowth[t])196 let e = rev * a.ebitMargin[t]197 let tax = e * a.taxRate198 let d = rev * a.depreciationPercentOfRevenue[t]199 let cx = rev * a.capexPercentOfRevenue[t]200 let dn = a.nwcPercentOfRevenue * (rev - prev)201 let f = e - tax + d - cx - dn202 let period = Double(t + 1) - offset203 let df = 1 / pow(1 + w, period)204 revenue.append(rev); ebit.append(e); taxes.append(tax); nopat.append(e - tax); da.append(d); capex.append(cx)205 dnwc.append(dn); fcf.append(f); ebitda.append(e + d); periods.append(period); dfs.append(df); pvs.append(f * df)206 prev = rev207 }208 let tv: Double, pvTV: Double209 switch a.terminal {210 case .gordonGrowth(let g):211 tv = fcf[n - 1] * (1 + g) / (w - g)212 pvTV = tv / pow(1 + w, Double(n) - offset)213 case .exitMultiple(let m):214 tv = ebitda[n - 1] * m215 pvTV = tv / pow(1 + w, Double(n))216 }217 let sumPV = pvs.reduce(0, +)218 let ev = sumPV + pvTV219 let equity = ev - a.debt + a.cash - a.minorityInterest - a.preferredEquity + a.nonOperatingAssets220 var coe: Double?221 if case .wacc(let wi) = a.discountRate { coe = wi.costOfEquity }222 return DCFResult(revenue: revenue, ebit: ebit, taxes: taxes, nopat: nopat, depreciation: da, capex: capex, changeInNWC: dnwc,223 ebitda: ebitda, freeCashFlow: fcf, discountPeriods: periods, discountFactors: dfs, presentValues: pvs,224 discountRate: w, costOfEquity: coe, terminalValue: tv, presentValueOfTerminal: pvTV, sumOfPresentValues: sumPV,225 enterpriseValue: ev, equityValue: equity, valuePerShare: equity / a.dilutedShares,226 terminalShareOfValue: pvTV / ev, impliedExitMultiple: tv / ebitda[n - 1],227 impliedPerpetualGrowth: (tv * w - fcf[n - 1]) / (tv + fcf[n - 1]))228 }229230 /// Value per share on a grid of discount rates (rows) × terminal parameters (columns: growth rates231 /// for a Gordon terminal value, multiples for an exit multiple). Infeasible cells (g ≥ rate) are NaN.232 public static func sensitivity(_ a: DCFAssumptions, discountRates: [Double], terminalParameters: [Double]) -> [[Double]] {233 discountRates.map { w in234 terminalParameters.map { p in235 var b = a236 b.discountRate = .fixed(w)237 switch a.terminal {238 case .gordonGrowth: b.terminal = .gordonGrowth(p)239 case .exitMultiple: b.terminal = .exitMultiple(p)240 }241 return (try? value(b))?.valuePerShare ?? .nan242 }243 }244 }245}246