import pandas as pd, numpy as np
from linearmodels.panel import PanelOLS
m=pd.read_csv("econ_panel.csv")
# established democracy: long-run mean FreeScore >= 85 (>=10 obs)
fs=m.groupby("iso3")["FreeScore"].agg(["mean","count"])
estab=set(fs[(fs["mean"]>=85)&(fs["count"]>=10)].index)
m["established"]=m["iso3"].isin(estab).astype(int)
m=m[(m["year"]>=1985)&(m["year"]<=2008)].copy()
m["entity"]=m["iso3"]
def panel(df,dv,rhs):
    d=df.dropna(subset=[dv]+rhs+["iso3","year"]).copy()
    d=d.set_index(["iso3","year"])
    y=d[dv]; X=d[rhs]
    res=PanelOLS(y,X,entity_effects=True,time_effects=True).fit(cov_type="clustered",cluster_entity=True)
    return res,d
L=[]
def report(tag,res,d,key):
    b=res.params[key]; se=res.std_errors[key]; p=res.pvalues[key]; n=int(res.nobs)
    L.append(f"{tag:42s} coef={b:+.3f}  se={se:.3f}  p={p:.4f}  N={n}  countries={d.index.get_level_values(0).nunique()}")

print("=== STUDY A: political budget cycle (1985-2008) ===")
for dv,lab in [("fiscbal","fiscal balance %GDP (neg=deficit)"),("govexp","govt expense %GDP"),("govdebt","govt debt %GDP")]:
    try:
        res,d=panel(m,dv,["elec","gdp_growth","log_gdppc"]); report(f"A: {lab} ~ election",res,d,"elec")
    except Exception as e: L.append(f"A: {lab} ERR {e}")
# split established vs rest, fiscal balance
for grp,name in [(1,"ESTABLISHED dem"),(0,"NEWER/other")]:
    try:
        res,d=panel(m[m.established==grp],"fiscbal",["elec","gdp_growth","log_gdppc"]); report(f"A: fiscbal ~ election [{name}]",res,d,"elec")
    except Exception as e: L.append(f"A: fiscbal [{name}] ERR {e}")

print("=== STUDY B: investment & electoral uncertainty (1985-2008) ===")
for dv in ["invest"]:
    try:
        res,d=panel(m,dv,["elec","gdp_growth","log_gdppc"]); report("B: investment ~ election year",res,d,"elec")
    except Exception as e: L.append(f"B ERR {e}")
    try:
        res,d=panel(m,dv,["elec_prev","gdp_growth","log_gdppc"]); report("B: investment ~ post-election year",res,d,"elec_prev")
    except Exception as e: L.append(f"B2 ERR {e}")
print("\n".join(L))
open("results_econ.txt","w").write("\n".join(L))
