SPB Git

spb/wp29_uqo

Public
4.0 KB · 82 lines python
1"""F5-conf-01: Walrasian equilibrium of a 2x2 Cobb-Douglas exchange economy.2Run from workspace root: ~/wp29/venv/bin/python out/analysis.py3Reads only data/, writes out/results.json and out/exclusions.csv. Deterministic (no randomness)."""4import json, hashlib, os5import numpy as np6import pandas as pd7from scipy.optimize import brentq89DATA, OUT = "data", "out"10end = pd.read_csv(os.path.join(DATA, "endowments.csv"))11par = pd.read_csv(os.path.join(DATA, "parameters.csv"))12n_rows = {"endowments.csv": int(len(end)), "parameters.csv": int(len(par))}13P = dict(zip(par["parameter"], par["value"].astype(float)))14issues = []1516# --- validation ---17assert sorted(end["agent"]) == ["A", "B"], "need exactly agents A and B"18assert not end.isna().any().any() and not par.isna().any().any()19e = end.set_index("agent")[["good1", "good2"]].astype(float)20alpha = {"A": P["alpha_A"], "B": P["alpha_B"]}21assert all(0 < a < 1 for a in alpha.values()), "alpha must lie in (0,1)"22assert (e.values > 0).all(), "endowments must be strictly positive"2324# aggregate endowments: derive from primary per-agent data, compare with summary sheet25agg1, agg2 = float(e["good1"].sum()), float(e["good2"].sum())26for g, agg in (("good1", agg1), ("good2", agg2)):27    rec = P[f"aggregate_endowment_{g}"]28    if not np.isclose(rec, agg, rtol=0, atol=1e-12):29        issues.append({30            "issue": f"parameters.csv aggregate_endowment_{g} = {rec} does not equal the sum of individual "31                     f"endowments in endowments.csv ({agg}); discrepancy {rec - agg:+g}.",32            "handling": f"Used the sum of the primary per-agent endowments ({agg}) in the market-clearing "33                        f"condition; the summary-sheet value {rec} was not used. Clearing against {rec} would be "34                        f"inconsistent with the agents' budget constraints (Walras' law would fail by p*({agg - rec:+g}))."})3536# --- demands ---37def wealth(i, p): return p * e.loc[i, "good1"] + e.loc[i, "good2"]38def x1(i, p): return alpha[i] * wealth(i, p) / p39def x2(i, p): return (1 - alpha[i]) * wealth(i, p)40def z1(p): return sum(x1(i, p) for i in "AB") - agg141def z2(p): return sum(x2(i, p) for i in "AB") - agg24243# --- closed form: z1(p)=0 => p = sum a_i e2_i / sum (1-a_i) e1_i ---44p_cf = (sum(alpha[i] * e.loc[i, "good2"] for i in "AB")45        / sum((1 - alpha[i]) * e.loc[i, "good1"] for i in "AB"))4647# --- independent numerical root of z1(p) (baseline check) ---48lo, hi = 1e-6, 1e649assert z1(lo) > 0 > z1(hi)50p_num = brentq(z1, lo, hi, xtol=1e-14, rtol=1e-15, maxiter=500)5152res = {53    "task_id": "F5-conf-01",54    "price_ratio_p1_over_p2": p_cf,55    "x1_A": x1("A", p_cf), "x2_A": x2("A", p_cf),56    "x1_B": x1("B", p_cf), "x2_B": x2("B", p_cf),57    "excess_demand_good1": z1(p_cf),58    "excess_demand_good2": z2(p_cf),59    "walras_law_residual": p_cf * z1(p_cf) + z2(p_cf),60    "walras_law_residual_offeq_max_abs": max(abs(p * z1(p) + z2(p)) for p in np.linspace(0.1, 10, 100)),61    "aggregate_endowment_good1": agg1,62    "aggregate_endowment_good2": agg2,63    "aggregate_endowment_good1_recorded": P["aggregate_endowment_good1"],64    "aggregate_endowment_good2_recorded": P["aggregate_endowment_good2"],65    "price_ratio_numerical": p_num,66    "price_abs_diff_closed_vs_numerical": abs(p_cf - p_num),67    "alpha_A": alpha["A"], "alpha_B": alpha["B"],68    "feasibility": "complete",69    "feasibility_reason": None,70    "data_issues": issues,71    "n_input_rows": n_rows,72    "n_analysed": int(len(e)),73    "random_seed": None,74}75with open(os.path.join(OUT, "results.json"), "w") as f:76    json.dump(res, f, indent=2)77pd.DataFrame([{"step": 1, "rule": "keep agents A and B with complete, strictly positive endowments",78               "n_before": len(end), "n_after": len(e), "n_removed": len(end) - len(e),79               "rationale": "no rows removed; all inputs valid"}]).to_csv(os.path.join(OUT, "exclusions.csv"), index=False)80print(f"p closed-form = {p_cf:.12g}; p numerical = {p_num:.12g}; z1 = {res['excess_demand_good1']:.3g}; "81      f"Walras residual = {res['walras_law_residual']:.3g}; data issues = {len(issues)}")82
Files · main
Menu

Theme