greeners 1.5.0

High-performance econometrics with R/Python formulas. Two-Way Clustering, Marginal Effects (AME/MEM), HC1-4, IV Predictions, Categorical C(var), Polynomial I(x^2), Interactions, Diagnostics. OLS, IV/2SLS, DiD, Logit/Probit, Panel (FE/RE), Time Series (VAR/VECM), Quantile!
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use ndarray::Array1;
use std::fmt;

/// A model summary for side-by-side comparison.
#[derive(Debug, Clone)]
pub struct ModelSummary {
    pub name: String,
    pub params: Vec<f64>,
    pub std_errors: Vec<f64>,
    pub p_values: Vec<f64>,
    pub variable_names: Vec<String>,
    pub n_obs: usize,
    pub r_squared: Option<f64>,
    pub adj_r_squared: Option<f64>,
    pub aic: Option<f64>,
    pub bic: Option<f64>,
    pub log_likelihood: Option<f64>,
    pub f_statistic: Option<f64>,
}

impl ModelSummary {
    /// Create from OlsResult-like data.
    pub fn new(name: &str) -> Self {
        ModelSummary {
            name: name.to_string(),
            params: Vec::new(),
            std_errors: Vec::new(),
            p_values: Vec::new(),
            variable_names: Vec::new(),
            n_obs: 0,
            r_squared: None,
            adj_r_squared: None,
            aic: None,
            bic: None,
            log_likelihood: None,
            f_statistic: None,
        }
    }

    pub fn with_coefficients(
        mut self,
        params: &Array1<f64>,
        std_errors: &Array1<f64>,
        p_values: &Array1<f64>,
        variable_names: &[String],
    ) -> Self {
        self.params = params.to_vec();
        self.std_errors = std_errors.to_vec();
        self.p_values = p_values.to_vec();
        self.variable_names = variable_names.to_vec();
        self
    }

    pub fn with_fit_stats(
        mut self,
        n_obs: usize,
        r_squared: Option<f64>,
        adj_r_squared: Option<f64>,
        aic: Option<f64>,
        bic: Option<f64>,
        log_likelihood: Option<f64>,
    ) -> Self {
        self.n_obs = n_obs;
        self.r_squared = r_squared;
        self.adj_r_squared = adj_r_squared;
        self.aic = aic;
        self.bic = bic;
        self.log_likelihood = log_likelihood;
        self
    }

    fn significance_stars(p: f64) -> &'static str {
        if p < 0.001 {
            "***"
        } else if p < 0.01 {
            "**"
        } else if p < 0.05 {
            "*"
        } else if p < 0.1 {
            "."
        } else {
            ""
        }
    }
}

/// Side-by-side model comparison table (like Stata's esttab or R's stargazer).
pub struct SummaryCol;

impl SummaryCol {
    /// Generate a side-by-side comparison of multiple models.
    pub fn compare(models: &[ModelSummary]) -> SummaryColResult {
        // Collect all unique variable names in order of appearance
        let mut all_vars: Vec<String> = Vec::new();
        for m in models {
            for v in &m.variable_names {
                if !all_vars.contains(v) {
                    all_vars.push(v.clone());
                }
            }
        }

        SummaryColResult {
            models: models.to_vec(),
            all_vars,
        }
    }
}

/// Result of summary_col comparison, can be displayed or exported.
#[derive(Debug)]
pub struct SummaryColResult {
    pub models: Vec<ModelSummary>,
    pub all_vars: Vec<String>,
}

impl SummaryColResult {
    /// Export as LaTeX table.
    pub fn to_latex(&self) -> String {
        let n = self.models.len();
        let mut s = String::new();

        s.push_str("\\begin{table}[htbp]\n\\centering\n");
        s.push_str("\\begin{tabular}{l");
        for _ in 0..n {
            s.push('c');
        }
        s.push_str("}\n\\hline\\hline\n");

        // Header
        s.push_str("  ");
        for m in &self.models {
            s.push_str(&format!(" & {}", m.name));
        }
        s.push_str(" \\\\\n\\hline\n");

        // Coefficients
        for var in &self.all_vars {
            // Coefficient row
            s.push_str(var);
            for m in &self.models {
                if let Some(idx) = m.variable_names.iter().position(|v| v == var) {
                    let stars = ModelSummary::significance_stars(m.p_values[idx]);
                    s.push_str(&format!(" & {:.4}{}", m.params[idx], stars));
                } else {
                    s.push_str(" & ");
                }
            }
            s.push_str(" \\\\\n");

            // SE row
            s.push_str("  ");
            for m in &self.models {
                if let Some(idx) = m.variable_names.iter().position(|v| v == var) {
                    s.push_str(&format!(" & ({:.4})", m.std_errors[idx]));
                } else {
                    s.push_str(" & ");
                }
            }
            s.push_str(" \\\\\n");
        }

        s.push_str("\\hline\n");

        // Fit statistics
        s.push('N');
        for m in &self.models {
            s.push_str(&format!(" & {}", m.n_obs));
        }
        s.push_str(" \\\\\n");

        if self.models.iter().any(|m| m.r_squared.is_some()) {
            s.push_str("R$^2$");
            for m in &self.models {
                match m.r_squared {
                    Some(r) => s.push_str(&format!(" & {:.4}", r)),
                    None => s.push_str(" & "),
                }
            }
            s.push_str(" \\\\\n");
        }

        if self.models.iter().any(|m| m.adj_r_squared.is_some()) {
            s.push_str("Adj. R$^2$");
            for m in &self.models {
                match m.adj_r_squared {
                    Some(r) => s.push_str(&format!(" & {:.4}", r)),
                    None => s.push_str(" & "),
                }
            }
            s.push_str(" \\\\\n");
        }

        if self.models.iter().any(|m| m.aic.is_some()) {
            s.push_str("AIC");
            for m in &self.models {
                match m.aic {
                    Some(a) => s.push_str(&format!(" & {:.2}", a)),
                    None => s.push_str(" & "),
                }
            }
            s.push_str(" \\\\\n");
        }

        s.push_str("\\hline\\hline\n");
        s.push_str("\\end{tabular}\n");
        s.push_str("\\caption{Regression Results}\n");
        s.push_str("\\end{table}\n");
        s
    }

    /// Export as HTML table.
    pub fn to_html(&self) -> String {
        let mut s = String::new();
        s.push_str("<table class=\"regression-table\">\n<thead>\n<tr>\n<th></th>\n");
        for m in &self.models {
            s.push_str(&format!("<th>{}</th>\n", m.name));
        }
        s.push_str("</tr>\n</thead>\n<tbody>\n");

        for var in &self.all_vars {
            s.push_str(&format!("<tr>\n<td>{}</td>\n", var));
            for m in &self.models {
                if let Some(idx) = m.variable_names.iter().position(|v| v == var) {
                    let stars = ModelSummary::significance_stars(m.p_values[idx]);
                    s.push_str(&format!(
                        "<td>{:.4}{}<br><small>({:.4})</small></td>\n",
                        m.params[idx], stars, m.std_errors[idx]
                    ));
                } else {
                    s.push_str("<td></td>\n");
                }
            }
            s.push_str("</tr>\n");
        }

        // Fit stats
        s.push_str("<tr class=\"fit-stats\">\n<td>N</td>\n");
        for m in &self.models {
            s.push_str(&format!("<td>{}</td>\n", m.n_obs));
        }
        s.push_str("</tr>\n");

        if self.models.iter().any(|m| m.r_squared.is_some()) {
            s.push_str("<tr>\n<td>R²</td>\n");
            for m in &self.models {
                match m.r_squared {
                    Some(r) => s.push_str(&format!("<td>{:.4}</td>\n", r)),
                    None => s.push_str("<td></td>\n"),
                }
            }
            s.push_str("</tr>\n");
        }

        s.push_str("</tbody>\n</table>\n");
        s
    }

    /// Export as CSV.
    pub fn to_csv(&self) -> String {
        let mut s = String::new();

        // Header
        s.push_str("Variable");
        for m in &self.models {
            s.push_str(&format!(",{} (coef),{} (se)", m.name, m.name));
        }
        s.push('\n');

        // Coefficients
        for var in &self.all_vars {
            s.push_str(var);
            for m in &self.models {
                if let Some(idx) = m.variable_names.iter().position(|v| v == var) {
                    s.push_str(&format!(",{:.6},{:.6}", m.params[idx], m.std_errors[idx]));
                } else {
                    s.push_str(",,");
                }
            }
            s.push('\n');
        }

        // Fit stats
        s.push('N');
        for m in &self.models {
            s.push_str(&format!(",{},", m.n_obs));
        }
        s.push('\n');

        if self.models.iter().any(|m| m.r_squared.is_some()) {
            s.push_str("R-squared");
            for m in &self.models {
                match m.r_squared {
                    Some(r) => s.push_str(&format!(",{:.6},", r)),
                    None => s.push_str(",,"),
                }
            }
            s.push('\n');
        }

        s
    }
}

impl fmt::Display for SummaryColResult {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let n = self.models.len();
        let var_width = 14;
        let col_width = 16;
        let total_width = var_width + 3 + col_width * n;

        writeln!(f, "\n{:=^w$}", " Regression Comparison ", w = total_width)?;

        // Header
        write!(f, "{:<w$} |", "", w = var_width)?;
        for m in &self.models {
            write!(f, " {:^w$}", m.name, w = col_width - 1)?;
        }
        writeln!(f)?;
        writeln!(f, "{:-^w$}", "", w = total_width)?;

        // Coefficients
        for var in &self.all_vars {
            // Coefficient row
            write!(f, "{:<w$} |", var, w = var_width)?;
            for m in &self.models {
                if let Some(idx) = m.variable_names.iter().position(|v| v == var) {
                    let stars = ModelSummary::significance_stars(m.p_values[idx]);
                    write!(
                        f,
                        " {:>w$.4}{}",
                        m.params[idx],
                        stars,
                        w = col_width - 1 - stars.len()
                    )?;
                } else {
                    write!(f, " {:>w$}", "", w = col_width - 1)?;
                }
            }
            writeln!(f)?;

            // SE row
            write!(f, "{:<w$} |", "", w = var_width)?;
            for m in &self.models {
                if let Some(idx) = m.variable_names.iter().position(|v| v == var) {
                    let se_str = format!("({:.4})", m.std_errors[idx]);
                    write!(f, " {:>w$}", se_str, w = col_width - 1)?;
                } else {
                    write!(f, " {:>w$}", "", w = col_width - 1)?;
                }
            }
            writeln!(f)?;
        }

        writeln!(f, "{:-^w$}", "", w = total_width)?;

        // N
        write!(f, "{:<w$} |", "N", w = var_width)?;
        for m in &self.models {
            write!(f, " {:>w$}", m.n_obs, w = col_width - 1)?;
        }
        writeln!(f)?;

        //        if self.models.iter().any(|m| m.r_squared.is_some()) {
            write!(f, "{:<w$} |", "R-squared", w = var_width)?;
            for m in &self.models {
                match m.r_squared {
                    Some(r) => write!(f, " {:>w$.4}", r, w = col_width - 1)?,
                    None => write!(f, " {:>w$}", "", w = col_width - 1)?,
                }
            }
            writeln!(f)?;
        }

        // Adj R²
        if self.models.iter().any(|m| m.adj_r_squared.is_some()) {
            write!(f, "{:<w$} |", "Adj. R-squared", w = var_width)?;
            for m in &self.models {
                match m.adj_r_squared {
                    Some(r) => write!(f, " {:>w$.4}", r, w = col_width - 1)?,
                    None => write!(f, " {:>w$}", "", w = col_width - 1)?,
                }
            }
            writeln!(f)?;
        }

        // AIC
        if self.models.iter().any(|m| m.aic.is_some()) {
            write!(f, "{:<w$} |", "AIC", w = var_width)?;
            for m in &self.models {
                match m.aic {
                    Some(a) => write!(f, " {:>w$.2}", a, w = col_width - 1)?,
                    None => write!(f, " {:>w$}", "", w = col_width - 1)?,
                }
            }
            writeln!(f)?;
        }

        // BIC
        if self.models.iter().any(|m| m.bic.is_some()) {
            write!(f, "{:<w$} |", "BIC", w = var_width)?;
            for m in &self.models {
                match m.bic {
                    Some(b) => write!(f, " {:>w$.2}", b, w = col_width - 1)?,
                    None => write!(f, " {:>w$}", "", w = col_width - 1)?,
                }
            }
            writeln!(f)?;
        }

        writeln!(f, "{:=^w$}", "", w = total_width)?;
        writeln!(f, "Significance: *** p<0.001, ** p<0.01, * p<0.05, . p<0.1")
    }
}