import csv import json import time import urllib.request from pathlib import Path OUT_DIR = Path("data") OUT_DIR.mkdir(exist_ok=True) INDICATORS = { "NY.GDP.MKTP.CD": "GDP current US$", "NY.GDP.MKTP.KD.ZG": "GDP growth annual %", "NE.EXP.GNFS.CD": "Exports of goods and services current US$", "NE.IMP.GNFS.CD": "Imports of goods and services current US$", "FP.CPI.TOTL.ZG": "Inflation consumer prices annual %", "SL.UEM.TOTL.ZS": "Unemployment total % of labor force", "IC.BUS.EASE.XQ": "Ease of doing business rank", "BX.KLT.DINV.CD.WD": "Foreign direct investment net inflows current US$" } START_YEAR = 2015 END_YEAR = 2024 def fetch_indicator(indicator_code): url = ( f"https://api.worldbank.org/v2/country/all/indicator/{indicator_code}" f"?format=json&per_page=20000&date={START_YEAR}:{END_YEAR}" ) with urllib.request.urlopen(url, timeout=60) as response: data = json.loads(response.read().decode("utf-8")) if not isinstance(data, list) or len(data) < 2: return [] return data[1] or [] records = [] for code, name in INDICATORS.items(): print(f"Downloading {code} - {name}") rows = fetch_indicator(code) for item in rows: country = item.get("country") or {} value = item.get("value") records.append({ "country": country.get("value"), "country_code": item.get("countryiso3code"), "indicator_code": code, "indicator_name": name, "year": int(item["date"]) if item.get("date") else None, "value": value, "source": "World Bank Open Data", "license": "CC BY 4.0" }) time.sleep(0.5) jsonl_path = OUT_DIR / "worldbank_business_indicators.jsonl" csv_path = OUT_DIR / "worldbank_business_indicators.csv" with jsonl_path.open("w", encoding="utf-8") as f: for record in records: f.write(json.dumps(record, ensure_ascii=False) + "\n") with csv_path.open("w", encoding="utf-8", newline="") as f: writer = csv.DictWriter(f, fieldnames=[ "country", "country_code", "indicator_code", "indicator_name", "year", "value", "source", "license" ]) writer.writeheader() writer.writerows(records) metadata = { "name": "Realigns World Bank Business Indicators", "description": "Developer-friendly business and economic indicators dataset from World Bank Open Data.", "source": "World Bank Open Data API", "license": "CC BY 4.0", "start_year": START_YEAR, "end_year": END_YEAR, "indicators": INDICATORS, "record_count": len(records) } (Path("metadata.json")).write_text(json.dumps(metadata, indent=2), encoding="utf-8") print(f"Done. Records: {len(records)}") print(f"Saved: {jsonl_path}") print(f"Saved: {csv_path}")