SPB Git

Repository Public Research preview

12_revision.py 6.9 KB 126 lines python

1"""Analyses added in response to the first internal review round (all labelled post-review in the paper).23R1. Shock relevance ("first stage"): do the news shocks move green-minus-brown equity returns?4R2. Option-side positive control: does a known risk shifter move the crash-risk skew by a known characteristic?5R3. Dated, signed climate-policy events: cross-sectional event study of the crash-risk skew on exposure.6R4. Leverage: share of exposure variance due to NOK and RUB; rank-based exposure.7R5. Economic benchmark for the equivalence margin (effect implied by a 1pp change in annual intensity).8"""9import json1011import numpy as np12import pandas as pd13import statsmodels.api as sm1415import jumpmodel as jm16from config import DER, EXT, RES17from panel import fe_ols18from sample import CONTROLS, add_interactions, daily_panel, raw_exposure, winsor1920out = {}21sh = pd.read_parquet(DER / "daily_shocks.parquet")222324def etf(s):25    j = json.load(open(EXT / "yahoo" / f"etf_{s}.json"))["chart"]["result"][0]26    x = pd.Series(j["indicators"]["adjclose"][0]["adjclose"], index=pd.to_datetime(j["timestamp"], unit="s").normalize()).dropna()27    return 100 * np.log(x[~x.index.duplicated()]).diff()282930# ---------------- R1: relevance31R = pd.DataFrame({s: etf(s) for s in ["PBW", "ICLN", "TAN", "XLE", "SPY"]})32d = sh.join(R).loc["2006-01-04":"2025-06-25"]33d["gmb_pbw"] = d.PBW - d.XLE34d["gmb_icln"] = d.ICLN - d.XLE35rows = []36for y in ["gmb_pbw", "gmb_icln", "PBW", "XLE"]:37    for X in (["u_pol", "u_phy"], ["u_agg"], ["bua_tri", "bua_pri"]):38        for ctl in ([], ["SPY", "r_brent"]):39            q = d[[y] + X + ctl].dropna()40            m = sm.OLS(q[y], sm.add_constant(q[X + ctl])).fit(cov_type="HAC", cov_kwds={"maxlags": 5})41            for x in X:42                rows.append(dict(y=y, x=x, ctl="+".join(ctl), b=m.params[x], se=m.bse[x], t=m.tvalues[x], n=int(m.nobs), sd_y=q[y].std()))43    # cumulative 2-day response (t and t+1), since newspapers and markets may be misaligned by a day44    q = d[[y, "u_pol", "u_phy", "SPY", "r_brent"]].copy(); q["y2"] = q[y] + q[y].shift(-1); q["c1"] = q.SPY + q.SPY.shift(-1); q["c2"] = q.r_brent + q.r_brent.shift(-1)45    q = q.dropna(); m = sm.OLS(q.y2, sm.add_constant(q[["u_pol", "u_phy", "c1", "c2"]])).fit(cov_type="HAC", cov_kwds={"maxlags": 5})46    for x in ["u_pol", "u_phy"]:47        rows.append(dict(y=y + " [t,t+1]", x=x, ctl="SPY+r_brent", b=m.params[x], se=m.bse[x], t=m.tvalues[x], n=int(m.nobs), sd_y=q.y2.std()))48FS = pd.DataFrame(rows); FS.to_csv(RES / "rev_first_stage.csv", index=False)49print(FS.round(4).to_string())5051# ---------------- R2: option-side positive control52OUT = ["d_cr25", "d_cr10", "d_atm", "d_bf10"]53p = winsor(daily_panel("1M"), OUT + ["r_fx"])54e = raw_exposure()55ccys = sorted(p.ccy.unique())56# pre-sample riskiness characteristic: (minus) log GDP per capita 2000-04 -> emerging-market status57em = -np.log(e.gdp_pc_pre.reindex(ccys)); em = (em - em.mean()) / em.std()58p["EM"] = p.ccy.map(em)59# characteristic based on the level of the skew in the first sample year (2006), i.e. predetermined crash-proneness60cr0 = p[p.date < "2007-01-01"].groupby("ccy").cr25.mean().reindex(ccys); cr0 = (cr0 - cr0.mean()) / cr0.std()61p["CR0"] = p.ccy.map(cr0)62pc = []63for ch in ["EM", "CR0", "F"]:64    for y in OUT:65        X = add_interactions(p, [], (ch,), CONTROLS)66        f = fe_ols(p, y, X)67        for j, nme in enumerate(f.names):68            pc.append(dict(char=ch, y=y, x=nme.split(":")[0], b=f.b[j], se=f.se()[j], t=f.t()[j], t_dk=f.t("dk")[j], n=f.n))69PC = pd.DataFrame(pc); PC.to_csv(RES / "rev_positive_control.csv", index=False)70print(PC[PC.x.isin(["d_vix", "r_brent"])].round(4).to_string())71# own spot return -> skew (within currency-date FE this is the textbook spot-skew relation)72f = fe_ols(p, "d_cr25", ["r_fx"]); out["b_spot_skew"] = float(f.b[0]); out["t_spot_skew"] = float(f.t()[0])7374# ---------------- R3: dated, signed events75EV = [  # (date of first trading day on which the news is in prices, sign: +1 tightening / -1 loosening, label, election?)76    ("2009-12-21", -1, "Copenhagen summit ends without binding deal", 0),77    ("2014-11-12", +1, "US-China joint climate announcement", 0),78    ("2015-12-14", +1, "Paris Agreement adopted (12 Dec)", 0),79    ("2016-02-10", -1, "US Supreme Court stays Clean Power Plan (9 Feb, after close)", 0),80    ("2016-11-09", -1, "US election 2016", 1),81    ("2017-06-01", -1, "US announces withdrawal from Paris Agreement", 0),82    ("2019-12-11", +1, "European Green Deal presented", 0),83    ("2020-11-09", +1, "US election 2020 called (7 Nov)", 1),84    ("2021-04-22", +1, "US pledges 50-52% cut at Leaders Summit", 0),85    ("2021-07-14", +1, "EU Fit for 55 package", 0),86    ("2022-06-30", -1, "West Virginia v. EPA", 0),87    ("2022-07-28", +1, "Inflation Reduction Act deal announced (27 Jul, after close)", 0),88    ("2024-11-06", -1, "US election 2024", 1),89]90lv = daily_panel("1M").sort_values(["ccy", "date"])91dates = np.sort(lv.date.unique())92er = []93for dte, sgn, lab, elec in EV:94    k = np.searchsorted(dates, np.datetime64(dte))95    for w, (a, b) in {"[-1,+1]": (-1, 1), "[-1,+5]": (-1, 5), "[-6,-1] placebo": (-6, -1)}.items():96        x0 = lv[lv.date == dates[k + a]].set_index("ccy"); x1 = lv[lv.date == dates[k + b]].set_index("ccy")97        dd = pd.DataFrame({"d_cr25": sgn * (x1.cr25 - x0.cr25), "d_cr10": sgn * (x1.cr10 - x0.cr10), "F": x0.F}).dropna()98        dd["event"], dd["win"], dd["elec"], dd["lab"] = dte, w, elec, lab99        er.append(dd.reset_index())100E = pd.concat(er)101ev = []102for w in E.win.unique():103    for nm, q in (("all 13 events", E[E.win == w]), ("10 non-election events", E[(E.win == w) & (E.elec == 0)])):104        for y in ["d_cr25", "d_cr10"]:105            q = q.copy(); q["date"] = pd.to_datetime(q.event)106            f = fe_ols(q, y, ["F"], fe=("time",))107            ev.append(dict(window=w, sample=nm, y=y, b=f.b[0], se=f.se()[0], t=f.t()[0], t_unit=f.t("unit")[0], n=f.n, sd_y=q[y].std()))108EVR = pd.DataFrame(ev); EVR.to_csv(RES / "rev_events.csv", index=False)109print(EVR.round(4).to_string())110per = E[E.win == "[-1,+1]"].groupby(["event", "lab"]).apply(lambda q: pd.Series({"slope": np.polyfit(q.F, q.d_cr25, 1)[0], "n": len(q)}), include_groups=False)111per.to_csv(RES / "rev_events_by_event.csv"); print(per.round(4).to_string())112113# ---------------- R4: leverage114F = e.F_netx_pre.reindex(ccys); dev2 = (F - F.mean()) ** 2115out["share_var_NOK_RUB"] = float(dev2[["NOK", "RUB"]].sum() / dev2.sum())116p["Frank"] = p.ccy.map((F.rank() - F.rank().mean()) / F.rank().std())117X = add_interactions(p, ["u_pol", "u_phy"], ("Frank",), CONTROLS)118f = fe_ols(p, "d_cr25", X); out.update(b_rank=float(f.b[0]), se_rank=float(f.se()[0]), t_rank=float(f.t()[0]))119120# ---------------- R5: economic benchmark121sig = p.atm.mean() / 100122for x in (0.05, 0.10, 0.20):123    out[f"bench_1pp_{int(x*100)}"] = float(100 * 0.01 * jm.dcr_dlam_exact(sig, 0.02, x, 1 / 12))   # vol points per 1pp of annual intensity124out["sd_dcr25"] = float(p.d_cr25.std())125json.dump(out, open(RES / "rev_misc.json", "w"), indent=1); print(json.dumps(out, indent=1))126
Files main
Menu

Theme