[Feature] Add Top Export Destinations By Country From UN Comtrade International Trade Statistics Database (EconDB) (#6644)

* add economy.export_destinations

* mypy

* elif

* unused argument

---------

Co-authored-by: Igor Radovanovic <74266147+IgorWounds@users.noreply.github.com>
This commit is contained in:
Danglewood
2024-09-05 13:31:57 -07:00
committed by GitHub
parent 4311c68142
commit de8b73e5b4
11 changed files with 571 additions and 0 deletions

View File

@@ -0,0 +1,30 @@
"""Export Destinations Standard Model."""
from typing import Union
from pydantic import Field
from openbb_core.provider.abstract.data import Data
from openbb_core.provider.abstract.query_params import QueryParams
from openbb_core.provider.utils.descriptions import QUERY_DESCRIPTIONS
class ExportDestinationsQueryParams(QueryParams):
"""Export Destinations Query."""
country: str = Field(description=QUERY_DESCRIPTIONS.get("country", ""))
class ExportDestinationsData(Data):
"""Export Destinations Data."""
origin_country: str = Field(
description="The country of origin.",
)
destination_country: str = Field(
description="The destination country.",
)
value: Union[float, int] = Field(
description="The value of the export.",
json_schema_extra={"x-unit_measurement": "currency"},
)

View File

@@ -1107,3 +1107,26 @@ def test_economy_survey_bls_series(params, headers):
result = requests.get(url, headers=headers, timeout=10)
assert isinstance(result, requests.Response)
assert result.status_code == 200
@parametrize(
"params",
[
(
{
"provider": "econdb",
"country": "IN,CN",
}
),
],
)
@pytest.mark.integration
def test_economy_export_destinations(params, headers):
"""Test the economy export destinations endpoint."""
params = {p: v for p, v in params.items() if v}
query_str = get_querystring(params, [])
url = f"http://0.0.0.0:8000/api/v1/economy/export_destinations?{query_str}"
result = requests.get(url, headers=headers, timeout=10)
assert isinstance(result, requests.Response)
assert result.status_code == 200

View File

@@ -1065,3 +1065,25 @@ def test_economy_survey_bls_series(params, obb):
assert result
assert isinstance(result, OBBject)
assert len(result.results) > 0
@parametrize(
"params",
[
(
{
"provider": "econdb",
"country": "IN,CN",
}
),
],
)
@pytest.mark.integration
def test_economy_export_destinations(params, obb):
"""Test the economy export destinations endpoint"""
params = {p: v for p, v in params.items() if v}
result = obb.economy.export_destinations(**params)
assert result
assert isinstance(result, OBBject)
assert len(result.results) > 0

View File

@@ -647,3 +647,19 @@ async def pce(
) -> OBBject:
"""Get Personal Consumption Expenditures (PCE) reports."""
return await OBBject.from_query(Query(**locals()))
@router.command(
model="ExportDestinations",
examples=[
APIEx(parameters={"provider": "econdb", "country": "us"}),
],
)
async def export_destinations(
cc: CommandContext,
provider_choices: ProviderChoices,
standard_params: StandardParams,
extra_params: ExtraParams,
) -> OBBject:
"""Get top export destinations by country from the UN Comtrade International Trade Statistics Database."""
return await OBBject.from_query(Query(**locals()))

View File

@@ -8849,6 +8849,111 @@
},
"model": "PersonalConsumptionExpenditures"
},
"/economy/export_destinations": {
"deprecated": {
"flag": null,
"message": null
},
"description": "Get top export destinations by country from the UN Comtrade International Trade Statistics Database.",
"examples": "\nExamples\n--------\n\n```python\nfrom openbb import obb\nobb.economy.export_destinations(provider='econdb', country='us')\n```\n\n",
"parameters": {
"standard": [
{
"name": "country",
"type": "Union[str, List[str]]",
"description": "The country to get data. Multiple items allowed for provider(s): econdb.",
"default": "",
"optional": false,
"choices": null
}
],
"econdb": []
},
"returns": {
"OBBject": [
{
"name": "results",
"type": "List[ExportDestinations]",
"description": "Serializable results."
},
{
"name": "provider",
"type": "Optional[Literal['econdb']]",
"description": "Provider name."
},
{
"name": "warnings",
"type": "Optional[List[Warning_]]",
"description": "List of warnings."
},
{
"name": "chart",
"type": "Optional[Chart]",
"description": "Chart object."
},
{
"name": "extra",
"type": "Dict[str, Any]",
"description": "Extra info."
}
]
},
"data": {
"standard": [
{
"name": "origin_country",
"type": "str",
"description": "The country of origin.",
"default": "",
"optional": false,
"choices": null
},
{
"name": "destination_country",
"type": "str",
"description": "The destination country.",
"default": "",
"optional": false,
"choices": null
},
{
"name": "value",
"type": "Union[float, int]",
"description": "The value of the export.",
"default": "",
"optional": false,
"choices": null
}
],
"econdb": [
{
"name": "units",
"type": "str",
"description": "The units of measurement for the value.",
"default": "",
"optional": false,
"choices": null
},
{
"name": "title",
"type": "str",
"description": "The title of the data.",
"default": "",
"optional": false,
"choices": null
},
{
"name": "footnote",
"type": "str",
"description": "The footnote for the data.",
"default": "",
"optional": false,
"choices": null
}
]
},
"model": "ExportDestinations"
},
"/equity/calendar/ipo": {
"deprecated": {
"flag": null,

View File

@@ -22,6 +22,7 @@ class ROUTER_economy(Container):
composite_leading_indicator
country_profile
cpi
export_destinations
fred_regional
fred_release_table
fred_search
@@ -1185,6 +1186,90 @@ class ROUTER_economy(Container):
)
)
@exception_handler
@validate
def export_destinations(
self,
country: Annotated[
Union[str, List[str]],
OpenBBField(
description="The country to get data. Multiple comma separated items allowed for provider(s): econdb."
),
],
provider: Annotated[
Optional[Literal["econdb"]],
OpenBBField(
description="The provider to use, by default None. If None, the priority list configured in the settings is used. Default priority: econdb."
),
] = None,
**kwargs
) -> OBBject:
"""Get top export destinations by country from the UN Comtrade International Trade Statistics Database.
Parameters
----------
country : Union[str, List[str]]
The country to get data. Multiple comma separated items allowed for provider(s): econdb.
provider : Optional[Literal['econdb']]
The provider to use, by default None. If None, the priority list configured in the settings is used. Default priority: econdb.
Returns
-------
OBBject
results : List[ExportDestinations]
Serializable results.
provider : Optional[Literal['econdb']]
Provider name.
warnings : Optional[List[Warning_]]
List of warnings.
chart : Optional[Chart]
Chart object.
extra : Dict[str, Any]
Extra info.
ExportDestinations
------------------
origin_country : str
The country of origin.
destination_country : str
The destination country.
value : Union[float, int]
The value of the export.
units : Optional[str]
The units of measurement for the value. (provider: econdb)
title : Optional[str]
The title of the data. (provider: econdb)
footnote : Optional[str]
The footnote for the data. (provider: econdb)
Examples
--------
>>> from openbb import obb
>>> obb.economy.export_destinations(provider='econdb', country='us')
""" # noqa: E501
return self._run(
"/economy/export_destinations",
**filter_inputs(
provider_choices={
"provider": self._get_provider(
provider,
"economy.export_destinations",
("econdb",),
)
},
standard_params={
"country": country,
},
extra_params=kwargs,
info={
"country": {
"econdb": {"multiple_items_allowed": True, "choices": None}
}
},
)
)
@exception_handler
@validate
def fred_regional(

View File

@@ -4,6 +4,7 @@ from openbb_core.provider.abstract.provider import Provider
from openbb_econdb.models.available_indicators import EconDbAvailableIndicatorsFetcher
from openbb_econdb.models.country_profile import EconDbCountryProfileFetcher
from openbb_econdb.models.economic_indicators import EconDbEconomicIndicatorsFetcher
from openbb_econdb.models.export_destinations import EconDbExportDestinationsFetcher
from openbb_econdb.models.gdp_nominal import EconDbGdpNominalFetcher
from openbb_econdb.models.gdp_real import EconDbGdpRealFetcher
from openbb_econdb.models.yield_curve import EconDbYieldCurveFetcher
@@ -24,6 +25,7 @@ aggregate statistics.""",
"AvailableIndicators": EconDbAvailableIndicatorsFetcher,
"CountryProfile": EconDbCountryProfileFetcher,
"EconomicIndicators": EconDbEconomicIndicatorsFetcher,
"ExportDestinations": EconDbExportDestinationsFetcher,
"GdpNominal": EconDbGdpNominalFetcher,
"GdpReal": EconDbGdpRealFetcher,
"YieldCurve": EconDbYieldCurveFetcher,

View File

@@ -0,0 +1,155 @@
"""EconDB Export Destinations Model."""
# pylint: disable=unused-argument
from typing import Any, Dict, List, Optional
from warnings import warn
from aiohttp.client_exceptions import ContentTypeError
from openbb_core.app.model.abstract.error import OpenBBError
from openbb_core.provider.abstract.fetcher import Fetcher
from openbb_core.provider.standard_models.export_destinations import (
ExportDestinationsData,
ExportDestinationsQueryParams,
)
from openbb_core.provider.utils.errors import EmptyDataError
from pydantic import Field
class EconDbExportDestinationsQueryParams(ExportDestinationsQueryParams):
"""EconDB Export Destinations Query Parameters."""
__json_schema_extra__ = {"country": {"multiple_items_allowed": True}}
class EconDbExportDestinationsData(ExportDestinationsData):
"""EconDB Export Destinations Data."""
units: str = Field(
description="The units of measurement for the value.",
)
title: str = Field(
description="The title of the data.",
)
footnote: Optional[str] = Field(
description="The footnote for the data.",
)
class EconDbExportDestinationsFetcher(
Fetcher[EconDbExportDestinationsQueryParams, List[EconDbExportDestinationsData]]
):
"""EconDB Export Destinations Fetcher."""
require_credentials = False
@staticmethod
def transform_query(params: Dict[str, Any]) -> EconDbExportDestinationsQueryParams:
"""Transform query parameters."""
return EconDbExportDestinationsQueryParams(**params)
@staticmethod
async def aextract_data(
query: EconDbExportDestinationsQueryParams,
credentials: Optional[Dict[str, str]],
**kwargs: Any,
) -> List[Dict]:
"""Extract the data from EconDB."""
# pylint: disable=import-outside-toplevel
import asyncio # noqa
from openbb_core.provider.utils.helpers import amake_request
from openbb_econdb.utils.helpers import COUNTRY_MAP
results: List = []
messages: List = []
countries = query.country.split(",")
MAP_COUNTRY = {v: k for k, v in COUNTRY_MAP.items()}
async def get_one_country(c):
"""Get data for one country."""
c = c.upper() if len(c) == 2 else c.lower()
if len(c) != 2:
c = COUNTRY_MAP.get(c, c)
if len(c) != 2 or c.upper() not in MAP_COUNTRY:
messages.append(f"Invalid country code -> {c}")
return
URL = f"https://www.econdb.com/widgets/top-trade-items/data/?country={c.upper()}&split_by=country"
result: List = []
row: Dict = {}
try:
res = await amake_request(URL)
except ContentTypeError as e:
if len(countries) == 1:
raise OpenBBError(e) from e
messages.append(f"No data available for the country -> {c}")
return
plots = res.get("plots", []) # type: ignore
data = plots[0].pop("data", []) if plots else []
meta = plots[0] if plots else {}
if not data or (len(data) == 1 and data[0].get("Value million USD") == 0):
messages.append(f"No data available for the country -> {c}")
return
origin_country = MAP_COUNTRY.get(c, c)
for item in data:
row = {
"origin_country": origin_country.replace("_", " ").title(),
**item,
"units": (
meta.get("series", [])[0]
.get("code", "")
.replace("Value million", "Millions of")
if meta.get("series", [])
else ""
),
"title": meta.get("title", ""),
"footnote": meta.get("footnote", ""),
}
result.append(
{
(
"value"
if k == "Value million USD"
else "destination_country" if k == "Country" else k
): (
MAP_COUNTRY.get(v, v).replace("_", " ").title()
if k == "Country"
else v
)
for k, v in row.items()
if v and v != 0
}
)
if result:
results.extend(result)
else:
messages.append(f"No data returned for the country -> {c}")
await asyncio.gather(*[get_one_country(c) for c in countries])
if not results:
raise (
EmptyDataError(f"{messages}")
if messages
else EmptyDataError(
f"No data returned for the given country -> {countries}"
)
)
if messages:
for message in messages:
warn(message)
return results
@staticmethod
def transform_data(
query: EconDbExportDestinationsQueryParams,
data: List[Dict],
**kwargs: Any,
) -> List[EconDbExportDestinationsData]:
"""Transform the data."""
return [EconDbExportDestinationsData.model_validate(d) for d in data]

View File

@@ -0,0 +1,60 @@
interactions:
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
method: GET
uri: https://www.econdb.com/widgets/top-trade-items/data/?country=US&split_by=country
response:
body:
string: !!binary |
H4sIAAAAAAAAA3XRXU/CMBQG4L/S7JoL2NaNcafgByJoHDMmhouyVV1S2qU9SySE/25booldTnbT
nj475017ijqhwEQz8n6KQDNpOmW43YLu+YhEcOzcLjJct9xErtKC8KU1ayXh353SQBpuoJUMWiU9
+lAKpALvStXrms9ItSFzdbAzGk6WEri+eCbI1tdKsHvbpjZkwYDtmc0x+pvsA9aq8S1fmeg5ObRC
2AakKhcOSnbAD5vWdIId3fmeaVepGfBPpX1prnoJdnneOWqHX8b9lp24cv8MW89InFKan0fkH1+/
oTzJ8mnI5xuMTyZpTkP+8IxxWsRZqKsVqpNpHOrVC66zQe/FDarjdBLqzSOm03GchvoaTZIUyeAK
l+gVJlM66F3eoTobvuYtniShxSA3eidxno9DfY++TjzOBkmWW1zTJNRP8MW1QbNTmhbnnf1+AMFP
oscFBAAA
headers:
CF-Cache-Status:
- DYNAMIC
CF-RAY:
- 8b9ea95219478438-YVR
Cache-Control:
- max-age=900
Connection:
- keep-alive
Content-Encoding:
- gzip
Content-Type:
- application/json
Date:
- Tue, 27 Aug 2024 20:02:49 GMT
Expires:
- Tue, 27 Aug 2024 20:11:42 GMT
NEL:
- '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}'
Referrer-Policy:
- same-origin
Report-To:
- '{"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v4?s=51d2bvbfJrm%2BEeZ3huFocT8M1LtGY1uCuHVzxLQOEWIwy2228srC7K%2FeOlkzvY42dkuzRgsDK%2FIJI2V%2BpDeY%2B%2BXqsYWzLMnHCrG%2B4ZIyBXVPVeXLpQ1b3lL5UC2rTsXXQI0yaSIIi43Blofm"}],"group":"cf-nel","max_age":604800}'
Server:
- cloudflare
Transfer-Encoding:
- chunked
Vary:
- Accept-Encoding
- Origin
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status:
code: 200
message: OK
version: 1

View File

@@ -0,0 +1,60 @@
interactions:
- request:
body: null
headers:
Accept:
- application/json
Accept-Encoding:
- gzip, deflate
Connection:
- keep-alive
method: GET
uri: https://www.econdb.com/widgets/top-trade-items/data/?country=US&split_by=country
response:
body:
string: !!binary |
H4sIAAAAAAAAA3XRXU/CMBQG4L/S7JoL2NaNcafgByJoHDMmhouyVV1S2qU9SySE/25booldTnbT
nj475017ijqhwEQz8n6KQDNpOmW43YLu+YhEcOzcLjJct9xErtKC8KU1ayXh353SQBpuoJUMWiU9
+lAKpALvStXrms9ItSFzdbAzGk6WEri+eCbI1tdKsHvbpjZkwYDtmc0x+pvsA9aq8S1fmeg5ObRC
2AakKhcOSnbAD5vWdIId3fmeaVepGfBPpX1prnoJdnneOWqHX8b9lp24cv8MW89InFKan0fkH1+/
oTzJ8mnI5xuMTyZpTkP+8IxxWsRZqKsVqpNpHOrVC66zQe/FDarjdBLqzSOm03GchvoaTZIUyeAK
l+gVJlM66F3eoTobvuYtniShxSA3eidxno9DfY++TjzOBkmWW1zTJNRP8MW1QbNTmhbnnf1+AMFP
oscFBAAA
headers:
CF-Cache-Status:
- DYNAMIC
CF-RAY:
- 8b9ea0585b382d3c-YVR
Cache-Control:
- max-age=900
Connection:
- keep-alive
Content-Encoding:
- gzip
Content-Type:
- application/json
Date:
- Tue, 27 Aug 2024 19:56:42 GMT
Expires:
- Tue, 27 Aug 2024 20:11:42 GMT
NEL:
- '{"success_fraction":0,"report_to":"cf-nel","max_age":604800}'
Referrer-Policy:
- same-origin
Report-To:
- '{"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report\/v4?s=Qv%2Fm9wBrsOOXrNxkgFKyvcwWSvrkUU5NErV3efQCtStbotvUpdeNjSokum2HdjRpZpIuFluPSusDKnXJh%2BrYKSShNoFVulTvkqsxx5vxT9T%2FO0KnHfgUma2KHO6qmro2TMHkRR1wEQHAdHSN"}],"group":"cf-nel","max_age":604800}'
Server:
- cloudflare
Transfer-Encoding:
- chunked
Vary:
- Accept-Encoding
- Origin
X-Content-Type-Options:
- nosniff
X-Frame-Options:
- DENY
status:
code: 200
message: OK
version: 1

View File

@@ -7,6 +7,7 @@ from openbb_core.app.service.user_service import UserService
from openbb_econdb.models.available_indicators import EconDbAvailableIndicatorsFetcher
from openbb_econdb.models.country_profile import EconDbCountryProfileFetcher
from openbb_econdb.models.economic_indicators import EconDbEconomicIndicatorsFetcher
from openbb_econdb.models.export_destinations import EconDbExportDestinationsFetcher
from openbb_econdb.models.gdp_nominal import EconDbGdpNominalFetcher
from openbb_econdb.models.gdp_real import EconDbGdpRealFetcher
from openbb_econdb.models.yield_curve import EconDbYieldCurveFetcher
@@ -119,3 +120,15 @@ def test_econdb_gdp_real_fetcher(credentials=test_credentials):
fetcher = EconDbGdpRealFetcher()
result = fetcher.test(params, credentials)
assert result is None
@pytest.mark.record_http
def test_econdb_export_destinations_fetcher(credentials=test_credentials):
"""Test EconDB Export Destinations Fetcher."""
params = {
"country": "US",
}
fetcher = EconDbExportDestinationsFetcher()
result = fetcher.test(params, credentials)
assert result is None