Repository Public Research preview
1"""Climate shocks, market controls and spot rates.23Outputs (data/derived):4 daily_shocks.parquet trading-day climate innovations and market controls5 monthly_shocks.parquet monthly CPU shocks and controls6 fx_spot.parquet USD price of each currency (bundle; Yahoo for currencies the bundle lacks)7"""8import json910import numpy as np11import openpyxl12import pandas as pd1314from config import DER, EXT1516POLICY = ["Climate Legislation/Regulations", "Carbon Tax", "Carbon Credits Market", "Agreements/Actions",17 "Climate Summits", "Government Programs", "Political Campaign", "Legal Actions",18 "Renewable Energy", "Carbon Reduction Technologies"]19PHYSICAL = ["Hurricanes/Floods", "Extreme Temperatures", "Water/Drought", "Glaciers/Ice Sheets",20 "Global Warming", "Ecosystems", "Forests", "Marine Wildlife", "Arctic Wildlife",21 "Food Shortage/Poverty", "Agriculture Shifts"]22BURN = 500 # trading days before the first out-of-sample innovation232425def fred(code):26 s = pd.read_csv(EXT / "fred" / f"{code}.csv", na_values=".")27 s.columns = ["date", code]28 s["date"] = pd.to_datetime(s["date"])29 return s.set_index("date")[code].astype(float)303132def trading_calendar():33 """US trading days = days with both a VIX close and an S&P 500 close (excludes exchange holidays)."""34 j = json.load(open(EXT / "gspc_yahoo.json"))["chart"]["result"][0]35 spx = pd.Series(j["indicators"]["quote"][0]["close"], index=pd.to_datetime(j["timestamp"], unit="s").normalize()).dropna()36 return fred("VIXCLS").dropna().loc["2003-01-01":"2026-06-30"].index.intersection(spx.index)373839def to_trading_days(s: pd.Series, cal) -> pd.Series:40 """Average calendar-day values into the next trading day (weekend news hits Monday)."""41 idx = cal.searchsorted(s.index, side="left")42 ok = idx < len(cal)43 return s[ok].groupby(cal[idx[ok]]).mean().reindex(cal)444546def expanding_ar_innovation(y: pd.Series, lags=5, burn=BURN) -> pd.Series:47 """One-step-ahead forecast errors from an expanding-window AR(lags) with weekday dummies.4849 Recursive least squares: coefficients used for day t only use data through t-1.50 """51 y = y.dropna()52 X = pd.concat([y.shift(k) for k in range(1, lags + 1)], axis=1)53 X.columns = [f"l{k}" for k in range(1, lags + 1)]54 wd = pd.get_dummies(y.index.dayofweek, dtype=float)55 wd.index = y.index56 X = pd.concat([X, wd], axis=1).dropna()57 yy = y.loc[X.index].values58 Xv = X.values59 k = Xv.shape[1]60 XtX = np.zeros((k, k))61 Xty = np.zeros(k)62 e = np.full(len(yy), np.nan)63 for t in range(len(yy)):64 if t >= burn:65 b = np.linalg.lstsq(XtX, Xty, rcond=None)[0]66 e[t] = yy[t] - Xv[t] @ b67 XtX += np.outer(Xv[t], Xv[t])68 Xty += Xv[t] * yy[t]69 return pd.Series(e, index=X.index)707172def std(s):73 return (s - s.mean()) / s.std()747576def daily():77 cal = trading_calendar()78 m = pd.read_csv(EXT / "mccc_2026_daily.csv.gz", parse_dates=["Date"]).set_index("Date")79 lv = pd.DataFrame({80 "mccc": to_trading_days(m["Aggregate"], cal),81 "mccc_pol": to_trading_days(m[POLICY].mean(axis=1), cal),82 "mccc_phy": to_trading_days(m[PHYSICAL].mean(axis=1), cal),83 })84 wb = openpyxl.load_workbook(EXT / "bua_pri_tri.xlsx", read_only=True)85 rows = [r[:5] for r in wb.worksheets[0].iter_rows(values_only=True) if r and hasattr(r[0], "year")]86 b = pd.DataFrame(rows, columns=["date", "tc", "tri", "pc", "pri"]).set_index("date").astype(float)87 # "concern" columns are the raw daily series; TRI/PRI are the authors' AR(1) innovations88 lv["bua_tc"] = to_trading_days(b["tc"], cal)89 lv["bua_pc"] = to_trading_days(b["pc"], cal)90 out = pd.DataFrame(index=cal)91 for c in ["mccc", "mccc_pol", "mccc_phy", "bua_tc", "bua_pc"]:92 out[c + "_lvl"] = lv[c]93 out["u_" + c.replace("mccc_", "").replace("bua_", "bua_")] = expanding_ar_innovation(lv[c])94 out = out.rename(columns={"u_mccc": "u_agg", "u_pol": "u_pol", "u_phy": "u_phy"})95 out["bua_tri"] = to_trading_days(b["tri"], cal)96 out["bua_pri"] = to_trading_days(b["pri"], cal)97 # market controls (daily changes / log returns)98 vix, brent, wti = fred("VIXCLS"), fred("DCOILBRENTEU"), fred("DCOILWTICO")99 usd, y2, y10, ovx = fred("DTWEXBGS"), fred("DGS2"), fred("DGS10"), fred("OVXCLS")100 out["vix"] = vix.reindex(cal)101 out["d_vix"] = out["vix"].diff()102 out["r_brent"] = 100 * np.log(brent[brent > 0]).reindex(cal).ffill(limit=3).diff()103 out["r_wti"] = 100 * np.log(wti[wti > 0]).reindex(cal).ffill(limit=3).diff()104 out["r_usd"] = 100 * np.log(usd).reindex(cal).ffill(limit=3).diff()105 out["d_y2"] = 100 * y2.reindex(cal).ffill(limit=3).diff()106 out["d_y10"] = 100 * y10.reindex(cal).ffill(limit=3).diff()107 out["d_ovx"] = ovx.reindex(cal).diff()108 j = json.load(open(EXT / "gspc_yahoo.json"))["chart"]["result"][0]109 spx = pd.Series(j["indicators"]["quote"][0]["close"],110 index=pd.to_datetime(j["timestamp"], unit="s").normalize()).dropna()111 spx = spx[~spx.index.duplicated()]112 out["spx"] = spx.reindex(cal)113 out["r_spx"] = 100 * np.log(out["spx"]).diff()114 sk = pd.read_csv(EXT / "SKEW_History.csv")115 sk["DATE"] = pd.to_datetime(sk["DATE"])116 out["skew_cboe"] = sk.set_index("DATE")["SKEW"].reindex(cal)117 # US daily news-based EPU (control for generic policy uncertainty)118 e = pd.read_csv(EXT / "All_Daily_Policy_Data.csv")119 e["date"] = pd.to_datetime(dict(year=e.year, month=e.month, day=e.day))120 epu = to_trading_days(np.log(e.set_index("date")["daily_policy_index"].clip(lower=1)), cal)121 out["u_epu"] = expanding_ar_innovation(epu)122 sd_cols = [c for c in out.columns if c.startswith("u_")] + ["bua_tri", "bua_pri"]123 samp = out.loc["2006-01-04":"2025-06-25", sd_cols]124 out[sd_cols] = (out[sd_cols] - samp.mean()) / samp.std()125 out.index.name = "date"126 out.to_parquet(DER / "daily_shocks.parquet")127 print(out.loc["2006":"2025-06", sd_cols + ["d_vix", "r_brent", "r_usd"]].describe().T.round(3))128 print(out.loc["2006":"2025-06", sd_cols + ["d_vix", "r_brent", "r_usd", "r_spx"]].corr().round(2).to_string())129130131def monthly():132 wb = openpyxl.load_workbook(EXT / "cpu_pu.xlsx", read_only=True)133 rows = list(wb["data"].iter_rows(values_only=True))134 c = pd.DataFrame(rows[1:], columns=rows[0])135 c["date"] = pd.PeriodIndex(c["date"].str.replace("M", "-"), freq="M")136 c = c.set_index("date").apply(pd.to_numeric, errors="coerce")137 out = c.copy()138 for col in ["cpu_index_narrow", "cpu_index_broad", "cpu_index_gavriilidis", "cpnews_index_narrow"]:139 y = np.log(c[col].where(c[col] > 0)).dropna()140 X = pd.concat([y.shift(1), y.shift(2), y.shift(3)], axis=1).dropna()141 Xc = np.column_stack([np.ones(len(X)), X.values])142 b = np.linalg.lstsq(Xc, y.loc[X.index].values, rcond=None)[0]143 out["u_" + col.replace("_index", "")] = y.loc[X.index] - Xc @ b144 out.to_parquet(DER / "monthly_shocks.parquet")145 print(out.loc["2006":"2025"].describe().T.round(3).to_string())146 print(out.loc["2006":"2025", [x for x in out.columns if x.startswith("u_") or "shock" in x or "instr" in x]].corr().round(2).to_string())147148149def spot():150 s = pd.read_parquet(DER / "fx_spot_bundle.parquet")151 have = set(s.ccy)152 add = []153 for ccy in ["CLP", "COP", "ILS", "PEN", "RUB", "THB", "HKD", "BRL"]:154 j = json.load(open(EXT / "yahoo" / f"{ccy}.json"))["chart"]["result"][0]155 x = pd.DataFrame({"date": pd.to_datetime(j["timestamp"], unit="s").normalize(),156 "px": j["indicators"]["quote"][0]["close"]}).dropna()157 x = x[x.px > 0].drop_duplicates("date")158 x["ccy"], x["s_usd"], x["src"] = ccy, 1 / x.px, "yahoo"159 if ccy in have: # overlap check only (BRL): report agreement with the bundle160 mm = x.merge(s[s.ccy == ccy], on=["ccy", "date"], suffixes=("_y", "_b"))161 print(ccy, "bundle-vs-yahoo daily log-return corr:",162 round(np.corrcoef(np.log(mm.s_usd_y).diff().dropna(), np.log(mm.s_usd_b).diff().dropna())[0, 1], 3))163 else:164 add.append(x[["ccy", "date", "s_usd", "src"]])165 s["src"] = "bloomberg"166 s = pd.concat([s] + add).sort_values(["ccy", "date"])167 s.to_parquet(DER / "fx_spot.parquet", index=False)168 print(s.groupby(["ccy", "src"]).date.agg(["min", "max", "count"]).to_string())169170171if __name__ == "__main__":172 daily()173 monthly()174 spot()175