From 711ac10c323c6ebddf9cc68faf9071663123d62c Mon Sep 17 00:00:00 2001 From: Danglewood <85772166+deeleeramone@users.noreply.github.com> Date: Thu, 3 Oct 2024 16:30:23 -0700 Subject: [PATCH] merge artifacts --- .../economy/openbb_economy/economy_views.py | 207 ------------------ .../openbb/package/commodity_price.py | 206 +++++++++++++++++ 2 files changed, 206 insertions(+), 207 deletions(-) create mode 100644 openbb_platform/openbb/package/commodity_price.py diff --git a/openbb_platform/extensions/economy/openbb_economy/economy_views.py b/openbb_platform/extensions/economy/openbb_economy/economy_views.py index f4ae6ae9d86..c602858ed0a 100644 --- a/openbb_platform/extensions/economy/openbb_economy/economy_views.py +++ b/openbb_platform/extensions/economy/openbb_economy/economy_views.py @@ -531,210 +531,3 @@ class EconomyViews: content = fig.to_plotly_json() return fig, content - - @staticmethod - def economy_survey_bls_series( - **kwargs, - ) -> Tuple["OpenBBFigure", Dict[str, Any]]: - """Economy Survey BLS Series Chart. - - Parameters - ---------- - data: Optional[Union[DataFrame, List[Data]]] - Filtered subset of the parent results. - target_symbol: Optional[str] - The target symbol(s) to plot. Plot multiple symbols by separating them with a comma. Max 10 symbols. - target_col: Optional[str] - The target column to plot. Default is 'value'. - plot_type: Literal["line", "bar"] - The type of plot to display. Default is 'line', unless the data is significantly small. - normalize: bool - Normalize the data before displaying. Default is False. - title: Optional[str] - The title of the chart. - xtitle: Optional[str] - The title of the x-axis. - ytitle: Optional[str] - The title of the y-axis. - bar_kwargs: Optional[Dict] - Additional keyword arguments applied to `fig.add_bar`. - scatter_kwargs: Optional[Dict] - Additional keyword arguments applied to `fig.add_scatter`. - layout_kwargs: Optional[Dict] - Additional keyword arguments applied to `fig.update_layout`. - """ - # pylint: disable=import-outside-toplevel - from openbb_charting.charts.generic_charts import bar_chart, line_chart - from openbb_charting.charts.helpers import ( - z_score_standardization, - ) - from openbb_core.app.utils import basemodel_to_df - from pandas import DataFrame - - provider = kwargs.get("provider") - - if provider != "bls": - raise RuntimeError( - f"This charting method does not support {provider}. Supported providers: bls." - ) - - _data = ( - kwargs.pop("data", None) - if "data" in kwargs and kwargs["data"] is not None - else kwargs.get("obbject_item") - ) - df = DataFrame() - - if isinstance(_data, DataFrame) and not _data.empty: - df = _data.reset_index() if _data.index.name == "date" else _data - else: - try: - df = basemodel_to_df(_data, index=None) # type: ignore - except Exception as e: - raise RuntimeError("Unable to process supplied data.") from e - - if df.empty or len(df) < 2: - raise RuntimeError("No data found to plot.") - - cols = df.columns.to_list() - target_col = kwargs.get("target_col", "value") - if target_col not in cols: - raise RuntimeError(f"Column '{target_col}' not found in the data.") - - new_df = df.pivot(columns="symbol", values=target_col, index="date") - target_symbols = kwargs.get("target_symbol", "").split(",")[:10] # type: ignore - - if not target_symbols or len(target_symbols) == 0 or target_symbols[0] == "": - target_symbols = new_df.columns.to_list()[:10] - - metadata = kwargs["extra"].get("results_metadata", {}) # type: ignore - ytitle = kwargs.get("ytitle", "") - - new_df = new_df.filter(target_symbols, axis=1) - - if "percent" in target_col.lower(): # type: ignore - ytitle = ( - ytitle - if ytitle - else target_col.replace("change_percent_", "").replace("M", " Month") # type: ignore - + " Change (%)" - ) - new_df = new_df.apply(lambda x: x * 100) - elif "change" in target_col.lower() and "percent" not in target_col.lower(): # type: ignore - ytitle = ( - ytitle - if ytitle - else target_col.replace("change_", "").replace("M", " Month") # type: ignore - + " Change" - ) - - title_map: Dict = {} - for symbol in target_symbols: - if symbol not in new_df.columns: - continue - survey_name = metadata.get(symbol, {}).get("survey_name", symbol) # type: ignore - series_title = metadata.get(symbol, {}).get("series_title", symbol) # type: ignore - - if survey_name != series_title: - title_map[symbol] = f"{survey_name} \n {series_title}" - - normalize = kwargs.get("normalize", False) - same_axis = kwargs.get("same_axis", False) - - if normalize: - new_df = new_df.apply(z_score_standardization) - same_axis = True - if ytitle: - ytitle = f"Normalized {ytitle.replace('(%)', '')}" # type: ignore - - plot_type = kwargs.get("plot_type") - - if plot_type is None: - plot_type = ( - "line" # type: ignore - if (len(new_df.index) > 36 and len(new_df.columns.to_list()) >= 1) - else "bar" - ) - - layout_kwargs: Dict = kwargs.pop("layout_kwargs", {}) # type: ignore - scatter_kwargs: Dict = kwargs.pop("scatter_kwargs", {}) # type: ignore - bar_kwargs: Dict = kwargs.pop("bar_kwargs", {}) # type: ignore - hovertemplate = scatter_kwargs.pop("hovertemplate", None) # type: ignore - trace_titles = { - symbol: metadata.get(symbol, {}) - .get("series_title", symbol) - .replace(",", " -") - for symbol in target_symbols - } - new_df.columns = [trace_titles.get(col, col) for col in new_df.columns] - scatter_kwargs["hovertemplate"] = ( # type: ignore - hovertemplate if hovertemplate else "%{fullData.name}:%{y}" - ) - - if len(target_symbols) == 1: - title = title_map.get(target_symbols[0], target_symbols[0]) - fig = ( - line_chart( - data=new_df, - title=title, - ytitle=ytitle, - y=list(trace_titles.values()), - scatter_kwargs=scatter_kwargs, - layout_kwargs=layout_kwargs, - **kwargs, - ) - if plot_type == "line" - else bar_chart( - data=new_df, - title=title, - ytitle=ytitle, - x=new_df.index, - y=list(trace_titles.values()), - layout_kwargs=layout_kwargs, - bar_kwargs=bar_kwargs, - **kwargs, - ) - ) - else: - survey_name = metadata.get(target_symbols[0], {}).get("survey_name", target_symbols[0]).split("\n")[0].strip() # type: ignore - _t = kwargs.pop("title", None) - title = _t if _t else f"{survey_name} - {ytitle}" if ytitle else survey_name - fig = ( - line_chart( - data=new_df, - y=list(trace_titles.values()), - title=title, - ytitle=ytitle, - same_axis=same_axis, - normalize=False, - scatter_kwargs=scatter_kwargs, - layout_kwargs=layout_kwargs, - **kwargs, - ) - if plot_type == "line" - else bar_chart( - data=new_df, - title=title, - ytitle=ytitle, - x=new_df.index, - y=list(trace_titles.values()), - layout_kwargs=layout_kwargs, - bar_kwargs=bar_kwargs, - **kwargs, - ) - ) - - fig.update_layout( - margin=dict(b=20), - legend=dict( - orientation="h", - yanchor="top", - xanchor="left", - y=-0.075, - x=0, - font=dict(size=12), - ), - ) - content = fig.to_plotly_json() - - return fig, content diff --git a/openbb_platform/openbb/package/commodity_price.py b/openbb_platform/openbb/package/commodity_price.py new file mode 100644 index 00000000000..09d87f7041b --- /dev/null +++ b/openbb_platform/openbb/package/commodity_price.py @@ -0,0 +1,206 @@ +### THIS FILE IS AUTO-GENERATED. DO NOT EDIT. ### + +import datetime +from typing import Literal, Optional, Union + +from openbb_core.app.model.field import OpenBBField +from openbb_core.app.model.obbject import OBBject +from openbb_core.app.static.container import Container +from openbb_core.app.static.utils.decorators import exception_handler, validate +from openbb_core.app.static.utils.filters import filter_inputs +from typing_extensions import Annotated + + +class ROUTER_commodity_price(Container): + """/commodity/price + spot + """ + + def __repr__(self) -> str: + return self.__doc__ or "" + + @exception_handler + @validate + def spot( + self, + start_date: Annotated[ + Union[datetime.date, None, str], + OpenBBField(description="Start date of the data, in YYYY-MM-DD format."), + ] = None, + end_date: Annotated[ + Union[datetime.date, None, str], + OpenBBField(description="End date of the data, in YYYY-MM-DD format."), + ] = None, + provider: Annotated[ + Optional[Literal["fred"]], + OpenBBField( + description="The provider to use, by default None. If None, the priority list configured in the settings is used. Default priority: fred." + ), + ] = None, + **kwargs + ) -> OBBject: + """Commodity Spot Prices. + + Parameters + ---------- + start_date : Union[date, None, str] + Start date of the data, in YYYY-MM-DD format. + end_date : Union[date, None, str] + End date of the data, in YYYY-MM-DD format. + provider : Optional[Literal['fred']] + The provider to use, by default None. If None, the priority list configured in the settings is used. Default priority: fred. + commodity : Literal['wti', 'brent', 'natural_gas', 'jet_fuel', 'propane', 'heating_oil', 'diesel_gulf_coast', 'diesel_ny_harbor', 'diesel_la', 'gasoline_ny_harbor', 'gasoline_gulf_coast', 'rbob', 'all'] + Commodity name associated with the EIA spot price commodity data, default is 'all'. (provider: fred) + frequency : Optional[Literal['a', 'q', 'm', 'w', 'd', 'wef', 'weth', 'wew', 'wetu', 'wem', 'wesu', 'wesa', 'bwew', 'bwem']] + Frequency aggregation to convert high frequency data to lower frequency. + None = No change + a = Annual + q = Quarterly + m = Monthly + w = Weekly + d = Daily + wef = Weekly, Ending Friday + weth = Weekly, Ending Thursday + wew = Weekly, Ending Wednesday + wetu = Weekly, Ending Tuesday + wem = Weekly, Ending Monday + wesu = Weekly, Ending Sunday + wesa = Weekly, Ending Saturday + bwew = Biweekly, Ending Wednesday + bwem = Biweekly, Ending Monday + (provider: fred) + aggregation_method : Literal['avg', 'sum', 'eop'] + A key that indicates the aggregation method used for frequency aggregation. + This parameter has no affect if the frequency parameter is not set. + avg = Average + sum = Sum + eop = End of Period + (provider: fred) + transform : Optional[Literal['chg', 'ch1', 'pch', 'pc1', 'pca', 'cch', 'cca', 'log']] + Transformation type + None = No transformation + chg = Change + ch1 = Change from Year Ago + pch = Percent Change + pc1 = Percent Change from Year Ago + pca = Compounded Annual Rate of Change + cch = Continuously Compounded Rate of Change + cca = Continuously Compounded Annual Rate of Change + log = Natural Log + (provider: fred) + + Returns + ------- + OBBject + results : List[CommoditySpotPrices] + Serializable results. + provider : Optional[Literal['fred']] + Provider name. + warnings : Optional[List[Warning_]] + List of warnings. + chart : Optional[Chart] + Chart object. + extra : Dict[str, Any] + Extra info. + + CommoditySpotPrices + ------------------- + date : date + The date of the data. + symbol : Optional[str] + Symbol representing the entity requested in the data. + commodity : Optional[str] + Commodity name. + price : float + Price of the commodity. + unit : Optional[str] + Unit of the commodity price. + + Examples + -------- + >>> from openbb import obb + >>> obb.commodity.price.spot(provider='fred') + >>> obb.commodity.price.spot(provider='fred', commodity='wti') + """ # noqa: E501 + + return self._run( + "/commodity/price/spot", + **filter_inputs( + provider_choices={ + "provider": self._get_provider( + provider, + "commodity.price.spot", + ("fred",), + ) + }, + standard_params={ + "start_date": start_date, + "end_date": end_date, + }, + extra_params=kwargs, + info={ + "commodity": { + "fred": { + "multiple_items_allowed": False, + "choices": [ + "wti", + "brent", + "natural_gas", + "jet_fuel", + "propane", + "heating_oil", + "diesel_gulf_coast", + "diesel_ny_harbor", + "diesel_la", + "gasoline_ny_harbor", + "gasoline_gulf_coast", + "rbob", + "all", + ], + } + }, + "frequency": { + "fred": { + "multiple_items_allowed": False, + "choices": [ + "a", + "q", + "m", + "w", + "d", + "wef", + "weth", + "wew", + "wetu", + "wem", + "wesu", + "wesa", + "bwew", + "bwem", + ], + } + }, + "aggregation_method": { + "fred": { + "multiple_items_allowed": False, + "choices": ["avg", "sum", "eop"], + } + }, + "transform": { + "fred": { + "multiple_items_allowed": False, + "choices": [ + "chg", + "ch1", + "pch", + "pc1", + "pca", + "cch", + "cca", + "log", + ], + } + }, + }, + ) + )