SPB Git

Repository Public

RegressionReports.swift 10.6 KB 221 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Sheet9// File             : Packages/SheetAnalytics/Sources/Statistics/Regression/RegressionReports.swift10// Module           : Statistics11// 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 SheetCore8990private enum RegressionReportBuilder {91    static func coefficientTable(names: [String], coef: [Double], se: [Double], stat: [Double], p: [Double], lo: [Double], hi: [Double],92                                 statLabel: String, level: Double, extra: (label: String, values: [Double])? = nil) -> [[Value]] {93        let pct = String(format: "%g%%", level * 100)94        var header: [Value] = [.text(""), .text("Coefficient"), .text("Std. Error"), .text(statLabel), .text("P>|\(statLabel)|"),95                               .text("Lower \(pct)"), .text("Upper \(pct)")]96        if let extra { header.append(.text(extra.label)) }97        var rows = [header]98        for i in names.indices {99            var row: [Value] = [.text(names[i]), Report.num(coef[i]), Report.num(se[i]), Report.num(stat[i]), Report.num(p[i]), Report.num(lo[i]), Report.num(hi[i])]100            if let extra { row.append(Report.num(extra.values[i])) }101            rows.append(row)102        }103        return rows104    }105}106107extension LinearModelResult: TableReport {108    /// Regression output: header block, coefficient table, then residual diagnostics109    /// (Durbin–Watson, Jarque–Bera, condition number). Rectangular grid, 7 columns wide.110    public func table() -> [[Value]] {111        var rows: [[Value]] = [112            [.text("\(method) regression"), .blank],113            Report.row("Dependent variable", dependentName),114            Report.row("Observations", nobs),115            Report.row("Df model", dfModel),116            Report.row("Df residuals", dfResidual),117            Report.row("Covariance type", covarianceType.label),118            Report.row(hasConstant ? "R-squared" : "R-squared (uncentered)", rSquared),119            Report.row("Adjusted R-squared", adjustedRSquared),120            [.text("F-statistic"), Report.num(fStatistic)],121            [.text("Prob (F-statistic)"), Report.num(fPValue)],122            Report.row("Residual std. error", residualStandardError),123            Report.row("Log-likelihood", logLikelihood),124            Report.row("AIC", aic),125            Report.row("BIC", bic),126            [],127        ]128        rows += RegressionReportBuilder.coefficientTable(names: names, coef: coefficients, se: standardErrors, stat: statistics, p: pValues,129                                                         lo: ciLower, hi: ciUpper, statLabel: usesT ? "t" : "z", level: confidenceLevel)130        rows.append([])131        rows.append([.text("Diagnostics"), .blank])132        let e = whitened.e133        rows.append(Report.row("Durbin–Watson", RegressionDiagnostics.durbinWatson(e)))134        if let jb = try? RegressionDiagnostics.jarqueBera(e) {135            let m = RegressionDiagnostics.residualMoments(e)136            rows.append(Report.row("Jarque–Bera", jb.statistic))137            rows.append([.text("Prob (JB)"), Report.num(jb.pValue)])138            rows.append(Report.row("Skewness", m.skewness))139            rows.append(Report.row("Kurtosis", m.kurtosis))140        }141        rows.append(Report.row("Condition number", conditionNumber))142        if vif.contains(where: { $0 != nil }) {143            rows.append([])144            rows.append([.text("Variance inflation factors"), .blank])145            for (name, v) in zip(names, vif) { if let v { rows.append(Report.row(name, v)) } }146        }147        return Report.rectangular(rows)148    }149}150151extension PanelResult: TableReport {152    /// Fixed-effects output: header block, coefficient table, then the estimated entity (and time) effects.153    public func table() -> [[Value]] {154        var rows: [[Value]] = [155            [.text("Fixed-effects (within) regression"), .blank],156            Report.row("Dependent variable", dependentName),157            Report.row("Observations", nobs),158            Report.row("Entities", entityCount),159        ]160        if timeCount > 0 { rows.append(Report.row("Time periods", timeCount)) }161        rows += [162            Report.row("Effects", timeEffects ? "entity + time" : "entity"),163            Report.row("Df residuals", dfResidual),164            Report.row("Covariance type", covarianceType.label),165            Report.row("R-squared (within)", rSquared),166            Report.row("F-statistic", fStatistic),167            Report.row("Prob (F-statistic)", fPValue),168        ]169        if let w = robustFStatistic, let p = robustFPValue { rows.append(Report.row("Robust F-statistic", w)); rows.append(Report.row("Prob (robust F)", p)) }170        rows += [171            Report.row("F test of poolability", poolabilityF),172            Report.row("Prob (poolability)", poolabilityPValue),173            [],174        ]175        rows += RegressionReportBuilder.coefficientTable(names: names, coef: coefficients, se: standardErrors, stat: statistics, p: pValues,176                                                         lo: ciLower, hi: ciUpper, statLabel: usesT ? "t" : "z", level: confidenceLevel)177        rows.append([])178        rows.append([.text("Entity"), .text("Effect")])179        for (l, v) in zip(entityLabels, entityEffects) { rows.append(Report.row(l, v)) }180        if timeEffects {181            rows.append([])182            rows.append([.text("Period"), .text("Effect")])183            for (l, v) in zip(timeLabels, timeEffectValues) { rows.append(Report.row(l, v)) }184        }185        return Report.rectangular(rows)186    }187}188189extension LogisticResult: TableReport {190    /// Logit output: header block, coefficient table with odds ratios, classification table.191    public func table() -> [[Value]] {192        var rows: [[Value]] = [193            [.text("Logistic regression"), .blank],194            Report.row("Dependent variable", dependentName),195            Report.row("Observations", nobs),196            Report.row("Df model", dfModel),197            Report.row("Df residuals", dfResidual),198            Report.row("Log-likelihood", logLikelihood),199            Report.row("Null log-likelihood", nullLogLikelihood),200            Report.row("McFadden pseudo R-squared", pseudoRSquared),201            Report.row("LR chi2", lrStatistic),202            [.text("Prob (LR)"), Report.num(lrPValue)],203            Report.row("AIC", aic),204            Report.row("BIC", bic),205            Report.row("Iterations", iterations),206            [],207        ]208        rows += RegressionReportBuilder.coefficientTable(names: names, coef: coefficients, se: standardErrors, stat: statistics, p: pValues,209                                                         lo: ciLower, hi: ciUpper, statLabel: "z", level: confidenceLevel,210                                                         extra: ("Odds ratio", oddsRatios))211        rows.append([])212        rows.append([.text("Classification (threshold \(String(format: "%g", threshold)))"), .text("Predicted 0"), .text("Predicted 1")])213        rows.append([.text("Actual 0"), Report.int(classificationTable[0][0]), Report.int(classificationTable[0][1])])214        rows.append([.text("Actual 1"), Report.int(classificationTable[1][0]), Report.int(classificationTable[1][1])])215        rows.append(Report.row("Accuracy", accuracy))216        rows.append(Report.row("Sensitivity", sensitivity))217        rows.append(Report.row("Specificity", specificity))218        return Report.rectangular(rows)219    }220}221
Files main
Menu

Theme