Repository navigation
Fix WorldBank urls and outdated data usage #1292
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
spjuhel
wants to merge
24
commits into
develop
Choose a base branch
from
fix-worldbank-urls
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
24 commits
Select commit
Hold shift + click to select a range
fc742d8
Attempts at fixing the old url with dead SSL cert
spjuhel 1e2be96
Fixes wealth accounts
spjuhel 32cf61b
Changelog
spjuhel 59d410e
Updates doc for real chained 2019 USD, fixes tests values
spjuhel b9d13cd
purge .gitignore
emanuel-schmid 1d67a34
makes soon to be old `measures` module a legacy
spjuhel 7655178
Oups these shouldn't be here!
spjuhel f648a6f
Forgotten places
spjuhel 254a605
Updates changelog
spjuhel dd804b7
Adds future documentation placeholders, warnings in legacy guides
spjuhel 9420254
This one does not exist yet
spjuhel 3132e78
Updates rst files
spjuhel a610c8f
Includes comment from Lukas (doc refs)
spjuhel d4f1c01
Forgot cost-benefit tutorial
spjuhel 5a578c0
Fix TCTracks.from_FAST duplicate loading from year loop (#1269)
simonameiler bfeacb8
Changelog
spjuhel e05f8e5
Merge remote-tracking branch 'origin/develop' into fix-worldbank-urls
spjuhel d18882f
Updates documentation
spjuhel d1c4e70
Better exception handling
spjuhel b46eba8
Merge branch 'develop' into fix-worldbank-urls
emanuel-schmid 36d3a57
Apply batched suggestions from code review / Emanuels comments
spjuhel 1b2fbdc
Reran litpop notebook
spjuhel b258ee0
Merge branch 'develop' into fix-worldbank-urls
spjuhel f0b0e78
fixes test
spjuhel File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -24,8 +24,6 @@ | |
| import json | ||
| import logging | ||
| import shutil | ||
| import zipfile | ||
| from pathlib import Path | ||
|
|
||
| import numpy as np | ||
| import pandas as pd | ||
|
|
@@ -37,18 +35,7 @@ | |
|
|
||
| LOGGER = logging.getLogger(__name__) | ||
|
|
||
| WORLD_BANK_WEALTH_ACC = ( | ||
| "https://databank.worldbank.org/data/download/Wealth-Accounts_CSV.zip" | ||
| ) | ||
| """Wealth historical data (1995, 2000, 2005, 2010, 2014) from World Bank (ZIP). | ||
| https://datacatalog.worldbank.org/dataset/wealth-accounting | ||
| Includes variable Produced Capital (NW.PCA.TO)""" | ||
|
|
||
| FILE_WORLD_BANK_WEALTH_ACC = "Wealth-AccountsData.csv" | ||
|
|
||
| WORLD_BANK_INC_GRP = ( | ||
| "http://databank.worldbank.org/data/download/site-content/OGHIST.xls" | ||
| ) | ||
| WORLD_BANK_INC_GRP = "https://ddh-openapi.worldbank.org/resources/DR0095334/download" | ||
| """Income group historical data from World bank.""" | ||
|
|
||
| INCOME_GRP_WB_TABLE = { | ||
|
|
@@ -73,6 +60,12 @@ | |
| """File with wealth-to-GDP factors from the | ||
| Credit Suisse's Global Wealth Report 2017 (household wealth)""" | ||
|
|
||
| WB_URBAN_LAND_MARKUP = 1.24 | ||
| """ | ||
| Markup factor of 24% used by the world bank to include built-value. | ||
| See Section 9.2 [Worldbank methodology](https://datacatalog.worldbank.org/search/dataset/0042066/wealth-accounting) | ||
| """ | ||
|
|
||
|
spjuhel marked this conversation as resolved.
|
||
|
|
||
| def _nat_earth_shp(resolution="10m", category="cultural", name="admin_0_countries"): | ||
| shp_file = shapereader.natural_earth( | ||
|
|
@@ -206,19 +199,20 @@ def download_world_bank_indicator( | |
| pages = np.inf | ||
| page = 1 | ||
| while page <= pages: | ||
| response = requests.get( | ||
| url = ( | ||
| f"https://api.worldbank.org/v2/countries/{country_code}/indicators/" | ||
| f"{indicator}?format=json&page={page}", | ||
| timeout=30, | ||
| f"{indicator}?format=json&page={page}" | ||
| ) | ||
| response = requests.get(url, timeout=30) | ||
| json_data = json.loads(response.text) | ||
|
|
||
| # 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?" | ||
| "correct country code and indicator ID?\n" | ||
| f"{url}" | ||
| ) | ||
| # If no, we should be fine | ||
| except KeyError: | ||
|
|
@@ -415,9 +409,9 @@ def world_bank_wealth_account( | |
| cntry_iso, ref_year, variable_name="NW.PCA.TO", no_land=True | ||
| ): | ||
| """ | ||
| Download and unzip wealth accounting historical data (1995, 2000, 2005, 2010, 2014) | ||
| from World Bank (https://datacatalog.worldbank.org/dataset/wealth-accounting). | ||
| Return requested variable for a country (cntry_iso) and a year (ref_year). | ||
| Download wealth accounting data from the World Bank API and return the requested | ||
| variable for a country (cntry_iso) and a year (ref_year). | ||
| https://datacatalog.worldbank.org/search/dataset/0042066 | ||
|
Collaborator
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. is this url correct? wasn't it meant to be replaced?
Collaborator
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. No this one is still good. The ones outdated were those (notably the ones pointing to files): |
||
|
|
||
| Parameters | ||
| ---------- | ||
|
|
@@ -426,10 +420,9 @@ def world_bank_wealth_account( | |
| ref_year : int | ||
| reference year | ||
|
|
||
| * available in data: 1995, 2000, 2005, 2010, 2014 | ||
| * other years between 1995 and 2014 are interpolated | ||
| * for years outside range, indicator is scaled | ||
| proportionally to GDP | ||
| * available in data: 1995-2020 | ||
| * years within the data range are interpolated | ||
| * for years outside range, indicator is scaled proportionally to GDP | ||
|
|
||
| variable_name : str | ||
| select one variable, i.e.: | ||
|
|
@@ -449,65 +442,60 @@ def world_bank_wealth_account( | |
| forests (timber and some nontimber forest products), and | ||
| protected areas. | ||
| 'NW.TOW.TO': Total wealth of country. | ||
| Note: Values are measured at market exchange rates in constant 2014 US dollars, | ||
| using a country-specific GDP deflator. | ||
| Note: Values are measured at market exchange rates in | ||
| real chained 2019 US dollars. | ||
| See https://datacatalogfiles.worldbank.org/ddh-published-v2/0042066/9/DR0094582/CWON%202024%20Methodology_10122024.pdf | ||
|
|
||
| no_land : boolean | ||
| If True, return produced capital without built-up land value | ||
| (applies to 'NW.PCA.*' only). Default: True. | ||
| (applies to 'NW.PCA.*' only). The world bank applies a 24% markup | ||
| 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. | ||
| """ | ||
|
|
||
| try: | ||
| data_file = SYSTEM_DIR.joinpath(FILE_WORLD_BANK_WEALTH_ACC) | ||
| if not data_file.is_file(): | ||
| data_file = SYSTEM_DIR.joinpath( | ||
| "Wealth-Accounts_CSV", FILE_WORLD_BANK_WEALTH_ACC | ||
| data_wealth = download_world_bank_indicator( | ||
| country_code=cntry_iso, | ||
| indicator=variable_name, | ||
| ).dropna() | ||
| except ValueError: | ||
| if "NW.PCA.TO" in variable_name: | ||
| LOGGER.warning( | ||
| "No data available for country. Using non-financial wealth instead" | ||
| ) | ||
| if not data_file.is_file(): | ||
| if not SYSTEM_DIR.joinpath("Wealth-Accounts_CSV").is_dir(): | ||
| SYSTEM_DIR.joinpath("Wealth-Accounts_CSV").mkdir() | ||
| file_down = download_file(WORLD_BANK_WEALTH_ACC) | ||
| zip_ref = zipfile.ZipFile(file_down, "r") | ||
| zip_ref.extractall(SYSTEM_DIR.joinpath("Wealth-Accounts_CSV")) | ||
| zip_ref.close() | ||
| Path(file_down).unlink() | ||
| LOGGER.debug("Download and unzip complete. Unzipping %s", str(data_file)) | ||
|
|
||
| data_wealth = pd.read_csv(data_file, sep=",", index_col=None, header=0) | ||
| except Exception as err: | ||
| raise type(err)( | ||
| "Downloading World Bank Wealth Accounting Data failed: " + str(err) | ||
| ) from err | ||
|
|
||
| data_wealth = data_wealth[ | ||
| data_wealth["Country Code"].str.contains(cntry_iso) | ||
| & data_wealth["Indicator Code"].str.contains(variable_name) | ||
| ].loc[:, "1995":"2014"] | ||
| years = list(map(int, list(data_wealth))) | ||
| if ( | ||
| data_wealth.size == 0 and "NW.PCA.TO" in variable_name | ||
| ): # if country is not found in data | ||
| LOGGER.warning( | ||
| "No data available for country. Using non-financial wealth instead" | ||
| ) | ||
| gdp_year, gdp_val = gdp(cntry_iso, ref_year) | ||
| fac = wealth2gdp(cntry_iso)[1] | ||
| return gdp_year, np.around((fac * gdp_val), 1), 0 | ||
| if ref_year in years: # indicator for reference year is available directly | ||
| result = data_wealth.loc[:, str(ref_year)].values[0] | ||
| elif np.min(years) < ref_year < np.max(years): # interpolate | ||
| result = np.interp(ref_year, years, data_wealth.values[0, :]) | ||
| elif ref_year < np.min(years): # scale proportionally to GDP | ||
| gdp_year, gdp_val = gdp(cntry_iso, ref_year) | ||
| fac = wealth2gdp(cntry_iso)[1] | ||
| return gdp_year, np.around((fac * gdp_val), 1), 0 | ||
| else: | ||
| raise | ||
|
|
||
| years = data_wealth.index.values | ||
| if ref_year in years: | ||
| result = data_wealth.loc[ref_year] | ||
| elif np.min(years) < ref_year < np.max(years): | ||
| result = np.interp(ref_year, years, data_wealth.values) | ||
| elif ref_year < np.min(years): | ||
| gdp_year, gdp0_val = gdp(cntry_iso, np.min(years)) | ||
| gdp_year, gdp_val = gdp(cntry_iso, ref_year) | ||
| result = data_wealth.values[0, 0] * gdp_val / gdp0_val | ||
| result = ( | ||
| data_wealth.iloc[data_wealth.index.get_loc(np.min(years))] | ||
| * gdp_val | ||
| / gdp0_val | ||
| ) | ||
| ref_year = gdp_year | ||
| else: | ||
| gdp_year, gdp0_val = gdp(cntry_iso, np.max(years)) | ||
| gdp_year, gdp_val = gdp(cntry_iso, ref_year) | ||
| result = data_wealth.values[0, -1] * gdp_val / gdp0_val | ||
| result = ( | ||
| data_wealth.iloc[data_wealth.index.get_loc(np.max(years))] | ||
| * gdp_val | ||
| / gdp0_val | ||
| ) | ||
| ref_year = gdp_year | ||
|
|
||
| if "NW.PCA." in variable_name and no_land: | ||
| # remove value of built-up land from produced capital | ||
| result = result / 1.24 | ||
| result = result / WB_URBAN_LAND_MARKUP | ||
| return ref_year, np.around(result, 1), 1 | ||
|
|
||
|
|
||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.