"""F1-conf-03: information-respecting LPM of next-year default on leverage. Run from workspace root: ~/wp29/venv/bin/python out/analysis.py""" import json, os import numpy as np, pandas as pd import statsmodels.api as sm OUT = "out" os.makedirs(OUT, exist_ok=True) raw = pd.read_csv("data/firm_panel.csv", dtype={"firm_id": str}) n_raw = len(raw) ledger = [] def step(name, rule, before, after, why): ledger.append(dict(step=name, rule=rule, n_before=before, n_after=after, n_removed=before - after, rationale=why)) d = raw.copy() # 1. drop leakage column (column removal, no rows removed) d = d.drop(columns=["rating_2025"]) step("1_drop_rating_2025", "remove column rating_2025 (known 2025, uses realised defaults)", n_raw, len(d), "violates information-availability rule (post-origin, outcome-derived)") # 2. exact duplicate rows b = len(d); n_keydup = int(raw.duplicated(["firm_id", "year"]).sum()) d = d.drop_duplicates().reset_index(drop=True) step("2_drop_exact_duplicates", "drop exact duplicate firm-year rows (keep first)", b, len(d), "assembly error: identical repeated firm-year records would double-count") assert not d.duplicated(["firm_id", "year"]).any() n_dup_removed = b - len(d) # 3. unobserved outcome b = len(d); miss_years = sorted(d.loc[d.default_next.isna(), "year"].unique().tolist()) d = d[d.default_next.notna()].copy() step("3_drop_missing_outcome", "drop rows with default_next missing", b, len(d), "outcome not observed at data cut (end 2022); outcomes are not imputed") # 4. missing predictors preds = ["leverage", "cash_ratio", "log_sales"] b = len(d); d = d.dropna(subset=preds) step("4_drop_missing_predictors", "drop rows with any missing predictor", b, len(d), "complete-case OLS") d["default_next"] = d["default_next"].astype(int) d = d.sort_values(["firm_id", "year"]).reset_index(drop=True) X = sm.add_constant(d[preds]); y = d["default_next"] codes = pd.factorize(d["firm_id"])[0] fit = sm.OLS(y, X).fit(cov_type="cluster", cov_kwds={"groups": codes}) n_floor = int((d.leverage == d.leverage.min()).sum()) res = { "task_id": "F1-conf-03", "n_analysed": int(len(d)), "n_firms": int(d.firm_id.nunique()), "predictors_used": preds, "variables_excluded": [ {"variable": "rating_2025", "reason": "known only in 2025 and constructed from the firm's realised default history through 2022 (contains the outcome) and average leverage over the sample; violates the end-of-year-t availability rule (look-ahead/target leakage)"}, {"variable": "default_next", "reason": "outcome variable, not a predictor (known only at end of t+1)"}, {"variable": "firm_id", "reason": "identifier; used only for clustering, not as a regressor"}, {"variable": "year", "reason": "origin-year identifier; not part of the specified model"}, ], "beta_leverage": float(fit.params["leverage"]), "se_leverage_cluster": float(fit.bse["leverage"]), "r2": float(fit.rsquared), "default_rate": float(y.mean()), "feasibility": "complete", "feasibility_reason": None, "data_issues": [ {"issue": f"{n_dup_removed} exact duplicate firm-year rows ({n_keydup} duplicated firm_id-year keys, all with identical values)", "handling": "dropped duplicates keeping one copy; panel becomes balanced 300 firms x 7 years"}, {"issue": f"default_next missing for {int(raw.default_next.isna().sum())} raw rows, all in origin year(s) {miss_years} (outcome year not observed at data cut)", "handling": "rows excluded from estimation (ledger step 3); no imputation"}, {"issue": "rating_2025 is a final-vintage field built from realised defaults (outcome leakage)", "handling": "column excluded from analytic dataset"}, {"issue": f"leverage has a mass point at its minimum 0.02 ({n_floor} firm-years in estimation sample), suggesting floor/censoring in the extract", "handling": "kept as recorded; noted as limitation"}, ], "n_input_rows": {"firm_panel.csv": int(n_raw)}, "random_seed": None, "baseline_default_rate": float(y.mean()), "intercept": float(fit.params["const"]), "beta_cash_ratio": float(fit.params["cash_ratio"]), "beta_log_sales": float(fit.params["log_sales"]), "se_leverage_classical": float(sm.OLS(y, X).fit().bse["leverage"]), "ci95_leverage_cluster": [float(v) for v in fit.conf_int().loc["leverage"]], "p_leverage_cluster": float(fit.pvalues["leverage"]), "n_clusters": int(len(np.unique(codes))), } d[["firm_id", "year"] + preds + ["default_next"]].to_csv(f"{OUT}/analytic.csv", index=False) pd.DataFrame(ledger).to_csv(f"{OUT}/exclusions.csv", index=False) with open(f"{OUT}/results.json", "w") as f: json.dump(res, f, indent=2) print(f"n={res['n_analysed']} beta_leverage={res['beta_leverage']:.6f} se={res['se_leverage_cluster']:.6f} r2={res['r2']:.6f} default_rate={res['default_rate']:.6f}")