"""VC1 · 45 · sensibilidades POSTERIORES (enmiendas 1-2): (s1) sin T2; (s2) τ² sin winsorizar; (s3) ambas. Recalcula hechos por año y la estabilidad B1→B2. No cambia el veredicto sellado. -> salidas/45_sensibilidad.json""" import duckdb, json, math, sys sys.path.insert(0, '/w/py') from comun import NMIN, Z998 c=duckdb.connect(); x=c.execute; A=50.0 x("CREATE TABLE l AS SELECT * FROM '/w/interno/lotes_p.parquet'") def tau2(rows, wins): zs=[(r-e)/s for r,e,s in rows if s>0]; I=len(zs) if I<2: return 0.0 if wins: q=sorted(zs); P=lambda p: q[int((I-1)*p)] + ((I-1)*p-int((I-1)*p))*(q[min(int((I-1)*p)+1,I-1)]-q[int((I-1)*p)]) lo,hi=P(.1),P(.9); zs=[min(max(z,lo),hi) for z in zs] phi=sum(z*z for z in zs)/I; w=[1/(s*s) for r,e,s in rows if s>0]; sw=sum(w); sw2=sum(a*a for a in w) return max((I*phi-(I-1))/(sw-sw2/sw),0.0) if I*phi>I-1 else 0.0 def corre(cond, wins): x(f"CREATE OR REPLACE TABLE l2 AS SELECT *, (fondo AND {cond})::INT kk FROM l") x("CREATE OR REPLACE TABLE pt AS SELECT tipo, anio, count(*)::DOUBLE n_t, sum(kk)::DOUBLE k_t FROM l2 GROUP BY ALL") x("CREATE OR REPLACE TABLE cm AS SELECT cpv_div, tipo, anio, count(*)::DOUBLE n_m, sum(kk)::DOUBLE k_m FROM l2 GROUP BY ALL") x("CREATE OR REPLACE TABLE co AS SELECT organo_clave, cpv_div, tipo, anio, count(*)::DOUBLE n_mo, sum(kk)::DOUBLE k_mo FROM l2 GROUP BY ALL") x(f"CREATE OR REPLACE TABLE cop AS SELECT co.*, (cm.k_m-co.k_mo+{A}*pt.k_t/pt.n_t)/(cm.n_m-co.n_mo+{A}) p FROM co JOIN cm USING (cpv_div,tipo,anio) JOIN pt USING (tipo,anio) WHERE organo_clave IS NOT NULL") out={} for nom, g in (('anio','anio'), ('bloque',"CASE WHEN anio<=2021 THEN 'B1' ELSE 'B2' END")): rows=x(f"SELECT organo_clave, {g} g, sum(n_mo) n, sum(k_mo) k, sum(n_mo*p) E, sum(n_mo*p*(1-p)) V FROM cop GROUP BY 1,2").fetchall() by={} for o,gg,n,k,E,V in rows: if n>=NMIN: by.setdefault(gg,[]).append((k/n,E/n,math.sqrt(V)/n)) t={gg:tau2(v,wins) for gg,v in by.items()} out[nom]={(o,gg):(n, n>=NMIN and k>=3 and (k/n-E/n)/math.sqrt(V/n/n+t[gg])>Z998) for o,gg,n,k,E,V in rows if gg in t} out[nom+'_tau2']=t ha={} for (o,a),(n,h) in out['anio'].items(): ha[a]=ha.get(a,0)+int(h) tb=[0,0,0,0] for (o,b),(n,h) in out['bloque'].items(): if b=='B1' and n>=NMIN and (o,'B2') in out['bloque'] and out['bloque'][(o,'B2')][0]>=NMIN: h2=out['bloque'][(o,'B2')][1]; tb[0 if h and h2 else 1 if h else 2 if h2 else 3]+=1 a_,b_,c_,d_=[v+.5 for v in tb] if 0 in tb else tb; orr=a_*d_/(b_*c_); se=math.sqrt(1/a_+1/b_+1/c_+1/d_) return {'hechos_por_anio':dict(sorted(ha.items())), 'hechos_total':sum(ha.values()), 'tau2_anio':{str(k):v for k,v in sorted(out['anio_tau2'].items())}, 'estabilidad_tabla':tb, 'OR':[orr, orr*math.exp(-1.96*se), orr*math.exp(1.96*se)]} R={'principal_recalculada':corre('TRUE',True), 's1_sin_T2':corre("tipo_cambio<>'T2'",True), 's2_tau_sin_winsor':corre('TRUE',False), 's3_ambas':corre("tipo_cambio<>'T2'",False)} json.dump(R, open('/w/salidas/45_sensibilidad.json','w'), ensure_ascii=False, indent=1, default=str) for k,v in R.items(): print(k, v['hechos_total'], v['estabilidad_tabla'], [round(z,2) for z in v['OR']], {a:round(t,5) for a,t in v['tau2_anio'].items()})