Skip to content

Commit

Permalink
[Feature] OptionsChains Properties (OpenBB-finance#6564)
Browse files Browse the repository at this point in the history
* stashing

* update providers

* edge cases

* linter

* grammar police

* yfinance tests?

* linter

* more linting

* one test update

* move properties code to separate file

* to_df

* tmx return type

* tradier tests

* cboe cassettes

* elif instead of if

* sort expirations and strikes

* test cassettes

* change tests

---------

Co-authored-by: Igor Radovanovic <[email protected]>
Co-authored-by: James Maslek <[email protected]>
  • Loading branch information
3 people authored Aug 1, 2024
1 parent a4ed8ab commit 29066b1
Show file tree
Hide file tree
Showing 26 changed files with 57,027 additions and 23,715 deletions.
81 changes: 64 additions & 17 deletions openbb_platform/core/openbb_core/app/model/obbject.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,17 +84,54 @@ def __repr__(self) -> str:
return f"{self.__class__.__name__}\n\n" + "\n".join(items)

def to_df(
self, index: Optional[Union[str, None]] = "date", sort_by: Optional[str] = None
self,
index: Optional[Union[str, None]] = "date",
sort_by: Optional[str] = None,
ascending: Optional[bool] = None,
) -> "DataFrame":
"""Alias for `to_dataframe`."""
return self.to_dataframe(index=index, sort_by=sort_by)
"""Alias for `to_dataframe`.
Supports converting creating Pandas DataFrames from the following
serializable data formats:
- List[BaseModel]
- List[Dict]
- List[List]
- List[str]
- List[int]
- List[float]
- Dict[str, Dict]
- Dict[str, List]
- Dict[str, BaseModel]
Other supported formats:
- str
Parameters
----------
index : Optional[str]
Column name to use as index.
sort_by : Optional[str]
Column name to sort by.
ascending: Optional[bool]
Sort by ascending for each column specified in `sort_by`.
Returns
-------
DataFrame
Pandas DataFrame.
"""
return self.to_dataframe(index=index, sort_by=sort_by, ascending=ascending)

def to_dataframe(
self, index: Optional[Union[str, None]] = "date", sort_by: Optional[str] = None
self,
index: Optional[Union[str, None]] = "date",
sort_by: Optional[str] = None,
ascending: Optional[bool] = None,
) -> "DataFrame":
"""Convert results field to pandas dataframe.
"""Convert results field to Pandas DataFrame.
Supports converting creating pandas DataFrames from the following
Supports converting creating Pandas DataFrames from the following
serializable data formats:
- List[BaseModel]
Expand All @@ -116,11 +153,13 @@ def to_dataframe(
Column name to use as index.
sort_by : Optional[str]
Column name to sort by.
ascending: Optional[bool]
Sort by ascending for each column specified in `sort_by`.
Returns
-------
DataFrame
Pandas dataframe.
Pandas DataFrame.
"""
# pylint: disable=import-outside-toplevel
from pandas import DataFrame, concat # noqa
Expand All @@ -142,8 +181,13 @@ def is_list_of_basemodel(items: Union[List[T], T]) -> bool:
df = None
sort_columns = True

# BaseModel
if isinstance(res, BaseModel):
df = DataFrame(res.model_dump(exclude_unset=True, exclude_none=True))
sort_columns = False

# List[Dict]
if isinstance(res, list) and len(res) == 1 and isinstance(res[0], dict):
elif isinstance(res, list) and len(res) == 1 and isinstance(res[0], dict):
r = res[0]
dict_of_df = {}

Expand Down Expand Up @@ -178,25 +222,29 @@ def is_list_of_basemodel(items: Union[List[T], T]) -> bool:
else:
try:
df = DataFrame(res) # type: ignore[call-overload]
# Set index, if any
if df is not None and index is not None and index in df.columns:
df.set_index(index, inplace=True)

except ValueError:
if isinstance(res, dict):
df = DataFrame([res])

if df is None:
raise OpenBBError("Unsupported data format.")

# Set index, if any
if index is not None and index in df.columns:
df.set_index(index, inplace=True)

# Drop columns that are all NaN, but don't rearrange columns
if sort_columns:
df.sort_index(axis=1, inplace=True)
df = df.dropna(axis=1, how="all")

# Sort by specified column
if sort_by:
df.sort_values(by=sort_by, inplace=True)
df.sort_values(
by=sort_by,
ascending=ascending if ascending is not None else True,
inplace=True,
)

except OpenBBError as e:
raise e
Expand All @@ -213,7 +261,7 @@ def is_list_of_basemodel(items: Union[List[T], T]) -> bool:

return df

def to_polars(self) -> "PolarsDataFrame":
def to_polars(self) -> "PolarsDataFrame": # type: ignore
"""Convert results field to polars dataframe."""
try:
from polars import from_pandas # type: ignore # pylint: disable=import-outside-toplevel
Expand All @@ -234,14 +282,13 @@ def to_dict(
"dict", "list", "series", "split", "tight", "records", "index"
] = "list",
) -> Union[Dict[Hashable, Any], List[Dict[Hashable, Any]]]:
"""Convert results field to a dictionary using any of pandas to_dict options.
"""Convert results field to a dictionary using any of Pandas `to_dict` options.
Parameters
----------
orient : Literal["dict", "list", "series", "split", "tight", "records", "index"]
Value to pass to `.to_dict()` method
Returns
-------
Union[Dict[Hashable, Any], List[Dict[Hashable, Any]]]
Expand Down Expand Up @@ -278,7 +325,7 @@ def to_llm(self) -> Union[Dict[Hashable, Any], List[Dict[Hashable, Any]]]:
date_unit="s",
)

return results
return results # type: ignore

def show(self, **kwargs: Any) -> None:
"""Display chart."""
Expand Down
Loading

0 comments on commit 29066b1

Please sign in to comment.