[BugFix] Fix TMX Request Timeout Configuration (#7142)

* let preferences set timeout

* read system_settings file

* set default timeout if not defined to aiohttp default 300 and fix ISIN filter

* duplicate operation

* still filter for Corp
This commit is contained in:
Danglewood
2025-06-09 12:53:11 -07:00
committed by GitHub
parent b0ee9d64c2
commit 4a2d74db1b
2 changed files with 57 additions and 26 deletions

View File

@@ -5,8 +5,9 @@ from datetime import (
date as dateType,
datetime,
)
from typing import TYPE_CHECKING, Any, Dict, List, Optional
from typing import TYPE_CHECKING, Any, Optional
from openbb_core.app.model.abstract.error import OpenBBError
from openbb_core.provider.abstract.fetcher import Fetcher
from openbb_core.provider.standard_models.bond_reference import (
BondReferenceData,
@@ -27,9 +28,8 @@ class TmxBondPricesQueryParams(BondReferenceQueryParams):
Source: https://bondtradedata.iiroc.ca/#/
"""
__alias_dict__ = {
# "isin": "isins",
}
__json_schema_extra__ = {"isin": {"multiple_items_allowed": True}}
issue_date_min: Optional[dateType] = Field(
default=None,
description="Filter by the minimum original issue date.",
@@ -126,13 +126,13 @@ class TmxBondPricesData(BondReferenceData):
class TmxBondPricesFetcher(
Fetcher[
TmxBondPricesQueryParams,
List[TmxBondPricesData],
list[TmxBondPricesData],
]
):
"""Tmx Bond Reference Fetcher."""
@staticmethod
def transform_query(params: Dict[str, Any]) -> TmxBondPricesQueryParams:
def transform_query(params: dict[str, Any]) -> TmxBondPricesQueryParams:
"""Transform query params."""
# pylint: disable=import-outside-toplevel
from datetime import timedelta
@@ -150,7 +150,7 @@ class TmxBondPricesFetcher(
@staticmethod
async def aextract_data(
query: TmxBondPricesQueryParams,
credentials: Optional[Dict[str, str]],
credentials: Optional[dict[str, str]],
**kwargs: Any,
) -> "DataFrame":
"""Get the raw data containing all bond data."""
@@ -165,17 +165,34 @@ class TmxBondPricesFetcher(
query: TmxBondPricesQueryParams,
data: "DataFrame",
**kwargs: Any,
) -> List[TmxBondPricesData]:
) -> list[TmxBondPricesData]:
"""Transform data."""
bonds = data.copy()
results = []
data = data[data["bondType"] == "Corp"]
# pylint: disable=import-outside-toplevel
from numpy import nan
bonds = data.copy()
if query.isin is not None:
isin_list = (
query.isin.split(",") if isinstance(query.isin, str) else query.isin
)
data = bonds[
bonds["isin"].str.contains("|".join(isin_list), na=False, case=False)
].query("bondType == 'Corp'")
if data.empty or len(data) == 0:
raise OpenBBError(
f"No bonds found for the provided ISIN(s) -> {', '.join(isin_list)}",
)
else:
data = bonds.query(
"bondType == 'Corp'"
"& maturityDate >= @query.maturity_date_min.strftime('%Y-%m-%d')"
).sort_values(by=["maturityDate"])
data.loc[:, "issuer"] = data.issuer.str.strip()
data = bonds.query(
"bondType == 'Corp'"
"& maturityDate >= @query.maturity_date_min.strftime('%Y-%m-%d')"
).sort_values(by=["maturityDate"])
data.issuer = data.loc[:, "issuer"].str.strip()
if query.maturity_date_max:
data = data.query(
"maturityDate <= @query.maturity_date_max.strftime('%Y-%m-%d')"
@@ -190,9 +207,13 @@ class TmxBondPricesFetcher(
data = data.query("couponRate <= @query.coupon_max")
if query.issuer_name:
data = data.query("issuer.str.contains(@query.issuer_name, case=False)")
if len(data) > 0:
data = data.drop(columns=["bondType", "securityId", "secKey"])
data = data.fillna("N/A").replace("N/A", None)
results = data.to_dict("records")
data = data.replace({nan: None})
else:
raise OpenBBError(
"No bonds found for the provided query parameters.",
)
return [TmxBondPricesData.model_validate(d) for d in results]
return [TmxBondPricesData.model_validate(d) for d in data.to_dict("records")]

View File

@@ -284,10 +284,20 @@ async def get_data_from_url(
"""Make an asynchronous HTTP request to a static file."""
# pylint: disable=import-outside-toplevel
from aiohttp_client_cache.session import CachedSession
from openbb_core.provider.utils.helpers import amake_request
from openbb_core.provider.utils.helpers import (
amake_request,
get_python_request_settings,
)
python_settings = get_python_request_settings()
if timeout := python_settings.get("timeout"):
kwargs.setdefault("timeout", timeout)
else:
kwargs.setdefault("timeout", 300)
data: Any = None
if use_cache is True:
if use_cache is True and backend is not None:
await backend.delete_expired_responses()
async with CachedSession(cache=backend) as cached_session:
try:
response = await cached_session.get(url, **kwargs)
@@ -295,7 +305,7 @@ async def get_data_from_url(
finally:
await cached_session.close()
else:
data = await amake_request(url, response_callback=response_callback, timeout=20)
data = await amake_request(url, response_callback=response_callback, **kwargs)
return data
@@ -307,11 +317,11 @@ async def get_data_from_gql(url: str, headers, data, **kwargs: Any) -> Any:
response = await amake_request(
url=url,
method="POST",
method=kwargs.pop("method", "POST"),
response_callback=response_callback,
headers=headers,
data=data,
timeout=30,
**kwargs,
)
return response
@@ -1112,10 +1122,10 @@ async def get_all_bonds(use_cache: bool = True) -> "DataFrame":
tmx_bonds_backend = SQLiteBackend(
f"{get_user_cache_directory()}/http/tmx_bonds", expire_after=timedelta(days=1)
)
_ = await tmx_bonds_backend.delete_expired_responses()
url = "https://bondtradedata.iiroc.ca/debtip/designatedbonds/list"
response = await get_data_from_url(
url, use_cache=use_cache, timeout=30, backend=tmx_bonds_backend
url, use_cache=use_cache, backend=tmx_bonds_backend
)
# Convert the response to a DataFrame and set the types for proper filtering in-fetcher.