Skip to content

Commit

Permalink
black .
Browse files Browse the repository at this point in the history
  • Loading branch information
epogrebnyak committed Apr 21, 2024
1 parent 1ab815c commit cec3186
Show file tree
Hide file tree
Showing 17 changed files with 63 additions and 101 deletions.
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ Dataset releases (vintages) are available back to 2007, the reported data goes b

| Release | Date |
| :--------------- | :-----------:|
| Latest confirmed | April 2022 |
| Latest confirmed | April 2024 |
| First | October 2007 |

Confirmed release is tested to be processed with `weo`.
Expand All @@ -32,7 +32,7 @@ Usually, if something breaks in a new release users raise an [issue here](https:

## Install

The program is tested to run with Python 3.7.13 (as in Google Colab) and higher.
The program is tested to run with Python 3.8 or higher.

To install:

Expand Down
2 changes: 1 addition & 1 deletion example.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from weo import download, WEO
from weo import WEO, download

path, url = download(2022, 1) # first (April) semiannual release
w = WEO(path)
Expand Down
1 change: 1 addition & 0 deletions example/aviz.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
AutoViz example, see https://github.com/AutoViML
"""

from autoviz.AutoViz_Class import AutoViz_Class

from weo import get
Expand Down
12 changes: 1 addition & 11 deletions example/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,17 +26,7 @@

# Is everyone growing fast?
figure()
g = (
(
w.gdp_growth().loc[
"2018":,
]
/ 100
+ 1
).prod()
** (1 / 7)
- 1
) * 100
g = ((w.gdp_growth().loc["2018":,] / 100 + 1).prod() ** (1 / 7) - 1) * 100
g.hist(bins=50)

figure()
Expand Down
17 changes: 3 additions & 14 deletions example/gdp.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,23 +33,12 @@ def plot_mekko(
for lab in labels:
z = widths.cumsum()
bx = z.index.get_loc(lab)
b = z.iloc[
bx,
]
b = z.iloc[bx,]
ax = bx - 1
a = (
0
if bx == 0
else z.iloc[
ax,
]
)
a = 0 if bx == 0 else z.iloc[ax,]
plt.text(
x=(a + b) / 2,
y=heights.loc[
lab,
]
+ y_shift,
y=heights.loc[lab,] + y_shift,
s=lab,
horizontalalignment="center",
)
Expand Down
3 changes: 2 additions & 1 deletion example/missingno.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import missingno as msno

from weo import WEO

w = WEO("../weo.csv")

import missingno as msno

msno.matrix(w.df.sort_values(["ISO", "WEO Subject Code"]))
for label in w.core_codes:
Expand Down
7 changes: 0 additions & 7 deletions example/pdfs.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import datetime

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages
Expand Down Expand Up @@ -41,9 +39,6 @@
# d['CreationDate'] = datetime.datetime(2009, 11, 13)
# d['ModDate'] = datetime.datetime.today()

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backends.backend_pdf import PdfPages

with PdfPages("multipage.pdf") as pp:
for i in range(0, 10):
Expand All @@ -55,8 +50,6 @@
ax2.plot(x, np.cos(x + i * np.pi / 10))
pp.savefig(fig)

import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages

# Initialize:
with PdfPages("foo.pdf") as pdf:
Expand Down
7 changes: 6 additions & 1 deletion justfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,19 @@ package := "weo"
list:
just --list

install:
npm install -g codedown
pip install dbnomics

# launch streamlit app
st:
streamlit run streamlit_app.py

# black and isort
lint:
black .
isort .
isort . --float-to-top
ruff check .

# run code from README
readme:
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "weo"
version = "0.8.0"
version = "0.8.3"
description = "Python client to download IMF World Economic Outlook (WEO) dataset as pandas dataframes."
authors = ["Evgeny Pogrebnyak <[email protected]>"]
readme = "README.md"
Expand Down
38 changes: 17 additions & 21 deletions readme.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
from weo import download, WEO

path, url = download(2022, 1) # first (April) semiannual release
w = WEO(path)
df_cpi = w.inflation()
print(df_cpi.USA.tail(8))

path, url = download(2022, 1)
# weo_2022_1.csv 18.8Mb
# Downloaded 2022-Apr WEO dataset

df_cpi = WEO(path).inflation()
print(df_cpi.USA.tail(8))
# USA
# 2020 1.549
# 2021 7.426
Expand All @@ -29,7 +28,7 @@

# download all releases
for (year, release) in weo.all_releases():
weo.download(year, release, directory="weo_data")
weo.download(year, release, directory="weo_data")

from weo import WEO

Expand All @@ -47,30 +46,27 @@
w.from_code("LUR")

# countries
w.countries("United") # Dataframe with United Arab Emirates, United Kingdom
# and United States
w.iso_code3("Netherlands") # 'NLD'
w.countries("United") # Dataframe with United Arab Emirates, United Kingdom
# and United States
w.iso_code3("Netherlands") # 'NLD'


w.get("General government gross debt", "Percent of GDP")
w.getc("NGDP_RPCH")
w.country("DEU")
w.fix_year(1994)

(
w.gdp_usd(2024)
.dropna()
.sort_values()
.tail(12)
.plot.barh(title="GDP by country, USD billion (2024)")
(w.gdp_usd(2024)
.dropna()
.sort_values()
.tail(12)
.plot
.barh(title="GDP by country, USD billion (2024)")
)

w.gdp_pc_usd(start_year=2000, end_year=2020)

from dbnomics import fetch_series_by_api_link

ts1 = fetch_series_by_api_link(
"https://api.db.nomics.world/v22/"
"series/IMF/WEO:latest/DEU.PCPI"
"?observations=1"
)
ts1 = fetch_series_by_api_link("https://api.db.nomics.world/v22/"
"series/IMF/WEO:latest/DEU.PCPI"
"?observations=1")
2 changes: 1 addition & 1 deletion tests/test_weo_dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
import pytest # type: ignore

from weo import WEO, download
from weo.dataframe import WEO_ParsingError, alpha3_to_2, convert
from weo.dataframe import alpha3_to_2, convert

# persist file for testing
path = "weo_2019_2.csv"
Expand Down
4 changes: 2 additions & 2 deletions tests/test_weo_dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@


def test_constructor():
d1 = Date(2020, 1)
d2 = Date(2020, 2)
Date(2020, 1)
Date(2020, 2)


def foo(a, b):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_weo_readme.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,5 +35,5 @@ def test_plot():

@pytest.mark.parametrize("w", [w1, w2])
def test_getc_in_2020_April(w):
for (s, u, x) in w.variables():
for s, u, x in w.variables():
w.getc(x).head()
6 changes: 0 additions & 6 deletions tests/test_weo_version.py

This file was deleted.

14 changes: 5 additions & 9 deletions weo/__init__.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,11 @@
import os
from typing import Optional

from .dataframe import WEO
from .dates import all_releases, download

try:
from importlib.metadata import version

__version__ = version(__name__)
except:
pass

import os
from typing import Optional
# addd everything to all
__all__ = ["all_releases", "download", "WEO", "get"]


def get(year: int, release: int, path: Optional[str] = None) -> WEO:
Expand Down
11 changes: 6 additions & 5 deletions weo/dataframe.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
w = WEO('weo.csv')
"""

import numpy as np # type: ignore
import pandas as pd # type: ignore
from iso3166 import countries # type: ignore
Expand Down Expand Up @@ -64,7 +65,7 @@ def inner(self, *arg, year=None, start_year=None, end_year=None):
elif start_year and end_year:
year = [start_year + y for y in range(end_year - start_year + 1)]
if year:
if type(year) == list:
if isinstance(year, list):
year = [str(y) for y in year]
else:
year = str(year)
Expand Down Expand Up @@ -132,7 +133,7 @@ def years(self):

@property
def daterange(self):
return pd.period_range(start=self.years[0], end=self.years[-1], freq="A")
return pd.period_range(start=self.years[0], end=self.years[-1], freq="Y")

@property
def core_codes(self):
Expand Down Expand Up @@ -283,7 +284,7 @@ def _get_by_code(self, variable_code):

def t(self, df, column):
"""Extract columns with years from *df*, make *column* an index."""
_df = df[self.years + [column]].set_index(column).transpose().applymap(convert)
_df = df[self.years + [column]].set_index(column).transpose().map(convert)
_df.columns.name = ""
_df.index = self.daterange
return _df
Expand All @@ -294,7 +295,7 @@ def _extract(self, ix, column):
self.df[ix][self.years + [column]]
.set_index(column)
.transpose()
.applymap(convert)
.map(convert)
)
_df.columns.name = ""
_df.index = self.daterange
Expand All @@ -316,7 +317,7 @@ def fix_year(self, year):
return (
self.df[["ISO", "WEO Subject Code", str(year)]]
.pivot(index="WEO Subject Code", columns="ISO", values=str(year))
.applymap(convert)
.map(convert)
)

def country(self, iso_code, year=None, compact=True):
Expand Down
32 changes: 14 additions & 18 deletions weo/dates.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,8 @@
]


def cur_year() -> int:
return datetime.today().year


def cur_month() -> int:
return datetime.today().month
def today():
return datetime.today()


class Release(Enum):
Expand All @@ -45,22 +41,22 @@ def __le__(self, x):


def succ(d: Date) -> Date:
year, rel = d.year, d.release
if rel == 2:
year, release = d.year, d.release
if release == 2:
year += 1
rel = 1
release = 1
else:
rel = 2
return Date(year, rel)
release = 2
return Date(year, release)


def first() -> Date:
return Date(2007, 2)


def current() -> Date:
y = cur_year()
m = cur_month()
y = today().year
m = today().month
if m <= 3:
return Date(y - 1, 2)
elif 4 <= m < 10:
Expand Down Expand Up @@ -101,17 +97,17 @@ def create_url(d: Date, prefix: str):
year = d.year
month = month_str(d)
long_month = long_month_str(d)
# New break in Apr 2024 - we assume the URL will persist
# New break in Apr 2024
if d >= Date(2024, 1):
return f"{base_url}/{year}/{long_month}/WEO{month}{year}{prefix}.xls"
# another url break in Apr 2021 - we assume the URL will persist
# URL format breaks in Apr 2021
if d >= Date(2021, 1):
return f"{base_url}/{year}/WEO{month}{year}{prefix}.ashx"
# url break in Oct 2020
# URL format breaks in Oct 2020
if d >= Date(2020, 2):
period_marker = period_str(d)
return f"{base_url}/{year}/{period_marker}/WEO{month}{year}{prefix}.xls"
# earliest files
# the earliest files
return f"{base_url}/{year}/WEO{month}{year}{prefix}.xls"


Expand Down Expand Up @@ -240,7 +236,7 @@ def download(
Year of WEO release.
release : int or str
For spring WEO release use 1 or 'Apr'
For fall WEO release use 2, 'Oct' or (in 2011) - 'Sep'.
For fall WEO release use 2, or 'Oct'. In 2011 use 2 or 'Sep'.
filename : str
Filename where to save file.
directory:
Expand Down

0 comments on commit cec3186

Please sign in to comment.