"""F1-conf-03: LPM of next-year default on end-of-year-t predictors. Run from workspace root.""" import json, os import numpy as np, pandas as pd import statsmodels.api as sm os.makedirs("out", exist_ok=True) raw = pd.read_csv("data/firm_panel.csv", dtype={"firm_id": str}) n_raw = len(raw) PRED = ["leverage", "cash_ratio", "log_sales"] 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)) step("0_read", "rows read from data/firm_panel.csv", n_raw, n_raw, "raw input") n_exact_dup = int(raw.duplicated().sum()) n_key_dup = int(raw.duplicated(["firm_id", "year"]).sum()) d = raw.drop_duplicates().reset_index(drop=True) assert not d.duplicated(["firm_id", "year"]).any(), "non-identical key duplicates present" step("1_dedupe", "drop exact duplicate rows (keep first)", n_raw, len(d), "assembly error: identical firm-year rows repeated") step("2_drop_rating_2025", "remove column rating_2025 (known 2025, uses realised defaults)", len(d), len(d), "violates information-availability rule; column removal only") n_b = len(d) n_miss_by_year = d.loc[d.default_next.isna(), "year"].value_counts().to_dict() d = d[d.default_next.notna()].copy() step("3_outcome_observed", "drop rows with missing default_next", n_b, len(d), "outcome year not observed at data cut (end 2022); no imputation") n_b = len(d) d = d.dropna(subset=PRED) step("4_complete_predictors", "drop rows with missing predictors", n_b, len(d), "listwise deletion (none expected)") d["default_next"] = d["default_next"].astype(int) d = d.sort_values(["firm_id", "year"]).reset_index(drop=True) analytic = d[["firm_id", "year"] + PRED + ["default_next"]] analytic.to_csv("out/analytic.csv", index=False) pd.DataFrame(ledger).to_csv("out/exclusions.csv", index=False) X = sm.add_constant(analytic[PRED]) groups = pd.factorize(analytic["firm_id"])[0] fit = sm.OLS(analytic["default_next"], X).fit(cov_type="cluster", cov_kwds={"groups": groups}) res = { "task_id": "F1-conf-03", "n_analysed": int(len(analytic)), "n_firms": int(analytic.firm_id.nunique()), "predictors_used": PRED, "variables_excluded": [ {"variable": "rating_2025", "reason": "Assigned in the 2025 review using realised default history through 2022 and sample-average leverage; not known at end of year t (look-ahead leakage). In the data every observed default is in rating D."}, {"variable": "firm_id", "reason": "identifier; used only for clustering, not as a predictor"}, {"variable": "year", "reason": "origin-year index; not part of the specified model"}, {"variable": "default_next", "reason": "outcome variable"}, ], "beta_leverage": float(fit.params["leverage"]), "se_leverage_cluster": float(fit.bse["leverage"]), "r2": float(fit.rsquared), "default_rate": float(analytic.default_next.mean()), "feasibility": "complete", "feasibility_reason": None, "data_issues": [ {"issue": f"{n_exact_dup} exact duplicate rows ({n_key_dup} duplicated firm_id-year keys, all identical copies)", "handling": "dropped duplicates keeping one copy; panel becomes 300 firms x 7 years"}, {"issue": "rating_2025 is a final-vintage field built from future defaults (information leakage)", "handling": "excluded from predictors and from out/analytic.csv"}, {"issue": f"default_next missing for {sum(n_miss_by_year.values())} deduplicated rows, by year: {{{', '.join(f'{int(k)}: {v}' for k, v in sorted(n_miss_by_year.items()))}}}", "handling": "excluded from estimation (outcome not observed at data cut); not imputed"}, ], "n_input_rows": {"firm_panel.csv": int(n_raw)}, "random_seed": None, # supplementary "beta_cash_ratio": float(fit.params["cash_ratio"]), "beta_log_sales": float(fit.params["log_sales"]), "intercept": float(fit.params["const"]), "ci95_leverage_low": float(fit.conf_int().loc["leverage", 0]), "ci95_leverage_high": float(fit.conf_int().loc["leverage", 1]), "p_leverage_cluster": float(fit.pvalues["leverage"]), "se_leverage_classical": float(sm.OLS(analytic["default_next"], X).fit().bse["leverage"]), "n_rows_after_dedupe": int(n_raw - n_exact_dup), } with open("out/results.json", "w") as f: json.dump(res, f, indent=2) print(json.dumps({k: res[k] for k in ["n_analysed", "n_firms", "beta_leverage", "se_leverage_cluster", "r2", "default_rate"]}, indent=2))