"""F1-conf-03: information-respecting analytic dataset and LPM of next-year default. Run from workspace root: ~/wp29/venv/bin/python out/analysis.py Reads only data/firm_panel.csv; writes out/results.json, out/analytic.csv, out/exclusions.csv. No randomness is used (random_seed = null).""" import json, os import numpy as np, pandas as pd import statsmodels.api as sm DATA = "data/firm_panel.csv" OUT = "out" os.makedirs(OUT, exist_ok=True) raw = pd.read_csv(DATA, dtype={"firm_id": str}) n_raw = len(raw) ledger, issues = [], [] 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 1: rows read step("1_read", "all data rows of firm_panel.csv", n_raw, n_raw, "rows read (excluding header)") # Step 2: drop rating_2025 column (information rule) PREDICTORS = ["leverage", "cash_ratio", "log_sales"] excluded = [{"variable": "rating_2025", "reason": "Final-vintage field assigned in 2025 using realised default history through 2022 " "and sample-average leverage; not known at end of origin year t (look-ahead / outcome leakage)."}, {"variable": "default_next", "reason": "Outcome variable (known only at end of year t+1); used as dependent variable, not as a predictor."}, {"variable": "firm_id", "reason": "Identifier; used only for clustering standard errors, not as a predictor."}, {"variable": "year", "reason": "Origin-year index; kept in analytic.csv for identification but not entered as a regressor " "(task model specifies leverage, cash_ratio, log_sales only)."}] df = raw.drop(columns=["rating_2025"]) step("2_drop_column_rating_2025", "remove column rating_2025 (known only in 2025)", len(df), len(df), "information-availability rule: value not known at end of year t; column removal, no rows removed") # Step 3: exact duplicate rows n_dup_key = int(raw.duplicated(["firm_id", "year"], keep=False).sum()) n_exact = int(raw.duplicated().sum()) before = len(df) df = df[~raw.duplicated()].copy() step("3_drop_exact_duplicates", "drop rows that are exact copies of an earlier row (all columns)", before, len(df), "assembly error: duplicated firm-year records; identical in every field so one copy kept") issues.append({"issue": f"{n_exact} exact duplicate rows ({n_dup_key} rows involved in duplicated firm_id-year keys); " "all duplicates identical across all columns", "handling": "kept first occurrence, dropped the copies (ledger step 3)"}) assert not df.duplicated(["firm_id", "year"]).any(), "conflicting firm-year duplicates remain" # Step 4: unobserved outcome before = len(df) miss = df["default_next"].isna() miss_years = sorted(df.loc[miss, "year"].unique().tolist()) df = df[~miss].copy() step("4_drop_unobserved_outcome", "drop firm-years with default_next empty", before, len(df), f"outcome year not observed at the end-2022 data cut (origin years {miss_years}); outcomes not imputed") issues.append({"issue": f"default_next missing for {int(miss.sum())} unique firm-years (origin years {miss_years}), " "because year t+1 is after the data cut", "handling": "excluded from estimation sample, not imputed (ledger step 4)"}) # Step 5: missing predictors (none expected, but checked) before = len(df) df = df.dropna(subset=PREDICTORS) step("5_drop_missing_predictors", "drop rows with any missing predictor", before, len(df), "complete-case requirement for OLS") n_floor = int((df["leverage"] == df["leverage"].min()).sum()) issues.append({"issue": f"leverage has a point mass of {n_floor} estimation-sample rows at its minimum " f"{df['leverage'].min()} (apparent floor/censoring in the extract)", "handling": "retained as recorded; noted as limitation"}) issues.append({"issue": "rating_2025 is a final-vintage field built from realised outcomes (perfectly separates " "defaulters: only rating D firms ever default)", "handling": "excluded from the analytic dataset (ledger step 2, variables_excluded)"}) df["default_next"] = df["default_next"].astype(int) df = df.sort_values(["firm_id", "year"]).reset_index(drop=True) # Baseline default_rate = float(df["default_next"].mean()) # OLS LPM with firm-clustered SE X = sm.add_constant(df[PREDICTORS]) y = df["default_next"] groups = pd.factorize(df["firm_id"])[0] fit = sm.OLS(y, X).fit(cov_type="cluster", cov_kwds={"groups": groups}) b = float(fit.params["leverage"]); se = float(fit.bse["leverage"]) df[["firm_id", "year"] + PREDICTORS + ["default_next"]].to_csv(f"{OUT}/analytic.csv", index=False) pd.DataFrame(ledger).to_csv(f"{OUT}/exclusions.csv", index=False) res = { "task_id": "F1-conf-03", "n_analysed": int(len(df)), "n_firms": int(df["firm_id"].nunique()), "predictors_used": PREDICTORS, "variables_excluded": excluded, "beta_leverage": round(b, 6), "se_leverage_cluster": round(se, 6), "ci95_leverage_cluster": [round(b - 1.959964 * se, 6), round(b + 1.959964 * se, 6)], "r2": round(float(fit.rsquared), 6), "default_rate": round(default_rate, 6), "coef_all": {k: round(float(v), 6) for k, v in fit.params.items()}, "se_all_cluster": {k: round(float(v), 6) for k, v in fit.bse.items()}, "se_leverage_nonrobust": round(float(sm.OLS(y, X).fit().bse["leverage"]), 6), "cluster_se_type": "statsmodels CR1 (small-sample corrected), G = number of firms", "feasibility": "complete", "feasibility_reason": None, "data_issues": issues, "n_input_rows": {"firm_panel.csv": int(n_raw)}, "random_seed": None, } with open(f"{OUT}/results.json", "w") as f: json.dump(res, f, indent=2) print(f"n_analysed={res['n_analysed']} n_firms={res['n_firms']} beta_leverage={res['beta_leverage']} " f"se={res['se_leverage_cluster']} r2={res['r2']} default_rate={res['default_rate']}")