Repository Public Research preview
1"""Assemble the estimation panels (daily and monthly) used by every analysis script."""2import numpy as np3import pandas as pd45from config import DER, EXCLUDE_BASELINE, RES, RUB_END, SAMPLE_END, SAMPLE_START67CONTROLS = ["r_brent", "d_vix", "r_usd", "d_y2"]8910def exposure(col="F_netx_pre", sample=None) -> pd.Series:11 e = pd.read_csv(RES / "country_exposure.csv", index_col=0)12 x = e[col].drop("USD", errors="ignore")13 if sample is not None:14 x = x.reindex(sample)15 return (x - x.mean()) / x.std()161718def raw_exposure() -> pd.DataFrame:19 return pd.read_csv(RES / "country_exposure.csv", index_col=0)202122def daily_panel(tenor="1M", exclude=EXCLUDE_BASELINE, fcol="F_netx_pre", max_gap=5) -> pd.DataFrame:23 p = pd.read_parquet(DER / "fx_panel_daily.parquet")24 p = p[(p.tenor == tenor) & (p.date >= SAMPLE_START) & (p.date <= SAMPLE_END) & ~p.ccy.isin(exclude)].copy()25 p = p[~((p.ccy == "RUB") & (p.date > RUB_END))]26 sh = pd.read_parquet(DER / "daily_shocks.parquet").reset_index()27 p = p[p.date.isin(sh.date)].sort_values(["ccy", "date"])28 lev = ["cr25", "cr10", "atm", "bf25", "bf10", "skew25", "skew10", "tail10", "left10", "right10"]29 g = p.groupby("ccy")30 gap = g["date"].diff().dt.days31 for v in lev:32 p["d_" + v] = g[v].diff().where(gap <= max_gap) # no differences across long quote gaps33 s = pd.read_parquet(DER / "fx_spot.parquet")34 s = s[s.date.isin(sh.date)].sort_values(["ccy", "date"])35 s["r_fx"] = 100 * np.log(s.s_usd).groupby(s.ccy).diff()36 s.loc[s.r_fx.abs() > 15, "r_fx"] = np.nan # bad ticks (documented in validation/)37 p = p.merge(s[["ccy", "date", "r_fx", "src"]], on=["ccy", "date"], how="left").merge(sh, on="date", how="left")38 ccys = sorted(p.ccy.unique())39 F = exposure(fcol, ccys)40 p["F"] = p.ccy.map(F)41 p["absF"] = p.ccy.map(_abs_gap(fcol, ccys))42 return p434445def _abs_gap(fcol, ccys):46 e = raw_exposure()[fcol]47 gap = (e.reindex(ccys) - e["USD"]).abs()48 return (gap - gap.mean()) / gap.std()495051def add_interactions(p, shocks, chars=("F",), controls=CONTROLS):52 cols = []53 for c in chars:54 for s in list(shocks) + list(controls):55 name = f"{s}:{c}"56 p[name] = p[s] * p[c]57 cols.append(name)58 return cols596061def winsor(p, cols, q=0.001):62 """Winsorise outcome changes at the q / 1-q quantiles (stale-then-jump quote artefacts)."""63 for c in cols:64 lo, hi = p[c].quantile([q, 1 - q])65 p[c] = p[c].clip(lo, hi)66 return p67