SPB Git

Repository Public Research preview

06_tables_figures_from_log.py 38.9 KB 874 lines python

1# =============================================================================2#                  SP BOUCHER | ACADEMIC RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : UQO Working Paper 19# File             : scripts/06_tables_figures_from_log.py10# Description      : 06_tables_figures_from_log.py — Rebuild every paper table11#                    (and the figures that can be rebuilt) from the preserved12#                    console log of the original run of13#                    scripts/05_sqr_multi_segment.py14#                    (results/sqr_multi_segment_output.txt).15# Module           : scripts16# Repository       : https://git.spboucher.ai/wp1_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"""6506_tables_figures_from_log.py — Rebuild every paper table (and the figures that can be66rebuilt) from the preserved console log of the original run of67scripts/05_sqr_multi_segment.py (results/sqr_multi_segment_output.txt).6869Added during the 2026-10-17 editorial-board revision. The Centris snapshot is not on70this machine, so the analysis could not be rerun; the log is the only audit trail of71the numbers reported in the paper. Every number written to paper/tables/*.tex and72figures/*.png by this script is parsed from that log (or derived from it by an73explicit formula stated in the table note). Nothing is typed by hand.7475Usage:  python3 scripts/06_tables_figures_from_log.py76Outputs: results/log_parsed.json, paper/tables/*.tex, figures/fig*.png (copied to77         paper/figures/).78"""7980import json81import math82import re83import shutil84from pathlib import Path8586import matplotlib87matplotlib.use("Agg")88import matplotlib.pyplot as plt89import numpy as np90from scipy import stats9192ROOT = Path(__file__).resolve().parents[1]93LOG = ROOT / "results" / "sqr_multi_segment_output.txt"94TAB = ROOT / "paper" / "tables"95FIG = ROOT / "figures"96PFIG = ROOT / "paper" / "figures"97TAUS = [0.10, 0.25, 0.50, 0.75, 0.90]98SEGS = ["Houses", "Condos", "Plex", "Land"]99AMEN = ["near_highway", "near_hospital", "near_park", "near_school",100        "near_transit", "near_golf", "has_garage"]101LABEL = {"near_highway": "Highway", "near_hospital": "Hospital", "near_park": "Park",102         "near_school": "School", "near_transit": "Transit", "near_golf": "Golf course",103         "has_garage": "Garage",104         "const": "Constant", "bedrooms_c": "Bedrooms", "total_baths_c": "Bathrooms",105         "stories_c": "Stories", "parking_spaces_c": "Parking spaces",106         "ln_dist_c": "$\\ln$(distance to Montreal)", "ln_floor_c": "$\\ln$(floor area)",107         "ln_land_c": "$\\ln$(land area)", "unit_total_c": "Number of units",108         "reg_Montreal": "Montreal", "reg_Quebec": "Qu\\'ebec City", "reg_Regions": "Other regions"}109SEGLABEL = {"Houses": "Single-family houses", "Condos": "Condominiums",110            "Plex": "Multiplexes", "Land": "Vacant land"}111112113# ----------------------------------------------------------------------------114# 1. Parse the log115# ----------------------------------------------------------------------------116def fnum(s):117    return float(s.replace(",", "").replace("$", "").replace("+", "").strip())118119120def parse_log(text):121    chunks = re.split(r"SEGMENT : ([A-Z]+)", text)122    out = {}123    for i in range(1, len(chunks), 2):124        name = chunks[i].capitalize()125        body = chunks[i + 1]126        seg = {"name": name}127        seg["n_raw"] = int(re.search(r"Annonces brutes : ([\d,]+)", body).group(1).replace(",", ""))128        seg["n"] = int(re.search(r"chantillon final : ([\d,]+)", body).group(1).replace(",", ""))129        m = re.search(r"Prix : \[([\d,]+) — ([\d,]+)\]", body)130        seg["price_min"], seg["price_max"] = fnum(m.group(1)), fnum(m.group(2))131        seg["median"] = fnum(re.search(r"Médiane : ([\d,]+)", body).group(1))132        seg["k"] = int(re.search(r"Variables : (\d+)", body).group(1))133        seg["regions"] = {}134        for r, n_r, med in re.findall(r"\n\s+(Gatineau|Montreal|Quebec|Regions)\s+:\s+(\d+)\s+\(médian:\s+([\d,]+) \$\)", body):135            seg["regions"][r] = {"n": int(n_r), "median": fnum(med)}136        seg["amenity_share"] = {v: float(s) for v, s in re.findall(r"\n\s+(near_\w+|has_garage)\s+:\s+([\d.]+)%", body)}137        seg["ols_adj_r2"] = float(re.search(r"R² ajusté = ([\d.]+)", body).group(1))138        m = re.search(r"Moran I \(résidus\) = ([\d.]+), Z = ([\d.]+)", body)139        seg["moran_ols"] = {"I": float(m.group(1)), "Z": float(m.group(2))}140        seg["pseudo_r2"] = {float(t): float(r) for t, r in re.findall(r"τ = ([\d.]+) : pseudo-R² = ([\d.]+)", body)}141        seg["first_stage_r2"] = float(re.search(r"première étape R² = ([\d.]+)", body).group(1))142        seg["rho50"] = float(re.search(r"ρ \(lag spatial, τ=0\.50\) = ([-\d.]+)", body).group(1))143        # OLS amenity coefficients (last column of the summary block, with stars)144        seg["ols"] = {}145        summary = body.split("┌──")[0]146        for line in summary.splitlines():147            t = line.split()148            if t and t[0] in AMEN and len(t) >= 7:149                last = t[-1]150                m = re.match(r"(-?[\d.]+)(\**)", last)151                seg["ols"][t[0]] = {"b": float(m.group(1)), "stars": m.group(2)}152        # Full QR tables per tau153        seg["qr"] = {}154        for tau_s, block in re.findall(r"┌── τ = ([\d.]+) ─+\n(.*?)└", body, re.S):155            tau = float(tau_s)156            coefs = {}157            for line in block.splitlines():158                m = re.match(r"\s*│\s+(\S+)\s+(-?[\d.]+)\s+([\d.]+)\s+(-?[\d.]+)\s+([\d.]+)\s*(\**)", line)159                if m:160                    coefs[m.group(1)] = {"b": float(m.group(2)), "se": float(m.group(3)),161                                         "z": float(m.group(4)), "p": float(m.group(5)), "stars": m.group(6)}162            seg["qr"][tau] = coefs163        # Wald tests164        seg["wald"] = {}165        wblock = body.split("Tests de Wald")[1].split("Moran I résidus")[0]166        for line in wblock.splitlines():167            t = line.split()168            if t and t[0] in AMEN:169                vals = re.findall(r"(-?[\d.]+)\s+(\*{1,3}|n\.s\.)", line)170                seg["wald"][t[0]] = {"10_90": float(vals[0][0]), "25_75": float(vals[1][0]), "10_50": float(vals[2][0])}171        # Moran on residuals172        seg["moran_resid"] = {}173        mblock = body.split("Moran I résidus")[1].split("Prix implicites")[0]174        for m in re.finditer(r"(QR|SQR) τ=([\d.]+)\s+([\d.]+)\s+([\d.]+)", mblock):175            seg["moran_resid"][(m.group(1), float(m.group(2)))] = {"I": float(m.group(3)), "Z": float(m.group(4))}176        # Implicit prices177        seg["wtp"] = {}178        pblock = body.split("Prix implicites")[1].split("Effets directs")[0]179        for line in pblock.splitlines():180            t = line.split()181            if t and t[0] in ("Highway", "Hospital", "Park", "School", "Transit", "Golf", "Garage"):182                seg["wtp"][t[0]] = [fnum(x) for x in t[1:6]]183        # Direct / indirect effects (SQR tau = 0.5)184        seg["effects"] = {}185        eblock = body.split("Effets directs")[1]186        eblock = eblock.split("▓")[0].split("GÉNÉRATION")[0]187        for line in eblock.splitlines():188            t = line.split()189            if t and t[0] in AMEN:190                seg["effects"][t[0]] = {"beta": float(t[1]), "total": float(t[2]),191                                        "indirect": float(t[3]), "dollar": fnum(t[4])}192        out[name] = seg193    return out194195196# ----------------------------------------------------------------------------197# 2. Helpers198# ----------------------------------------------------------------------------199def stars_from_p(p):200    return "***" if p < 0.01 else "**" if p < 0.05 else "*" if p < 0.10 else ""201202203def star_p_from_z(b, se):204    z = b / se if se > 0 else 0.0205    return 2 * (1 - stats.norm.cdf(abs(z)))206207208def num(x, nd=3):209    """number with a typographic minus sign."""210    t = f"{abs(x):.{nd}f}"211    return ("$-$" + t) if x < 0 and t.strip("0.") != "" else t212213214def fmt_coef(b, se):215    """coefficient with conventional stars (p<0.10 *, p<0.05 **, p<0.01 ***) and SE below."""216    p = star_p_from_z(b, se)217    st = stars_from_p(p)218    return (num(b) + (f"$^{{{st}}}$" if st else "")), f"({se:.3f})"219220221def money(x):222    s = f"{abs(x):,.0f}"223    return ("$-$" if x < 0 else "$+$") + s224225226def write(name, content):227    (TAB / name).write_text(content)228    print("  wrote", TAB / name)229230231NOTE_STARS = ("$^{***}$, $^{**}$ and $^{*}$ denote significance at the 1, 5 and 10 percent levels "232              "(two-sided normal test using bootstrap standard errors, $B = 200$ paired resamples).")233NOTE_SRC = ("All entries are parsed from \\texttt{results/sqr\\_multi\\_segment\\_output.txt}, the preserved "234            "log of the original run of \\texttt{scripts/05\\_sqr\\_multi\\_segment.py}, by "235            "\\texttt{scripts/06\\_tables\\_figures\\_from\\_log.py}.")236237238# ----------------------------------------------------------------------------239# 3. Tables240# ----------------------------------------------------------------------------241def table_sample(D):242    rows = []243    rows.append("Raw listings & " + " & ".join(f"{D[s]['n_raw']:,}" for s in SEGS) + " \\\\")244    rows.append("Estimation sample & " + " & ".join(f"{D[s]['n']:,}" for s in SEGS) + " \\\\")245    rows.append("Retention rate (\\%) & " + " & ".join(f"{100*D[s]['n']/D[s]['n_raw']:.1f}" for s in SEGS) + " \\\\")246    rows.append("Number of regressors & " + " & ".join(f"{D[s]['k']}" for s in SEGS) + " \\\\")247    rows.append("\\midrule")248    rows.append("Minimum asking price (\\$) & " + " & ".join(f"{D[s]['price_min']:,.0f}" for s in SEGS) + " \\\\")249    rows.append("Median asking price (\\$) & " + " & ".join(f"{D[s]['median']:,.0f}" for s in SEGS) + " \\\\")250    rows.append("Maximum asking price (\\$) & " + " & ".join(f"{D[s]['price_max']:,.0f}" for s in SEGS) + " \\\\")251    body = "\n".join(rows)252    write("sample.tex", f"""\\begin{{table}}[H]253\\centering254\\caption{{Sample construction by market segment}}255\\label{{tab:sample}}256\\begin{{threeparttable}}257\\begin{{tabular}}{{lrrrr}}258\\toprule259& Houses & Condominiums & Multiplexes & Vacant land \\\\260\\midrule261{body}262\\bottomrule263\\end{{tabular}}264\\begin{{tablenotes}}265\\small266\\item \\textit{{Notes:}} Centris active listings, Quebec, snapshot of May 2026. The estimation sample retains listings with a positive asking price, valid coordinates, non-missing structural variables required by the segment specification (Table~\\ref{{tab:specification}}), floor area above 100 sq.\\,ft.\\ where applicable, land area above zero (above 10 sq.\\,ft.\\ for land), land area winsorised at its 99th percentile, and asking price, floor area and land area trimmed at the 0.5th and 99.5th percentiles of their logarithms. The number of regressors excludes the constant. Minimum and maximum prices are those of the estimation sample. {NOTE_SRC}267\\end{{tablenotes}}268\\end{{threeparttable}}269\\end{{table}}270""")271272273def table_descriptive(D):274    REG = [("Montreal", "Montreal area"), ("Quebec", "Qu\\'ebec City area"),275           ("Gatineau", "Gatineau"), ("Regions", "Other regions")]276    rows = ["\\multicolumn{5}{l}{\\textit{Amenity indicators (share of listings, \\%)}} \\\\"]277    for v in AMEN:278        cells = []279        for s in SEGS:280            cells.append(f"{D[s]['amenity_share'][v]:.1f}" if v in D[s]["amenity_share"] else "---")281        rows.append(f"\\quad {LABEL[v]} & " + " & ".join(cells) + " \\\\")282    rows.append("\\midrule")283    rows.append("\\multicolumn{5}{l}{\\textit{Regional composition (share of listings, \\%)}} \\\\")284    for r, lab in REG:285        rows.append(f"\\quad {lab} & " + " & ".join(f"{100*D[s]['regions'][r]['n']/D[s]['n']:.1f}" for s in SEGS) + " \\\\")286    rows.append("\\midrule")287    rows.append("\\multicolumn{5}{l}{\\textit{Median asking price by region (\\$)}} \\\\")288    for r, lab in REG:289        rows.append(f"\\quad {lab} & " + " & ".join(f"{D[s]['regions'][r]['median']:,.0f}" for s in SEGS) + " \\\\")290    rows.append(f"\\quad All listings & " + " & ".join(f"{D[s]['median']:,.0f}" for s in SEGS) + " \\\\")291    rows.append("\\midrule")292    rows.append("Estimation sample ($N$) & " + " & ".join(f"{D[s]['n']:,}" for s in SEGS) + " \\\\")293    body = "\n".join(rows)294    write("descriptive.tex", f"""\\begin{{table}}[H]295\\centering296\\caption{{Amenity prevalence, regional composition and median asking prices of the estimation samples}}297\\label{{tab:descriptive}}298\\begin{{threeparttable}}299\\begin{{tabular}}{{lrrrr}}300\\toprule301& Houses & Condominiums & Multiplexes & Vacant land \\\\302\\midrule303{body}304\\bottomrule305\\end{{tabular}}306\\begin{{tablenotes}}307\\small308\\item \\textit{{Notes:}} Amenity indicators equal one when the corresponding keyword appears in the Centris ``amenities nearby'' field; the garage indicator is built from the parking-type field and is not defined for vacant land. Regional shares are computed from the listing counts recorded in the log (e.g.\\ 1,180 Montreal-area houses). Moments of the structural variables (bedrooms, bathrooms, areas) were not written to the preserved log and are therefore not reported; see Section~\\ref{{sec:data}}. {NOTE_SRC}309\\end{{tablenotes}}310\\end{{threeparttable}}311\\end{{table}}312""")313314315def table_ols_moran(D):316    rows = []317    for s in SEGS:318        d = D[s]319        rows.append(f"{SEGLABEL[s]} & {d['n']:,} & {d['ols_adj_r2']:.3f} & {d['moran_ols']['I']:.3f} & {d['moran_ols']['Z']:.1f} & $<0.001$ \\\\")320    body = "\n".join(rows)321    write("moran.tex", f"""\\begin{{table}}[H]322\\centering323\\caption{{OLS fit and Moran's $I$ test on OLS residuals, by segment}}324\\label{{tab:moran}}325\\begin{{threeparttable}}326\\begin{{tabular}}{{lrcccc}}327\\toprule328Segment & $N$ & Adjusted $R^2$ & Moran's $I$ & $z$-statistic & $p$-value \\\\329\\midrule330{body}331\\bottomrule332\\end{{tabular}}333\\begin{{tablenotes}}334\\small335\\item \\textit{{Notes:}} OLS estimates of equation~\\eqref{{eq:hedonic}} with HC3 standard errors. Moran's $I$ uses the row-standardised inverse-distance $k$-nearest-neighbour matrix ($k = 10$) of equation~\\eqref{{eq:W}}; the $z$-statistic uses the randomisation (kurtosis-adjusted) variance of \\citet{{cliff1981spatial}}; $p$-values are two-sided normal. {NOTE_SRC}336\\end{{tablenotes}}337\\end{{threeparttable}}338\\end{{table}}339""")340341342def table_qr_amenities(D, seg, fname, label, caption):343    d = D[seg]344    amen = [v for v in AMEN if v in d["qr"][0.5]]345    rows = []346    for v in amen:347        line1, line2 = [LABEL[v]], [""]348        for t in TAUS:349            c = d["qr"][t][v]350            a, b = fmt_coef(c["b"], c["se"])351            line1.append(a)352            line2.append(b)353        o = d["ols"][v]354        line1.append(num(o['b']) + (f"$^{{{o['stars']}}}$" if o["stars"] else ""))355        line2.append("")356        rows.append(" & ".join(line1) + " \\\\")357        rows.append(" & ".join(line2) + " \\\\[2pt]")358    rows.append("\\midrule")359    rows.append("Pseudo-$R^2$ / adj.\\ $R^2$ & " + " & ".join(f"{d['pseudo_r2'][t]:.3f}" for t in TAUS) + f" & {d['ols_adj_r2']:.3f} \\\\")360    rows.append(f"$N$ & \\multicolumn{{6}}{{c}}{{{d['n']:,}}} \\\\")361    body = "\n".join(rows)362    write(fname, f"""\\begin{{table}}[H]363\\centering364\\caption{{{caption}}}365\\label{{{label}}}366\\begin{{threeparttable}}367\\small368\\begin{{tabular}}{{lcccccc}}369\\toprule370& \\multicolumn{{5}}{{c}}{{Quantile regression, $\\tau$}} & OLS \\\\371\\cmidrule(lr){{2-6}}372Amenity indicator & 0.10 & 0.25 & 0.50 & 0.75 & 0.90 & \\\\373\\midrule374{body}375\\bottomrule376\\end{{tabular}}377\\begin{{tablenotes}}378\\small379\\item \\textit{{Notes:}} Dependent variable: log asking price. Each column is a separate estimate of equation~\\eqref{{eq:qr}} (quantile regression) or equation~\\eqref{{eq:hedonic}} (OLS) including all structural, locational and regional controls listed in Table~\\ref{{tab:specification}}. Bootstrap standard errors in parentheses. {NOTE_STARS} OLS stars use HC3 standard errors and are reported as printed in the log (the log applies the thresholds 0.001, 0.01 and 0.05 to the OLS column, so OLS stars are conservative relative to the quantile columns). The pseudo-$R^2$ is that of \\citet{{koenker1999goodness}}. {NOTE_SRC}380\\end{{tablenotes}}381\\end{{threeparttable}}382\\end{{table}}383""")384385386def table_structural_houses(D):387    d = D["Houses"]388    order = ["const", "bedrooms_c", "total_baths_c", "stories_c", "parking_spaces_c", "ln_floor_c",389             "ln_land_c", "ln_dist_c", "reg_Montreal", "reg_Quebec", "reg_Regions"]390    rows = []391    for v in order:392        line1, line2 = [LABEL[v]], [""]393        for t in TAUS:394            c = d["qr"][t][v]395            a, b = fmt_coef(c["b"], c["se"])396            line1.append(a)397            line2.append(b)398        rows.append(" & ".join(line1) + " \\\\")399        rows.append(" & ".join(line2) + " \\\\[2pt]")400    body = "\n".join(rows)401    write("qr_houses_structural.tex", f"""\\begin{{table}}[H]402\\centering403\\caption{{Structural, locational and regional coefficients by quantile --- single-family houses}}404\\label{{tab:qr_houses_structural}}405\\begin{{threeparttable}}406\\small407\\begin{{tabular}}{{lccccc}}408\\toprule409& \\multicolumn{{5}}{{c}}{{Quantile regression, $\\tau$}} \\\\410\\cmidrule(lr){{2-6}}411Variable & 0.10 & 0.25 & 0.50 & 0.75 & 0.90 \\\\412\\midrule413{body}414\\bottomrule415\\end{{tabular}}416\\begin{{tablenotes}}417\\small418\\item \\textit{{Notes:}} Same regressions as Table~\\ref{{tab:qr_houses}} ($N = {d['n']:,}$). Continuous variables are centred at their sample means, so the constant is the conditional quantile of log price for a mean-characteristic house in the Gatineau reference region without any amenity indicator. Regional dummies are relative to Gatineau. Bootstrap standard errors in parentheses. {NOTE_STARS} {NOTE_SRC}419\\end{{tablenotes}}420\\end{{threeparttable}}421\\end{{table}}422""")423424425def wald_sig(w):426    p = 1 - stats.chi2.cdf(w, 1)427    return f"{w:.2f}" + (f"$^{{{stars_from_p(p)}}}$" if stars_from_p(p) else "")428429430def table_wald(D):431    rows = []432    for v in AMEN:433        cells = []434        for s in SEGS:435            cells.append(wald_sig(D[s]["wald"][v]["10_90"]) if v in D[s]["wald"] else "---")436        rows.append(f"{LABEL[v]} & " + " & ".join(cells) + " \\\\")437    rows.append("\\midrule")438    counts = []439    for s in SEGS:440        n_sig = sum(1 for v in AMEN if v in D[s]["wald"] and (1 - stats.chi2.cdf(D[s]["wald"][v]["10_90"], 1)) < 0.05)441        n_tot = sum(1 for v in AMEN if v in D[s]["wald"])442        counts.append(f"{n_sig}/{n_tot}")443    rows.append("Rejections at 5\\% & " + " & ".join(counts) + " \\\\")444    body = "\n".join(rows)445    write("wald.tex", f"""\\begin{{table}}[H]446\\centering447\\caption{{Wald tests of equal amenity coefficients at $\\tau = 0.10$ and $\\tau = 0.90$, by segment}}448\\label{{tab:wald}}449\\begin{{threeparttable}}450\\begin{{tabular}}{{lcccc}}451\\toprule452Amenity indicator & Houses & Condominiums & Multiplexes & Vacant land \\\\453\\midrule454{body}455\\bottomrule456\\end{{tabular}}457\\begin{{tablenotes}}458\\small459\\item \\textit{{Notes:}} Entries are the statistic of equation~\\eqref{{eq:wald}}, $W = [\\hat\\beta_k(0.10) - \\hat\\beta_k(0.90)]^2 / [\\widehat{{\\mathrm{{Var}}}}(\\hat\\beta_k(0.10)) + \\widehat{{\\mathrm{{Var}}}}(\\hat\\beta_k(0.90))]$, with bootstrap variances, referred to a $\\chi^2(1)$ distribution. The denominator omits the (typically positive) covariance between the two quantile estimators, which makes the test conservative. $^{{***}}$, $^{{**}}$ and $^{{*}}$ denote rejection at the 1, 5 and 10 percent levels. {NOTE_SRC}460\\end{{tablenotes}}461\\end{{threeparttable}}462\\end{{table}}463""")464465466def table_wald_houses(D):467    d = D["Houses"]468    rows = []469    for v in AMEN:470        w = d["wald"][v]471        rows.append(f"{LABEL[v]} & {wald_sig(w['10_90'])} & {wald_sig(w['25_75'])} & {wald_sig(w['10_50'])} \\\\")472    body = "\n".join(rows)473    write("wald_houses.tex", f"""\\begin{{table}}[H]474\\centering475\\caption{{Wald tests of inter-quantile equality for three quantile pairs --- single-family houses}}476\\label{{tab:wald_houses}}477\\begin{{threeparttable}}478\\begin{{tabular}}{{lccc}}479\\toprule480Amenity indicator & $\\tau = 0.10$ vs.\\ $0.90$ & $\\tau = 0.25$ vs.\\ $0.75$ & $\\tau = 0.10$ vs.\\ $0.50$ \\\\481\\midrule482{body}483\\bottomrule484\\end{{tabular}}485\\begin{{tablenotes}}486\\small487\\item \\textit{{Notes:}} See Table~\\ref{{tab:wald}}. $^{{***}}$, $^{{**}}$ and $^{{*}}$ denote rejection at the 1, 5 and 10 percent levels. {NOTE_SRC}488\\end{{tablenotes}}489\\end{{threeparttable}}490\\end{{table}}491""")492493494def implied_F(r2, n, k):495    return (r2 / k) / ((1 - r2) / (n - k - 1))496497498def table_sqr(D):499    """First stage, rho(0.50) and amenity coefficients: OLS vs QR(0.50) vs 2SQR(0.50), by segment."""500    panels = []501    for s in SEGS:502        d = D[s]503        k_first = 2 * d["k"]504        F = implied_F(d["first_stage_r2"], d["n"], k_first)505        head = f"\\multicolumn{{4}}{{l}}{{\\textit{{{SEGLABEL[s]}}} ($N = {d['n']:,}$)}} \\\\"506        rows = [head]507        for v in AMEN:508            if v not in d["effects"]:509                continue510            o = d["ols"][v]["b"]511            q = d["qr"][0.5][v]["b"]512            sq = d["effects"][v]["beta"]513            rows.append(f"\\quad {LABEL[v]} & {num(o)} & {num(q)} & {num(sq)} \\\\")514        rows.append(f"\\quad First-stage $R^2$ & --- & --- & {d['first_stage_r2']:.3f} \\\\")515        rows.append(f"\\quad Implied overall first-stage $F({k_first},\\,{d['n']-k_first-1:,})$ & --- & --- & {F:,.0f} \\\\")516        rows.append(f"\\quad Spatial lag $\\hat\\rho(0.50)$ & --- & --- & {d['rho50']:.3f} \\\\")517        panels.append("\n".join(rows))518    body = "\n\\midrule\n".join(panels)519    write("sqr.tex", f"""\\begin{{table}}[H]520\\centering521\\caption{{Two-stage spatial quantile regression at the median: first-stage fit, spatial lag and amenity coefficients}}522\\label{{tab:sqr}}523\\begin{{threeparttable}}524\\small525\\begin{{tabular}}{{lccc}}526\\toprule527& OLS & QR, $\\tau = 0.50$ & 2SQR, $\\tau = 0.50$ \\\\528\\midrule529{body}530\\bottomrule531\\end{{tabular}}532\\begin{{tablenotes}}533\\small534\\item \\textit{{Notes:}} The first stage regresses $\\mathbf{{W}}\\ln\\mathbf{{P}}$ on the constant, $\\mathbf{{X}}$ and $\\mathbf{{WX}}$ (equation~\\eqref{{eq:firststage}}). The log records only the first-stage $R^2$; the overall $F$-statistic is implied by $F = [R^2/q]/[(1-R^2)/(N-q-1)]$ with $q$ the number of first-stage regressors, and is \\emph{{not}} the partial $F$ on the excluded instruments $\\mathbf{{WX}}$ required for a weak-instrument diagnostic (Section~\\ref{{sec:limitations}}). $\\hat\\rho(0.50)$ is the coefficient on the fitted spatial lag in the median second stage (equation~\\eqref{{eq:2sqr}}); the original run did not bootstrap the second stage, so no standard error is available for $\\hat\\rho$ or for the 2SQR coefficients. The 2SQR column reports the amenity coefficients of the same median second stage. {NOTE_SRC}535\\end{{tablenotes}}536\\end{{threeparttable}}537\\end{{table}}538""")539540541def table_moran_resid(D):542    rows = []543    for s in SEGS:544        d = D[s]545        rows.append(f"{SEGLABEL[s]} & {d['moran_ols']['I']:.3f} & "546                    + " & ".join(f"{d['moran_resid'][('QR', t)]['I']:.3f}" for t in TAUS) + " & "547                    + " & ".join(f"{d['moran_resid'][('SQR', t)]['I']:.3f}" for t in TAUS) + " \\\\")548    body = "\n".join(rows)549    write("moran_resid.tex", f"""\\begin{{table}}[H]550\\centering551\\caption{{Moran's $I$ on residuals: OLS, quantile regression and 2SQR second stage, by quantile and segment}}552\\label{{tab:moran_resid}}553\\begin{{threeparttable}}554\\small555\\begin{{tabular}}{{lcccccccccccc}}556\\toprule557& OLS & \\multicolumn{{5}}{{c}}{{QR residuals, $\\tau$}} & \\multicolumn{{5}}{{c}}{{2SQR second-stage residuals, $\\tau$}} \\\\558\\cmidrule(lr){{3-7}} \\cmidrule(lr){{8-12}}559Segment & & 0.10 & 0.25 & 0.50 & 0.75 & 0.90 & 0.10 & 0.25 & 0.50 & 0.75 & 0.90 \\\\560\\midrule561{body}562\\bottomrule563\\end{{tabular}}564\\begin{{tablenotes}}565\\small566\\item \\textit{{Notes:}} All statistics are significant at any conventional level ($z$-statistics between 21 and 70). The 2SQR residuals are those of the second stage, $\\ln P_i - \\hat\\alpha(\\tau) - \\mathbf{{X}}_i'\\hat{{\\boldsymbol\\beta}}(\\tau) - \\hat\\rho(\\tau)\\widehat{{[\\mathbf{{W}}\\ln\\mathbf{{P}}]}}_i$, computed with the \\emph{{fitted}} spatial lag; because the fitted lag is a linear combination of $\\mathbf{{X}}$ and $\\mathbf{{WX}}$, these residuals cannot be expected to display less spatial autocorrelation than the QR residuals (Section~\\ref{{sec:moran_sqr}}). Structural residuals using the observed lag were not computed in the original run. {NOTE_SRC}567\\end{{tablenotes}}568\\end{{threeparttable}}569\\end{{table}}570""")571572573def reference_prices(d):574    """P(tau) = exp(sample quantile of ln P) is not printed in the log; recover it from the575    highway row as WTP / (exp(beta) - 1), where beta is the printed 4-decimal coefficient."""576    out = {}577    for j, t in enumerate(TAUS):578        b = d["qr"][t]["near_highway"]["b"]579        out[t] = d["wtp"]["Highway"][j] / (math.exp(b) - 1)580    return out581582583def table_implicit_prices(D):584    d = D["Houses"]585    P = reference_prices(d)586    rows = []587    name_map = {"Highway": "near_highway", "Hospital": "near_hospital", "Park": "near_park",588                "School": "near_school", "Transit": "near_transit", "Golf": "near_golf", "Garage": "has_garage"}589    for lab, v in name_map.items():590        cells = []591        for j, t in enumerate(TAUS):592            c = d["qr"][t][v]593            p = star_p_from_z(c["b"], c["se"])594            st = stars_from_p(p)595            cells.append(money(d["wtp"][lab][j]) + (f"$^{{{st}}}$" if st else ""))596        rows.append(f"{LABEL[v]} & " + " & ".join(cells) + " \\\\")597    body = "\n".join(rows)598    head_prices = " & ".join(f"(\\${P[t]/1000:,.0f}K)" for t in TAUS)599    write("implicit_prices.tex", f"""\\begin{{table}}[H]600\\centering601\\caption{{Dollar-equivalent implicit prices of amenity indicators by quantile --- single-family houses (CAD)}}602\\label{{tab:implicit_prices}}603\\begin{{threeparttable}}604\\begin{{tabular}}{{lrrrrr}}605\\toprule606& $\\tau = 0.10$ & $\\tau = 0.25$ & $\\tau = 0.50$ & $\\tau = 0.75$ & $\\tau = 0.90$ \\\\607Amenity indicator & {head_prices} \\\\608\\midrule609{body}610\\bottomrule611\\end{{tabular}}612\\begin{{tablenotes}}613\\small614\\item \\textit{{Notes:}} Entries are $\\pi_k(\\tau) = P(\\tau)\\,[\\exp(\\hat\\beta_k(\\tau)) - 1]$ (equation~\\eqref{{eq:implicit}}), where $P(\\tau)$ is the unconditional sample quantile of the asking price (in parentheses in the header, rounded to the nearest thousand). These are capitalisation differentials in asking prices, not welfare measures (Section~\\ref{{sec:identification}}). Stars carry over the significance of the underlying coefficient in Table~\\ref{{tab:qr_houses}}. {NOTE_SRC}615\\end{{tablenotes}}616\\end{{threeparttable}}617\\end{{table}}618""")619620621def table_effects(D):622    panels = []623    for s in SEGS:624        d = D[s]625        rho = d["rho50"]626        rows = [f"\\multicolumn{{5}}{{l}}{{\\textit{{{SEGLABEL[s]}}} ($\\hat\\rho(0.50) = {rho:.3f}$, $1/(1-\\hat\\rho) = {1/(1-rho):.3f}$, median price \\${d['median']:,.0f})}} \\\\"]627        for v in AMEN:628            if v not in d["effects"]:629                continue630            e = d["effects"][v]631            rows.append(f"\\quad {LABEL[v]} & {num(e['beta'])} & {num(e['indirect'])} & {num(e['total'])} & {money(e['dollar'])} \\\\")632        panels.append("\n".join(rows))633    body = "\n\\midrule\n".join(panels)634    write("effects.tex", f"""\\begin{{table}}[H]635\\centering636\\caption{{Scalar approximation of direct, indirect and total amenity effects in the median 2SQR}}637\\label{{tab:effects}}638\\begin{{threeparttable}}639\\small640\\begin{{tabular}}{{lcccr}}641\\toprule642Amenity indicator & Direct $\\approx \\hat\\beta_k$ & Indirect $\\approx \\hat\\rho\\hat\\beta_k/(1-\\hat\\rho)$ & Total $\\approx \\hat\\beta_k/(1-\\hat\\rho)$ & Total, \\$ at median \\\\643\\midrule644{body}645\\bottomrule646\\end{{tabular}}647\\begin{{tablenotes}}648\\small649\\item \\textit{{Notes:}} Scalar approximations of equation~\\eqref{{eq:effects}} evaluated at $\\tau = 0.50$; the dollar column is $\\tilde P_{{0.50}}\\,[\\exp(\\text{{Total}}) - 1]$ with $\\tilde P_{{0.50}}$ the median asking price of the segment. The log labels $\\hat\\beta_k/(1-\\hat\\rho)$ ``direct''; it is the total effect of the scalar approximation, and the columns are relabelled accordingly (direct $+$ indirect $=$ total). No standard errors are available (Section~\\ref{{sec:limitations}}). {NOTE_SRC}650\\end{{tablenotes}}651\\end{{threeparttable}}652\\end{{table}}653""")654655656def table_pseudo_r2(D):657    rows = []658    for s in SEGS:659        d = D[s]660        rows.append(f"{SEGLABEL[s]} & " + " & ".join(f"{d['pseudo_r2'][t]:.3f}" for t in TAUS) + f" & {d['ols_adj_r2']:.3f} \\\\")661    body = "\n".join(rows)662    write("pseudo_r2.tex", f"""\\begin{{table}}[H]663\\centering664\\caption{{Pseudo-$R^2$ of the quantile regressions and adjusted $R^2$ of OLS, by segment}}665\\label{{tab:pseudo_r2}}666\\begin{{threeparttable}}667\\begin{{tabular}}{{lcccccc}}668\\toprule669& \\multicolumn{{5}}{{c}}{{Quantile regression, $\\tau$}} & OLS \\\\670\\cmidrule(lr){{2-6}}671Segment & 0.10 & 0.25 & 0.50 & 0.75 & 0.90 & adj.\\ $R^2$ \\\\672\\midrule673{body}674\\bottomrule675\\end{{tabular}}676\\begin{{tablenotes}}677\\small678\\item \\textit{{Notes:}} Pseudo-$R^2$ of \\citet{{koenker1999goodness}}, equation~\\eqref{{eq:pseudor2}}; it is not comparable to the OLS $R^2$ and only loosely comparable across quantiles. {NOTE_SRC}679\\end{{tablenotes}}680\\end{{threeparttable}}681\\end{{table}}682""")683684685# ----------------------------------------------------------------------------686# 4. Figures (rebuilt from the log; validated categorical palette, fixed order)687# ----------------------------------------------------------------------------688COLORS = {"Houses": "#2a78d6", "Condos": "#eb6834", "Plex": "#1baf7a", "Land": "#eda100"}689MARK = {"Houses": "o", "Condos": "s", "Plex": "^", "Land": "D"}690plt.rcParams.update({"font.size": 9, "axes.titlesize": 10, "axes.labelsize": 9, "legend.fontsize": 8,691                     "axes.spines.top": False, "axes.spines.right": False, "axes.grid": True,692                     "grid.color": "#e5e5e5", "grid.linewidth": 0.6, "savefig.dpi": 300,693                     "savefig.bbox": "tight", "figure.facecolor": "white"})694SIX = ["near_highway", "near_hospital", "near_park", "near_school", "near_transit", "near_golf"]695696697def fig_coefficients(D):698    fig, axes = plt.subplots(2, 3, figsize=(10, 6.2))699    for ax, v in zip(axes.flat, SIX):700        ax.axhline(0, color="#777777", lw=0.8)701        for s in SEGS:702            d = D[s]703            b = np.array([d["qr"][t][v]["b"] for t in TAUS])704            se = np.array([d["qr"][t][v]["se"] for t in TAUS])705            ax.fill_between(TAUS, b - 1.96 * se, b + 1.96 * se, color=COLORS[s], alpha=0.10, lw=0)706            ax.plot(TAUS, b, marker=MARK[s], ms=4, lw=1.6, color=COLORS[s], label=SEGLABEL[s])707        ax.set_title(LABEL[v])708        ax.set_xticks(TAUS)709        ax.set_xlabel(r"Quantile $\tau$")710        ax.set_ylabel("Coefficient (log points)")711    axes[0, 0].legend(frameon=False, loc="upper right")712    fig.tight_layout()713    fig.savefig(FIG / "fig_coefficients_by_quantile.png")714    plt.close(fig)715716717def fig_implicit_prices(D):718    fig, axes = plt.subplots(2, 3, figsize=(10, 6.2))719    lab_map = {"near_highway": "Highway", "near_hospital": "Hospital", "near_park": "Park",720               "near_school": "School", "near_transit": "Transit", "near_golf": "Golf"}721    for ax, v in zip(axes.flat, SIX):722        ax.axhline(0, color="#777777", lw=0.8)723        for s in SEGS:724            y = np.array(D[s]["wtp"][lab_map[v]]) / 1000725            ax.plot(TAUS, y, marker=MARK[s], ms=4, lw=1.6, color=COLORS[s], label=SEGLABEL[s])726        ax.set_title(LABEL[v])727        ax.set_xticks(TAUS)728        ax.set_xlabel(r"Quantile $\tau$")729        ax.set_ylabel("Implicit price (thousand CAD)")730    axes[0, 0].legend(frameon=False, loc="upper left")731    fig.tight_layout()732    fig.savefig(FIG / "fig_implicit_prices_by_quantile.png")733    plt.close(fig)734735736def fig_ols_qr_sqr(D):737    fig, axes = plt.subplots(2, 2, figsize=(10, 7))738    for ax, s in zip(axes.flat, SEGS):739        d = D[s]740        vs = [v for v in AMEN if v in d["effects"]]741        x = np.arange(len(vs))742        w = 0.26743        ols = [d["ols"][v]["b"] for v in vs]744        qr = [d["qr"][0.5][v]["b"] for v in vs]745        sq = [d["effects"][v]["beta"] for v in vs]746        ax.bar(x - w, ols, w * 0.92, color="#9a9a9a", label="OLS")747        ax.bar(x, qr, w * 0.92, color="#2a78d6", label=r"QR, $\tau=0.50$")748        ax.bar(x + w, sq, w * 0.92, color="#eb6834", label=r"2SQR, $\tau=0.50$")749        ax.axhline(0, color="#333333", lw=0.8)750        ax.set_xticks(x)751        ax.set_xticklabels([LABEL[v] for v in vs], rotation=30, ha="right")752        ax.set_title(f"{SEGLABEL[s]} (N = {d['n']:,})")753        ax.set_ylabel("Coefficient (log points)")754        ax.grid(axis="x", visible=False)755    axes[0, 0].legend(frameon=False)756    fig.tight_layout()757    fig.savefig(FIG / "fig_ols_qr_sqr_median.png")758    plt.close(fig)759760761def fig_pseudo_r2(D):762    fig, ax = plt.subplots(figsize=(6.5, 4))763    for s in SEGS:764        d = D[s]765        y = [d["pseudo_r2"][t] for t in TAUS]766        ax.plot(TAUS, y, marker=MARK[s], ms=5, lw=1.8, color=COLORS[s], label=SEGLABEL[s])767        ax.annotate(SEGLABEL[s], (TAUS[-1], y[-1]), xytext=(5, 0), textcoords="offset points",768                    va="center", fontsize=8, color="#333333")769    ax.set_xticks(TAUS)770    ax.set_xlim(0.05, 1.05)771    ax.set_xlabel(r"Quantile $\tau$")772    ax.set_ylabel(r"Pseudo-$R^2$")773    ax.legend(frameon=False, loc="center left")774    fig.tight_layout()775    fig.savefig(FIG / "fig_pseudo_r2.png")776    plt.close(fig)777778779def fig_wald_heatmap(D):780    fig, axes = plt.subplots(2, 2, figsize=(11, 7.2), constrained_layout=True)781    pairs = [(TAUS[j], TAUS[j + 1]) for j in range(4)]782    cmap = matplotlib.colors.LinearSegmentedColormap.from_list("blues", ["#f4f7fb", "#2a78d6", "#0b2a5c"])783    for ax, s in zip(axes.flat, SEGS):784        d = D[s]785        vs = [v for v in SIX if v in d["qr"][0.5]]786        M = np.zeros((len(vs), 4))787        for i, v in enumerate(vs):788            for j, (t1, t2) in enumerate(pairs):789                b1, b2 = d["qr"][t1][v]["b"], d["qr"][t2][v]["b"]790                s1, s2 = d["qr"][t1][v]["se"], d["qr"][t2][v]["se"]791                M[i, j] = ((b1 - b2) ** 2) / (s1 ** 2 + s2 ** 2)792        im = ax.imshow(M, cmap=cmap, vmin=0, vmax=12, aspect="auto")793        ax.set_xticks(range(4))794        ax.set_xticklabels([f"{t1:.2f}\u2013{t2:.2f}" for t1, t2 in pairs], fontsize=8)795        ax.set_xlabel(r"Adjacent quantile pair ($\tau_j$\u2013$\tau_{j+1}$)")796        ax.set_yticks(range(len(vs)))797        ax.set_yticklabels([LABEL[v] for v in vs])798        ax.set_title(SEGLABEL[s])799        ax.grid(False)800        for i in range(len(vs)):801            for j in range(4):802                p = 1 - stats.chi2.cdf(M[i, j], 1)803                st = stars_from_p(p)804                ax.text(j, i, f"{M[i, j]:.1f}{st}", ha="center", va="center", fontsize=7.5,805                        color="white" if M[i, j] > 6 else "#111111")806    fig.colorbar(im, ax=axes.ravel().tolist(), shrink=0.8, label="Wald statistic")807    fig.savefig(FIG / "fig_wald_adjacent_quantiles.png")808    plt.close(fig)809810811# ----------------------------------------------------------------------------812def main():813    text = LOG.read_text()814    D = parse_log(text)815    TAB.mkdir(exist_ok=True)816    FIG.mkdir(exist_ok=True)817    PFIG.mkdir(exist_ok=True)818819    # consistency checks against the log's own summary block820    for s in SEGS:821        d = D[s]822        assert len(d["qr"]) == 5 and all(len(d["qr"][t]) == d["k"] + 1 for t in TAUS), s823        assert set(d["wald"]) == set(d["effects"]), s824    print("parsed", {s: (D[s]["n"], D[s]["k"]) for s in SEGS})825826    table_sample(D)827    table_descriptive(D)828    table_ols_moran(D)829    table_qr_amenities(D, "Houses", "qr_houses.tex", "tab:qr_houses",830                       "Amenity coefficients by quantile --- single-family houses")831    table_qr_amenities(D, "Condos", "qr_condos.tex", "tab:qr_condos",832                       "Amenity coefficients by quantile --- condominiums")833    table_qr_amenities(D, "Plex", "qr_plex.tex", "tab:qr_plex",834                       "Amenity coefficients by quantile --- multiplexes")835    table_qr_amenities(D, "Land", "qr_land.tex", "tab:qr_land",836                       "Amenity coefficients by quantile --- vacant land")837    table_structural_houses(D)838    table_pseudo_r2(D)839    table_wald(D)840    table_wald_houses(D)841    table_sqr(D)842    table_moran_resid(D)843    table_implicit_prices(D)844    table_effects(D)845846    fig_coefficients(D)847    fig_implicit_prices(D)848    fig_ols_qr_sqr(D)849    fig_pseudo_r2(D)850    fig_wald_heatmap(D)851    for f in FIG.glob("fig_*.png"):852        shutil.copy(f, PFIG / f.name)853    print("  figures ->", FIG, "and", PFIG)854855    # machine-readable dump (tuple keys -> strings)856    def clean(o):857        if isinstance(o, dict):858            return {(k if isinstance(k, str) else ("_".join(map(str, k)) if isinstance(k, tuple) else str(k))): clean(v) for k, v in o.items()}859        if isinstance(o, list):860            return [clean(v) for v in o]861        return o862    P = reference_prices(D["Houses"])863    dump = clean(D)864    dump["Houses"]["reference_prices"] = {str(t): P[t] for t in TAUS}865    for s in SEGS:866        d = D[s]867        dump[s]["implied_first_stage_F"] = implied_F(d["first_stage_r2"], d["n"], 2 * d["k"])868    (ROOT / "results" / "log_parsed.json").write_text(json.dumps(dump, indent=1, ensure_ascii=False))869    print("  wrote results/log_parsed.json")870871872if __name__ == "__main__":873    main()874
Files main
Menu

Theme