SPB Git

Repository Public

StatementMath.swift 4.7 KB 80 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Terminal/StatementMath.swift3// Description: Display arithmetic of the Statements section: the change between two periods, the inputs named by a derived row's formula, and the CSV of what is on screen. Nothing here estimates a value: a missing input gives a missing result.4import Foundation56public enum StatementMath {7    /// The change of a line between two periods.8    public struct Change: Sendable, Equatable {9        /// `value − base`, in the unit of the line (for `percent` rows: a difference of fractions, shown in points).10        public var absolute: Double?11        /// `(value − base) / base` as a fraction; nil when the base is missing, zero or negative (the server's own12        /// rule for growth rows) and for `percent` rows, where a relative change of a rate misleads.13        public var relative: Double?14        public init(absolute: Double?, relative: Double?) { self.absolute = absolute; self.relative = relative }15    }1617    public static func change(from base: Double?, to value: Double?, unit: String) -> Change {18        guard let base, let value, base.isFinite, value.isFinite else { return Change(absolute: nil, relative: nil) }19        let relative: Double? = unit == "percent" || base <= 0 ? nil : (value - base) / base20        return Change(absolute: value - base, relative: relative)21    }2223    /// The line keys a formula names, in order of first appearance: `ebit × (1 − incomeTaxExpense / incomeBeforeTax)`24    /// → `[ebit, incomeTaxExpense, incomeBeforeTax]`. Only identifiers that are known lines are returned, so the25    /// words of an explanatory note ("null when equity ≤ 0") are not taken for inputs.26    public static func inputs(ofFormula formula: String, known: Set<String>) -> [String] {27        var out: [String] = []28        var token = ""29        func flush() {30            if !token.isEmpty, known.contains(token), !out.contains(token) { out.append(token) }31            token = ""32        }33        for ch in formula {34            if ch.isASCII, ch.isLetter || ch.isNumber || ch == "_" { token.append(ch) } else { flush() }35        }36        flush()37        return out38    }3940    /// The part of a formula before its parenthesised note: `a / b (null when b ≤ 0)` → (`a / b`, `null when b ≤ 0`).41    public static func splitNote(_ formula: String) -> (expression: String, note: String?) {42        guard formula.hasSuffix(")"), let open = formula.range(of: " (", options: .backwards) else { return (formula, nil) }43        let note = String(formula[open.upperBound...].dropLast())44        // a trailing group of identifiers and operators is part of the calculation; a note is a sentence45        guard ["null", "when", "not ", "average"].contains(where: note.contains) else { return (formula, nil) }46        return (String(formula[..<open.lowerBound]), note)47    }4849    public struct CSVRow: Sendable, Equatable {50        public var label: String, key: String, unit: String51        public var values: [Double?]52        public var formula: String?53        public init(label: String, key: String, unit: String, values: [Double?], formula: String?) { self.label = label; self.key = key; self.unit = unit; self.values = values; self.formula = formula }54    }5556    /// RFC 4180 CSV: one row per line, values as received (full precision, no scaling, `percent` and `ratio` as57    /// fractions); an empty field is a missing value. With `compare`, the change between the two periods follows.58    public static func csv(periods: [String], rows: [CSVRow], compare: (base: Int, value: Int)? = nil) -> String {59        func num(_ v: Double?) -> String {60            guard let v, v.isFinite else { return "" }61            if v.rounded() == v, abs(v) < 9e15 { return String(Int64(v)) }62            return String(v)63        }64        var header = ["line", "key", "unit"] + periods65        if let c = compare, periods.indices.contains(c.base), periods.indices.contains(c.value) { header += ["change \(periods[c.base]) to \(periods[c.value])", "change_fraction"] }66        header.append("formula")67        var out = header.map(CSV.field).joined(separator: ",") + "\r\n"68        for r in rows {69            var f = [CSV.field(r.label), CSV.field(r.key), r.unit] + periods.indices.map { num(r.values.indices.contains($0) ? r.values[$0] : nil) }70            if let c = compare, periods.indices.contains(c.base), periods.indices.contains(c.value) {71                let ch = change(from: r.values.indices.contains(c.base) ? r.values[c.base] : nil, to: r.values.indices.contains(c.value) ? r.values[c.value] : nil, unit: r.unit)72                f += [num(ch.absolute), num(ch.relative)]73            }74            f.append(CSV.field(r.formula ?? ""))75            out += f.joined(separator: ",") + "\r\n"76        }77        return out78    }79}80
Files main
Menu

Theme