[BugFix] Handle Dictionaries & Single Model Results Better In to_dataframe (#7099)

* handle dictionaries and single model results better in to_df

* fix tests
This commit is contained in:
Danglewood
2025-04-24 12:47:27 -07:00
committed by GitHub
parent b991baa861
commit 50f2e06a8e
3 changed files with 24 additions and 8 deletions

View File

@@ -161,7 +161,7 @@ class OBBject(Tagged, Generic[T]):
Pandas DataFrame.
"""
# pylint: disable=import-outside-toplevel
from pandas import DataFrame, concat # noqa
from pandas import DataFrame, Series, concat # noqa
from openbb_core.app.utils import basemodel_to_df # noqa
def is_list_of_basemodel(items: Union[List[T], T]) -> bool:
@@ -182,7 +182,21 @@ class OBBject(Tagged, Generic[T]):
# BaseModel
if isinstance(res, BaseModel):
df = DataFrame(res.model_dump(exclude_unset=True, exclude_none=True))
res_dict = res.model_dump(exclude_unset=True, exclude_none=True)
series = Series(res_dict, name=res.__class__.__name__)
df = series.to_frame().reset_index()
sort_columns = False
# Dict[str, Any]
elif isinstance(res, dict):
try:
df = DataFrame.from_dict(res).T
except ValueError:
try:
df = DataFrame.from_dict(res, orient="index")
except ValueError:
series = Series(res, name="values")
df = series.to_frame().reset_index()
sort_columns = False
# List[Dict]

View File

@@ -129,7 +129,7 @@ class MockDataFrame(Data):
"3": {"x": 3, "y": 1},
"4": {"x": 4, "y": 6},
},
pd.DataFrame(
pd.DataFrame.from_dict(
{
"0": {"x": 0, "y": 2},
"1": {"x": 1, "y": 3},
@@ -137,13 +137,15 @@ class MockDataFrame(Data):
"3": {"x": 3, "y": 1},
"4": {"x": 4, "y": 6},
},
orient="index",
),
),
# Test case 8: Dict of Lists
(
{"0": [0, 2], "1": [1, 3], "2": [2, 0], "3": [3, 1], "4": [4, 6]},
pd.DataFrame(
{"0": [0, 2], "1": [1, 3], "2": [2, 0], "3": [3, 1], "4": [4, 6]}
pd.DataFrame.from_dict(
{"0": [0, 2], "1": [1, 3], "2": [2, 0], "3": [3, 1], "4": [4, 6]},
orient="index",
),
),
# Test case 9: List of dict of data
@@ -305,7 +307,7 @@ def test_to_df_daylight_savings(results):
# Test case 3: Dict of lists
(
{"0": [0, 2], "1": [1, 3], "2": [2, 0], "3": [3, 1], "4": [4, 6]},
{"0": [0, 2], "1": [1, 3], "2": [2, 0], "3": [3, 1], "4": [4, 6]},
{0: [0, 1, 2, 3, 4], 1: [2, 3, 0, 1, 6]},
),
# Test case 4: No results
([], OpenBBError("Results not found.")),
@@ -335,7 +337,7 @@ def test_to_df_daylight_savings(results):
"3": {"x": 3, "y": 1},
"4": {"x": 4, "y": 6},
},
{"x": [0, 1, 2, 3, 4], "y": [2, 3, 0, 1, 6]},
{"0": [0, 2], "1": [1, 3], "2": [2, 0], "3": [3, 1], "4": [4, 6]},
),
],
)

View File

@@ -38,7 +38,7 @@ def z_score_standardization(data: "Series") -> "Series":
def calculate_returns(data: "Series") -> "Series":
"""Calculate the returns of a column."""
return ((1 + data.pct_change().dropna()).cumprod() - 1) * 100
return ((1 + data.pct_change(fill_method=None).fillna(0)).cumprod() - 1) * 100
def should_share_axis(