ShawnChamberlain's picture
Publish Mortgage Rate Lock-In research package
d8c288c verified
Raw
History Blame Contribute Delete
101 kB
"""Report generation.
Every file written here begins with a ``GENERATED`` header and must not be
hand-edited. Reports are built **only** from result artifacts in ``outputs/``, so
every number in a report is traceable to a reproducible artifact with provenance.
Two hard rules, enforced in code with no override flag:
1. If any input artifact has ``data_class == "SYNTHETIC"``, the synthetic banner is
rendered. :func:`_assert_banner` raises otherwise.
2. Causal language is only emitted for artifacts whose ``evidence_tier`` is
``quasi_experimental`` **and** whose pre-trend test passed. Everything else gets
"is associated with" / "under the model". :func:`verb_for` is the single place
that decision is made.
"""
from __future__ import annotations
from datetime import UTC, datetime
from pathlib import Path
from typing import Any
import polars as pl
from lockin.artifacts import list_artifacts, try_read_artifact
from lockin.config import Config
SYNTHETIC_BANNER = """> ⚠️ **SYNTHETIC DATA.** The loan-level numbers in this report were computed from
> synthetic fixtures generated for engineering tests (`lockin.fixtures`, seed
> recorded in the manifest). They are **not** empirical findings about U.S.
> mortgages — they recover the parameters of this repository's own
> data-generating process. The public aggregate series in this report (Freddie Mac
> PMMS, FHFA HPI, HMDA, Census Building Permits Survey) **are** real.
>
> To produce empirical loan-level results, complete the registration in
> `data/DATA_ACCESS.md` §R1 and re-run. See `AGENTS.md` §1 and
> `data/LICENSE_AND_REDISTRIBUTION.md` §4."""
ATTRIBUTION = """**Data sources.** Freddie Mac Single-Family Loan-Level Dataset (registered; subject
to Freddie Mac terms of use; not redistributed here) — or labeled synthetic fixtures
where indicated. Freddie Mac Primary Mortgage Market Survey. Federal Housing Finance
Agency House Price Index. Home Mortgage Disclosure Act data via the Consumer
Financial Protection Bureau Data Browser. U.S. Census Bureau Building Permits Survey.
Retrieval timestamps and file checksums are recorded in the manifests accompanying
each result artifact."""
VOCAB_NOTE = """**Outcome vocabulary.** `prepayment` means Freddie Mac Zero Balance Code 01,
*"Prepaid or Matured (Voluntary Payoff)"*. It conflates voluntary payoff with
scheduled maturity and does **not** distinguish a refinance from a sale-related
payoff. It is **not** a home sale and **not** a household move. No field in the
source data supports either of those events, and this project never constructs one."""
def verb_for(art: dict[str, Any] | None) -> str:
"""The only permitted verb phrase for an artifact, given its tier and diagnostics."""
if art is None:
return "could not be estimated"
tier = art.get("evidence_tier")
if tier == "simulation":
return "under the model, changes"
if tier == "quasi_experimental":
es = art.get("result", {}).get("event_study", {})
pt = es.get("pretrend_test", {}) if isinstance(es, dict) else {}
if pt.get("passes_at_alpha_0.10"):
return "reduced" if _post_sign(art) < 0 else "increased"
return "is associated with a change in"
if tier == "hazard_association":
return "is associated with"
return "describes"
def _post_sign(art: dict[str, Any]) -> float:
es = art.get("result", {}).get("event_study", {})
v = es.get("mean_post_effect") if isinstance(es, dict) else None
return -1.0 if (v is not None and v < 0) else 1.0
def _fmt(x: Any, nd: int = 4) -> str:
if x is None:
return "—"
if isinstance(x, bool):
return "yes" if x else "no"
if isinstance(x, (int,)):
return f"{x:,}"
if isinstance(x, float):
if x != x:
return "—"
return f"{x:,.{nd}f}"
return str(x)
class ReportContext:
"""Collects the artifacts a report needs and tracks whether any input is synthetic."""
def __init__(self, cfg: Config) -> None:
self.cfg = cfg
self.used: list[dict[str, Any]] = []
self.any_synthetic = False
def get(self, group: str, name: str) -> dict[str, Any] | None:
art = try_read_artifact(self.cfg, group, name)
if art is not None:
self.used.append(art)
if art["provenance"]["data_class"] == "SYNTHETIC":
self.any_synthetic = True
return art
def header(self, title: str, subtitle: str) -> str:
ts = datetime.now(UTC).isoformat(timespec="seconds")
prov = self.used[0]["provenance"] if self.used else {}
lines = [
f"# {title}",
"",
"<!-- GENERATED by `make report` (lockin.reporting.render). DO NOT HAND-EDIT. -->",
"",
f"*{subtitle}*",
"",
"| | |",
"|---|---|",
f"| Generated | `{ts}` |",
f"| Git commit | `{prov.get('git_commit', 'unknown')}` |",
f"| Config | `{prov.get('config_name', '?')}` (digest `{prov.get('config_digest', '?')}`) |",
f"| Data class | **{prov.get('data_class', '?')}** |",
f"| Data period | `{prov.get('data_period', '?')}` |",
f"| Artifacts used | {len(self.used)} |",
"",
]
if self.any_synthetic:
lines += [SYNTHETIC_BANNER, ""]
return "\n".join(lines)
def sources_table(self) -> str:
prov = self.used[0]["provenance"] if self.used else {}
sv = prov.get("source_versions", {})
if not sv:
return ""
rows = [
"",
"### Source versions",
"",
"| dataset | schema@retrieved#checksum |",
"|---|---|",
]
for k, v in sorted(sv.items()):
rows.append(f"| `{k}` | `{v}` |")
return "\n".join(rows) + "\n"
def artifact_index(self) -> str:
rows = [
"",
"### Artifacts this report was built from",
"",
"| artifact | tier | population | weight |",
"|---|---|---|---|",
]
for a in self.used:
rows.append(
f"| `{a['group']}/{a['artifact']}` | `{a['evidence_tier']}` | "
f"{a['population'][:70]}… | {a['weight'][:40]} |"
)
return "\n".join(rows) + "\n"
def _assert_banner(ctx: ReportContext, text: str) -> None:
"""Refuse to write a report that consumed synthetic data without the banner."""
if ctx.any_synthetic and "SYNTHETIC DATA" not in text:
raise RuntimeError(
"a report consumed SYNTHETIC artifacts but does not render the synthetic "
"banner. There is no flag to disable this check."
)
def _write(cfg: Config, name: str, ctx: ReportContext, body: str) -> Path:
text = (
ctx.header(*_TITLES[name])
+ body
+ "\n"
+ ctx.artifact_index()
+ ctx.sources_table()
+ "\n---\n\n"
+ ATTRIBUTION
+ "\n"
)
_assert_banner(ctx, text)
out = cfg.path("reports", f"{name}.md")
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(text)
return out
_TITLES: dict[str, tuple[str, str]] = {
"technical_report": (
"Technical Report: Mortgage Rate Lock-In, Housing Liquidity, and Local Market Dynamics",
"Full technical synthesis. Every section states its evidence tier.",
),
"executive_housing_policy_memo": (
"Executive Memo: Mortgage Rate Lock-In",
"For a policy audience. Answers ten questions and states what is not known.",
),
"loan_hazard_analysis": (
"Loan-Level Duration Analysis",
"Kaplan–Meier, cumulative incidence, discrete-time hazards, competing risks, Cox, "
"and a predictive benchmark. Tier: descriptive and hazard-association only.",
),
"local_market_event_study": (
"Local-Market Event Study",
"Continuous-treatment event study on predetermined lock-in exposure, with "
"pre-trends and placebos.",
),
"demand_supply_decomposition": (
"Demand versus Supply Decomposition",
"Why lock-in reduces transactions unambiguously but has an ambiguous price effect.",
),
"policy_counterfactuals": (
"Policy Counterfactuals",
"Model-dependent scenario projections. Not forecasts.",
),
"methodology_and_limitations": (
"Methodology and Limitations",
"What was built, what the data can and cannot support, and where the design fails.",
),
"failed_hypotheses": (
"Failed and Fragile Specifications",
"Specifications that did not survive. Recorded, not buried.",
),
"replication_protocol": (
"Replication Protocol",
"How to reproduce every number, and what cannot be reproduced without registered data.",
),
"benchmark_comparison": (
"Benchmark Comparison",
"Our estimands against published lock-in research. Nothing here is an exact replication.",
),
}
# ---------------------------------------------------------------------------
# individual reports
# ---------------------------------------------------------------------------
def render_loan_hazard(cfg: Config) -> Path:
ctx = ReportContext(cfg)
ds = ctx.get("hazards", "survival_dataset")
km = ctx.get("hazards", "km_prepayment")
cif = ctx.get("hazards", "cif_competing_risks")
logit = ctx.get("hazards", "dt_logit_prepayment")
cloglog = ctx.get("hazards", "dt_cloglog_prepayment")
credit = ctx.get("hazards", "dt_logit_credit_event")
base = ctx.get("hazards", "baseline_hazard")
gap = ctx.get("hazards", "gap_profile_nonlinear")
het = ctx.get("hazards", "heterogeneity")
cox = ctx.get("hazards", "cox_ph_prepayment")
gbm = ctx.get("hazards", "predictive_benchmark")
b: list[str] = [VOCAB_NOTE, ""]
b += ["## 1. Population and event construction", ""]
if ds:
r = ds["result"]
ll = r["loan_level"]
b += [
f"- **{_fmt(ll['n_loans'])}** loans; "
f"**{_fmt(ll['n_prepayments'])}** prepayments, "
f"**{_fmt(ll['n_credit_events'])}** credit events, "
f"**{_fmt(ll['n_censored'])}** censored.",
f"- **{_fmt(ll['n_left_truncated'])}** loans are left truncated "
f"(median entry loan age {_fmt(ll['median_entry_age'], 1)} months). Risk sets "
"exclude loans not yet observed at each age.",
f"- Estimation sample: {_fmt(r['estimation_sample']['n_rows'])} loan-months over "
f"`{r['estimation_sample']['period']}`; out-of-time sample "
f"{_fmt(r['out_of_time_sample']['n_rows'])} loan-months over "
f"`{r['out_of_time_sample']['period']}` (split at "
f"`{r['out_of_time_split']}`).",
f"- Sampling design: `{r['estimation_sample']['sampling_design']['scheme']}`.",
"",
"**Event taxonomy** (from the official Zero Balance Code priority table):",
"",
"| class | codes | treatment |",
"|---|---|---|",
"| `prepayment` | 01 | event — pools refinance, sale-related payoff, and maturity |",
"| `credit_event` | 02, 03, 09 | competing event |",
"| `censored` | none, or 15, 16, 96 | right censoring — 15/16/96 are Freddie Mac "
"portfolio and representation-and-warranty actions, not borrower decisions |",
"",
]
else:
b += ["*Artifact `hazards/survival_dataset` unavailable.*", ""]
b += [
"## 2. Descriptive survival and cumulative incidence",
"",
"*Evidence tier: `descriptive`.*",
"",
]
if km:
r = km["result"]
o = r["overall"]
if o["survival"]:
b += [
f"- Kaplan–Meier over {_fmt(len(o['times']))} distinct exit ages; "
f"survival at the last observed age is **{_fmt(o['survival'][-1], 3)}**.",
f"- {o['competing_risks_treatment']}",
]
groups = list(r["by_entry_rate_gap_bucket"]["groups"])
if groups:
b += ["", "Curves are stratified by the rate gap at first observation:", ""]
b += [f" - {g}" for g in groups]
b += [
"",
"Stratifying controls for nothing: loans in different gap buckets were "
"originated in different years to different borrowers at different LTVs.",
"",
]
if cif:
f = cif["result"]["final_cif"]
b += [
"",
"**Cumulative incidence** (Aalen–Johansen, not 1−KM):",
"",
f"- prepayment: **{_fmt(f.get('cause_1'), 4)}**",
f"- credit event: **{_fmt(f.get('cause_2'), 4)}**",
"",
f"> {cif['result']['why_not_one_minus_km']}",
"",
]
b += [
"## 3. Discrete-time hazard models",
"",
"*Evidence tier: `hazard_association`. These are conditional correlations.*",
"",
]
for art, label in ((logit, "Logit"), (cloglog, "Complementary log-log")):
if not art:
continue
r = art["result"]
b += [
f"### {label} — prepayment",
"",
f"{_fmt(r['n_obs'])} loan-months, {_fmt(r['n_events'])} events, "
f"{_fmt(r['n_loans'])} loans. Standard errors: {r['standard_errors']}. "
f"AIC {_fmt(r['aic'], 1)}.",
"",
"| term | coef | s.e. | hazard ratio |",
"|---|---|---|---|",
]
for c in r["coefficients"]:
if c["term"].startswith("age_"):
continue
b.append(
f"| `{c['term']}` | {_fmt(c['coef'])} | {_fmt(c['std_err'])} | "
f"{_fmt(c['hazard_ratio'], 3)} |"
)
ame = r.get("rate_gap_average_marginal_effect_monthly")
if ame is not None:
b += [
"",
f"**Average marginal effect of the rate gap: {_fmt(ame, 6)}** — "
f"{r['rate_gap_ame_interpretation']}.",
]
b += ["", f"> {r['interpretation_warning']}", ""]
if credit:
r = credit["result"]
rg = next((c for c in r["coefficients"] if c["term"] == "rate_gap"), None)
b += [
"### Competing risk — credit events (cause-specific hazard)",
"",
f"{_fmt(r['n_obs'])} loan-months, {_fmt(r['n_events'])} credit events.",
]
if rg:
b.append(f"Rate-gap coefficient {_fmt(rg['coef'])} (s.e. {_fmt(rg['std_err'])}).")
b += [
"",
"A cause-specific coefficient does not translate directly into an effect on "
"cumulative incidence: a covariate can raise one cause-specific hazard while "
"lowering the other cause's CIF.",
"",
]
b += ["## 4. Duration dependence and the nonlinear rate-gap profile", ""]
if base:
rows = base["result"]["prepayment"]["rows"]
b += [
"**Empirical monthly prepayment hazard by loan-age bin** (no covariates):",
"",
"| age bin | loan-months | events | hazard |",
"|---|---|---|---|",
]
for r0 in rows:
b.append(
f"| `{r0['age_bin']}` | {_fmt(r0['n_at_risk'])} | {_fmt(r0['n_events'])} | "
f"{_fmt(r0['hazard'], 5)} |"
)
b += [
"",
"This age profile mixes genuine duration dependence with cohort and "
"calendar-time composition and should not be read as pure seasoning.",
"",
]
if gap:
emp = gap["result"]["prepayment"]["empirical"]
b += [
"**Empirical monthly prepayment hazard by rate-gap bucket:**",
"",
"| rate-gap bucket | loan-months | events | hazard | mean gap (pp) |",
"|---|---|---|---|---|",
]
for r0 in emp:
b.append(
f"| {r0['label']} | {_fmt(r0['n_at_risk'])} | {_fmt(r0['n_events'])} | "
f"{_fmt(r0['hazard'], 5)} | {_fmt(r0['mean_rate_gap'], 2)} |"
)
b += [
"",
"The binned specification uses *0 to +100 bp* as the reference bucket, so "
"each coefficient reads as 'relative to a barely locked-in loan'.",
"",
]
b += ["## 5. Heterogeneity", ""]
if het:
r = het["result"]
b += [
"Pre-specified subgroups: initial note rate, loan age, current LTV, credit "
"score, loan balance, occupancy, loan purpose. Exploratory subgroups are "
"labeled separately in the artifact and carry no multiplicity correction.",
"",
]
for name, rows in (r.get("prespecified") or {}).items():
if not isinstance(rows, list) or not rows or "error" in rows[0]:
continue
b += [
f"**{name}**",
"",
"| group | loans | prepayments | monthly hazard | mean gap |",
"|---|---|---|---|---|",
]
for r0 in rows:
b.append(
f"| {r0.get('group')} | {_fmt(r0.get('n_loans'))} | "
f"{_fmt(r0.get('n_prepayments'))} | "
f"{_fmt(r0.get('monthly_prepay_hazard'), 5)} | "
f"{_fmt(r0.get('mean_rate_gap'), 2)} |"
)
b.append("")
b += [f"> {r.get('note', '')}", ""]
b += ["## 6. Cox proportional hazards and PH diagnostics", ""]
if cox:
r = cox["result"]
if r.get("status") in ("skipped", "failed"):
b += [f"*Not estimated: {r.get('reason')}*", ""]
else:
b += [
f"{_fmt(r['n_obs'])} loans, {_fmt(r['n_events'])} events, concordance "
f"{_fmt(r['concordance'], 4)}.",
"",
f"> {r['covariate_note']}",
"",
"| term | coef | s.e. | hazard ratio | p |",
"|---|---|---|---|---|",
]
for c in r["coefficients"]:
b.append(
f"| `{c['term']}` | {_fmt(c['coef'])} | {_fmt(c['std_err'])} | "
f"{_fmt(c['hazard_ratio'], 3)} | {_fmt(c['p'], 4)} |"
)
ph = r.get("proportional_hazards_test", {})
if ph.get("status") == "run":
b += [
"",
"**Proportional-hazards test** (Schoenfeld, rank transform):",
"",
"| covariate | statistic | p |",
"|---|---|---|",
]
for k, v in ph["per_covariate"].items():
b.append(f"| `{k}` | {_fmt(v['test_statistic'], 2)} | {_fmt(v['p'], 4)} |")
b += ["", f"> {ph['interpretation']}", ""]
b += ["## 7. Predictive benchmark (out of time)", ""]
if gbm:
r = gbm["result"]
if r.get("status") == "skipped":
b += [f"*Not run: {r.get('reason')}*", ""]
else:
b += [
"| metric | gradient boosting | discrete-time logit |",
"|---|---|---|",
f"| out-of-time AUC | {_fmt(r['out_of_time_auc_gbm'], 4)} | "
f"{_fmt(r['out_of_time_auc_discrete_time_logit'], 4)} |",
f"| out-of-time Brier | {_fmt(r['out_of_time_brier_gbm'], 6)} | "
f"{_fmt(r['out_of_time_brier_logit'], 6)} |",
"",
f"Train `{r['train_period']}`, test `{r['test_period']}`, test base rate "
f"{_fmt(r['base_rate_test'], 5)}.",
"",
f"> {r['interpretation_warning']}",
"",
]
b += [
"## 8. Refinancing versus mobility — the decisive limitation",
"",
"This section exists because it is the most important thing in this report.",
"",
'Zero Balance Code 01 is officially *"Prepaid or Matured (Voluntary Payoff)"*. '
"It pools three economically distinct events:",
"",
"1. a **refinance** — the household stays put and replaces the loan;",
"2. a **sale-related payoff** — the household may or may not have moved;",
"3. a **scheduled maturity** — no decision at all.",
"",
"The dataset contains no field that separates them, no property identifier, and a "
"postal code truncated to three digits plus `00`. Field 27 "
"(`Pre-Relief-Refinance Loan Sequence Number`) links only Relief Refinance / HARP "
"chains — a policy-program subset, not ordinary refinancing "
"(`docs/DECISION_LOG.md` D005).",
"",
"**Consequences, applied throughout this project:**",
"",
"- The loan-level outcome is called `prepayment`, never *sale* and never *move*.",
"- Refinancing behaviour is characterised through the **refinance incentive** "
"measure (note rate minus market rate), not through any individual event label.",
"- Mobility-adjacent market activity is approached only through **independent** "
"local measures — HMDA purchase originations — at the market level, never by "
"assigning an individual prepayment to a move.",
"- The policy module reports every transaction-denominated quantity across a "
"**range** of assumed prepayment-to-transaction shares, because that share is "
"not identified from these data.",
"",
"A reader who wants the effect of lock-in on *moving* needs linked "
"mortgage-and-property records or a credit-bureau address panel. This project "
"does not have them and does not pretend to.",
"",
]
return _write(cfg, "loan_hazard_analysis", ctx, "\n".join(b))
def render_event_study(cfg: Config) -> Path:
ctx = ReportContext(cfg)
exp = ctx.get("eventstudy", "exposure_distribution")
placebo = ctx.get("eventstudy", "placebos")
outcomes = [
a.stem.replace("es_", "")
for a in list_artifacts(cfg, "eventstudy")
if a.stem.startswith("es_")
]
arts = {o: ctx.get("eventstudy", f"es_{o}") for o in sorted(outcomes)}
b = [
"## 1. Design",
"",
"$$y_{gt} = \\alpha_g + \\gamma_t + \\sum_{k \\neq k_0} \\beta_k "
"\\left(E_g \\times \\mathbf 1\\{t=k\\}\\right) + X_{gt}'\\theta + \\varepsilon_{gt}$$",
"",
"$E_g$ is **predetermined** lock-in exposure: the frozen pre-shock local coupon "
"distribution evaluated at the later national mortgage-rate path,",
"",
"$$E_g = \\sum_k \\omega_{gk}^{\\text{pre}} \\cdot "
"\\mathbf 1\\{\\bar R^{\\text{post}} - r_k > \\tau\\}.$$",
"",
"All cross-sectional variation comes from the frozen shares "
"$\\omega_{gk}^{\\text{pre}}$; $\\bar R^{\\text{post}}$ is a national scalar.",
"",
"**What is not identified.** The national rate path is common to every geography "
"and is absorbed by $\\gamma_t$. Only *relative* effects across exposure are "
'identified. No statement of the form "the rate increase reduced national '
'transactions by X%" is available from this design.',
"",
"**No instrumental-variable interpretation is claimed.** Predetermined is not "
"exogenous — see `docs/IDENTIFICATION_STRATEGY.md` §A4.",
"",
]
if exp:
p = exp["result"]["primary"]
if p.get("status") == "ok":
b += [
"## 2. Exposure distribution and balance",
"",
f"Exposure measure: `{p['exposure']}`, frozen at "
f"`{exp['result']['pre_shock_date']}`, {_fmt(p['n_geographies'])} geographies.",
"",
"| statistic | value |",
"|---|---|",
f"| mean | {_fmt(p['mean'])} |",
f"| s.d. | {_fmt(p['sd'])} |",
f"| min | {_fmt(p['min'])} |",
f"| p25 | {_fmt(p['p25'])} |",
f"| median | {_fmt(p['median'])} |",
f"| p75 | {_fmt(p['p75'])} |",
f"| max | {_fmt(p['max'])} |",
"",
"Most exposed: "
+ ", ".join(f"`{t['geography']}` ({_fmt(t['exposure'], 3)})" for t in p["top_5"])
+ ".",
"",
"Least exposed: "
+ ", ".join(f"`{t['geography']}` ({_fmt(t['exposure'], 3)})" for t in p["bottom_5"])
+ ".",
"",
]
if p.get("balance_table"):
b += [
"**Balance table — exposure is not randomly assigned.**",
"",
"| pre-period variable | correlation with exposure |",
"|---|---|",
]
for r0 in p["balance_table"]:
b.append(f"| `{r0['variable']}` | {_fmt(r0['correlation_with_exposure'], 3)} |")
b += ["", f"> {p['balance_interpretation']}", ""]
b += ["## 3. Results by outcome", ""]
for name, art in arts.items():
if art is None:
continue
es = art["result"].get("event_study", {})
did = art["result"].get("did_two_period", {})
b += [
f"### `{name}`",
"",
f"- **Evidence tier: `{art['evidence_tier']}`**",
f"- Outcome definition: {art['outcome_definition']}",
]
if es.get("status") != "ok":
b += [f"- *Not estimable: {es.get('reason')}*", ""]
continue
pt = es["pretrend_test"]
b += [
f"- {_fmt(es['n_obs'])} observations, {_fmt(es['n_geographies'])} geographies, "
f"{_fmt(es['n_periods'])} periods, {es['standard_errors']}.",
f"- Coefficient units: {es['coefficient_units']}.",
f"- Controls: {', '.join(f'`{c}`' for c in es['controls']) or 'none'}. "
f"Fixed effects: {', '.join(f'`{c}`' for c in es['fixed_effects'])}.",
"",
"**Pre-trend test** (joint Wald that all pre-period interactions are zero): "
+ (
f"p = {_fmt(pt.get('pvalue'), 3)}"
if pt.get("pvalue") is not None
else f"*{pt.get('test', 'not testable')}*"
)
+ (
f"; wild-cluster-bootstrap p = {_fmt(pt.get('wild_cluster_bootstrap_pvalue'), 3)}"
if pt.get("wild_cluster_bootstrap_pvalue") is not None
else ""
)
+ f" → **{'PASSES' if pt.get('passes_at_alpha_0.10') else 'FAILS'}** at α = 0.10.",
"",
]
if not pt.get("passes_at_alpha_0.10"):
b += [
"> This outcome is **demoted to `descriptive`** and carries no causal "
"language. It is recorded in `reports/failed_hypotheses.md`.",
"",
]
b += ["| period | coef | s.e. | 95% CI | |", "|---|---|---|---|---|"]
for d in es["dynamic_effects"]:
tag = "reference" if d["is_reference"] else ("pre" if d["is_pre"] else "post")
b.append(
f"| {d['time']} | {_fmt(d['coef'])} | {_fmt(d['std_err'])} | "
f"[{_fmt(d['ci_low'], 3)}, {_fmt(d['ci_high'], 3)}] | {tag} |"
)
b += ["", f"Mean post-shock effect: **{_fmt(es.get('mean_post_effect'))}**."]
if did.get("status") == "ok":
b += [
f" Collapsed pre/post DiD: **{_fmt(did['coef'])}** "
f"(s.e. {_fmt(did['std_err'])}, t = {_fmt(did.get('t'), 2)}, "
f"{_fmt(did['n_clusters'])} clusters).",
]
if art.get("caveats"):
b += ["", "Caveats:"] + [f"- {c}" for c in art["caveats"]]
b.append("")
if placebo:
r = placebo["result"]
b += ["## 4. Falsification", "", f"Headline outcome: `{r.get('headline_outcome')}`.", ""]
if r.get("placebo_shock_dates"):
b += [
"**Placebo shock dates** — a placebo passes when it is insignificant.",
"",
"| placebo date | coef | s.e. | t |",
"|---|---|---|---|",
]
for k, v in r["placebo_shock_dates"].items():
d = v["did"]
if d.get("status") != "ok":
b.append(f"| {k} | *{d.get('reason')}* | | |")
else:
b.append(
f"| {k} | {_fmt(d['coef'])} | {_fmt(d['std_err'])} | "
f"{_fmt(d.get('t'), 2)} |"
)
b.append("")
if r.get("placebo_outcomes"):
b += ["**Placebo outcomes**", "", "| outcome | coef | s.e. | t |", "|---|---|---|---|"]
for k, d in r["placebo_outcomes"].items():
if d.get("status") != "ok":
b.append(f"| `{k}` | *{d.get('reason')}* | | |")
else:
b.append(
f"| `{k}` | {_fmt(d['coef'])} | {_fmt(d['std_err'])} | "
f"{_fmt(d.get('t'), 2)} |"
)
b.append("")
b += [f"> {r.get('interpretation', '')}", ""]
b += [
"## 5. Threats this design does not resolve",
"",
"| threat | why it matters | what we did |",
"|---|---|---|",
"| Pandemic demand reallocation | boom markets refinanced most, so they have the "
"highest exposure *and* mean-reverted for unrelated reasons | control for 2019–21 "
"price growth; exclude top-decile boom markets as a robustness cell |",
"| Differential refinancing booms | a market that already refinanced has an "
"exhausted pipeline, mechanically depressing later refi counts | refi outcomes "
"labeled contaminated; purchase originations are the headline |",
"| Remote-work exposure | drives migration and construction independently | "
"**unresolved** in this slice; no teleworkable-share control is wired in |",
"| Local labour shocks | move both exits and originations | **unresolved** in this "
"slice; the optional unemployment adapter is not in the critical path |",
"| Supply constraints | determine whether a demand shift shows up in price or "
"quantity | part of the mechanism, not a nuisance; discussed in the decomposition |",
"| Coverage error in exposure | exposure is measured on Freddie-acquired loans only | "
"loan counts per geography are carried as a coverage variable |",
"| Spillovers | a locked-in household who does not move also does not buy elsewhere | "
"biases estimates toward zero; not corrected |",
"",
"Full treatment: `docs/IDENTIFICATION_STRATEGY.md` §3.",
"",
]
return _write(cfg, "local_market_event_study", ctx, "\n".join(b))
def render_decomposition(cfg: Config) -> Path:
ctx = ReportContext(cfg)
purchase = ctx.get("eventstudy", "es_log_purchase_originations")
refi = ctx.get("eventstudy", "es_log_refi_originations")
hpi = ctx.get("eventstudy", "es_hpi_growth")
p1 = ctx.get("eventstudy", "es_log_permits_1unit")
p5 = ctx.get("eventstudy", "es_log_permits_5plus")
gap = ctx.get("hazards", "gap_profile_nonlinear")
b = [
"## 1. The central asymmetry",
"",
"A locked-in owner is **both** a potential seller and a potential buyer. When the "
"rate gap makes moving expensive, that household withdraws from *both* sides of "
"the market at once.",
"",
"```mermaid",
"flowchart TD",
" R[Market rate rises above existing note rates] --> G[Rate gap opens]",
" G --> L[Locked-in owner does not move]",
" L --> S[Fewer existing homes listed<br/>EXISTING-HOME SUPPLY FALLS]",
" L --> D[Same owner does not buy a replacement<br/>REPEAT-BUYER DEMAND FALLS]",
" S --> Q[Transaction volume falls]",
" D --> Q",
" S --> PU[Upward pressure on price]",
" D --> PD[Downward pressure on price]",
" PU --> N[NET PRICE EFFECT: AMBIGUOUS]",
" PD --> N",
" G --> FTB[First-time buyers are NOT locked in<br/>their demand is unaffected by lock-in<br/>but is hit by the higher rate itself]",
" FTB --> N",
" G --> INV[Investors and all-cash buyers are NOT locked in]",
" INV --> N",
" N --> C{Local supply elasticity}",
" C -->|elastic| BUILD[More new construction,<br/>less price response]",
" C -->|inelastic| PRICE[More price response,<br/>less construction]",
"```",
"",
"**Quantities are unambiguous; prices are not.** Both channels reduce transaction "
"volume, so purchase-mortgage originations should fall with exposure. The price "
"effect depends on which side is more inelastic, on the share of demand from "
"first-time buyers and investors (who are not locked in), and on how readily new "
"construction substitutes for existing homes.",
"",
"> **A fall in transactions is not evidence of a supply-only mechanism.** This is "
"the single most common inferential error in casual accounts of lock-in. The same "
"aggregate decline in sales is consistent with a pure listing-side contraction, a "
"pure repeat-buyer-demand contraction, or any mixture.",
"",
]
b += [
"## 2. What the evidence in this repository can and cannot separate",
"",
"| channel | measurable here? | with what |",
"|---|---|---|",
"| Locked-in owners listing fewer homes | **no, not separately** | no listings "
"data and no sale indicator |",
"| Locked-in owners buying fewer homes | **no, not separately** | would need to "
"link a payoff to a subsequent purchase by the same household |",
"| Combined effect on transaction volume | **yes** | HMDA purchase originations "
"by state-year |",
"| First-time-buyer demand | partially | HMDA does not flag first-time status; "
"the loan-level file does, but only for purchase loans it acquired |",
"| Investor demand | partially | Freddie `Occupancy Status` = `I`, but investor "
"activity is concentrated in cash and non-agency channels we never see |",
"| New construction | **yes** | Census BPS units authorized |",
"| Local migration | **no** | no migration adapter in the critical path |",
"| Credit availability | partially | HMDA denial rate |",
"",
"The honest summary: this design identifies the **combined** withdrawal, not its "
"decomposition. Claiming a decomposition would require listings data, "
"transaction records, or a household panel.",
"",
]
b += [
"## 3. Sign table from the estimated results",
"",
"No sign is presumed. Each cell reports what the artifacts actually show, with "
"the tier that governs how it may be read.",
"",
"| outcome | mean post effect (per 1 s.d. exposure) | tier | pre-trend | reading |",
"|---|---|---|---|---|",
]
for label, art in (
("purchase originations (log)", purchase),
("refinance originations (log)", refi),
("house price growth", hpi),
("single-family permits (log)", p1),
("multifamily 5+ permits (log)", p5),
):
if art is None:
b.append(f"| {label} | — | — | — | artifact unavailable |")
continue
es = art["result"].get("event_study", {})
if es.get("status") != "ok":
b.append(f"| {label} | — | `{art['evidence_tier']}` | — | not estimable |")
continue
pt = es["pretrend_test"]
passes = pt.get("passes_at_alpha_0.10")
v = es.get("mean_post_effect")
reading = (
f"{verb_for(art)}" if passes else "descriptive only — pre-trend fails or is untestable"
)
b.append(
f"| {label} | {_fmt(v)} | `{art['evidence_tier']}` | "
f"{'pass' if passes else 'fail'} | {reading} |"
)
b.append("")
if gap:
emp = gap["result"]["prepayment"]["empirical"]
if emp:
lo = emp[0]["hazard"]
hi = emp[-1]["hazard"]
b += [
"## 4. The loan-level gradient that motivates the market-level design",
"",
f"The monthly prepayment hazard falls from **{_fmt(lo, 5)}** in the "
f"most-refinance-incentivised bucket to **{_fmt(hi, 5)}** in the "
f"most-locked-in bucket — a ratio of roughly "
f"**{_fmt(lo / hi if hi else float('nan'), 1)}×**.",
"",
"*Evidence tier: `hazard_association`.* This gradient is the borrower-level "
"mechanism the market-level design is looking for. It is **not** itself "
"evidence about listings, sales, moves, or prices.",
"",
]
b += [
"## 5. Why the price sign matters for policy",
"",
"If lock-in raises prices (listing channel dominates), policies that unlock "
"existing owners improve affordability by adding supply. If lock-in lowers prices "
"(repeat-buyer channel dominates), the same policies add demand and could raise "
"prices while raising transaction volume. **The two cases imply opposite "
"affordability consequences from the same intervention**, which is why "
"`reports/policy_counterfactuals.md` reports quantity and price responses "
"separately and never nets them into a single welfare claim.",
"",
"The supply-elasticity scenario in the policy module exists to make this concrete: "
"the *same* modelled demand shift produces mostly-quantity or mostly-price "
"responses depending on a calibrated elasticity that this project does not "
"estimate.",
"",
]
return _write(cfg, "demand_supply_decomposition", ctx, "\n".join(b))
def render_policy(cfg: Config) -> Path:
ctx = ReportContext(cfg)
comp = ctx.get("scenarios", "scenario_comparison")
names = [a.stem for a in list_artifacts(cfg, "scenarios") if a.stem != "scenario_comparison"]
arts = [ctx.get("scenarios", n) for n in sorted(names)]
b = [
"> **These are model-dependent projections, not forecasts.**",
"",
"## 1. How the simulator works",
"",
"1. Take the estimated discrete-time prepayment hazard from "
"`outputs/hazards/dt_logit_prepayment.json`.",
"2. Perturb the **rate gap** (or the effective gap under a policy) for every loan "
"in the active stock at a baseline month.",
"3. Re-predict each loan's monthly prepayment probability and sum the difference.",
"4. Map the modelled change in prepayments into transaction, price, and permit "
"responses through **calibrated** elasticities.",
"",
"**The honesty boundary.** Step 1 is *estimated*. Steps 2–3 assume a hazard "
"*association* behaves as a structural response function — which the "
"identification strategy does not establish. Step 4 is *entirely calibrated*.",
"",
"**The largest single source of uncertainty** is that a prepayment is not a move. "
"Converting modelled prepayments into modelled transactions requires the share of "
"prepayments that correspond to a property transaction, and that share is **not "
"identified** from these data. Every transaction-denominated quantity is therefore "
"reported across a range of assumed shares, and no point value is preferred.",
"",
]
if comp:
r = comp["result"]
b += [
"## 2. Scenario ranking",
"",
f"Baseline month `{r['baseline_month']}`, "
f"{_fmt(r['n_loans_in_baseline_stock'])} active loans.",
"",
"| scenario | policy | additional monthly prepayments | % change | "
"additional monthly prepaid UPB |",
"|---|---|---|---|---|",
]
for row in r["ranking"]:
b.append(
f"| `{row['scenario']}` | {row['policy_type']} | "
f"{_fmt(row['additional_monthly_prepayments'], 1)} | "
f"{_fmt((row['pct_change_in_prepayments'] or 0) * 100, 1)}% | "
f"${_fmt(row['additional_monthly_prepaid_upb'], 0)} |"
)
b += [
"",
f"> {r['how_to_read_this']}",
"",
"### Calibrated inputs (no error bars, chosen not estimated)",
"",
"| parameter | value |",
"|---|---|",
]
for k, v in r["calibrated_inputs"].items():
b.append(f"| `{k}` | {_fmt(v)} |")
b += ["", "### Estimated inputs", "", "| field | value |", "|---|---|"]
for k, v in r["estimated_inputs"].items():
if isinstance(v, list):
continue
b.append(f"| `{k}` | {_fmt(v)} |")
b.append("")
b += ["## 3. Scenario detail", ""]
for art in arts:
if art is None:
continue
r = art["result"]
pol = r.get("policy", {})
b += [
f"### `{r.get('scenario')}` — {pol.get('type', '')}",
"",
f"- Implementation: {pol.get('implementation', '—')}",
f"- Baseline expected monthly prepayments: "
f"**{_fmt(r.get('baseline_expected_monthly_prepayments'), 1)}**",
f"- Scenario expected monthly prepayments: "
f"**{_fmt(r.get('scenario_expected_monthly_prepayments'), 1)}**",
f"- Modelled additional monthly prepayments: "
f"**{_fmt(r.get('modelled_additional_monthly_prepayments'), 1)}** "
f"({_fmt((r.get('modelled_pct_change_in_prepayments') or 0) * 100, 1)}%)",
]
for k, v in pol.items():
if k in ("type", "implementation"):
continue
b.append(f"- `{k}`: {_fmt(v)}")
mapping = r.get("transaction_price_construction_mapping", {})
if mapping:
b += [
"",
"Transaction / price / construction mapping across the unidentified "
"prepayment-to-transaction share:",
"",
"| assumed move share | additional transactions/month | % change in flow | "
"log price change | % change in permits |",
"|---|---|---|---|---|",
]
for _k, m in mapping.items():
b.append(
f"| {_fmt(m['assumed_share_of_prepayments_that_are_property_transactions'])} | "
f"{_fmt(m['modelled_additional_transactions_per_month'], 1)} | "
f"{_fmt(m['modelled_pct_change_in_transaction_flow'] * 100, 2)}% | "
f"{_fmt(m['modelled_log_price_change'], 5)} | "
f"{_fmt(m['modelled_pct_change_in_permits'] * 100, 2)}% |"
)
if art.get("caveats"):
b += ["", "Caveats:"] + [f"- {c}" for c in art["caveats"]]
b.append("")
b += [
"## 4. What none of these scenarios do",
"",
"- They do not forecast. They hold the loan population, housing-stock composition, "
"credit conditions, income, and migration fixed.",
"- They do not attach confidence intervals. The hazard coefficients have sampling "
"error; the calibrated elasticities have none at all; the "
"prepayment-to-transaction share is unidentified.",
"- They do not net quantity and price responses into a welfare claim.",
"- They do not model who bears the cost of portability or assumability. Those "
"policies **transfer** a below-market-coupon loss rather than eliminating it.",
"- They do not model capitalisation of demand-side subsidies into prices, which in "
"an inelastic-supply market can absorb much of the intended benefit.",
"- They are not additive. Running two scenarios together is not the sum of the two.",
"",
"The **ordering** of scenarios is the useful output. Any single magnitude should be "
"read as an order of magnitude at best.",
"",
]
return _write(cfg, "policy_counterfactuals", ctx, "\n".join(b))
def render_failed(cfg: Config) -> Path:
ctx = ReportContext(cfg)
grid_art = ctx.get("robustness", "robustness_grid")
es_arts = [
ctx.get("eventstudy", a.stem)
for a in list_artifacts(cfg, "eventstudy")
if a.stem.startswith("es_")
]
b = [
"This file exists so that specifications which did not survive are **recorded, "
"not buried**. A research system that only reports what worked is not a research "
"system.",
"",
"## 1. Outcomes demoted from `quasi_experimental` to `descriptive`",
"",
"The event-study runner assigns the tier from the data: a pre-trend test that "
"fails or cannot be run **automatically** demotes the artifact. There is no manual "
"override.",
"",
"| outcome | tier assigned | pre-trend p | reason |",
"|---|---|---|---|",
]
demoted = 0
for art in es_arts:
if art is None:
continue
es = art["result"].get("event_study", {})
pt = es.get("pretrend_test", {}) if es.get("status") == "ok" else {}
if art["evidence_tier"] == "quasi_experimental":
continue
demoted += 1
reason = (
es.get("reason")
if es.get("status") != "ok"
else (
"pre-trend test failed"
if pt.get("pvalue") is not None
else pt.get("test", "pre-trends not testable")
)
)
b.append(
f"| `{art['artifact']}` | `{art['evidence_tier']}` | "
f"{_fmt(pt.get('pvalue'), 3)} | {reason} |"
)
if demoted == 0:
b.append("| *(none)* | | | every estimated outcome passed its pre-trend test |")
b.append("")
if grid_art:
r = grid_art["result"]
if r.get("status") == "skipped":
b += ["## 2. Robustness grid", "", f"*Not run: {r.get('reason')}*", ""]
else:
b += [
"## 2. Robustness grid",
"",
f"Baseline coefficient **{_fmt(r.get('baseline_coefficient'))}** "
f"(s.e. {_fmt(r.get('baseline_std_err'))}) across {_fmt(r['n_cells'])} cells.",
"",
"| verdict | cells |",
"|---|---|",
]
for v in r["verdict_counts"]:
b.append(f"| `{v['verdict']}` | {_fmt(v['n'])} |")
b += ["", "**Verdict definitions**", ""]
for k, v in r["verdict_definitions"].items():
b.append(f"- `{k}`: {v}")
b += ["", f"### Flagged cells ({_fmt(r['n_flagged'])})", ""]
if r["n_flagged"] == 0:
b += [
"*No cell produced a sign flip, an inestimable specification, or a "
"failing placebo.*",
"",
]
else:
b += [
"| axis | variant | outcome | coef | s.e. | t | verdict | rationale |",
"|---|---|---|---|---|---|---|---|",
]
for c in r["flagged_cells"]:
b.append(
f"| {c['axis']} | {c['variant']} | `{c['outcome']}` | "
f"{_fmt(c['coef'])} | {_fmt(c['std_err'])} | {_fmt(c['t'], 2)} | "
f"**{c['verdict']}** | {c['rationale']} |"
)
b.append("")
b += [
"### Every cell",
"",
"| axis | variant | outcome | coef | s.e. | t | n | clusters | verdict |",
"|---|---|---|---|---|---|---|---|---|",
]
for c in r["cells"]:
b.append(
f"| {c['axis']} | {c['variant']} | `{c['outcome']}` | {_fmt(c['coef'])} | "
f"{_fmt(c['std_err'])} | {_fmt(c['t'], 2)} | {_fmt(c['n_obs'])} | "
f"{_fmt(c['n_clusters'])} | `{c['verdict']}` |"
)
b.append("")
sens = ctx.get("hazards", "sensitivity_cells")
if sens:
rs = sens["result"]
b += [
"## 3. Loan-level sensitivity to modelling choices",
"",
"Three checks re-estimate the headline discrete-time prepayment hazard under "
"alternatives the baseline deliberately does **not** use. Each corresponds to "
"a choice documented elsewhere as an *assumption* rather than a fact.",
"",
f"Baseline rate-gap coefficient: **{_fmt(rs['baseline_rate_gap_coef'])}** "
f"(s.e. {_fmt(rs['baseline_std_err'])}).",
"",
"| cell | coefficient | s.e. | verdict |",
"|---|---|---|---|",
]
for c in rs["cells"]:
if c["cell"] == "baseline":
continue
b.append(
f"| `{c['cell']}` | {_fmt(c.get('coef'))} | {_fmt(c.get('std_err'))} | "
f"**{c.get('verdict')}** |"
)
b += ["", "Verdicts are measured in **baseline standard errors**:", ""]
for k, v in rs["verdict_definitions"].items():
b.append(f"- `{k}`: {v}")
b += [""]
for c in rs["cells"]:
if c["cell"] == "baseline" or not c.get("interpretation"):
continue
b += [
f"**`{c['cell']}`** — {c.get('description', '')}",
"",
f"> {c['interpretation']}",
"",
]
movers = [
c
for c in rs["cells"]
if c.get("verdict") in ("large_shift", "sign_flip", "moderate_shift")
]
if movers:
b += [
"**These are fragilities, not bugs.** "
+ ", ".join(f"`{c['cell']}`" for c in movers)
+ " move the coefficient by more than one baseline standard error. That "
"means the corresponding modelling choice is doing real work, and it "
"should be stated whenever the magnitude is quoted.",
"",
]
b += [
"## 4. Design errors caught during construction",
"",
"These were genuine mistakes in this project, found by diagnostics rather than by "
"inspection. They are recorded because the diagnostic that caught each one is now "
"part of the pipeline.",
"",
"| # | error | how it was caught | fix |",
"|---|---|---|---|",
"| D016 | Exposure was measured as the *contemporaneous* locked-in share at the "
"pre-shock date. In 2021-12 the market rate was near its historic low, so "
"essentially nobody was locked in yet and the treatment variable had **exactly "
"zero variance in every state**. | The exposure-distribution artifact reported "
"sd = 0.000. | Exposure is now the frozen pre-shock coupon distribution evaluated "
"at the **later** national rate path — the actual shift-share design. |",
"| D017 | The HMDA Data Browser API **silently ignores** unrecognised query "
"parameters. Passing the singular `loan_purpose` (correct name: `loan_purposes`) "
"returned **all-purpose totals** that looked like a clean purchase-only series, "
"making purchase and refinance originations numerically identical. | Purchase and "
"refi counts were byte-identical in the panel. | Use `loan_purposes`; assert the "
"API echoes every filter back in its `parameters` block, on both fetch and cache "
"read; version the cache filenames so bad cells cannot be reused. |",
"| D018 | `Current Actual UPB` is the **end**-of-period balance and is 0 in a "
"zero-balance month, so the payment-gap covariate was zero in exactly the months "
"where an exit occurred — corrupting the covariate for **every event**. | An "
"episode validation check found 2,927 rows where the payment gap and the rate gap "
"disagreed in sign. | All lock-in measures now use the **start-of-month** balance, "
"with `upb_timing_source` recording its provenance per row. |",
"| D019 | The annual panel was built only over years with an active mortgage stock "
"(2021+), leaving **no pre-shock periods**, so pre-trends were untestable and every "
"result was auto-demoted. | Every event study reported `n_pre_coefficients = 0`. | "
"The panel now spans the union of outcome years (2018+); exposure is a "
"geography-level constant legitimately attached to pre-shock years. |",
"| D009 | The config asked FHFA for **monthly** purchase-only HPI at **state** "
"level, a combination FHFA does not publish (monthly purchase-only is national and "
"census-division only). The filter matched zero rows. | `load_series` returned an "
"empty frame and the LTV scaling silently degraded. | Default is now quarterly; "
"`load_series` raises with the full list of published combinations; "
"quarterly→monthly expansion is labeled in `index_basis`. |",
"",
]
b += [
"## 5. Hypotheses this project cannot test at all",
"",
"Not failures of execution — failures of data availability. Recording them "
"prevents a future reader from assuming they were tested and passed.",
"",
"- **Does lock-in reduce household mobility?** No mobility measure exists in these "
"data. Not tested. Not testable here.",
"- **Does lock-in reduce home *listings*?** No listings data. Not tested.",
"- **What fraction of prepayments are sales rather than refinances?** Zero Balance "
"Code 01 pools them. Not identified.",
"- **Do locked-in owners trade down instead of moving?** Requires linking a payoff "
"to a subsequent purchase by the same household. No property or household "
"identifier exists.",
"- **Is the exposure measure a valid instrument?** No. See "
"`docs/IDENTIFICATION_STRATEGY.md` §A4. We do not use IV language.",
"- **Do FHA/VA, jumbo, non-QM, or all-cash segments behave the same way?** They are "
"entirely outside the loan-level population.",
"",
]
return _write(cfg, "failed_hypotheses", ctx, "\n".join(b))
def render_methodology(cfg: Config) -> Path:
ctx = ReportContext(cfg)
val = ctx.get("validation", "validation_report")
ds = ctx.get("hazards", "survival_dataset")
exp = ctx.get("eventstudy", "exposure_distribution")
b = [
VOCAB_NOTE,
"",
"## 1. Pipeline",
"",
"```",
"official public docs -> verified schema (32 + 32 fields)",
"registered or SYNTHETIC loan files",
" -> streaming origination parser -> partitioned Parquet (cohort=)",
" -> streaming performance parser -> partitioned Parquet (cohort=, period_year=)",
" -> loan-event table (exits, censoring, left truncation)",
" -> loan-month episode table (point-in-time rates + 8 lock-in measures)",
" -> geography-month active stock (count- and UPB-weighted)",
" -> predetermined exposure (frozen pre-shock coupon shares x later rate path)",
" -> local market panel (+ FHFA HPI, HMDA, Census BPS)",
" -> hazard ladder | event studies | robustness grid | scenarios",
" -> generated reports",
"```",
"",
"Memory discipline: the loan-by-month panel is never materialised as a Python "
"object. Parsers stream line chunks; the episode builder is a Polars lazy plan "
"collected in streaming mode; aggregation prunes partitions. A configurable row "
"budget (`survival.max_episode_rows`) fails the run rather than swapping.",
"",
]
b += [
"## 2. The eight lock-in measures",
"",
"| # | measure | definition |",
"|---|---|---|",
"| 1 | `rate_gap` | market rate − note rate. Positive ⇒ locked in |",
"| 2 | `lockin_gap` | max(rate_gap, 0) |",
"| 3 | `refi_incentive` | note rate − market rate. Positive ⇒ refinancing pays |",
"| 4 | `payment_gap` | monthly P&I change if the **start-of-month** balance were "
"refinanced at the market rate over the remaining term |",
"| 5 | `pv_financing_gap` | PV of measure 4 over a **calibrated** holding period "
"at a **calibrated** discount rate |",
"| 6 | `locked_share_*` | share of active loans above a bp threshold |",
"| 7 | `locked_share_upb_*` | measure 6, UPB-weighted |",
"| 8 | `locked_share_count_*` | measure 6, loan-count-weighted |",
"",
"All are **point-in-time**: the market rate attached to month *m* is the last "
"PMMS observation available on or before the first day of *m*. The alignment is "
"enforced by a backward as-of join and asserted by "
"`lockin.rates.assert_no_look_ahead`, which is called by `make validate-data` and "
"by a unit test.",
"",
]
b += [
"## 3. Conforming-mortgage selection — the population is not the market",
"",
"The loan-level population is **Freddie Mac acquisitions**: conventional, "
"conforming, single-family. What that excludes, and why each exclusion matters "
"for lock-in specifically:",
"",
"| excluded | why it matters |",
"|---|---|",
"| **FHA / VA** | disproportionately first-time, lower-income, and lower-wealth "
"buyers. FHA and VA loans are also **assumable**, so the lock-in mechanism "
"operates differently — the excluded segment is the one where the policy "
"counterfactual already partly exists |",
"| **Jumbo** | high-price metros are systematically under-represented, biasing "
"any geographic heterogeneity |",
"| **Non-QM, portfolio, credit-union** | different borrower risk profiles and "
"different refinance frictions |",
"| **Fannie Mae** | roughly half the conforming conventional universe is absent, "
"so `n_active_loans` is a coverage variable, not a market size |",
"| **All-cash purchases** | a large and cyclically varying share of transactions "
"involves no mortgage at all and cannot be locked in |",
"| **Mortgage-free owners** | roughly a third of owner-occupied U.S. homes carry "
"no mortgage. These households are **structurally immune** to lock-in and are "
"entirely absent from any share we compute |",
"",
'Consequence for interpretation: a statement like "X% of loans are locked in '
'above 200 bp" is a statement about **Freddie-acquired loans**, and the '
"corresponding share of *U.S. households* is necessarily smaller. Every artifact "
"carries this in its `population` field.",
"",
]
b += [
"## 4. Censoring, truncation, and competing risks",
"",
"- **Left truncation.** Performance records begin at Freddie Mac *acquisition*, "
"not origination, and the configured performance window truncates earlier "
"cohorts further. Risk sets exclude loans not yet observed at each loan age. The "
"two causes are reported separately in validation because only the first is a "
"property of the data.",
"- **Right censoring.** At the performance cutoff, or at an administrative "
"removal (ZB 15/16/96).",
"- **Administrative removals as censoring.** ZB 15 (whole-loan sale), 16 (RPL "
"securitization), and 96 (defect prior to other termination) are Freddie Mac "
"portfolio and representation-and-warranty actions. Counting them as prepayment "
"would inflate the hazard; counting them as still-alive would be false. "
"Censoring is the least-wrong option **and it is an assumption**: it requires "
"the removal to be uninformative about the borrower's latent exit time, which is "
"not guaranteed.",
"- **Competing risks.** Cause-specific hazards for prepayment and credit events, "
"with Aalen–Johansen cumulative incidence rather than 1−KM.",
"- **Missing performance months** contribute no risk time and are counted in "
"`n_month_gaps`.",
"- **Modifications** reset loan age per the official guide; the validator "
"tolerates the reset and flags affected loans.",
"- **Reappearing loans** (performance months after an exit) are truncated at the "
"exit and flagged.",
"",
]
if ds:
ll = ds["result"]["loan_level"]
b += [
f"In this run: {_fmt(ll['n_left_truncated'])} of {_fmt(ll['n_loans'])} loans "
f"left truncated; {_fmt(ll['n_censored'])} censored.",
"",
]
b += [
"## 5. Frequency and index-concept discipline",
"",
"- **HMDA is annual** and is never interpolated for estimation. HMDA event "
"studies run at annual frequency.",
"- **FHFA purchase-only HPI is quarterly at state level** (monthly exists only "
"nationally). Growth is computed at the published frequency; where a monthly "
"value is needed as an input to the LTV scaling, the quarterly level is held "
"constant within the quarter and `index_basis` is suffixed "
"`+held-constant-within-quarter`. An expanded series is never a regression "
"outcome.",
"- **Index concepts are never mixed.** purchase-only, all-transactions, and "
"expanded-data are different objects; `load_series` requires the flavor "
"explicitly.",
"- **Census BPS measures permits authorized**, not starts and not completions. "
"The monthly `c` vintage is preliminary. Partial years are dropped rather than "
"compared against full-year totals.",
"- **PMMS methodology regimes** are labeled, not silently spliced: the survey "
"changed to an application-based method on 2022-11-17, and the fees/points and "
"5/1 ARM series were discontinued at the same time.",
"",
]
if exp:
p = exp["result"]["primary"]
if p.get("status") == "ok":
b += [
"## 6. Treatment definition",
"",
f"Exposure `{p['exposure']}`, frozen at "
f"`{exp['result']['pre_shock_date']}`, mean {_fmt(p['mean'])}, "
f"s.d. {_fmt(p['sd'])} across {_fmt(p['n_geographies'])} geographies. "
"Standardised in every regression so coefficients read per standard "
"deviation.",
"",
]
b += ["## 7. Validation", ""]
if val:
r = val["result"]
b += [
f"`make validate-data`: **{_fmt(r['n_hard'])} hard**, "
f"{_fmt(r['n_soft'])} soft, {_fmt(r['n_info'])} informational findings.",
"",
"| severity | meaning |",
"|---|---|",
]
for k, v in r["severity_meaning"].items():
b.append(f"| `{k}` | {v} |")
b.append("")
for section, problems in r["sections"].items():
if not problems:
continue
b += [f"**{section}**", ""]
b += [f"- {p}" for p in problems]
b.append("")
b += [
"## 8. Limitations, ranked by how much they should change your reading",
"",
"1. **A prepayment is not a move, a sale, or a refinance.** Zero Balance Code 01 "
"pools all three. Nothing in this project can separate them. This caps what the "
"loan-level results can mean.",
"2. **Only relative effects are identified at the market level.** The national rate "
"path is absorbed by time fixed effects. There is no aggregate causal magnitude "
"here.",
"3. **Predetermined exposure is not exogenous.** It correlates with pandemic price "
"growth and with refinance intensity, both of which independently predict "
"post-2022 outcomes. No IV language is used.",
"4. **The population is a selected slice of the mortgage market**, which is itself "
"a selected slice of the housing market (§3).",
"5. **The demand/supply decomposition is not achieved**, only framed. No listings "
"data, no transaction records, no household panel.",
"6. **Policy scenarios rest on an association used as a response function** plus "
"calibrated elasticities with no error bars.",
"7. **The rate gap is measured with error**: PMMS is national, while local offered "
"rates differ by tens of basis points. This attenuates loan-level coefficients.",
"8. **A state house price index is a poor proxy for an individual property's price "
"path**, so estimated current LTV is noisy.",
"9. **HMDA reporting-threshold changes** break comparability of counts across "
"2017/2018 and across the closed-end threshold change.",
"10. **Remote-work exposure and local labour shocks are unresolved threats** in "
"this slice; the optional adapters are not in the critical path.",
"",
]
return _write(cfg, "methodology_and_limitations", ctx, "\n".join(b))
def render_replication_protocol(cfg: Config) -> Path:
ctx = ReportContext(cfg)
ctx.get("validation", "validation_report")
b = [
"## 1. Reproducing this run exactly",
"",
"```bash",
"make setup",
"make fetch-public-data",
"make reproduce-sample",
"make test",
"```",
"",
"`make reproduce-sample` executes, in order: `prepare-sample-data`, "
"`ingest-mortgages`, `build-loan-events`, `build-lockin`, `build-local-panel`, "
"`validate-data`, `estimate-hazards`, `estimate-local-effects`, `benchmark`, "
"`simulate-policy`, `report`.",
"",
"Determinism:",
"",
"- Synthetic fixtures are generated from `mortgage.synthetic_seed` (recorded in "
"the fixture manifest).",
"- Model seeds come from `survival.seed`.",
"- Every artifact records `git_commit`, `config_digest`, `data_period`, "
"`source_versions` (schema@retrieved#checksum per dataset), and a UTC timestamp.",
"- Every dataset on disk has a manifest with a SHA-256 checksum; "
"`make validate-data` re-checksums and fails on mismatch.",
"",
"The one non-deterministic input is the **public data vintage**. PMMS, FHFA HPI, "
"and Census BPS are revised; HMDA is re-released. A rerun weeks later will fetch "
"newer vintages. The manifests record exactly which vintage was used, so a "
"difference is diagnosable rather than mysterious.",
"",
]
b += [
"## 2. What cannot be reproduced without registered data",
"",
"Loan-level results in this run were computed from **synthetic fixtures** unless "
"the artifact's `data_class` says `REGISTERED`. To reproduce them empirically:",
"",
"1. Register at the Freddie Mac Single-Family Loan-Level Dataset page and accept "
"the terms of use **yourself**. This repository does not and will not bypass that "
"wall, and the terms prohibit redistributing the records.",
"2. Place the archives unmodified in `data/raw/freddie/`.",
"3. Set `mortgage.mode: registered_sample` (or `registered_full`) and rerun.",
"",
"The adapter discovers `historical_data_YYYYQn.zip` / `sample_YYYY.zip` "
"automatically, reads members without full extraction, and the `SYNTHETIC` stamps "
"and report banners disappear on their own. **No code changes are needed** — that "
"is the point of the mode switch.",
"",
"Public aggregate results (PMMS path, FHFA HPI growth, HMDA origination counts, "
"Census permits) are **fully reproducible now**, because those sources need no "
"registration.",
"",
]
b += [
"## 3. Artifact-to-claim traceability",
"",
"Every number in every generated report comes from a JSON artifact under "
"`outputs/`. To trace one:",
"",
"```bash",
"uv run lockin dump-artifact hazards dt_logit_prepayment",
"```",
"",
"Each artifact carries `evidence_tier`, `population`, `geography`, "
"`outcome_definition`, `weight`, `caveats`, and full `provenance`. A report "
"sentence with no artifact behind it is a defect.",
"",
"Reports are regenerated by `make report` and begin with a `GENERATED` header. "
"Hand-editing them is a defect: the edit is destroyed on the next run and breaks "
"traceability in the meantime.",
"",
]
b += [
"## 4. Verification checklist for a reviewer",
"",
"| check | command |",
"|---|---|",
"| schema matches the official layout | `uv run lockin verify-schema` |",
"| all manifests checksum-clean | `make validate-data` |",
"| market rates have no look-ahead | `make validate-data` (rates section) |",
"| payment and rate-gap math | `make test` (`tests/test_amortization.py`, "
"`tests/test_lockin_measures.py`) |",
"| prepayment is not called mobility | `make test` "
"(`tests/test_governance.py::test_no_mobility_language`) |",
"| no restricted data is tracked by git | `make validate-data` (governance section) |",
"| pipeline stage status | `uv run lockin status` |",
"",
"## 5. Known non-reproducible or fragile steps",
"",
"- The FRED cross-check on PMMS is an optional network call and may time out; its "
"failure is recorded and does not stop the pipeline.",
"- Census BPS monthly files are fetched at the `c` (preliminary) vintage by "
'default. Passing `vintages_to_try=("r", "c")` prefers revised where it exists, '
"at the cost of one failed request per missing month.",
"- The HMDA aggregations API is rate-sensitive; the adapter caches every cell and "
"records which cells failed, so a partial fetch is visible rather than silently "
"filled with zeros.",
"",
]
return _write(cfg, "replication_protocol", ctx, "\n".join(b))
def render_benchmark(cfg: Config) -> Path:
ctx = ReportContext(cfg)
art = ctx.get("benchmark", "benchmark_comparison")
b: list[str] = []
if not art:
b += ["*Artifact `benchmark/benchmark_comparison` unavailable. Run `make benchmark`.*"]
return _write(cfg, "benchmark_comparison", ctx, "\n".join(b))
r = art["result"]
b += [
f"> **{r['standing_rule']}**",
"",
"## Comparison types",
"",
"| type | meaning |",
"|---|---|",
]
for k, v in r["comparison_type_definitions"].items():
b.append(f"| `{k}` | {v} |")
b += ["", f"> {r['verification_note']}", "", "---", ""]
for bm in r["benchmarks"]:
b += [
f"## {bm['id']}",
"",
f"**Comparison type: `{bm['comparison_type']}`**",
"",
f"- **Citation.** {bm['citation']}",
f"- **Target estimand.** {bm['target_estimand']}",
f"- **Original data.** {bm['original_data']}",
f"- **Original identification.** {bm['original_identification']}",
f"- **Our available data.** {bm['our_available_data']}",
f"- **Population differences.** {bm['population_differences']}",
f"- **Outcome-definition differences.** {bm['outcome_definition_differences']}",
f"- **Published magnitude (reference).** {bm['published_magnitude_reference']}",
f"- **Verification status.** {bm['verification_status']}",
f"- **Why not exact.** {bm['why_not_exact']}",
"",
"**Our estimate.**",
"",
]
oe = bm.get("our_estimate", {})
if oe.get("status") == "unavailable":
b += [f"*Unavailable: {oe.get('reason')}*", ""]
else:
for k, v in oe.items():
if k in ("rows", "dynamic_effects"):
b.append(
f"- `{k}`: {len(v) if isinstance(v, list) else '—'} rows in the artifact"
)
continue
b.append(f"- `{k}`: {_fmt(v)}")
b.append("")
if oe.get("comparison_blocked"):
b += [f"> ⚠️ **Comparison blocked.** {oe['comparison_blocked']}", ""]
b += ["---", ""]
return _write(cfg, "benchmark_comparison", ctx, "\n".join(b))
def render_executive_memo(cfg: Config) -> Path:
ctx = ReportContext(cfg)
gap = ctx.get("hazards", "gap_profile_nonlinear")
logit = ctx.get("hazards", "dt_logit_prepayment")
het = ctx.get("hazards", "heterogeneity")
purchase = ctx.get("eventstudy", "es_log_purchase_originations")
hpi = ctx.get("eventstudy", "es_hpi_growth")
p1 = ctx.get("eventstudy", "es_log_permits_1unit")
exp = ctx.get("eventstudy", "exposure_distribution")
comp = ctx.get("scenarios", "scenario_comparison")
grid = ctx.get("robustness", "robustness_grid")
def tier_line(art: dict[str, Any] | None) -> str:
if art is None:
return "*not available*"
es = art["result"].get("event_study", {})
pt = es.get("pretrend_test", {}) if isinstance(es, dict) else {}
v = es.get("mean_post_effect") if isinstance(es, dict) else None
ok = pt.get("passes_at_alpha_0.10")
return (
f"{_fmt(v)} per s.d. of exposure · tier `{art['evidence_tier']}` · "
f"pre-trend {'passes' if ok else 'fails/untestable'}"
)
b = [
"## The ten questions",
"",
"### 1. How is mortgage lock-in defined?",
"",
"Lock-in is a **state**, not an effect: the borrower's outstanding note rate sits "
"below the rate a new mortgage would carry, so moving means giving up cheap "
"financing. We measure it eight ways rather than one — a raw rate gap, its "
"positive part, the mirror-image refinance incentive, a dollar-per-month "
"payment-equivalent cost, a present-value financing gap, and three "
"geography-level exposure shares (loan-count- and UPB-weighted). Every measure is "
"computed **point-in-time**, using only the market rate observable on or before "
"the date in question.",
"",
"The distinction that matters most: lock-in is a *state* we can measure; its "
"*effect* has to be estimated, and the two are constantly conflated in public "
"commentary.",
"",
"### 2. Which borrower groups are most exposed?",
"",
]
if het:
pre = het["result"].get("prespecified", {})
rows = pre.get("note_rate_tercile") or []
if rows and "error" not in rows[0]:
b += [
"By initial note rate (the dominant driver — a low coupon *is* exposure):",
"",
"| note-rate tercile | loans | mean rate gap (pp) | mean payment gap ($/mo) |",
"|---|---|---|---|",
]
for r0 in rows:
b.append(
f"| {r0.get('group')} | {_fmt(r0.get('n_loans'))} | "
f"{_fmt(r0.get('mean_rate_gap'), 2)} | "
f"{_fmt(r0.get('mean_payment_gap'), 0)} |"
)
b.append("")
b += [
"Exposure is mechanically concentrated in the 2020–21 origination and "
"refinance cohorts. Borrowers who transacted at the rate trough hold the "
"largest gaps; borrowers who transacted before 2019 or after mid-2022 hold "
"small or negative gaps.",
"",
"Two groups are **structurally immune** and are invisible in any share we "
"compute: mortgage-free owners (roughly a third of owner-occupied U.S. "
"homes) and all-cash buyers.",
"",
]
b += ["### 3. Does higher lock-in predict lower mortgage exits?", ""]
if gap:
emp = gap["result"]["prepayment"]["empirical"]
if emp:
b += [
"**Yes, strongly and monotonically.** Empirical monthly prepayment "
"hazard by rate-gap bucket:",
"",
"| rate-gap bucket | monthly prepayment hazard |",
"|---|---|",
]
for r0 in emp:
b.append(f"| {r0['label']} | {_fmt(r0['hazard'], 5)} |")
lo, hi = emp[0]["hazard"], emp[-1]["hazard"]
b += [
"",
f"The most-locked-in bucket prepays at roughly "
f"**1/{_fmt(lo / hi if hi else float('nan'), 1)}** the rate of the "
f"most-refinance-incentivised bucket.",
"",
]
if logit:
rg = next((c for c in logit["result"]["coefficients"] if c["term"] == "rate_gap"), None)
if rg:
b += [
f"Conditional on loan age, credit score, DTI, LTV, balance, and local "
f"price growth, the discrete-time logit coefficient on the rate gap is "
f"**{_fmt(rg['coef'])}** (s.e. {_fmt(rg['std_err'])}), a hazard ratio of "
f"**{_fmt(rg['hazard_ratio'], 3)}** per percentage point.",
"",
]
b += [
"**Tier: `hazard_association`.** This is a conditional correlation, not a causal "
"elasticity. The rate gap is a deterministic function of the note rate the "
"borrower chose and the national rate path, and borrowers with different note "
"rates differ in cohort, credit, equity, and tenure.",
"",
"**And note what this is *not*.** These are prepayments — Zero Balance Code 01, "
'*"Prepaid or Matured (Voluntary Payoff)"* — which pools refinancing, '
"sale-related payoff, and maturity. It is **not** a measure of moving.",
"",
]
b += [
"### 4. Does local lock-in exposure predict lower purchase-market activity?",
"",
f"Log HMDA purchase originations: **{tier_line(purchase)}**.",
"",
]
if purchase:
es = purchase["result"].get("event_study", {})
did = purchase["result"].get("did_two_period", {})
if es.get("status") == "ok" and did.get("status") == "ok":
t = did.get("t")
sig = abs(t) >= 1.645 if t is not None else False
b += [
f"The collapsed pre/post estimate is {_fmt(did['coef'])} "
f"(s.e. {_fmt(did['std_err'])}, t = {_fmt(t, 2)}, "
f"{_fmt(did['n_clusters'])} clusters) — "
+ (
"statistically distinguishable from zero at 10%."
if sig
else "**not statistically distinguishable from zero.**"
),
"",
"The sign is negative, consistent with the mechanism, but with "
f"{_fmt(did['n_clusters'])} state clusters and a within-sample exposure "
"spread of only a fraction of a standard deviation in economic terms, this "
"design has limited power. **A negative point estimate that does not "
"clear conventional significance is not evidence of an effect, and it is "
"not evidence against one either.**",
"",
]
b += [
"### 5. What happens to local prices?",
"",
f"House price growth: **{tier_line(hpi)}**.",
"",
"**We do not assume a sign, and the theory does not give us one.** A locked-in "
"owner withdraws from *both* sides of the market: they do not list, and they do "
"not buy a replacement. The first raises prices, the second lowers them. The net "
"effect depends on which side is more inelastic and on how much demand comes "
"from first-time buyers and investors, who are not locked in at all.",
"",
"This is why the decomposition report exists and why any confident public claim "
'that lock-in "propped up prices" is running ahead of the identification.',
"",
]
b += [
"### 6. What happens to construction?",
"",
f"Log single-family permits authorized: **{tier_line(p1)}**.",
"",
"Two channels point in opposite directions. If lock-in makes existing homes "
"scarce and expensive, builders substitute toward new construction. If it "
"suppresses trade-up demand, permits fall. Census BPS measures permits "
"**authorized**, not starts and not completions, so even a clean estimate would "
"be an intention rather than an outcome.",
"",
]
b += [
"### 7. Which evidence is causal?",
"",
"**Candidate causal evidence:** the continuous-treatment event studies on "
"predetermined exposure, and **only** those outcomes whose pre-trend test passes "
"and whose placebos are clean. The tier is assigned by the code from the "
"diagnostics, not by an author's judgement — a failed pre-trend automatically "
"demotes the artifact to `descriptive` with no override.",
"",
]
if exp:
p = exp["result"]["primary"]
if p.get("balance_table"):
worst = max(p["balance_table"], key=lambda x: abs(x["correlation_with_exposure"]))
b += [
f"Even where pre-trends pass, exposure is **not randomly assigned**: its "
f"correlation with `{worst['variable']}` is "
f"{_fmt(worst['correlation_with_exposure'], 2)}. Predetermined is not "
"exogenous, and we use **no instrumental-variable language** anywhere.",
"",
]
b += [
"What is *not* identified even in the best case: the **aggregate** effect of the "
"national rate increase. The rate path is common to every geography and is "
"absorbed by time fixed effects. This design can only speak to differences "
"across exposure.",
"",
]
b += [
"### 8. Which evidence is correlational?",
"",
"- Every loan-level hazard result (`hazard_association`).",
"- Every descriptive table, survival curve, and cumulative-incidence function "
"(`descriptive`).",
"- Every event-study outcome demoted by a failed or untestable pre-trend.",
"- The predictive-benchmark comparison, which speaks to fit and nothing else.",
"",
"The loan-level and market-level results are deliberately reported in separate "
"files so that a reader cannot accidentally borrow the credibility of one for "
"the other.",
"",
]
b += ["### 9. Which policy scenarios appear most effective under the model?", ""]
if comp:
r = comp["result"]
b += ["| scenario | modelled additional monthly prepayments | % change |", "|---|---|---|"]
for row in r["ranking"][:8]:
b.append(
f"| {row['policy_type']} | "
f"{_fmt(row['additional_monthly_prepayments'], 1)} | "
f"{_fmt((row['pct_change_in_prepayments'] or 0) * 100, 1)}% |"
)
b += [
"",
"**Read the ordering, not the magnitudes.** These are "
"`simulation`-tier projections and explicitly **not forecasts**. They apply "
"a hazard *association* as if it were a structural response function, and "
"the mapping into transactions, prices, and permits rests on calibrated "
"elasticities with no error bars plus an **unidentified** "
"prepayment-to-transaction share (reported across a range, never as a point "
"value).",
"",
"Three points a policy reader should take from the scenario set:",
"",
"1. **Portability and assumability transfer the below-market-coupon loss, "
"they do not eliminate it.** Someone holds the cheap coupon; the scenarios "
"do not model who pays.",
"2. **Cost per *additional* transaction is far above cost per assisted "
"borrower**, because most assisted borrowers would have transacted anyway. "
"The buydown scenario reports both.",
"3. **Supply elasticity and lock-in policy are complements.** The same "
"modelled demand shift converts into mostly-quantity or mostly-price "
"depending on a calibrated supply elasticity — which is why a demand-side "
"unlock in an inelastic market partly capitalises into prices.",
"",
]
b += [
"### 10. What are the largest limitations?",
"",
"1. **A prepayment is not a move.** Zero Balance Code 01 pools refinancing, "
"sale-related payoff, and maturity. Nothing here separates them, so nothing here "
"measures mobility.",
"2. **Only relative effects are identified**, never the aggregate effect of the "
"rate increase.",
"3. **Predetermined exposure is not exogenous** — it correlates with pandemic "
"price growth and refinance intensity, which independently predict post-2022 "
"outcomes.",
"4. **The population is doubly selected**: conforming conventional Freddie Mac "
"acquisitions, within a mortgage market that itself excludes cash buyers and the "
"roughly one third of owner-occupied homes with no mortgage.",
"5. **The demand/supply decomposition is framed, not achieved.** No listings "
"data, no transaction records, no household panel.",
"6. **Low power at the state level.** 26 clusters and a narrow exposure spread.",
]
if grid and grid["result"].get("n_flagged") is not None:
b.append(
f"7. **Robustness:** {_fmt(grid['result']['n_flagged'])} of "
f"{_fmt(grid['result']['n_cells'])} specification cells were flagged as sign "
"flips, inestimable, or failing placebos. See `reports/failed_hypotheses.md`."
)
b.append("")
b += [
"---",
"",
"## What would change these conclusions",
"",
"| would resolve | needs |",
"|---|---|",
"| lock-in and mobility | linked mortgage-and-property records, or a "
"credit-bureau address panel |",
"| refinance vs sale payoff | a property identifier, or a servicer panel |",
"| listing vs repeat-buyer channel | MLS listings data |",
"| statistical power | MSA-level analysis with a versioned crosswalk, plus both "
"Enterprises' loan-level files |",
"| exogenous exposure | a shifter of the local coupon distribution unrelated to "
"local demand — we have not found one |",
"",
]
return _write(cfg, "executive_housing_policy_memo", ctx, "\n".join(b))
def render_technical(cfg: Config) -> Path:
ctx = ReportContext(cfg)
ds = ctx.get("hazards", "survival_dataset")
logit = ctx.get("hazards", "dt_logit_prepayment")
gap = ctx.get("hazards", "gap_profile_nonlinear")
exp = ctx.get("eventstudy", "exposure_distribution")
purchase = ctx.get("eventstudy", "es_log_purchase_originations")
grid = ctx.get("robustness", "robustness_grid")
comp = ctx.get("scenarios", "scenario_comparison")
val = ctx.get("validation", "validation_report")
b = [
VOCAB_NOTE,
"",
"## 0. How to read this document",
"",
"Every claim below is tagged with an **evidence tier**. The tiers are not "
"decorative: they determine the verb the sentence is allowed to use.",
"",
"| tier | permitted language | what it means |",
"|---|---|---|",
'| `descriptive` | "describes", "among … the rate was" | means, rates, '
"distributions. No causal content |",
'| `hazard_association` | "is associated with", "predicts" | conditional '
"correlation from a duration model |",
'| `quasi_experimental` | "reduced", "increased" — **only** with passing '
"pre-trends and clean placebos | event study / DiD with a stated identification "
"argument |",
'| `simulation` | "under the model", "model-dependent" | counterfactual '
"projection. **Never a forecast** |",
"",
"A sentence that mixes tiers is a defect. The decision rule is in "
"`docs/IDENTIFICATION_STRATEGY.md` §6 and is enforced by "
"`lockin.reporting.render.verb_for`.",
"",
"---",
"",
"## 1. Research question and design",
"",
"> How does the gap between homeowners' existing mortgage rates and current market "
"mortgage rates affect mortgage exits, housing-market activity, local prices, and "
"new construction?",
"",
"Four layers:",
"",
"1. **Loan-level duration analysis** — does a larger rate gap predict lower "
"prepayment? (`hazard_association`)",
"2. **Local-market panel** — how do exposure, originations, prices, and permits "
"co-move? (`descriptive`)",
"3. **Quasi-experimental design** — continuous-treatment event study on "
"predetermined exposure. (`quasi_experimental`, conditional on diagnostics)",
"4. **Counterfactual module** — hazard-based policy scenarios. (`simulation`)",
"",
"The layers answer different questions and are reported in separate files "
"precisely so their credibility does not leak into one another.",
"",
]
b += [
"## 2. Data and population",
"",
"| source | what it is | role | access |",
"|---|---|---|---|",
"| Freddie Mac Single-Family Loan-Level | origination + monthly performance | "
"exits, coupon distribution | **registration required**; not redistributed |",
"| Freddie Mac PMMS | weekly national average offered rate | the market rate in "
"every gap measure | public |",
"| FHFA HPI | repeat-sales index | price outcome, LTV scaling | public |",
"| HMDA (CFPB Data Browser) | applications and originations | purchase/refi "
"activity, denial rate | public API |",
"| Census BPS | permits authorized | construction outcome | public |",
"",
]
if ds:
ll = ds["result"]["loan_level"]
r = ds["result"]
b += [
f"This run: **{_fmt(ll['n_loans'])}** loans, "
f"**{_fmt(r['estimation_sample']['n_rows'])}** estimation loan-months over "
f"`{r['estimation_sample']['period']}`, "
f"**{_fmt(ll['n_prepayments'])}** prepayments, "
f"**{_fmt(ll['n_credit_events'])}** credit events, "
f"**{_fmt(ll['n_censored'])}** censored, "
f"**{_fmt(ll['n_left_truncated'])}** left truncated.",
"",
]
b += [
"**The population is not the market.** Conforming conventional Freddie Mac "
"acquisitions only: no FHA/VA (which are *assumable*, so lock-in works "
"differently there), no jumbo, no non-QM, no portfolio, no Fannie Mae, no "
"all-cash purchases, and no mortgage-free owners. Full treatment in "
"`reports/methodology_and_limitations.md` §3.",
"",
]
b += ["## 3. Loan-level results — `hazard_association`", ""]
if gap:
emp = gap["result"]["prepayment"]["empirical"]
if emp:
b += [
"Monthly prepayment hazard by rate-gap bucket:",
"",
"| bucket | loan-months | hazard |",
"|---|---|---|",
]
for r0 in emp:
b.append(f"| {r0['label']} | {_fmt(r0['n_at_risk'])} | {_fmt(r0['hazard'], 5)} |")
b.append("")
if logit:
r = logit["result"]
rg = next((c for c in r["coefficients"] if c["term"] == "rate_gap"), None)
if rg:
b += [
f"Discrete-time logit, {_fmt(r['n_obs'])} loan-months, "
f"{_fmt(r['n_events'])} events, {r['standard_errors']}: rate-gap "
f"coefficient **{_fmt(rg['coef'])}** (s.e. {_fmt(rg['std_err'])}), hazard "
f"ratio **{_fmt(rg['hazard_ratio'], 3)}** per pp, average marginal effect "
f"**{_fmt(r.get('rate_gap_average_marginal_effect_monthly'), 6)}** per month.",
"",
]
b += [f"> {r['interpretation_warning']}", ""]
b += [
"Full ladder — Kaplan–Meier, cumulative incidence, logit, cloglog, "
"cause-specific competing risks, Cox with PH diagnostics, and a gradient-boosted "
"predictive benchmark — in `reports/loan_hazard_analysis.md`.",
"",
]
b += [
"## 4. Identification for the market-level design",
"",
"$$E_g = \\sum_k \\omega_{gk}^{\\text{pre}} \\cdot "
"\\mathbf 1\\{\\bar R^{\\text{post}} - r_k > \\tau\\}$$",
"",
"Frozen pre-shock coupon shares × the later national rate level. All "
"cross-sectional variation is in the shares.",
"",
]
if exp:
p = exp["result"]["primary"]
if p.get("status") == "ok":
b += [
f"Exposure `{p['exposure']}`: mean {_fmt(p['mean'])}, s.d. "
f"{_fmt(p['sd'])}, range [{_fmt(p['min'])}, {_fmt(p['max'])}] across "
f"{_fmt(p['n_geographies'])} states, standardised in every regression.",
"",
]
if p.get("balance_table"):
b += ["| pre-period variable | correlation with exposure |", "|---|---|"]
for r0 in p["balance_table"]:
b.append(f"| `{r0['variable']}` | {_fmt(r0['correlation_with_exposure'], 3)} |")
b += [
"",
"These correlations are the reason **no IV interpretation is "
"claimed**. Predetermined ≠ exogenous.",
"",
]
b += [
"Assumptions, threats, and the decision rule for causal language: "
"`docs/IDENTIFICATION_STRATEGY.md`.",
"",
]
b += ["## 5. Market-level results", ""]
if purchase:
es = purchase["result"].get("event_study", {})
did = purchase["result"].get("did_two_period", {})
pt = es.get("pretrend_test", {}) if es.get("status") == "ok" else {}
b += [
f"Headline outcome: log HMDA purchase originations. Tier "
f"`{purchase['evidence_tier']}`; pre-trend p = {_fmt(pt.get('pvalue'), 3)} "
f"({'passes' if pt.get('passes_at_alpha_0.10') else 'fails'} at α = 0.10).",
"",
]
if did.get("status") == "ok":
b += [
f"Collapsed DiD: **{_fmt(did['coef'])}** (s.e. {_fmt(did['std_err'])}, "
f"t = {_fmt(did.get('t'), 2)}, {_fmt(did['n_clusters'])} clusters).",
"",
]
b += [
"Every outcome, its dynamic path, pre-trends, and placebos: "
"`reports/local_market_event_study.md`. Why quantities are unambiguous and prices "
"are not: `reports/demand_supply_decomposition.md`.",
"",
]
b += ["## 6. Robustness", ""]
if grid and grid["result"].get("n_cells"):
r = grid["result"]
b += [
f"{_fmt(r['n_cells'])} specification cells; {_fmt(r['n_flagged'])} flagged.",
"",
"| verdict | cells |",
"|---|---|",
]
for v in r["verdict_counts"]:
b.append(f"| `{v['verdict']}` | {_fmt(v['n'])} |")
b += [
"",
"Cells vary the exposure definition, the bp threshold, the weighting "
"(count vs UPB), the control set, sample exclusions (pandemic-boom and "
"high-refi markets), the HMDA coverage regime, panel balance, placebo shock "
"dates, and placebo outcomes.",
"",
"Failures are enumerated in `reports/failed_hypotheses.md`, together with "
"five genuine **design errors** caught during construction and the "
"diagnostics that caught them.",
"",
]
b += ["## 7. Counterfactuals — `simulation`", ""]
if comp:
r = comp["result"]
b += ["| scenario | additional monthly prepayments | % change |", "|---|---|---|"]
for row in r["ranking"][:6]:
b.append(
f"| {row['policy_type']} | "
f"{_fmt(row['additional_monthly_prepayments'], 1)} | "
f"{_fmt((row['pct_change_in_prepayments'] or 0) * 100, 1)}% |"
)
b += ["", f"> {r['not_a_forecast']}", ""]
b += [
"Detail, calibrated inputs, and the unidentified prepayment-to-transaction share: "
"`reports/policy_counterfactuals.md`.",
"",
]
b += ["## 8. Validation and reproducibility", ""]
if val:
r = val["result"]
b += [
f"`make validate-data`: **{_fmt(r['n_hard'])} hard**, {_fmt(r['n_soft'])} "
f"soft, {_fmt(r['n_info'])} informational findings. A hard finding fails the "
"run.",
"",
]
b += [
"Every artifact records git commit, config digest, data period, and per-dataset "
"`schema@retrieved#checksum`. Every dataset on disk carries a manifest with a "
"SHA-256 checksum that `make validate-data` re-verifies. Reproduction steps and "
"the reviewer checklist: `reports/replication_protocol.md`.",
"",
"## 9. What this project does not establish",
"",
"1. Any effect of lock-in on household **mobility**. No mobility measure exists "
"in these data.",
"2. Any effect on home **sales** or **listings**. No sale indicator, no listings source.",
"3. The **aggregate** effect of the 2022–23 rate increase. Absorbed by time fixed effects.",
"4. A **decomposition** of the listing-side and repeat-buyer-side channels.",
"5. Behaviour of FHA/VA, jumbo, non-QM, portfolio, or all-cash segments.",
"6. Any **forecast**. The scenario module is explicitly not one.",
"",
]
return _write(cfg, "technical_report", ctx, "\n".join(b))
def render_all(cfg: Config) -> list[Path]:
"""Regenerate every report. Order matters only for readability of the log."""
# Stamp the reports directory with the profile that produced it. `reports/` is a
# shared path, so without this a reader -- or a governance test -- has no way to tell
# whether the markdown on disk came from a SYNTHETIC or a REGISTERED run, and would
# have to guess from whichever config it happened to load.
from lockin import dataset_stamp
dataset_stamp.write(cfg, cfg.path("reports"))
return [
render_loan_hazard(cfg),
render_event_study(cfg),
render_decomposition(cfg),
render_policy(cfg),
render_failed(cfg),
render_methodology(cfg),
render_replication_protocol(cfg),
render_benchmark(cfg),
render_executive_memo(cfg),
render_technical(cfg),
]
def _unused(x: pl.DataFrame) -> None: # pragma: no cover
return None