diff --git a/AUTHORS.md b/AUTHORS.md index 49ecd1e24..96ea7ff07 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -39,3 +39,4 @@ * Dahyann Araya * Giovanni Cozzolongo * Thomas Struys +* Napat Phasundhiae diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c6e1434f..004d913f7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ Code freeze date: YYYY-MM-DD ### Fixed +- `climada.util.finance`: Introduce `NoDataError` (`LookupError` subclass) for missing country/indicator data, handle missing World Bank indicators, fallback Natural Earth ISO attributes (`ISO_A3`, `WB_A3`, `ADM0_A3_US`), zero-GDP territories, and missing `wealth2gdp` factors [#1331](https://github.com/CLIMADA-project/climada_python/issues/1331) [#1349](https://github.com/CLIMADA-project/climada_python/pull/1349). + ### Deprecated ### Removed diff --git a/climada/util/finance.py b/climada/util/finance.py index 153555423..b850772dd 100644 --- a/climada/util/finance.py +++ b/climada/util/finance.py @@ -19,14 +19,16 @@ Finance functionalities. """ -__all__ = ["net_present_value", "income_group", "gdp"] +__all__ = ["NoDataError", "net_present_value", "income_group", "gdp"] import json import logging import shutil +import warnings import numpy as np import pandas as pd +import pycountry import requests from cartopy.io import shapereader @@ -36,6 +38,11 @@ LOGGER = logging.getLogger(__name__) + +class NoDataError(LookupError): + """Exception raised when requested financial data is unavailable for a country.""" + + WORLD_BANK_INC_GRP = "https://ddh-openapi.worldbank.org/resources/DR0095334/download" """Income group historical data from World bank.""" @@ -117,10 +124,20 @@ def income_group(cntry_iso, ref_year, shp_file=None): shape file with INCOME_GRP attribute for every country. Load Natural Earth admin0 if not provided. + + Returns + ------- + int, int + Closest year (0 for Natural Earth) and income group (1 to 4). + + Raises + ------ + NoDataError + If no income group data is found in World Bank or Natural Earth. """ try: close_year, close_val = world_bank(cntry_iso, ref_year, "INC_GRP") - except (KeyError, IndexError): + except NoDataError: # take value from natural earth repository close_year, close_val = nat_earth_adm0( cntry_iso, "INCOME_GRP", shp_file=shp_file @@ -142,14 +159,22 @@ def gdp(cntry_iso, ref_year, shp_file=None, per_capita=False): reference year shp_file : cartopy.io.shapereader.Reader, optional shape file with - INCOME_GRP attribute for every country. Load Natural Earth admin0 + GDP_MD attribute for every country. Load Natural Earth admin0 if not provided. per_capita : boolean, optional If True, GDP is returned per capita Returns ------- - float + int, float + Closest year and GDP value in current USD. + + Raises + ------ + NoDataError + If no GDP data is found in World Bank or Natural Earth. + ValueError + If ``cntry_iso`` is rejected as invalid by the World Bank API. """ if cntry_iso == "TWN": LOGGER.warning( @@ -163,9 +188,13 @@ def gdp(cntry_iso, ref_year, shp_file=None, per_capita=False): close_year, close_val = world_bank(cntry_iso, ref_year, "NY.GDP.PCAP.CD") else: close_year, close_val = world_bank(cntry_iso, ref_year, "NY.GDP.MKTP.CD") - except (ValueError, IndexError, requests.exceptions.ConnectionError) as err: + except (NoDataError, requests.exceptions.ConnectionError) as err: if isinstance(err, requests.exceptions.ConnectionError): - LOGGER.warning("Internet connection failed while retrieving GDPs.") + warnings.warn( + "Internet connection failed while retrieving GDPs.", + UserWarning, + stacklevel=2, + ) close_year, close_val = nat_earth_adm0( cntry_iso, "GDP_MD", "GDP_YEAR", shp_file ) @@ -174,6 +203,39 @@ def gdp(cntry_iso, ref_year, shp_file=None, per_capita=False): return close_year, close_val +def _is_missing_wb_country(country_code: str, indicator: str) -> bool: + """Return True if a World Bank ``id == '120'`` error is for a valid ISO3 + country lacking World Bank coverage rather than an invalid parameter. + """ + if ( + not isinstance(country_code, str) + or not isinstance(indicator, str) + or not indicator + or any(char in indicator for char in "/?#") + or pycountry.countries.get(alpha_3=country_code.upper()) is None + ): + return False + ind_url = f"https://api.worldbank.org/v2/indicators/{indicator}?format=json" + ind_resp = requests.get(ind_url, timeout=30) + if ind_resp.status_code != 200: + return False + try: + ind_data = json.loads(ind_resp.text) + except ValueError: + return False + return ( + isinstance(ind_data, list) + and len(ind_data) > 1 + and isinstance(ind_data[1], list) + and any( + isinstance(entry, dict) + and isinstance(entry.get("id"), str) + and entry["id"].upper() == indicator.upper() + for entry in ind_data[1] + ) + ) + + def download_world_bank_indicator( country_code: str, indicator: str, parse_dates: bool = False ): @@ -194,6 +256,13 @@ def download_world_bank_indicator( ------- pd.Series A series with the values of the indicator for all dates (years) on record + + Raises + ------ + ValueError + If the World Bank API rejects ``country_code`` or ``indicator``. + NoDataError + If no data is available for a valid ISO alpha-3 country and indicator. """ # Download data from API raw_data = [] @@ -209,20 +278,25 @@ def download_world_bank_indicator( # Check if we received an error message try: - if json_data[0]["message"][0]["id"] == "120": - raise ValueError( - "Error requesting data from the World Bank API. Did you use the " - "correct country code and indicator ID?\n" - f"{url}" + error_id = json_data[0]["message"][0]["id"] + except (KeyError, IndexError, TypeError): + error_id = None + if error_id == "120": + if _is_missing_wb_country(country_code, indicator): + raise NoDataError( + f"No data available for country {country_code}, " + f"indicator {indicator}" ) - # If no, we should be fine - except KeyError: - pass + raise ValueError( + "Error requesting data from the World Bank API. Did you use the " + "correct country code and indicator ID?\n" + f"{url}" + ) # Check if there is no data available pages = json_data[0]["pages"] if pages == 0: - raise ValueError( + raise NoDataError( f"No data available for country {country_code}, indicator {indicator}" ) @@ -247,26 +321,31 @@ def download_world_bank_indicator( def world_bank(cntry_iso, ref_year, info_ind): - """Get country's GDP from World Bank's data at a given year, or - closest year value. If no data, get the natural earth's approximation. + """Get a World Bank indicator value for a country at the closest available year. Parameters ---------- cntry_iso : str - key = ISO alpha_3 country + Country code in ISO 3166-1 alpha-3 format. ref_year : int - reference year + Reference year. info_ind : str - indicator of World Bank, e.g. 'NY.GDP.MKTP.CD'. If - 'INC_GRP', historical income groups from excel file used. + World Bank API indicator ID (e.g., ``'NY.GDP.MKTP.CD'``), or + ``'INC_GRP'`` to read historical income groups from ``OGHIST.xls``. Returns ------- - int, float + int, float or int + Closest year and indicator value (``int`` for ``'INC_GRP'``, ``float`` otherwise). Raises ------ - IOError, KeyError, IndexError + NoDataError + If the country has no non-missing data for ``info_ind``. + ValueError + If ``cntry_iso`` or ``info_ind`` is rejected by the World Bank API. + requests.exceptions.RequestException, climada.util.files_handler.DownloadException + If downloading the World Bank data fails. """ if info_ind != "INC_GRP": cntry_gdp = download_world_bank_indicator( @@ -275,6 +354,10 @@ def world_bank(cntry_iso, ref_year, info_ind): years = cntry_gdp.index sort_years = np.abs(years - ref_year).argsort() close_val = cntry_gdp.iloc[sort_years].dropna() + if close_val.empty: + raise NoDataError( + f"No World Bank indicator '{info_ind}' data available for {cntry_iso}" + ) close_year = close_val.index[0] close_val = float(close_val.iloc[0]) else: # income group level @@ -289,10 +372,19 @@ def world_bank(cntry_iso, ref_year, info_ind): INCOME_GRP_WB_TABLE.keys(), INCOME_GRP_WB_TABLE.values() ) - cntry_dfr = dfr_wb.loc[cntry_iso] + try: + cntry_dfr = dfr_wb.loc[cntry_iso] + except KeyError as err: + raise NoDataError( + f"No World Bank indicator '{info_ind}' data available for {cntry_iso}" + ) from err close_val = cntry_dfr.iloc[ np.abs(np.array(cntry_dfr.index[1:]) - ref_year).argsort() + 1 ].dropna() + if close_val.empty: + raise NoDataError( + f"No World Bank indicator '{info_ind}' data available for {cntry_iso}" + ) close_year = close_val.index[0] close_val = int(close_val.iloc[0]) @@ -300,7 +392,7 @@ def world_bank(cntry_iso, ref_year, info_ind): def nat_earth_adm0(cntry_iso, info_name, year_name=None, shp_file=None): - """Get country's parameter from natural earth's admin0 shape file. + """Get country's parameter from Natural Earth's admin0 shape file. Parameters ---------- @@ -313,37 +405,59 @@ def nat_earth_adm0(cntry_iso, info_name, year_name=None, shp_file=None): e.g. 'GDP_YEAR' shp_file : cartopy.io.shapereader.Reader, optional shape file with - INCOME_GRP attribute for every country. Load Natural Earth admin0 + the requested attribute for every country. Load Natural Earth admin0 if not provided. Returns ------- - int, float + int, float or int + Attribute year (0 if ``year_name`` is omitted) and value. Raises ------ - ValueError + NoDataError + If no matching country record or valid attribute value is found. """ + if not cntry_iso or cntry_iso == "-99": + raise NoDataError(f"No {info_name} data for country {cntry_iso} found.") if not shp_file: shp_file = _nat_earth_shp("10m", "cultural", "admin_0_countries") - close_val = 0 + close_val = None close_year = 0 for info in shp_file.records(): - if info.attributes["ADM0_A3"] == cntry_iso: - close_val = info.attributes[info_name] - if year_name: - close_year = int(info.attributes[year_name]) + attrs = info.attributes + if cntry_iso in ( + attrs.get("ADM0_A3"), + attrs.get("ISO_A3"), + attrs.get("WB_A3"), + attrs.get("ADM0_A3_US"), + ): + close_val = attrs[info_name] + close_year = int(attrs[year_name]) if year_name else 0 break - if not close_val: - raise ValueError("No GDP for country %s found." % cntry_iso) - # the variable name changed in Natural Earth v5.0.0 - if info_name in ["GDP_MD", "GDP_MD_EST"]: - close_val *= 1e6 + if info_name in ["GDP_MD", "GDP_MD_EST"] and close_val is not None: + if close_val < 0: + close_val = None + else: + if close_val == 0: + warnings.warn( + f"Natural Earth {info_name} for country {cntry_iso} is 0.", + UserWarning, + stacklevel=2, + ) + close_val *= 1e6 elif info_name == "INCOME_GRP": - close_val = INCOME_GRP_NE_TABLE.get(int(close_val[0])) + close_val = ( + INCOME_GRP_NE_TABLE.get(int(close_val[0])) + if isinstance(close_val, str) and close_val[:1].isdigit() + else None + ) + + if close_val is None: + raise NoDataError(f"No {info_name} data for country {cntry_iso} found.") return close_year, close_val @@ -447,6 +561,18 @@ def world_bank_wealth_account( to include the built-up (or urban) land value, thus this divides by a factor 1.24. (See section 9.2 of the worldbank methodology mentioned above). Default: True. + + Returns + ------- + int, float, int + Year, wealth value in USD, and quality flag (``1`` WB data, ``0`` GDP fallback). + + Raises + ------ + NoDataError + If data is missing and cannot be estimated via the ``'NW.PCA.TO'`` fallback. + ValueError + If ``cntry_iso`` or ``variable_name`` is rejected by the World Bank API. """ try: @@ -454,16 +580,30 @@ def world_bank_wealth_account( country_code=cntry_iso, indicator=variable_name, ).dropna() - except ValueError: + if data_wealth.empty: + raise NoDataError( + f"No World Bank indicator '{variable_name}' data available " + f"for {cntry_iso}" + ) + except NoDataError: if "NW.PCA.TO" in variable_name: - LOGGER.warning( - "No data available for country. Using non-financial wealth instead" + warnings.warn( + "No data available for country. Using non-financial wealth instead", + UserWarning, + stacklevel=2, ) gdp_year, gdp_val = gdp(cntry_iso, ref_year) fac = wealth2gdp(cntry_iso)[1] + if np.isnan(fac): + warnings.warn( + f"Missing wealth-to-gdp factor for country {cntry_iso}. " + "Using GDP instead.", + UserWarning, + stacklevel=2, + ) + fac = 1.0 return gdp_year, np.around((fac * gdp_val), 1), 0 - else: - raise + raise years = data_wealth.index.values if ref_year in years: diff --git a/climada/util/test/test_finance.py b/climada/util/test/test_finance.py index 67545a19e..76adaa1d1 100644 --- a/climada/util/test/test_finance.py +++ b/climada/util/test/test_finance.py @@ -20,13 +20,17 @@ """ import unittest +from unittest.mock import patch import numpy as np +import pandas as pd from cartopy.io import shapereader from climada.util.finance import ( WB_URBAN_LAND_MARKUP, + NoDataError, _gdp_twn, + _is_missing_wb_country, download_world_bank_indicator, gdp, income_group, @@ -101,6 +105,84 @@ def test_ne_gdp_aia_2012_pass(self): self.assertEqual(ne_year, ref_year) self.assertEqual(ne_val, ref_val) + def test_ne_fallback_iso_and_zero_gdp_pass(self): + """Test nat_earth_adm0 fallback ISO attributes, zero-GDP warning, and NoDataError.""" + ne_year, ne_val = nat_earth_adm0("ESH", "GDP_MD", "GDP_YEAR", SHP_FILE) + self.assertEqual(ne_year, 2007) + self.assertEqual(ne_val, 9.07e08) + + ne_year, ne_val = nat_earth_adm0("ALA", "INCOME_GRP", shp_file=SHP_FILE) + self.assertEqual(ne_year, 0) + self.assertEqual(ne_val, 4) + + with self.assertWarnsRegex( + UserWarning, "Natural Earth GDP_MD for country HMD is 0." + ): + ne_year, ne_val = nat_earth_adm0("HMD", "GDP_MD", "GDP_YEAR", SHP_FILE) + self.assertEqual(ne_year, 2016) + self.assertEqual(ne_val, 0.0) + + with self.assertRaisesRegex( + NoDataError, "No GDP_MD data for country ZZZ found." + ): + nat_earth_adm0("ZZZ", "GDP_MD", "GDP_YEAR", SHP_FILE) + + with self.assertRaisesRegex( + NoDataError, "No GDP_MD data for country VAT found." + ): + nat_earth_adm0("VAT", "GDP_MD", "GDP_YEAR", SHP_FILE) + + with self.assertRaisesRegex( + NoDataError, "No GDP_MD data for country -99 found." + ): + nat_earth_adm0("-99", "GDP_MD", "GDP_YEAR", SHP_FILE) + + with self.assertRaisesRegex( + NoDataError, "No INCOME_GRP data for country SPI found." + ): + nat_earth_adm0("SPI", "INCOME_GRP", shp_file=SHP_FILE) + + def test_no_data_error_hierarchy_and_propagation(self): + """Test NoDataError subclasses LookupError and fallbacks do not catch ValueError.""" + self.assertTrue(issubclass(NoDataError, LookupError)) + + with patch("climada.util.finance.requests.get") as mock_get: + mock_get.return_value.status_code = 500 + mock_get.return_value.text = '[{"total": 1}, [{"id": "NY.GDP.MKTP.CD"}]]' + self.assertFalse(_is_missing_wb_country("ESH", "NY.GDP.MKTP.CD")) + mock_get.return_value.status_code = 200 + mock_get.return_value.text = '[{"total": 1}, [{"id": null}]]' + self.assertFalse(_is_missing_wb_country("ESH", "NY.GDP.MKTP.CD")) + self.assertFalse(_is_missing_wb_country(None, "NY.GDP.MKTP.CD")) + + empty_series = pd.Series([np.nan, np.nan], index=[2019, 2020]) + with patch( + "climada.util.finance.download_world_bank_indicator", + return_value=empty_series, + ): + with self.assertRaisesRegex( + NoDataError, + "No World Bank indicator 'NY.GDP.MKTP.CD' data available for GIB", + ): + world_bank("GIB", 2020, "NY.GDP.MKTP.CD") + + with self.assertRaisesRegex( + NoDataError, "No World Bank indicator 'INC_GRP' data available for AIA" + ): + world_bank("AIA", 2012, "INC_GRP") + + with patch( + "climada.util.finance.world_bank", side_effect=NoDataError("missing") + ): + self.assertEqual(income_group("ALA", 2012, SHP_FILE), (0, 4)) + self.assertEqual(gdp("ESH", 2012, SHP_FILE), (2007, 9.07e08)) + + with patch("climada.util.finance.world_bank", side_effect=ValueError("bad")): + with self.assertRaisesRegex(ValueError, "bad"): + income_group("ALA", 2012, SHP_FILE) + with self.assertRaisesRegex(ValueError, "bad"): + gdp("ESH", 2012, SHP_FILE) + def test_gdp_sxm_2010_pass(self): """Test gdp function Sint Maarten.""" # If World Bank input data changes, make sure to set ref_year to a year where @@ -163,9 +245,19 @@ def test_download_wb_data(self): download_world_bank_indicator("ESP", "BogusIndicator") with self.assertRaisesRegex( ValueError, + "Did you use the correct country code", + ): + download_world_bank_indicator("ESH", "BogusIndicator") + with self.assertRaisesRegex( + NoDataError, "No data available for country AIA, indicator NY.GDP.MKTP.CD", ): download_world_bank_indicator("AIA", "NY.GDP.MKTP.CD") + with self.assertRaisesRegex( + NoDataError, + "No data available for country ESH, indicator NY.GDP.MKTP.CD", + ): + download_world_bank_indicator("ESH", "NY.GDP.MKTP.CD") class TestWealth2GDP(unittest.TestCase): @@ -272,6 +364,29 @@ def test_pca_CUB_2015_pass(self): self.assertEqual(wb_year, ref_year) self.assertIn(wb_val, ref_val) + def test_pca_missing_wealth2gdp_factor_pass(self): + """Test world_bank_wealth_account warnings, fallback, and ValueError propagation.""" + ref_year = 2015 + cntry_iso = "LBY" + with self.assertWarnsRegex( + UserWarning, "Missing wealth-to-gdp factor for country LBY." + ): + wb_year, wb_val, q = world_bank_wealth_account( + cntry_iso, ref_year, no_land=True + ) + gdp_year, gdp_val = gdp(cntry_iso, ref_year) + self.assertEqual(q, 0) + self.assertEqual(wb_year, gdp_year) + self.assertFalse(np.isnan(wb_val)) + self.assertAlmostEqual(wb_val, np.around(gdp_val, 1)) + + with patch( + "climada.util.finance.download_world_bank_indicator", + side_effect=ValueError("bad input"), + ): + with self.assertRaisesRegex(ValueError, "bad input"): + world_bank_wealth_account("LBY", ref_year, no_land=True) + # Execute Tests if __name__ == "__main__":