#!/usr/bin/env python3 # Author: Simon-Pierre Boucher — contact@spboucher.ai """Step 05 — Generate every LaTeX table used in the paper (13 files). Tables are built from the results tier selected with ``--results``. Since the October 2026 revision the default is ``reproduced`` (the fully reproducible pipeline with FSA-derived provinces); ``reference`` re-creates the six tables of the May 2026 version from the archived original outputs. Usage: python scripts/05_make_tables.py [--results reproduced|reference] """ import argparse import json import sys from pathlib import Path import numpy as np import pandas as pd sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src")) from wp9 import sample # noqa: E402 from wp9.config import REFERENCE, REPRODUCED, TABLES, ensure_dirs # noqa: E402 SUMMARY_VARS = [("price_cad", "List price (CAD)", "{:,.0f}"), ("ppm2", "Price per m$^2$ (CAD)", "{:,.0f}"), ("living_m2", "Living area (m$^2$)", "{:,.1f}"), ("bedrooms", "Bedrooms", "{:.2f}"), ("bathrooms", "Full bathrooms", "{:.2f}"), ("half_baths", "Half bathrooms", "{:.2f}"), ("parking_n", "Parking spaces", "{:.2f}"), ("stories_n", "Storeys", "{:.2f}"), ("lot_m2_f", "Lot area (m$^2$)", "{:,.0f}")] COEF_ORDER = [("ln_living", "$\\ln$ living area"), ("bathrooms", "Full bathrooms"), ("half_baths", "Half bathrooms"), ("bedrooms", "Bedrooms"), ("parking_n", "Parking spaces"), ("stories_n", "Storeys"), ("has_lot", "Has lot info"), ("ln_lot", "$\\ln(1+$lot m$^2)$")] def write(name: str, content: str) -> None: (TABLES / name).write_text(content + "\n") print(" tab", name) def stars(p: float) -> str: return "$^{***}$" if p < 0.01 else "$^{**}$" if p < 0.05 else "$^{*}$" if p < 0.1 else "" def cell(coefs: pd.DataFrame, key: str) -> str: if key not in coefs.index: return "" b, se, p = coefs.loc[key, ["coef", "se", "p"]] return f"\\makecell{{{b:.3f}{stars(p)}\\\\\\scriptsize({se:.3f})}}" # -------------------------------------------------------------------------- def table_summary_stats(res_dir: Path) -> None: stats_file = res_dir / "summary_stats.csv" if stats_file.exists(): stats = pd.read_csv(stats_file, index_col=0) n = int(stats.attrs.get("n", 0)) or int(stats["n"].iloc[0]) else: # reproduced tier: compute from the micro sample s = sample.load_sample() rows = {} for var, _, _ in SUMMARY_VARS: col = s[var] rows[var] = {"mean": col.mean(), "sd": col.std(), "p25": col.quantile(0.25), "median": col.median(), "p75": col.quantile(0.75), "n": len(s)} stats = pd.DataFrame(rows).T stats.to_csv(res_dir / "summary_stats.csv") n = len(s) lines = [] for var, label, fmt in SUMMARY_VARS: r = stats.loc[var] lines.append(f"{label} & {fmt.format(r['mean'])} & {fmt.format(r['sd'])} & " f"{fmt.format(r['p25'])} & {fmt.format(r['median'])} & " f"{fmt.format(r['p75'])} \\\\") write("summary_stats.tex", "\\begin{table}[htbp]\\centering\n\\caption{Descriptive statistics}\n" "\\label{tab:summary_stats}\n\\begin{threeparttable}\n" "\\begin{tabular}{lccccc}\n\\toprule\n" "Variable & Mean & SD & P25 & Median & P75 \\\\\n\\midrule\n" + "\n".join(lines) + "\n\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\\footnotesize\\item " f"Notes: Estimation sample of {n:,} residential dwellings (houses, " "condominiums, plexes, townhouses and apartments) from the Canadian MLS, " "after parsing and trimming the extreme 1\\% tails of price and living area.\n" "\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}") # -------------------------------------------------------------------------- def table_regression(res_dir: Path) -> None: fit = json.load(open(res_dir / "fit.json")) n_fe = int(fit["M5"].get("n_fe", 1153)) coefs = {m: pd.read_csv(res_dir / f"coef_{m}.csv", index_col=0) for m in ("M1", "M2", "M3", "M5")} lines = [label + " & " + " & ".join(cell(coefs[m], key) for m in ("M1", "M2", "M3", "M5")) + " \\\\" for key, label in COEF_ORDER] footer = ["\\midrule", "Dwelling-type FE & No & Yes & Yes & Yes \\\\", "Ownership FE & No & Yes & Yes & Yes \\\\", "Province FE & No & No & Yes & --- \\\\", "FSA fixed effects & No & No & No & Yes \\\\", f"$R^2$ & {fit['M1']['r2']:.3f} & {fit['M2']['r2']:.3f} & " f"{fit['M3']['r2']:.3f} & {fit['M5']['r2']:.3f} \\\\", f"Observations & {fit['M1']['n']:,} & {fit['M2']['n']:,} & " f"{fit['M3']['n']:,} & {fit['M5']['n']:,} \\\\"] write("regression.tex", "\\begin{table}[htbp]\\centering\n\\caption{Hedonic regression estimates}\n" "\\label{tab:regression}\n\\begin{threeparttable}\n" "\\begin{tabular}{lcccc}\n\\toprule\n" " & (1) & (2) & (3) & (4) \\\\\n" " & Structural & +Type/Own. & +Province & Grand+FSA \\\\\n\\midrule\n" + "\n".join(lines + footer) + "\n\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\\footnotesize\\item " "Notes: Dependent variable is $\\ln(\\text{list price})$. Columns (1)--(3) use the " "house subsample; column (4) is the grand model over all residential dwellings " f"with {n_fe:,} absorbed FSA fixed effects (incl. nine province-level residual " "categories pooling FSAs with fewer than 25 listings). Columns (2)--(4) also include " "dwelling-type, ownership and listing-category dummies (Table~\\ref{tab:type_effects}). " "Cluster-robust standard errors (by FSA) in parentheses. " "$^{*}p<0.1$, $^{**}p<0.05$, $^{***}p<0.01$.\n" "\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}") # -------------------------------------------------------------------------- def table_robustness(res_dir: Path) -> None: rob = pd.read_csv(res_dir / "robustness.csv") lines = [] for _, r in rob.iterrows(): lines.append( f"{r['label']} & {r['n']:,.0f} & {r['r2']:.3f} & " f"\\makecell{{{r['ln_living']:.3f}\\\\\\scriptsize({r['se_living']:.3f})}} & " f"\\makecell{{{r['bathrooms']:.3f}\\\\\\scriptsize({r['se_bath']:.3f})}} & " f"\\makecell{{{r['ln_lot']:.3f}\\\\\\scriptsize({r['se_lot']:.3f})}} \\\\") write("robustness.tex", "\\begin{table}[htbp]\\centering\n" "\\caption{Robustness of key implicit prices across samples}\n" "\\label{tab:robustness}\n\\begin{threeparttable}\n" "\\begin{tabular}{lccccc}\n\\toprule\n" "Sample / specification & $N$ & $R^2$ & $\\ln$ area & Full bath & $\\ln$ lot \\\\\n" "\\midrule\n" + "\n".join(lines) + "\n\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\\footnotesize\\item " "Notes: Each row re-estimates the grand FSA-fixed-effects model on a different " "sample. Cluster-robust (FSA) standard errors in parentheses. The last two rows " "cap storeys and parking counts at their 99th percentiles and drop the " "province-level categories that pool FSAs with fewer than 25 listings.\n" "\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}") # -------------------------------------------------------------------------- def table_quantile(res_dir: Path) -> None: q = pd.read_csv(res_dir / "quantile.csv") taus = q[q["tau"].notna()] ols = q[q["tau"].isna()].iloc[0] lines = [] for _, r in taus.iterrows(): tau = f"{r['tau']:g}" lines.append( f"$\\tau={tau}$ & " f"\\makecell{{{r['ln_living']:.3f}\\\\\\scriptsize({r['se_living']:.3f})}} & " f"\\makecell{{{r['bathrooms']:.3f}\\\\\\scriptsize({r['se_bath']:.3f})}} & " f"\\makecell{{{r['ln_lot']:.3f}\\\\\\scriptsize({r['se_lot']:.3f})}} \\\\") write("quantile.tex", "\\begin{table}[htbp]\\centering" "\\caption{Quantile hedonic estimates across the price distribution}\n" "\\label{tab:quantile}\\begin{threeparttable}\\begin{tabular}{lccc}\n\\toprule\n" "Quantile & $\\ln$ area & Full bath & $\\ln$ lot \\\\\n\\midrule\n" + "\n".join(lines) + "\n\\midrule\nOLS & " f"{ols['ln_living']:.3f} & {ols['bathrooms']:.3f} & {ols['ln_lot']:.3f} \\\\\n" "\\bottomrule\\end{tabular}\\begin{tablenotes}\\footnotesize\\item Notes: House " "subsample, province fixed effects (province derived from the FSA), structural " "controls and ownership dummies. Kernel-based heteroskedasticity-robust standard " "errors (Epanechnikov kernel, Hall--Sheather bandwidth) in parentheses; the OLS row " "reports HC1 standard errors.\\end{tablenotes}\\end{threeparttable}\\end{table}") # -------------------------------------------------------------------------- def table_lopo(res_dir: Path) -> None: lopo = pd.read_csv(res_dir / "lopo.csv") lines = [f"{r['prov']} & {r['n']:,.0f} & {r['r2_within']:.3f} \\\\" for _, r in lopo.iterrows()] write("lopo.tex", "\\begin{table}[htbp]\\centering" "\\caption{Leave-one-province-out spatial cross-validation}\n" "\\label{tab:lopo}\\begin{threeparttable}\\begin{tabular}{lcc}\n\\toprule\n" "Held-out province & $N$ & Within-province $R^2$ \\\\\n\\midrule\n" + "\n".join(lines) + f"\n\\midrule\nMean & --- & {lopo['r2_within'].mean():.3f} \\\\\n" "\\bottomrule\\end{tabular}\\begin{tablenotes}\\footnotesize\\item Notes: The " "structural hedonic model is estimated on all provinces except one and used to " "predict the held-out province; a province-specific intercept is allowed (the " "price \\emph{level} is not identified out of sample), so the metric captures " "whether the \\emph{structural} implicit prices transfer across space." "\\end{tablenotes}\\end{threeparttable}\\end{table}") # -------------------------------------------------------------------------- def table_oos(res_dir: Path) -> None: oos = json.load(open(res_dir / "oos.json")) write("oos.tex", "\\begin{table}[htbp]\\centering\n" "\\caption{Out-of-sample valuation performance (80/20 split)}\n" "\\label{tab:oos}\n\\begin{threeparttable}\n\\begin{tabular}{lc}\n\\toprule\n" "Metric & Value \\\\\n\\midrule\n" f"Training listings & {oos['n_train']:,} \\\\\n" f"Test listings & {oos['n_test']:,} \\\\\n" f"Out-of-sample $R^2$ (log price) & {oos['oos_r2']:.3f} \\\\\n" f"RMSE (log points) & {oos['rmse_log']:.3f} \\\\\n" f"Median absolute \\% error & {oos['median_ape']:.1f}\\% \\\\\n" f"Mean absolute \\% error & {oos['mean_ape']:.1f}\\% \\\\\n" f"Share priced within $\\pm$10\\% & {oos['within10']:.1f}\\% \\\\\n" f"Share priced within $\\pm$20\\% & {oos['within20']:.1f}\\% \\\\\n" "\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\\footnotesize\\item Notes: " "Model trained on a random 80\\% of listings and scored on the held-out 20\\% " "(restricted to neighbourhoods observed in training). Prices back-transformed " "with Duan's smearing estimator. Table~\\ref{tab:spatial_holdout} reports " "repeated splits and spatial (FSA-level) holdouts.\n" "\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}") # ========================================================================== # Tables added in the October 2026 revision (reproduced tier only) # ========================================================================== def _pct(b): return f"{(np.exp(b) - 1) * 100:+.1f}" def table_shapley(res_dir: Path) -> None: sh = pd.read_csv(res_dir / "shapley.csv") lines = [] for sample_label, g in sh.groupby("sample", sort=False): lines.append(f"\\multicolumn{{4}}{{l}}{{\\emph{{{sample_label}}} " f"($N={int(g['n'].iloc[0]):,}$, $R^2={g['total_r2'].iloc[0]:.3f}$)}} \\\\") for _, r in g.iterrows(): owen = "---" if pd.isna(r["owen"]) else f"{r['owen'] * 100:.1f}" if r["block"] == "Neighbourhood (FSA)": owen = f"{r['owen'] * 100:.1f}\\tnote{{a}}" lines.append(f"\\quad {r['block']} & {r['sequential'] * 100:.1f} & " f"{r['shapley'] * 100:.1f} & {owen} \\\\") lines.append("\\addlinespace") write("shapley.tex", "\\begin{table}[htbp]\\centering\n" "\\caption{Decomposition of the explained variance of log list prices " "(percentage points of $R^2$)}\n\\label{tab:shapley}\n\\begin{threeparttable}\n" "\\begin{tabular}{lccc}\n\\toprule\n" "Block & Sequential & Shapley & Owen (grouped) \\\\\n\\midrule\n" + "\n".join(lines) + "\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\\footnotesize\n" "\\item Notes: \\emph{Sequential} is the increment in $R^2$ when the block is " "added in the order structure $\\to$ type/ownership $\\to$ province $\\to$ FSA. " "\\emph{Shapley} averages the increment over all $4!$ orderings of the four blocks " "\\citep{israeli2007shapley,gromping2007estimators}. \\emph{Owen} treats province and " "FSA as a single location group and averages over the $3!$ orderings of the three " "groups \\citep{huettner2012axiomatic}. Province dummies are nested in the FSA effects, " "so the province block adds nothing once FSA effects are present.\n" "\\item[a] Location group (province $+$ FSA).\n" "\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}") def table_se_comparison(res_dir: Path) -> None: se = pd.read_csv(res_dir / "se_comparison.csv") labels = {"ln_living": "$\\ln$ living area", "bathrooms": "Full bathrooms", "half_baths": "Half bathrooms", "bedrooms": "Bedrooms", "ln_lot": "$\\ln(1+$lot m$^2)$"} lines = [] for _, r in se.iterrows(): lines.append(f"{labels[r['variable']]} & {r['coef']:.3f} & {r['se_hc1']:.4f} & " f"{r['se_fsa']:.4f} & {r['se_prov']:.4f} & {r['se_twoway']:.4f} & " f"{r['p_wild_prov']:.3f} \\\\") g_fsa, g_prov = int(se["n_fsa_clusters"].iloc[0]), int(se["n_prov_clusters"].iloc[0]) write("se_comparison.tex", "\\begin{table}[htbp]\\centering\n" "\\caption{Grand-model coefficients under alternative variance estimators}\n" "\\label{tab:se_comparison}\n\\begin{threeparttable}\\small\n" "\\begin{tabular}{lcccccc}\n\\toprule\n" " & & \\multicolumn{4}{c}{Standard error} & Wild-cluster \\\\\n" "\\cmidrule(lr){3-6}\n" f" & Coef. & HC1 & \\makecell{{FSA\\\\($G={g_fsa:,}$)}} & \\makecell{{Province\\\\($G={g_prov}$)}} & Two-way & " "$p$-value \\\\\n\\midrule\n" + "\n".join(lines) + "\n\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\\footnotesize\\item Notes: " "Grand model (M5) estimated on the FSA-demeaned data. HC1 is the " "heteroskedasticity-robust estimator; FSA and province cluster by neighbourhood " "and by province; two-way clusters by both. The last column is the $p$-value of a " "restricted wild-cluster bootstrap-$t$ test at the province level with Rademacher " "weights and full enumeration of the $2^{9}=512$ sign vectors " "\\citep{cameron2015practitioner,mackinnon2017wild}; its smallest attainable value " "is $2/512=0.004$.\n\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}") def table_spline(res_dir: Path) -> None: sp = pd.read_csv(res_dir / "spline.csv") lines = [f"{int(r['segment'])} & {r['lo_m2']:.0f}--{r['hi_m2']:.0f} & " f"\\makecell{{{r['elasticity']:.3f}\\\\\\scriptsize({r['se']:.3f})}} \\\\" for _, r in sp.iterrows()] r0 = sp.iloc[0] write("spline.tex", "\\begin{table}[htbp]\\centering\n" "\\caption{Living-area elasticity by size segment (piecewise-linear spline, grand model)}\n" "\\label{tab:spline}\n\\begin{threeparttable}\n" "\\begin{tabular}{lcc}\n\\toprule\n" "Segment & Living area (m$^2$) & Elasticity \\\\\n\\midrule\n" + "\n".join(lines) + f"\n\\midrule\n$R^2$: linear / quadratic / spline & \\multicolumn{{2}}{{c}}{{{r0['r2_linear']:.4f} / " f"{r0['r2_quadratic']:.4f} / {r0['r2_spline']:.4f}}} \\\\\n" "\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\\footnotesize\\item Notes: " "Linear spline in $\\ln(\\text{area})$ with knots at the quintiles of living area, " "all other grand-model controls and FSA fixed effects included. Each entry is the " "elasticity of price with respect to area within the segment; FSA-clustered standard " "errors in parentheses.\n\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}") def table_spatial_holdout(res_dir: Path) -> None: sh = json.load(open(res_dir / "spatial_holdout.json")) rm, rs = sh["random_mean"], sh["random_sd"] pm, ps = sh["fsa_holdout_mean_prov_mean"], sh["fsa_holdout_sd_prov_mean"] nm, ns = sh["fsa_holdout_mean_nn_idw"], sh["fsa_holdout_sd_nn_idw"] def c(m, s_, key, fmt): return f"{fmt.format(m[key])} \\scriptsize({fmt.format(s_[key])})" rows = [("Out-of-sample $R^2$ (log price)", "oos_r2", "{:.3f}"), ("RMSE (log points)", "rmse_log", "{:.3f}"), ("Median absolute \\% error", "median_ape", "{:.1f}"), ("Mean absolute \\% error (top 1\\% trimmed)", "mean_ape_trim", "{:.1f}"), ("Share within $\\pm$10\\%", "within10", "{:.1f}"), ("Share within $\\pm$20\\%", "within20", "{:.1f}")] lines = [f"{lab} & {c(rm, rs, k, f)} & {c(pm, ps, k, f)} & {c(nm, ns, k, f)} \\\\" for lab, k, f in rows] n_held = sh["fsa_holdout"][0]["n_fsa_held"] write("spatial_holdout.tex", "\\begin{table}[htbp]\\centering\n" "\\caption{Random versus spatial holdouts: valuation accuracy}\n" "\\label{tab:spatial_holdout}\n\\begin{threeparttable}\\small\n" "\\begin{tabular}{lccc}\n\\toprule\n" " & Random 80/20 & \\multicolumn{2}{c}{Held-out FSAs (20\\%)} \\\\\n" "\\cmidrule(lr){3-4}\n" "Metric & \\makecell{(within\\\\support)} & \\makecell{Province-mean\\\\effect} & \\makecell{IDW of 5\\\\nearest FSAs} \\\\\n\\midrule\n" + "\n".join(lines) + "\n\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\\footnotesize\\item Notes: " "Means over five replications, standard deviations across replications in " "parentheses. Column~1: random 80/20 splits of listings, evaluation restricted to " "FSAs observed in training. Columns~2--3: 20\\% of the FSAs (" f"{n_held}" " of the " "non-pooled neighbourhoods) are held out entirely; their listings are valued with the " "structural coefficients from the training FSAs and a neighbourhood effect imputed " "either as the mean effect of the training FSAs in the same province or as the " "inverse-distance-weighted mean of the five nearest training FSAs (centroid " "distance). Prices back-transformed with Duan's smearing estimator. The trimmed mean " "excludes the largest 1\\% of errors in each replication: a few listings with " "implausible parking or storey counts (up to 3{,}620 spaces) otherwise dominate " "the untrimmed mean.\n" "\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}") def table_moran_sensitivity(res_dir: Path) -> None: ms = pd.read_csv(res_dir / "moran_sensitivity.csv") seeds = sorted(ms["seed"].unique()) lines = [] for k in sorted(ms["k"].unique()): cells = [] for seed in seeds: for model in ("structure_only", "grand_model"): r = ms[(ms["k"] == k) & (ms["seed"] == seed) & (ms["model"] == model)].iloc[0] cells.append(f"{r['I']:.3f} \\scriptsize($z={r['z']:.0f}$)") lines.append(f"$k={k}$ & " + " & ".join(cells) + " \\\\") write("moran_sensitivity.tex", "\\begin{table}[htbp]\\centering\n" "\\caption{Moran's $I$ of residuals: sensitivity to the weight matrix and subsample}\n" "\\label{tab:moran_sensitivity}\n\\begin{threeparttable}\n" "\\begin{tabular}{lcccc}\n\\toprule\n" " & \\multicolumn{2}{c}{Subsample A} & \\multicolumn{2}{c}{Subsample B} \\\\\n" "\\cmidrule(lr){2-3}\\cmidrule(lr){4-5}\n" "Neighbours & Structure only & Grand model & Structure only & Grand model \\\\\n\\midrule\n" + "\n".join(lines) + "\n\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\\footnotesize\\item Notes: " "Moran's $I$ with row-standardised $k$-nearest-neighbour weights (great-circle " "distance) on two independent random subsamples of 15{,}000 listings. $z$-scores " "from 199 random permutations; every permutation $p$-value equals its minimum " "attainable value of $1/200=0.005$. ``Structure only'' is the residual of the " "model with structural, type and ownership controls but no location effects.\n" "\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}") def table_type_effects(res_dir: Path) -> None: coefs = pd.read_csv(res_dir / "coef_M5.csv", index_col=0) groups = [("Dwelling type (ref.: apartment)", "bt_", {"House": "House", "Row/Townhouse": "Row / townhouse", "Duplex": "Duplex", "Triplex": "Triplex", "Fourplex": "Fourplex", "Manufactured": "Manufactured home", "Other": "Other"}), ("Ownership (ref.: co-op / co-ownership)", "ow_", {"Freehold": "Freehold", "Condo/Strata": "Condominium / strata", "Leasehold": "Leasehold", "Unknown": "Not reported", "Other": "Other"})] lines = [] for title, pfx, labels in groups: lines.append(f"\\multicolumn{{4}}{{l}}{{\\emph{{{title}}}}} \\\\") for key, lab in labels.items(): name = pfx + key if name not in coefs.index: continue b, se, p = coefs.loc[name, ["coef", "se", "p"]] kennedy = (np.exp(b - 0.5 * se ** 2) - 1) * 100 lines.append(f"\\quad {lab} & {b:.3f}{stars(p)} & ({se:.3f}) & {kennedy:+.1f} \\\\") lines.append("\\addlinespace") write("type_effects.tex", "\\begin{table}[htbp]\\centering\n" "\\caption{Dwelling-type and ownership effects in the grand model}\n" "\\label{tab:type_effects}\n\\begin{threeparttable}\n" "\\begin{tabular}{lccc}\n\\toprule\n" " & Coefficient & SE & \\% effect \\\\\n\\midrule\n" + "\n".join(lines) + "\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\\footnotesize\\item Notes: " "Grand model (M5), all residential dwellings, FSA fixed effects absorbed, " "FSA-clustered standard errors. The percentage effect is the \\citet{kennedy1981estimation} " "estimator $100\\,[\\exp(\\hat\\gamma-\\tfrac{1}{2}\\widehat{V}(\\hat\\gamma))-1]$, " "which corrects the \\citet{halvorsen1980interpretation} transformation for " "estimation error. Effects are relative to the omitted category and conditional " "on living area, the other structural attributes and the neighbourhood. " "$^{*}p<0.1$, $^{**}p<0.05$, $^{***}p<0.01$.\n" "\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}") def table_gradient(res_dir: Path) -> None: g = json.load(open(res_dir / "gradient_metro.json")) bins = pd.read_csv(res_dir / "gradient_bins.csv") edges = [0, 5, 10, 20, 40, 80, 160, 320] blines = [] for i, r in bins.iterrows(): lab = f"{edges[i]}--{edges[i + 1]}" if i + 1 < len(edges) else f"$>${edges[-1]}" blines.append(f"\\quad {lab} km & {int(r['n']):,} & {r['x']:.0f} & {(np.exp(r['prem']) - 1) * 100:+.1f} \\\\") p, m, q = g["pooled"], g["metro_fe"], g["quadratic"] write("gradient.tex", "\\begin{table}[htbp]\\centering\n" "\\caption{The urban price gradient: location premium and distance to the nearest metro}\n" "\\label{tab:gradient}\n\\begin{threeparttable}\n" "\\begin{tabular}{lccc}\n\\toprule\n" "\\multicolumn{4}{l}{\\emph{Panel A: mean location premium by distance band}} \\\\\n" "Distance band & Listings & Median km & Premium (\\%) \\\\\n\\midrule\n" + "\n".join(blines) + "\n\\midrule\n\\multicolumn{4}{l}{\\emph{Panel B: regressions of the location premium on $\\ln(\\text{distance})$}} \\\\\n" " & Slope & SE & $R^2$ \\\\\n\\midrule\n" f"\\quad Pooled & {p['beta']:.4f} & ({p['se_fsa']:.4f}) & {p['r2']:.3f} \\\\\n" f"\\quad Nearest-metro intercepts & {m['beta']:.4f} & ({m['se_fsa']:.4f}) & {m['r2']:.3f} \\\\\n" f"\\quad Quadratic: $\\ln d$ & {q['b1']:.4f} & ({q['se1']:.4f}) & \\multirow{{2}}{{*}}{{{q['r2']:.3f}}} \\\\\n" f"\\quad \\phantom{{Quadratic:}} $(\\ln d)^2$ & {q['b2']:.4f} & ({q['se2']:.4f}) & \\\\\n" "\\bottomrule\n\\end{tabular}\n\\begin{tablenotes}\\footnotesize\\item Notes: " "The location premium is the residual of the model with structural, type and " "ownership controls but no location effects; the premium in Panel~A is " "$100\\,(e^{\\bar{u}}-1)$ for the band mean $\\bar{u}$. Distance is the great-circle " "distance to the nearest of nine metropolitan centres (Toronto, Montreal, Vancouver, " "Calgary, Ottawa--Gatineau, Edmonton, Winnipeg, Quebec City, Halifax); listings within " "0.5~km of a centre are excluded from Panel~B. FSA-clustered standard errors.\n" "\\end{tablenotes}\n\\end{threeparttable}\n\\end{table}") def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--results", choices=["reference", "reproduced"], default="reproduced", help="results tier (default: reproduced — current pipeline)") args = parser.parse_args() res_dir = REFERENCE if args.results == "reference" else REPRODUCED ensure_dirs() table_summary_stats(res_dir) table_regression(res_dir) table_robustness(res_dir) table_quantile(res_dir) table_lopo(res_dir) table_oos(res_dir) if args.results == "reproduced": table_shapley(res_dir) table_se_comparison(res_dir) table_spline(res_dir) table_spatial_holdout(res_dir) table_moran_sensitivity(res_dir) table_type_effects(res_dir) table_gradient(res_dir) print("all tables written to", TABLES) if __name__ == "__main__": main()