SPB Git

Repository Public

PanelRegressionTool.swift 8.6 KB 114 lines swift

1import Foundation2import SheetCore3import Statistics4import AnalysisKit56/// Fixed-effects (within) panel regression.7enum PanelRegressionTool {8    static let descriptor: ToolDescriptor = {9        var t = ToolDescriptor(10            id: "regression.panel", title: L("Fixed-Effects Panel Regression"), group: L("Regression"), systemImage: "square.stack.3d.up",11            summary: L("Within estimator with entity fixed effects and optional time effects, for balanced or unbalanced panels in long format."),12            fields: [13                .range("data", L("Data range"), help: L("Long format: one row per entity and period.")),14                .column("y", L("Dependent variable (y)")),15                .columns("x", L("Regressors (X)")),16                .column("entity", L("Entity identifier"), numeric: false),17                .column("time", L("Time identifier"), numeric: false, optional: true),18                .toggle("timeEffects", L("Include time fixed effects"), false, visible: { $0.columnIndex("time") != nil }),19                .choice("cov", L("Standard errors"), [FieldOption("unadjusted", L("Classical")), FieldOption("robust", L("Heteroskedasticity-robust")),20                                                      FieldOption("cluster", L("Clustered by entity"))]),21                .percent("level", L("Confidence level"), 0.95, min: 0.5, max: 0.9999),22                .alpha(L("Significance level α")),23            ],24            info: [25                L("Validated against linearmodels PanelOLS and statsmodels LSDV (coefficients and standard errors to 1e-9)."),26                L("R² is the within R²: variation of y after the included effects are removed."),27                L("Clustered standard errors use the linearmodels scaling; Stata's xtreg, fe vce(cluster) scaling is not shipped."),28                L("Time-invariant regressors are not identified by the within estimator and are reported as a singular problem."),29                L("Random-effects, between and first-difference estimators and the Hausman test are not shipped."),30            ],31            run: run)32        t.demo = { _, v in33            v.set("data", range: "Panel!A1:E61")34            v.set("y", column: 2); v.set("x", columns: [3, 4]); v.set("entity", column: 0); v.set("time", column: 1)35            v.set("cov", choice: "cluster")36        }37        return t38    }()3940    static func fit(_ input: ToolInput) throws -> (result: PanelResult, design: RegressionDesign) {41        let hasTime = input.optionalColumn("time") != nil42        let d = try RegressionDesign.build(input, categorical: nil, labelExtras: hasTime ? ["entity", "time"] : ["entity"])43        guard let entity = d.labelExtras["entity"] else { throw ToolError(L("Choose the column that identifies the entities.")) }44        let cov: PanelCovariance45        switch input.values.choice("cov") {46        case "robust": cov = .robust47        case "cluster": cov = .clusteredByEntity(correction: .linearmodels)48        default: cov = .unadjusted49        }50        let level = Sup.level(input)51        if let time = d.labelExtras["time"] {52            // numeric periods sort numerically, text periods alphabetically53            let numbers = time.map { Double($0) }54            if numbers.allSatisfy({ $0 != nil }) {55                return (try PanelRegression.fixedEffects(y: d.y, x: d.x, names: d.names, entity: entity, time: numbers.map { $0! },56                                                         timeEffects: input.values.bool("timeEffects"), covariance: cov, confidenceLevel: level, dependentName: d.yName), d)57            }58            return (try PanelRegression.fixedEffects(y: d.y, x: d.x, names: d.names, entity: entity, time: time,59                                                     timeEffects: input.values.bool("timeEffects"), covariance: cov, confidenceLevel: level, dependentName: d.yName), d)60        }61        return (try PanelRegression.fixedEffects(y: d.y, x: d.x, names: d.names, entity: entity, covariance: cov, confidenceLevel: level, dependentName: d.yName), d)62    }6364    static func run(_ input: ToolInput) throws -> ToolResult {65        let (r, d) = try fit(input)66        let alpha = Sup.alpha(input), loc = input.locale67        var blocks: [ResultBlock] = [.metrics([68            Metric(L("Observations"), Double(r.nobs), .integer), Metric(L("Entities"), Double(r.entityCount), .integer),69            Metric(L("Within R²"), r.rSquared, .fixed(4)), Metric(L("F statistic"), r.fStatistic, .fixed(3)), Metric(L("p-value (F)"), r.fPValue, .pValue),70        ])]71        blocks.append(.table(Sup.coefficientTable(title: L("Coefficients"), names: r.names, estimates: r.coefficients, se: r.standardErrors, statistics: r.statistics,72                                                  pValues: r.pValues, lower: r.ciLower, upper: r.ciUpper, usesT: r.usesT, level: r.confidenceLevel, locale: loc)))73        let covLabel: String = {74            switch input.values.choice("cov") {75            case "robust": L("heteroskedasticity-robust")76            case "cluster": L("clustered by entity")77            default: L("classical")78            }79        }()80        var items: [(String, Value, CellFormat)] = [81            (L("Effects"), .text(r.timeEffects ? L("entity and time") : L("entity")), .auto), (L("Standard errors"), .text(covLabel), .auto),82            (L("Observations"), .finite(Double(r.nobs)), .integer), (L("Entities"), .finite(Double(r.entityCount)), .integer),83        ]84        if r.timeCount > 0 { items.append((L("Periods"), .finite(Double(r.timeCount)), .integer)) }85        items += [86            (L("Degrees of freedom (residual)"), .finite(Double(r.dfResidual)), .integer),87            (L("Within R²"), .finite(r.rSquared), .fixed(6)), (L("Residual variance"), .finite(r.sigma2), .auto),88            (L("F statistic (all slopes zero)"), .finite(r.fStatistic), .fixed(4)), (L("p-value (F)"), .finite(r.fPValue), .pValue),89        ]90        if let f = r.robustFStatistic { items += [(L("Robust F statistic"), .finite(f), .fixed(4)), (L("p-value (robust F)"), .finite(r.robustFPValue), .pValue)] }91        items += [(L("Poolability F (all effects equal)"), .finite(r.poolabilityF), .fixed(4)), (L("p-value (poolability)"), .finite(r.poolabilityPValue), .pValue)]92        blocks.append(.table(ReportTable.keyValue(title: L("Fit statistics"), header: (L("Quantity"), L("Value")), items)))93        blocks.append(.interpretation(Interpret.decision(p: r.poolabilityPValue, alpha: alpha, null: L("all fixed effects are equal (pooled OLS is adequate)"), locale: loc)))94        blocks.append(.table(ReportTable(title: L("Estimated entity effects"),95                                         rows: [[.text(L("Entity")), .text(L("Effect"))]] + zip(r.entityLabels, r.entityEffects).map { [.text($0), .finite($1)] },96                                         columnFormats: [1: .fixed(4)])))97        if r.timeEffects, !r.timeLabels.isEmpty {98            blocks.append(.table(ReportTable(title: L("Estimated time effects"),99                                             rows: [[.text(L("Period")), .text(L("Effect"))]] + zip(r.timeLabels, r.timeEffectValues).map { [.text($0), .finite($1)] },100                                             columnFormats: [1: .fixed(4)], note: L("The first period is the reference (effect 0)."))))101        }102        blocks.append(.chart(ChartBlock(title: L("Entity effects"), spec: ChartKit.columns(categories: r.entityLabels, series: [(L("Effect"), r.entityEffects)], xTitle: L("Entity"), yTitle: L("Effect")),103                                        summary: L("Bar chart of %d estimated entity effects, from %@ to %@.", r.entityCount,104                                                   Fmt.number(r.entityEffects.min() ?? .nan, locale: loc), Fmt.number(r.entityEffects.max() ?? .nan, locale: loc)), height: 210)))105        blocks.append(.note(d.notes + [r.usesT ? L("Inference uses Student's t with %@ degrees of freedom.", Fmt.df(r.dfInference, locale: loc))106                                               : L("Inference uses the normal distribution (robust covariance).")]))107        let actions = [Sup.writeColumns(id: "write-residuals", title: L("Write Residuals and Estimated Effects"), label: L("Write Residuals and Estimated Effects"), frame: d.frame,108                                        names: [L("Residual %@", d.yName), L("Fixed effect")],109                                        columns: [d.frame.expand(r.residuals, rows: d.rows), d.frame.expand(r.estimatedEffects, rows: d.rows)])]110        return ToolResult(title: L("Fixed-Effects Panel Regression"), subtitle: L("%@ — dependent variable: %@", d.frame.label, d.yName),111                          blocks: blocks, actions: actions, sheetName: L("Panel regression"))112    }113}114
Files main
Menu

Theme