Repository Public Research preview
1"""H6 (S&P 500 tails, pre-specified) and three analyses labelled exploratory in experiments/DEVIATIONS.md:2directional climate policy uncertainty, long-dated options, dated policy events."""3import importlib4import re5import zipfile67import numpy as np8import pandas as pd9import statsmodels.api as sm1011from config import BUNDLE, DER, EXCLUDE_BASELINE, EXT, RES, RUB_END12from panel import fe_ols13from sample import exposure1415sh = pd.read_parquet(DER / "daily_shocks.parquet")16rows = []1718# ---------- H6: weekly S&P 500 option-implied tails (Bollerslev-Todorov estimates in the bundle) ----------19t = pd.read_csv(BUNDLE / "data/analytical/tails/spx_tail_risk_measures.csv", parse_dates=["date"])20# 32 Friday labels carry two estimates (quarter boundaries in the archive); keep converged fits and average them21t = t[(t.alpha_minus_success) & (t.LJV > 0) & (t.RJV > 0)]22t = t.groupby("date")[["LJV", "RJV", "LJI", "fear_component", "LTP", "atm_vol"]].mean()23wk = sh.loc["2009-12-01":"2025-07-04"].copy()24wk["rs_dn"] = wk.r_spx.clip(upper=0) ** 225wk["rs_up"] = wk.r_spx.clip(lower=0) ** 226W = wk.resample("W-FRI").agg({"u_pol": "sum", "u_phy": "sum", "u_agg": "sum", "bua_tri": "sum", "bua_pri": "sum",27 "u_epu": "sum", "r_spx": "sum", "rs_dn": "sum", "rs_up": "sum", "vix": "last",28 "skew_cboe": "last", "r_brent": "sum"})29W = W.join(t[["LJV", "RJV", "LJI", "fear_component", "LTP", "atm_vol"]])30for c in ["LJV", "RJV", "LJI", "atm_vol", "vix"]:31 W["dl_" + c] = np.log(W[c]).diff()32W["d_fear"] = W.fear_component.diff() * 10033W["d_skew"] = W.skew_cboe.diff()34W["rsemi"] = np.sqrt(W.rs_dn) - np.sqrt(W.rs_up) # realised downside-minus-upside semi-vol (weekly)35W["f_rsemi"] = W.rsemi.shift(-1)36W["f_rsdn4"] = np.sqrt(W.rs_dn.rolling(4).sum().shift(-4))37for c in ["u_pol", "u_phy", "u_agg", "bua_tri", "bua_pri", "u_epu"]:38 W[c] = W[c] / W[c].std()39for y in ["dl_LJV", "dl_RJV", "dl_LJI", "d_fear", "dl_atm_vol", "dl_vix", "d_skew", "r_spx", "rsemi", "f_rsemi", "f_rsdn4"]:40 for X in (["u_pol", "u_phy"], ["bua_tri", "bua_pri"], ["u_agg"]):41 for ctl in ([], ["r_spx"]):42 if ctl and y in ("r_spx", "rsemi"):43 continue44 q = W[[y] + X + ctl].replace([np.inf, -np.inf], np.nan).dropna()45 m = sm.OLS(q[y], sm.add_constant(q[X + ctl])).fit(cov_type="HAC", cov_kwds={"maxlags": 4})46 for x in X:47 rows.append(dict(block="H6 SPX weekly", y=y, x=x, ctl="+".join(ctl), b=m.params[x], se=m.bse[x], t=m.tvalues[x],48 n=int(m.nobs), sd_y=q[y].std()))4950# ---------- Exploratory A: directional CPU (Basaglia et al. 2025: uncertainty about strengthening vs weakening) ----------51mod = importlib.import_module("05_monthly")52d = mod.monthly_panel()53b = pd.read_csv(EXT / "cpu_base_pos_neg_all_countries_monthly.csv")54b.index = pd.PeriodIndex.from_fields(year=b.year, month=b.month, freq="M")55gk = pd.read_parquet(DER / "monthly_shocks.parquet")56dirs = {}57for c in ["CPU_US", "CPU_pos_US", "CPU_neg_US"]:58 y = np.log1p(b[c]).dropna()59 X = sm.add_constant(pd.concat([y.shift(1), y.shift(2), y.shift(3)], axis=1)).dropna()60 e = sm.OLS(y.loc[X.index], X).fit().resid61 dirs["u_" + c] = e / e.loc["2006-01":"2025-06"].std()62e = gk["cpsent_index"].dropna(); e = np.log(e)63X = sm.add_constant(pd.concat([e.shift(1), e.shift(2), e.shift(3)], axis=1)).dropna()64r = sm.OLS(e.loc[X.index], X).fit().resid; dirs["u_cpsent"] = r / r.loc["2006-01":].std()65D = pd.DataFrame(dirs)66d = d.merge(D, left_on="m", right_index=True, how="left")67for c in ["d_cr25", "d_cr10", "d_skew25", "d_atm", "d_bf10"]:68 lo, hi = d[c].quantile([.005, .995]); d[c] = d[c].clip(lo, hi)69for y in ["d_cr25", "d_cr10", "d_skew25", "d_atm"]:70 for S in (["u_CPU_pos_US", "u_CPU_neg_US"], ["u_CPU_US"], ["u_cpsent"]):71 X = []72 for v in S + mod.CTL:73 d[f"{v}:F"] = d[v] * d["F"]; X.append(f"{v}:F")74 f = fe_ols(d, y, X)75 for j, s in enumerate(S):76 rows.append(dict(block="Expl A directional monthly", y=y, x=s, ctl="controls", b=f.b[j], se=f.se()[j], t=f.t()[j],77 t_dk=f.t("dk")[j], n=f.n, sd_y=d[y].std()))7879# ---------- Exploratory B: long-dated options (climate transition is a long-horizon risk) ----------80z = zipfile.ZipFile(BUNDLE / "data/processed/bloom/option_price.zip")81o = pd.read_csv(z.open("option_price.csv"), engine="pyarrow")82m = o["ticker"].str.extract(r"^([A-Z]{3})([A-Z]{3})(V|\d+[RB])(\d+[DWMY]|ON) Curncy$")83o["base"], o["ctr"], o["q"], o["tenor"] = m[0], m[1], m[2], m[3]84o = o[((o.base == "USD") | (o.ctr == "USD")) & o.tenor.isin(["2Y", "5Y"]) & o.q.isin(["V", "25R", "25B"])]85o["ccy"] = np.where(o.base == "USD", o.ctr, o.base); o["date"] = pd.to_datetime(o["date"])86w = o.pivot_table(index=["ccy", "base", "tenor", "date"], columns="q", values="PX_LAST", aggfunc="first").reset_index().dropna()87w["cr25"] = np.where(w.base == "USD", 1, -1) * w["25R"]88w = w[(w.V > 0) & (w.cr25.abs() < w.V) & ~w.ccy.isin(EXCLUDE_BASELINE) & (w.date >= "2006-01-04")]89w = w[~((w.ccy == "RUB") & (w.date > RUB_END))].sort_values(["ccy", "tenor", "date"])90cov = w.groupby(["tenor", "ccy"]).size().unstack(0)91print("long-tenor coverage (currency-days):\n", cov.T.to_string())92for ten in ["2Y", "5Y"]:93 q = w[w.tenor == ten].copy()94 keep = q.groupby("ccy").size(); q = q[q.ccy.isin(keep[keep > 1500].index)]95 gap = q.groupby("ccy").date.diff().dt.days96 q["d_cr25"] = q.groupby("ccy").cr25.diff().where(gap <= 5)97 lo, hi = q.d_cr25.quantile([.001, .999]); q["d_cr25"] = q.d_cr25.clip(lo, hi)98 q = q.merge(sh.reset_index(), on="date")99 q["F"] = q.ccy.map(exposure("F_netx_pre", sorted(q.ccy.unique())))100 X = []101 for v in ["u_pol", "u_phy", "r_brent", "d_vix", "r_usd", "d_y2"]:102 q[f"{v}:F"] = q[v] * q.F; X.append(f"{v}:F")103 f = fe_ols(q, "d_cr25", X)104 for j in (0, 1):105 rows.append(dict(block=f"Expl B tenor {ten} daily", y="d_cr25", x=X[j], ctl="controls", b=f.b[j], se=f.se()[j], t=f.t()[j],106 t_dk=f.t("dk")[j], n=f.n, N=f.ni, sd_y=q.d_cr25.std()))107108R = pd.DataFrame(rows); R.to_csv(RES / "spx_and_exploratory.csv", index=False)109pd.set_option("display.width", 250)110print(R.round(4).to_string())111