Repository Public Research preview
1"""Country-level fossil-fuel (transition) exposure from the World Bank WDI API.23Downloads are cached as raw JSON under data/external/wb/ (not in git; URLs are deterministic).4Output: results/country_exposure.csv (public aggregate data, in git)56Baseline exposure F_i (pre-analysis plan): net fuel exports / GDP, averaged over 2000-2004, i.e.7strictly before the option sample starts, so that it is predetermined with respect to every8climate shock used in the paper. Alternatives: fossil-fuel rents / GDP, fuel share of9merchandise exports, full-sample averages, CO2 intensity of GDP.10"""11import json12import subprocess1314import numpy as np15import pandas as pd1617from config import CCY_ISO3, EXT, RES1819IND = {20 "oil_rents": "NY.GDP.PETR.RT.ZS", "gas_rents": "NY.GDP.NGAS.RT.ZS", "coal_rents": "NY.GDP.COAL.RT.ZS",21 "fuel_x_share": "TX.VAL.FUEL.ZS.UN", "fuel_m_share": "TM.VAL.FUEL.ZS.UN",22 "merch_x": "TX.VAL.MRCH.CD.WT", "merch_m": "TM.VAL.MRCH.CD.WT", "gdp": "NY.GDP.MKTP.CD",23 "co2_int": "EN.GHG.CO2.RT.GDP.PP.KD", "gdp_pc": "NY.GDP.PCAP.CD",24}25WB = EXT / "wb"26WB.mkdir(parents=True, exist_ok=True)272829def fetch(code: str) -> pd.DataFrame:30 f = WB / f"{code}.json"31 if not f.exists():32 iso = ";".join(sorted(set(CCY_ISO3.values()) - {"TWN"}) + ["USA"])33 url = f"https://api.worldbank.org/v2/country/{iso}/indicator/{code}?format=json&per_page=20000&date=1995:2024"34 subprocess.run(["curl", "-sL", "-m", "60", "-o", str(f), url], check=True)35 js = json.loads(f.read_text())36 rows = [(r["countryiso3code"] or r["country"]["id"], int(r["date"]), r["value"]) for r in js[1]]37 return pd.DataFrame(rows, columns=["iso3", "year", code])383940def main():41 d = None42 for name, code in IND.items():43 x = fetch(code).rename(columns={code: name})44 d = x if d is None else d.merge(x, on=["iso3", "year"], how="outer")45 d["fossil_rents"] = d[["oil_rents", "gas_rents", "coal_rents"]].sum(axis=1, min_count=3)46 d["net_fuel_x_gdp"] = 100 * (d.fuel_x_share / 100 * d.merch_x - d.fuel_m_share / 100 * d.merch_m) / d.gdp47 iso2ccy = {v: k for k, v in CCY_ISO3.items()}48 iso2ccy["USA"] = "USD"4950 def avg(lo, hi, col):51 return d[(d.year >= lo) & (d.year <= hi)].groupby("iso3")[col].mean()5253 out = pd.DataFrame({54 "F_rents_pre": avg(2000, 2004, "fossil_rents"),55 "F_rents_full": avg(2005, 2021, "fossil_rents"),56 "F_oilgas_pre": avg(2000, 2004, "oil_rents") + avg(2000, 2004, "gas_rents"),57 "F_coal_pre": avg(2000, 2004, "coal_rents"),58 "F_netx_pre": avg(2000, 2004, "net_fuel_x_gdp"),59 "F_netx_full": avg(2005, 2021, "net_fuel_x_gdp"),60 "F_xshare_pre": avg(2000, 2004, "fuel_x_share"),61 "co2_int_pre": avg(2000, 2004, "co2_int"),62 "gdp_pc_pre": avg(2000, 2004, "gdp_pc"),63 })64 out.index = out.index.map(lambda i: iso2ccy.get(i, i))65 out.index.name = "ccy"66 out = out.sort_values("F_rents_pre", ascending=False)67 out.to_csv(RES / "country_exposure.csv")68 print(out.round(2).to_string())697071if __name__ == "__main__":72 main()73