From bc24709cbaeb5eb19a8c4ce4ece45a65f99d91f2 Mon Sep 17 00:00:00 2001 From: Danglewood <85772166+deeleeramone@users.noreply.github.com> Date: Fri, 9 Feb 2024 12:13:59 -0800 Subject: [PATCH 1/2] [HotFix] Index Router Docstrings & `sp500_multiples()` Cleanup (#6063) * sp500 multiples cleanup * remove dict from standard model * static pacakge * pylint --- .../standard_models/sp500_multiples.py | 91 ++++++++++--------- .../index/integration/test_index_api.py | 2 +- .../index/integration/test_index_python.py | 2 +- .../index/openbb_index/index_router.py | 52 +++++++++-- .../index/openbb_index/price/price_router.py | 12 ++- openbb_platform/openbb/package/index.py | 10 +- .../openbb_nasdaq/models/sp500_multiples.py | 14 ++- .../nasdaq/openbb_nasdaq/utils/series_ids.py | 77 ++++++++-------- 8 files changed, 158 insertions(+), 102 deletions(-) diff --git a/openbb_platform/core/openbb_core/provider/standard_models/sp500_multiples.py b/openbb_platform/core/openbb_core/provider/standard_models/sp500_multiples.py index cd7b247a8d8..8631478c467 100644 --- a/openbb_platform/core/openbb_core/provider/standard_models/sp500_multiples.py +++ b/openbb_platform/core/openbb_core/provider/standard_models/sp500_multiples.py @@ -12,57 +12,58 @@ from openbb_core.provider.utils.descriptions import ( QUERY_DESCRIPTIONS, ) +SERIES_NAMES = Literal[ + "shiller_pe_month", + "shiller_pe_year", + "pe_year", + "pe_month", + "dividend_year", + "dividend_month", + "dividend_growth_quarter", + "dividend_growth_year", + "dividend_yield_year", + "dividend_yield_month", + "earnings_year", + "earnings_month", + "earnings_growth_year", + "earnings_growth_quarter", + "real_earnings_growth_year", + "real_earnings_growth_quarter", + "earnings_yield_year", + "earnings_yield_month", + "real_price_year", + "real_price_month", + "inflation_adjusted_price_year", + "inflation_adjusted_price_month", + "sales_year", + "sales_quarter", + "sales_growth_year", + "sales_growth_quarter", + "real_sales_year", + "real_sales_quarter", + "real_sales_growth_year", + "real_sales_growth_quarter", + "price_to_sales_year", + "price_to_sales_quarter", + "price_to_book_value_year", + "price_to_book_value_quarter", + "book_value_year", + "book_value_quarter", +] + class SP500MultiplesQueryParams(QueryParams): """SP500 Multiples Query.""" - series_name: Literal[ - "Shiller PE Ratio by Month", - "Shiller PE Ratio by Year", - "PE Ratio by Year", - "PE Ratio by Month", - "Dividend by Year", - "Dividend by Month", - "Dividend Growth by Quarter", - "Dividend Growth by Year", - "Dividend Yield by Year", - "Dividend Yield by Month", - "Earnings by Year", - "Earnings by Month", - "Earnings Growth by Year", - "Earnings Growth by Quarter", - "Real Earnings Growth by Year", - "Real Earnings Growth by Quarter", - "Earnings Yield by Year", - "Earnings Yield by Month", - "Real Price by Year", - "Real Price by Month", - "Inflation Adjusted Price by Year", - "Inflation Adjusted Price by Month", - "Sales by Year", - "Sales by Quarter", - "Sales Growth by Year", - "Sales Growth by Quarter", - "Real Sales by Year", - "Real Sales by Quarter", - "Real Sales Growth by Year", - "Real Sales Growth by Quarter", - "Price to Sales Ratio by Year", - "Price to Sales Ratio by Quarter", - "Price to Book Value Ratio by Year", - "Price to Book Value Ratio by Quarter", - "Book Value per Share by Year", - "Book Value per Share by Quarter", - ] = Field( - description="The name of the series. Defaults to 'PE Ratio by Month'.", - default="PE Ratio by Month", + series_name: SERIES_NAMES = Field( + description="The name of the series. Defaults to 'pe_month'.", + default="pe_month", ) - - start_date: Optional[str] = Field( - description=QUERY_DESCRIPTIONS.get("start_date", ""), default="" + start_date: Optional[dateType] = Field( + description=QUERY_DESCRIPTIONS.get("start_date", ""), default=None ) - end_date: Optional[str] = Field( - description=QUERY_DESCRIPTIONS.get("end_date", ""), default="" + end_date: Optional[dateType] = Field( + description=QUERY_DESCRIPTIONS.get("end_date", ""), default=None ) diff --git a/openbb_platform/extensions/index/integration/test_index_api.py b/openbb_platform/extensions/index/integration/test_index_api.py index dff0265d57a..9a0df1c8e44 100644 --- a/openbb_platform/extensions/index/integration/test_index_api.py +++ b/openbb_platform/extensions/index/integration/test_index_api.py @@ -334,7 +334,7 @@ def test_index_snapshots(params, headers): [ ( { - "series_name": "PE Ratio by Month", + "series_name": "pe_month", "start_date": "2023-01-01", "end_date": "2023-06-06", "collapse": "monthly", diff --git a/openbb_platform/extensions/index/integration/test_index_python.py b/openbb_platform/extensions/index/integration/test_index_python.py index 600a1279d7e..80139634288 100644 --- a/openbb_platform/extensions/index/integration/test_index_python.py +++ b/openbb_platform/extensions/index/integration/test_index_python.py @@ -318,7 +318,7 @@ def test_index_snapshots(params, obb): [ ( { - "series_name": "PE Ratio by Month", + "series_name": "pe_month", "start_date": "2023-01-01", "end_date": "2023-06-06", "collapse": "monthly", diff --git a/openbb_platform/extensions/index/openbb_index/index_router.py b/openbb_platform/extensions/index/openbb_index/index_router.py index 7b1298c8aae..5b4432325f2 100644 --- a/openbb_platform/extensions/index/openbb_index/index_router.py +++ b/openbb_platform/extensions/index/openbb_index/index_router.py @@ -38,56 +38,88 @@ async def market( return await OBBject.from_query(Query(**locals())) -@router.command(model="IndexConstituents") +@router.command( + model="IndexConstituents", + exclude_auto_examples=True, + examples=[ + 'obb.index.constituents("dowjones", provider="fmp").to_df()', + "#### Providers other than FMP will use the ticker symbol. ####", + 'obb.index.constituents("BEP50P", provider="cboe").to_df()', + ], +) async def constituents( cc: CommandContext, provider_choices: ProviderChoices, standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Index Constituents. Constituents of an index.""" + """Index Constituents.""" return await OBBject.from_query(Query(**locals())) -@router.command(model="IndexSnapshots") +@router.command( + model="IndexSnapshots", + exclude_auto_examples=True, + examples=[ + 'obb.index.snapshots(region="us",provider="cboe").to_df()', + ], +) async def snapshots( cc: CommandContext, provider_choices: ProviderChoices, standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Index Snapshots. Current levels for all indices from a provider.""" + """Index Snapshots. Current levels for all indices from a provider, grouped by `region`.""" return await OBBject.from_query(Query(**locals())) -@router.command(model="AvailableIndices") +@router.command( + model="AvailableIndices", + exclude_auto_examples=True, + examples=[ + 'obb.index.available(provider="yfinance").to_df()', + ], +) async def available( cc: CommandContext, provider_choices: ProviderChoices, standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Available Indices. Available indices for a given provider.""" + """All indices available from a given provider.""" return await OBBject.from_query(Query(**locals())) -@router.command(model="IndexSearch") +@router.command( + model="IndexSearch", + exclude_auto_examples=True, + examples=[ + "obb.index.search(query='SPX', provider='cboe').to_df()", + ], +) async def search( cc: CommandContext, provider_choices: ProviderChoices, standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Index Search. Search for indices.""" + """Filters indices for rows containing the query.""" return await OBBject.from_query(Query(**locals())) -@router.command(model="SP500Multiples") +@router.command( + model="SP500Multiples", + exclude_auto_examples=True, + examples=[ + 'obb.index.sp500_multiples(series_name="shiller_pe_year", provider="nasdaq").to_df()', + ], +) async def sp500_multiples( cc: CommandContext, provider_choices: ProviderChoices, standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """S&P 500 Multiples. Historical S&P 500 multiples and Shiller PE ratios.""" + """Historical S&P 500 multiples and Shiller PE ratios.""" return await OBBject.from_query(Query(**locals())) diff --git a/openbb_platform/extensions/index/openbb_index/price/price_router.py b/openbb_platform/extensions/index/openbb_index/price/price_router.py index 36feb2547f4..c5f44332eff 100644 --- a/openbb_platform/extensions/index/openbb_index/price/price_router.py +++ b/openbb_platform/extensions/index/openbb_index/price/price_router.py @@ -15,12 +15,20 @@ router = Router(prefix="/price") # pylint: disable=unused-argument -@router.command(model="IndexHistorical") +@router.command( + model="IndexHistorical", + exclude_auto_examples=True, + examples=[ + 'obb.index.price.historical("^GSPC", provider="fmp").to_df()', + "#### Not all providers have the same symbols. ####", + 'obb.index.price.historical("SPX", provider="intrinio").to_df()', + ], +) async def historical( cc: CommandContext, provider_choices: ProviderChoices, standard_params: StandardParams, extra_params: ExtraParams, ) -> OBBject: - """Index Historical Price. Load stock data for a specific index.""" + """Historical Index Levels.""" return await OBBject.from_query(Query(**locals())) diff --git a/openbb_platform/openbb/package/index.py b/openbb_platform/openbb/package/index.py index 28f923ee7e6..b2930f7244d 100644 --- a/openbb_platform/openbb/package/index.py +++ b/openbb_platform/openbb/package/index.py @@ -28,7 +28,7 @@ class ROUTER_index(Container): def available( self, provider: Optional[Literal["fmp", "yfinance"]] = None, **kwargs ) -> OBBject: - """Available Indices. Available indices for a given provider. + """All indices available from a given provider. Parameters ---------- @@ -69,7 +69,7 @@ class ROUTER_index(Container): Example ------- >>> from openbb import obb - >>> obb.index.available() + >>> obb.index.available(provider="yfinance").to_df() """ # noqa: E501 return self._run( @@ -93,7 +93,7 @@ class ROUTER_index(Container): provider: Optional[Literal["fmp"]] = None, **kwargs ) -> OBBject: - """Index Constituents. Constituents of an index. + """Index Constituents. Parameters ---------- @@ -140,7 +140,9 @@ class ROUTER_index(Container): Example ------- >>> from openbb import obb - >>> obb.index.constituents(index="^IBEX") + >>> obb.index.constituents("dowjones", provider="fmp").to_df() + >>> #### Providers other than FMP will use the ticker symbol. #### + >>> obb.index.constituents("BEP50P", provider="cboe").to_df() """ # noqa: E501 return self._run( diff --git a/openbb_platform/providers/nasdaq/openbb_nasdaq/models/sp500_multiples.py b/openbb_platform/providers/nasdaq/openbb_nasdaq/models/sp500_multiples.py index bc5bcdff74f..5b81188e629 100644 --- a/openbb_platform/providers/nasdaq/openbb_nasdaq/models/sp500_multiples.py +++ b/openbb_platform/providers/nasdaq/openbb_nasdaq/models/sp500_multiples.py @@ -1,5 +1,7 @@ """Nasdaq SP500 Multiples Model.""" +# pylint: disable=unused-argument + from typing import Any, Dict, List, Optional import nasdaqdatalink @@ -10,6 +12,7 @@ from openbb_core.provider.standard_models.sp500_multiples import ( ) from openbb_nasdaq.utils.query_params import DataLinkQueryParams from openbb_nasdaq.utils.series_ids import SP500MULTIPLES +from pydantic import model_validator class NasdaqSP500MultiplesQueryParams(SP500MultiplesQueryParams, DataLinkQueryParams): @@ -19,6 +22,15 @@ class NasdaqSP500MultiplesQueryParams(SP500MultiplesQueryParams, DataLinkQueryPa class NasdaqSP500MultiplesData(SP500MultiplesData): """Nasdaq SP500 Multiples Data.""" + @model_validator(mode="before") + @classmethod + def normalize_percent(cls, values): + """Normalize percent values.""" + for k, v in values.items(): + if any(x in k for x in ["yield", "growth"]): + values[k] = float(v) / 100 + return values + class NasdaqSP500MultiplesFetcher( Fetcher[NasdaqSP500MultiplesQueryParams, List[NasdaqSP500MultiplesData]] @@ -68,5 +80,5 @@ class NasdaqSP500MultiplesFetcher( data: List[Dict], **kwargs: Any, ) -> List[NasdaqSP500MultiplesData]: - """Parse data into the NasdaqSP500MultiplesData format.""" + """Transform the data to the model.""" return [NasdaqSP500MultiplesData.model_validate(d) for d in data] diff --git a/openbb_platform/providers/nasdaq/openbb_nasdaq/utils/series_ids.py b/openbb_platform/providers/nasdaq/openbb_nasdaq/utils/series_ids.py index bd6ccb08e05..2194889db6f 100644 --- a/openbb_platform/providers/nasdaq/openbb_nasdaq/utils/series_ids.py +++ b/openbb_platform/providers/nasdaq/openbb_nasdaq/utils/series_ids.py @@ -1,44 +1,45 @@ """Nasdaq Data Link Series ID Dictionaries.""" -SP500MULTIPLES = { - "Shiller PE Ratio by Month": "MULTPL/SHILLER_PE_RATIO_MONTH", - "Shiller PE Ratio by Year": "MULTPL/SHILLER_PE_RATIO_YEAR", - "PE Ratio by Year": "MULTPL/SP500_PE_RATIO_YEAR", - "PE Ratio by Month": "MULTPL/SP500_PE_RATIO_MONTH", - "Dividend by Year": "MULTPL/SP500_DIV_YEAR", - "Dividend by Month": "MULTPL/SP500_DIV_MONTH", - "Dividend Growth by Quarter": "MULTPL/SP500_DIV_GROWTH_QUARTER", - "Dividend Growth by Year": "MULTPL/SP500_DIV_GROWTH_YEAR", - "Dividend Yield by Year": "MULTPL/SP500_DIV_YIELD_YEAR", - "Dividend Yield by Month": "MULTPL/SP500_DIV_YIELD_MONTH", - "Earnings by Year": "MULTPL/SP500_EARNINGS_YEAR", - "Earnings by Month": "MULTPL/SP500_EARNINGS_MONTH", - "Earnings Growth by Year": "MULTPL/SP500_EARNINGS_GROWTH_YEAR", - "Earnings Growth by Quarter": "MULTPL/SP500_EARNINGS_GROWTH_QUARTER", - "Real Earnings Growth by Year": "MULTPL/SP500_REAL_EARNINGS_GROWTH_YEAR", - "Real Earnings Growth by Quarter": "MULTPL/SP500_REAL_EARNINGS_GROWTH_QUARTER", - "Earnings Yield by Year": "MULTPL/SP500_EARNINGS_YIELD_YEAR", - "Earnings Yield by Month": "MULTPL/SP500_EARNINGS_YIELD_MONTH", - "Real Price by Year": "MULTPL/SP500_REAL_PRICE_YEAR", - "Real Price by Month": "MULTPL/SP500_REAL_PRICE_MONTH", - "Inflation Adjusted Price by Year": "MULTPL/SP500_INFLADJ_YEAR", - "Inflation Adjusted Price by Month": "MULTPL/SP500_INFLADJ_MONTH", - "Sales by Year": "MULTPL/SP500_SALES_YEAR", - "Sales by Quarter": "MULTPL/SP500_SALES_QUARTER", - "Sales Growth by Year": "MULTPL/SP500_SALES_GROWTH_YEAR", - "Sales Growth by Quarter": "MULTPL/SP500_SALES_GROWTH_Quarter", - "Real Sales by Year": "MULTPL/SP500_REAL_SALES_YEAR", - "Real Sales by Quarter": "MULTPL/SP500_REAL_SALES_QUARTER", - "Real Sales Growth by Year": "MULTPL/SP500_REAL_SALES_GROWTH_YEAR", - "Real Sales Growth by Quarter": "MULTPL/SP500_REAL_SALES_GROWTH_QUARTER", - "Price to Sales Ratio by Year": "MULTPL/SP500_PSR_YEAR", - "Price to Sales Ratio by Quarter": "MULTPL/SP500_PSR_QUARTER", - "Price to Book Value Ratio by Year": "MULTPL/SP500_PBV_RATIO_YEAR", - "Price to Book Value Ratio by Quarter": "MULTPL/SP500_PBV_RATIO_QUARTER", - "Book Value per Share by Year": "MULTPL/SP500_BVPS_YEAR", - "Book Value per Share by Quarter": "MULTPL/SP500_BVPS_QUARTER", -} +# pylint: disable=too-many-lines, line-too-long +SP500MULTIPLES = { + "shiller_pe_month": "MULTPL/SHILLER_PE_RATIO_MONTH", + "shiller_pe_year": "MULTPL/SHILLER_PE_RATIO_YEAR", + "pe_year": "MULTPL/SP500_PE_RATIO_YEAR", + "pe_month": "MULTPL/SP500_PE_RATIO_MONTH", + "dividend_year": "MULTPL/SP500_DIV_YEAR", + "dividend_month": "MULTPL/SP500_DIV_MONTH", + "dividend_growth_quarter": "MULTPL/SP500_DIV_GROWTH_QUARTER", + "dividend_growth_year": "MULTPL/SP500_DIV_GROWTH_YEAR", + "dividend_yield_year": "MULTPL/SP500_DIV_YIELD_YEAR", + "dividend_yield_month": "MULTPL/SP500_DIV_YIELD_MONTH", + "earnings_year": "MULTPL/SP500_EARNINGS_YEAR", + "earnings_month": "MULTPL/SP500_EARNINGS_MONTH", + "earnings_growth_year": "MULTPL/SP500_EARNINGS_GROWTH_YEAR", + "earnings_growth_quarter": "MULTPL/SP500_EARNINGS_GROWTH_QUARTER", + "real_earnings_growth_year": "MULTPL/SP500_REAL_EARNINGS_GROWTH_YEAR", + "real_earnings_growth_quarter": "MULTPL/SP500_REAL_EARNINGS_GROWTH_QUARTER", + "earnings_yield_year": "MULTPL/SP500_EARNINGS_YIELD_YEAR", + "earnings_yield_month": "MULTPL/SP500_EARNINGS_YIELD_MONTH", + "real_price_month": "MULTPL/SP500_REAL_PRICE_YEAR", + "real_price_year": "MULTPL/SP500_REAL_PRICE_MONTH", + "inflation_adjusted_price_year": "MULTPL/SP500_INFLADJ_YEAR", + "inflation_adjusted_price_month": "MULTPL/SP500_INFLADJ_MONTH", + "sales_year": "MULTPL/SP500_SALES_YEAR", + "sales_quarter": "MULTPL/SP500_SALES_QUARTER", + "sales_growth_year": "MULTPL/SP500_SALES_GROWTH_YEAR", + "sales_growth_quarter": "MULTPL/SP500_SALES_GROWTH_Quarter", + "real_sales_year": "MULTPL/SP500_REAL_SALES_YEAR", + "real_sales_quarter": "MULTPL/SP500_REAL_SALES_QUARTER", + "real_sales_growth_year": "MULTPL/SP500_REAL_SALES_GROWTH_YEAR", + "real_sales_growth_quarter": "MULTPL/SP500_REAL_SALES_GROWTH_QUARTER", + "price_to_sales_year": "MULTPL/SP500_PSR_YEAR", + "price_to_sales_quarter": "MULTPL/SP500_PSR_QUARTER", + "price_to_book_value_year": "MULTPL/SP500_PBV_RATIO_YEAR", + "price_to_book_value_quarter": "MULTPL/SP500_PBV_RATIO_QUARTER", + "book_value_year": "MULTPL/SP500_BVPS_YEAR", + "book_value_quarter": "MULTPL/SP500_BVPS_QUARTER", +} CFTC = { "098662": { From 6881314b6980f728ed8ebe879f73cde5bb910802 Mon Sep 17 00:00:00 2001 From: Danglewood <85772166+deeleeramone@users.noreply.github.com> Date: Fri, 9 Feb 2024 12:14:11 -0800 Subject: [PATCH 2/2] [Feature] FMP Current Holdings (#6043) * add fmp current holdings to etf holdings * pylint unused argument --------- Co-authored-by: montezdesousa <79287829+montezdesousa@users.noreply.github.com> Co-authored-by: Igor Radovanovic <74266147+IgorWounds@users.noreply.github.com> --- .../fmp/openbb_fmp/models/etf_holdings.py | 73 ++++++++++++++++--- 1 file changed, 61 insertions(+), 12 deletions(-) diff --git a/openbb_platform/providers/fmp/openbb_fmp/models/etf_holdings.py b/openbb_platform/providers/fmp/openbb_fmp/models/etf_holdings.py index d7df4ec76cd..94f91942959 100644 --- a/openbb_platform/providers/fmp/openbb_fmp/models/etf_holdings.py +++ b/openbb_platform/providers/fmp/openbb_fmp/models/etf_holdings.py @@ -1,8 +1,15 @@ """FMP ETF Holdings Model.""" -from datetime import date as dateType +# pylint: disable=unused-argument + +import warnings +from datetime import ( + date as dateType, + datetime, +) from typing import Any, Dict, List, Optional, Union +from openbb_core.provider.abstract.data import ForceInt from openbb_core.provider.abstract.fetcher import Fetcher from openbb_core.provider.standard_models.etf_holdings import ( EtfHoldingsData, @@ -10,7 +17,9 @@ from openbb_core.provider.standard_models.etf_holdings import ( ) from openbb_core.provider.utils.descriptions import QUERY_DESCRIPTIONS from openbb_fmp.utils.helpers import create_url, get_data_many -from pydantic import Field +from pydantic import Field, field_validator + +_warn = warnings.warn class FMPEtfHoldingsQueryParams(EtfHoldingsQueryParams): @@ -21,6 +30,7 @@ class FMPEtfHoldingsQueryParams(EtfHoldingsQueryParams): date: Optional[Union[str, dateType]] = Field( description=QUERY_DESCRIPTIONS.get("date", "") + + " Entering a date will attempt to return the NPORT-P filing for the entered date." + " This needs to be _exactly_ the date of the filing." + " Use the holdings_date command/endpoint to find available filing dates for the ETF.", default=None, @@ -36,26 +46,36 @@ class FMPEtfHoldingsQueryParams(EtfHoldingsQueryParams): class FMPEtfHoldingsData(EtfHoldingsData): """FMP ETF Holdings Data.""" + __alias_dict__ = { + "weight": "weightPercentage", + "value": "marketValue", + "symbol": "asset", + "balance": "sharesNumber", + } + lei: Optional[str] = Field(description="The LEI of the holding.", default=None) title: Optional[str] = Field(description="The title of the holding.", default=None) cusip: Optional[str] = Field(description="The CUSIP of the holding.", default=None) isin: Optional[str] = Field(description="The ISIN of the holding.", default=None) - balance: Optional[float] = Field( - description="The balance of the holding.", default=None + balance: Optional[ForceInt] = Field( + description="The balance of the holding, in shares or units.", default=None ) units: Optional[Union[float, str]] = Field( - description="The units of the holding.", default=None + description="The type of units.", default=None ) currency: Optional[str] = Field( description="The currency of the holding.", alias="cur_cd", default=None ) value: Optional[float] = Field( - description="The value of the holding in USD.", alias="valUsd", default=None + description="The value of the holding, in dollars.", + alias="valUsd", + default=None, ) weight: Optional[float] = Field( - description="The weight of the holding in ETF in %.", + description="The weight of the holding, as a normalized percent.", alias="pctVal", default=None, + json_schema_extra={"unit_measurement": "percent", "frontend_multiply": 100}, ) payoff_profile: Optional[str] = Field( description="The payoff profile of the holding.", @@ -104,6 +124,25 @@ class FMPEtfHoldingsData(EtfHoldingsData): alias="acceptanceTime", default=None, ) + updated: Optional[Union[dateType, datetime]] = Field( + description="The date the data was updated.", default=None + ) + + @field_validator("weight", mode="before", check_fields=False) + @classmethod + def normalize_percent(cls, v): + """Normalize percent values.""" + return float(v) / 100 if v else None + + @field_validator("cusip", "isin", "balance", "name", "symbol", "value") + @classmethod + def replace_empty(cls, v): + """Replace empty strings and 0s with None.""" + if isinstance(v, str): + return v if v not in ("", "0") else None + if isinstance(v, (float, int)): + return v if v and v not in (0.0, 0) else None + return v if v else None class FMPEtfHoldingsFetcher( @@ -127,12 +166,22 @@ class FMPEtfHoldingsFetcher( ) -> List[Dict]: """Return the raw data from the FMP endpoint.""" api_key = credentials.get("fmp_api_key") if credentials else "" + data = [] + if query.date is not None: + url = create_url( + version=4, endpoint="etf-holdings", api_key=api_key, query=query + ) + try: + data = await get_data_many(url, **kwargs) + except Exception: + _warn( + "No data found for this symbol and date, attempting to retrieve the most recent data available." + ) - url = create_url( - version=4, endpoint="etf-holdings", api_key=api_key, query=query - ) - - return await get_data_many(url, **kwargs) + if query.date is None or not data: + url = f"https://financialmodelingprep.com/api/v3/etf-holder/{query.symbol}?apikey={api_key}" + data = await get_data_many(url, **kwargs) + return data @staticmethod def transform_data(