SPB Git

Repository Public Research preview

19_make_revision_tables.py 15.6 KB 270 lines python

1#!/usr/bin/env python32# -*- coding: utf-8 -*-3# =============================================================================4#                  SP BOUCHER | ACADEMIC RESEARCH5#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING6# =============================================================================7#8# PROJECT METADATA9# -----------------------------------------------------------------------------10# Project          : UQO Working Paper 1411# File             : scripts/19_make_revision_tables.py12# Description      : Génère les tables LaTeX de la révision 2026-10-17 à partir13#                    de results/revision_2026-10-17.json (produit par14#                    scripts/18_revision_language_leakage_spatial.py).15# Module           : scripts16# Repository       : https://git.spboucher.ai/wp14_uqo17# Created          : 2026-10-1718# Last Modified    : 2026-10-1719#20# =============================================================================21# SOFTWARE MAINTAINER & AFFILIATION22# =============================================================================23#24# Maintainer       : Simon-Pierre Boucher25# Position         : Professor of Finance26# Institution      : Université du Québec en Outaouais (UQO)27# Department       : Département des sciences administratives28# Website          : https://spboucher.ai29# Git              : https://git.spboucher.ai30#31# Research Contact : research@spboucher.ai32# Direct Contact   : simon@spboucher.ai33# Security/Admin   : admin@spboucher.ai34#35# The affiliation is descriptive. It is not an institutional endorsement,36# a license grant or a determination of ownership.37#38# =============================================================================39# COPYRIGHT, AUTHORSHIP & DATA40# =============================================================================41#42# Copyright (c) the author(s) of this work.43# Ownership is not asserted by this notice; see the repository records.44#45# This header identifies the maintainer of the software. Scientific46# authorship of any associated paper is stated in the paper itself and47# is not changed by this notice. Datasets and third-party materials48# remain the property of their respective owners and licensors.49#50# This file is governed by the applicable project license, copyright51# notices, institutional agreements and relevant law.52#53# =============================================================================54# LICENSE & MAINTENANCE55# =============================================================================56#57# License          : None specified (no license file in this repository)58# Classification   : Public59#60# =============================================================================61# END OF SP BOUCHER SOURCE HEADER62# =============================================================================6364"""Génère les tables LaTeX de la révision 2026-10-17 à partir de results/revision_2026-10-17.json65(produit par scripts/18_revision_language_leakage_spatial.py). Aucun calcul : mise en forme seulement.66Sorties : paper/tables/rob_language_source.tex, rob_spatial.tex, rob_ai_coefs.tex, agreement.tex."""67import json68OUT = json.load(open("results/revision_2026-10-17.json"))69y = [0] * OUT["text_leakage"]["n"]7071def f3(x): return f"${x:.3f}$" if x < 0 else f"{x:.3f}"72def pct(x): return f"{x*100:.1f}\\%"73def num(n): return f"{n:,}".replace(",", "{,}")7475# ---- Table: language and text leakage (robustness of the AI layers) ----76A = OUT["ablation_A"]; R = OUT["cv"]["random"]77def row_abl(label, key):78    a = A[key]; return f"      {label} & {num(a['n'])} & {f3(a['base'])} & {a['d_text']*100:+.1f} & {a['d_vision']*100:+.1f} \\\\"79def row_cv(label, key, est):80    r2 = [R[L][est][key]["r2"] for L in ("L2", "L3", "L4")]; n = R["L2"][est][key]["n"]81    return f"      {label} & {num(n)} & {f3(r2[0])} & {(r2[1]-r2[0])*100:+.1f} & {(r2[2]-r2[1])*100:+.1f} \\\\"82tab = r"""% Auto-generated by scripts/18_revision_language_leakage_spatial.py (2026-10-17)83\begin{table}[htbp]84  \centering85  \begin{threeparttable}86    \caption{Gains from the AI Feature Layers by Language, Platform, and Presence of a Price in the Text}87    \label{tab:rob_language_source}88    \small89    \begin{tabular}{@{}lcccc@{}}90      \toprule91      Subsample & $N$ & $R^2$ base & $\Delta R^2$ text (pp) & $\Delta R^2$ vision (pp) \\92      \midrule93      \multicolumn{5}{@{}l}{\textit{Panel A: In-sample $R^2$, Model~A (measured area), municipality FE}} \\[2pt]94""" + "\n".join([row_abl("All listings", "all"), row_abl("\\quad French descriptions", "fr"),95                row_abl("\\quad English descriptions", "en"), row_abl("\\quad Mixed / bilingual", "mixed"),96                row_abl("\\quad Realtor.ca (no asking price in text)", "realtor"),97                row_abl("\\quad DuProprio (asking price in text)", "duproprio"),98                row_abl("\\quad Realtor.ca, no dollar amount in text", "realtor_no_dollar"),99                row_abl("All listings, RTA fixed effects", "fsa_fe")]) + r"""100      \addlinespace101      \multicolumn{5}{@{}l}{\textit{Panel B: Out-of-sample $R^2$ (5-fold, random), OLS, full sample}} \\[2pt]102""" + "\n".join([row_cv("All listings", "all", "ols"), row_cv("\\quad French", "fr", "ols"), row_cv("\\quad English", "en", "ols"),103                row_cv("\\quad Realtor.ca", "realtor", "ols"), row_cv("\\quad DuProprio", "duproprio", "ols")]) + r"""104      \addlinespace105      \multicolumn{5}{@{}l}{\textit{Panel C: Out-of-sample $R^2$ (5-fold, random), gradient boosting, full sample}} \\[2pt]106""" + "\n".join([row_cv("All listings", "all", "gbm"), row_cv("\\quad French", "fr", "gbm"), row_cv("\\quad English", "en", "gbm"),107                row_cv("\\quad Realtor.ca", "realtor", "gbm"), row_cv("\\quad DuProprio", "duproprio", "gbm")]) + r"""108      \bottomrule109    \end{tabular}110    \begin{tablenotes}[flushleft]111      \footnotesize112      \item \textit{Notes:} Panel~A re-estimates the nested in-sample ablation of Model~A (structural, amenity, room, and113      listing controls with municipality and type fixed effects; then $+$ LLM text layer; then $+$ façade vision layer) on114      each subsample; ``$\Delta R^2$'' is the gain, in percentage points, from adding the layer. Language is classified115      from French and English stop-word counts (ratio rule of 1.5; ``mixed'' listings are mostly DuProprio descriptions that116      concatenate an English translation and the French original). Every DuProprio description contains the asking price117      (``Asking Price \$\dots''); """ + f"{OUT['text_leakage']['realtor_dollar_share']*100:.1f}" + r"""\% of Realtor.ca118      descriptions contain some dollar amount (usually a municipal assessment, a renovation budget, or a tax; the 141119      Model~A listings concerned are too few for a separate regression). Panels~B and120      C evaluate the full-sample cross-validated predictions (Table~\ref{tab:ablation}, identical folds) within each121      subsample; the base is the structural $+$ amenity $+$ rooms $+$ listing specification. Within-subsample $R^2$122      values can be negative (DuProprio, OLS) when the pooled model is miscalibrated for the subsample.123    \end{tablenotes}124  \end{threeparttable}125\end{table}126"""127open("paper/tables/rob_language_source.tex", "w").write(tab)128129# ---- Table: random vs spatial holdout ----130S = OUT["cv"]["spatial_fsa"]131def row_sp(label, est):132    r = [R[L][est]["all"]["r2"] for L in ("L2", "L3", "L4")]; s = [S[L][est]["all"]["r2"] for L in ("L2", "L3", "L4")]133    mr = [R[L][est]["all"]["mdape"] for L in ("L2", "L3", "L4")]; ms = [S[L][est]["all"]["mdape"] for L in ("L2", "L3", "L4")]134    return (f"      {label} & {f3(r[0])} & {f3(r[1])} & {f3(r[2])} & {mr[2]:.1f}\\% & {f3(s[0])} & {f3(s[1])} & {f3(s[2])} & {ms[2]:.1f}\\% \\\\")135tab = r"""% Auto-generated by scripts/18_revision_language_leakage_spatial.py (2026-10-17)136\begin{table}[htbp]137  \centering138  \begin{threeparttable}139    \caption{Random versus Spatial (RTA-Grouped) Cross-Validation}140    \label{tab:rob_spatial}141    \small142    \begin{tabular}{@{}lcccc@{\hskip 0.8cm}cccc@{}}143      \toprule144      & \multicolumn{4}{c}{Random 5-fold} & \multicolumn{4}{c}{Spatial 5-fold (RTA groups)} \\145      \cmidrule(lr){2-5}\cmidrule(lr){6-9}146      Estimator & Base & $+$Text & $+$Vision & MdAPE & Base & $+$Text & $+$Vision & MdAPE \\147      \midrule148""" + "\n".join([row_sp("OLS (linear hedonic)", "ols"), row_sp("Gradient boosting", "gbm")]) + r"""149      \bottomrule150    \end{tabular}151    \begin{tablenotes}[flushleft]152      \footnotesize153      \item \textit{Notes:} Out-of-sample $R^2$ on $\ln(\text{Price})$ and median absolute percentage error (MdAPE, for the154      full text\,$+$\,vision specification). ``Base'' is the structural $+$ amenity $+$ rooms $+$ listing specification; the155      next two columns add the LLM text layer and the façade vision layer. In the spatial design the """ + num(OUT["cv"]["spatial_groups"]) + r""" forward156      sortation areas (RTA, first three characters of the postal code) are assigned to five folds by \texttt{GroupKFold}, so157      no listing is predicted from a model that has seen a listing of the same RTA; municipality indicators of RTAs held158      out in their entirety are unobserved in training and the model falls back on the reference category. Random-fold159      entries may differ by $\pm0.001$ from Table~\ref{tab:ablation}, which comes from a separate run. $N=$""" + num(len(y)) + r""".160    \end{tablenotes}161  \end{threeparttable}162\end{table}163"""164open("paper/tables/rob_spatial.tex", "w").write(tab)165166# ---- Table: robustness of AI coefficients ----167O = OUT["ols"]; CB = OUT["cluster_bootstrap_A"]168def star(p): return "$^{***}$" if p < .01 else "$^{**}$" if p < .05 else "$^{*}$" if p < .1 else ""169def cellc(spec, k):170    c = O[spec]["coef"].get(k)171    if not c: return "", ""172    s = "$-$" if c["b"] < 0 else ""173    return f"{s}{abs(c['b']):.3f}{star(c['p'])}", f"({c['se']:.3f})"174labels = [("v_curb", "Curb appeal (1--10)"), ("v_reno", "Renovation level (ord.)"), ("v_luxury", "Luxury (visual)"),175          ("v_garage_vis", "Garage visible"), ("v_mat_brique", "Brick façade"), ("v_mat_pierre", "Stone façade"),176          ("v_mat_vinyle", "Vinyl façade"), ("v_set_rural", "Rural setting"), ("v_land", "Landscaping (ord.)"),177          ("g_cond", "Condition (LLM, ord.)"), ("g_renovated_kitchen", "Reno.\\ kitchen (LLM)"), ("g_hardwood", "Hardwood floor (LLM)"),178          ("lang_en", "English description"), ("lang_mixed", "Mixed-language description")]179specs_ = ["A", "A_lang", "A_fsa_lang", "A_realtor_fsa_lang"]180L = []181for k, lab in labels:182    cells = [cellc(s, k) for s in specs_]183    ci = CB["ci95"].get(k)184    cic = f"[${ci[0]:.3f}$, ${ci[1]:.3f}$]" if ci else ""185    L.append(f"      {lab} & " + " & ".join(c[0] for c in cells) + f" & {cic} \\\\")186    L.append("       & " + " & ".join(c[1] for c in cells) + " & \\\\[2pt]")187tab = r"""% Auto-generated by scripts/18_revision_language_leakage_spatial.py (2026-10-17)188\begin{table}[htbp]189  \centering190  \begin{threeparttable}191    \caption{Robustness of the AI-Derived Implicit Prices (Model~A)}192    \label{tab:rob_ai_coefs}193    \footnotesize194    \setlength{\tabcolsep}{4pt}195    \begin{tabular}{@{}lccccc@{}}196      \toprule197      & (1) & (2) & (3) & (4) & (5) \\198      & Baseline & $+$Language & RTA FE & Realtor.ca only & Cluster bootstrap \\199      & & & $+$Language & RTA FE $+$Lang. & 95\% CI \\200      \midrule201""" + "\n".join(L) + r"""202      \midrule203      Fixed effects & Municipality & Municipality & RTA & RTA & Municipality \\204      Observations & """ + " & ".join(num(O[s]["n"]) for s in specs_) + r""" & """ + num(O["A"]["n"]) + r""" \\205      $R^2$ & """ + " & ".join(f3(O[s]["r2"]) for s in specs_) + r""" & \\206      \bottomrule207    \end{tabular}208    \begin{tablenotes}[flushleft]209      \footnotesize210      \item \textit{Notes:} OLS estimates of Equation~\eqref{eq:hedonic} on the measured-area subsample with the full211      control set (coefficients of the controls not shown). Column~(1) is the baseline of Table~\ref{tab:regression}.212      Column~(2) adds indicators for English and mixed-language descriptions and the description length (thousands of213      characters). Column~(3) replaces the """ + str(OUT["fsa"]["n_city_fe"]) + r""" municipality fixed effects by """ + str(OUT["fsa"]["n_fsa_fe"]) + r""" forward-sortation-area (RTA) fixed214      effects (RTAs with at least 20 listings; the remainder pooled). Column~(4) restricts the sample to Realtor.ca215      listings, whose descriptions never contain the asking price. Standard errors in parentheses are clustered at the216      level of the fixed effects. Column~(5) reports the 2.5th and 97.5th percentiles of a pairs cluster bootstrap217      (""" + str(CB["B"]) + r""" replications, resampling the """ + str(CB["n_clusters"]) + r""" municipalities with replacement) for the baseline218      specification. $^{***}$, $^{**}$, $^{*}$: significance at 1\%, 5\%, 10\%.219    \end{tablenotes}220  \end{threeparttable}221\end{table}222"""223open("paper/tables/rob_ai_coefs.tex", "w").write(tab)224225# ---- Table: agreement ----226AG = OUT["agreement"]227def row_ag(label, r):228    return (f"      {label} & {num(r['n'])} & {pct(r['share_a'])} & {pct(r['share_ref'])} & {pct(r['agreement'])} & {r['kappa']:.2f} & "229            f"{pct(r['precision_vs_ref'])} & {pct(r['recall_vs_ref'])} \\\\")230rows = [row_ag(l, AG["llm_vs_keyword"][k]) for k, l in [("garage", "Garage"), ("pool", "Swimming pool"), ("waterfront", "Waterfront"),231                                                        ("fireplace", "Fireplace"), ("central_ac", "Central A/C or heat pump"),232                                                        ("finished_basement", "Finished basement")]]233rows2 = [row_ag("Garage visible vs.\\ garage (LLM)", AG["vision_vs_text"]["garage_visible_vs_llm_garage"]),234         row_ag("Garage visible vs.\\ garage (keyword)", AG["vision_vs_text"]["garage_visible_vs_keyword_garage"]),235         row_ag("Waterfront setting vs.\\ waterfront (keyword)", AG["vision_vs_text"]["waterfront_setting_vs_keyword"]),236         row_ag("Row house vs.\\ townhouse (listing type)", AG["vision_rowhouse_vs_listing_type"])]237sto = AG["vision_storeys_vs_structured"]238tab = r"""% Auto-generated by scripts/18_revision_language_leakage_spatial.py (2026-10-17)239\begin{table}[htbp]240  \centering241  \begin{threeparttable}242    \caption{Agreement Between Machine-Generated Attributes and Independent Sources}243    \label{tab:agreement}244    \footnotesize245    \setlength{\tabcolsep}{3.5pt}246    \begin{tabular}{@{}lccccccc@{}}247      \toprule248      Attribute & $N$ & Share (AI) & Share (ref.) & Agreement & $\kappa$ & Precision & Recall \\249      \midrule250      \multicolumn{8}{@{}l}{\textit{Panel A: LLM text layer vs.\ bilingual keyword rule on the same text}} \\[2pt]251""" + "\n".join(rows) + r"""252      \addlinespace253      \multicolumn{8}{@{}l}{\textit{Panel B: Façade vision layer vs.\ text or structured fields (exterior shots only)}} \\[2pt]254""" + "\n".join(rows2) + r"""255      \bottomrule256    \end{tabular}257    \begin{tablenotes}[flushleft]258      \footnotesize259      \item \textit{Notes:} ``Share (AI)'' is the prevalence of the attribute according to the AI layer, ``Share (ref.)''260      according to the reference source; ``Agreement'' is the share of listings on which the two coincide, $\kappa$ is261      Cohen's kappa, and precision and recall treat the reference as ground truth (it is not: keyword rules miss262      negations and synonyms, and a garage need not be visible on the façade photograph). Visual storey count agrees263      exactly with the structured storey field for """ + f"{sto['exact']*100:.1f}" + r"""\% of """ + num(sto["n"]) + r""" listings and within half a storey for """ + f"{sto['within_half_storey']*100:.1f}" + r"""\%.264    \end{tablenotes}265  \end{threeparttable}266\end{table}267"""268open("paper/tables/agreement.tex", "w").write(tab)269print("-> paper/tables/rob_language_source.tex, rob_spatial.tex, rob_ai_coefs.tex, agreement.tex")270
Files main
Menu

Theme