Hotfix/ Improve setting/loading Streamlit session state variables (#4905)

* improve setting/loading streamlit session state variables

* Update streamlit_helpers.py

* fix margins

* fix hex color markdown showing on forecast tables

---------

Co-authored-by: James Maslek <jmaslek11@gmail.com>
This commit is contained in:
teh_coderer
2023-04-27 11:24:22 -05:00
committed by GitHub
parent 18204202ac
commit 64e37bf0a2
10 changed files with 73 additions and 27 deletions

View File

@@ -27,6 +27,7 @@ st.set_page_config(
initial_sidebar_state="expanded",
)
st_helpers.set_css()
st_helpers.set_current_page("Forecasting")
EXPLAINABILITY_FIGURE: Union[OpenBBFigure, None] = None
@@ -89,10 +90,10 @@ class Handler:
st_helpers.load_state("last_tickers", "")
st_helpers.load_state("last_intervals", "1d")
st_helpers.load_state("df", pd.DataFrame())
default_opts = {
self.default_opts = {
key: [] for key in ["target_widget", "column_widget", "past_covs_widget"]
}
st_helpers.load_widget_options(default_opts, "Forecasting")
st_helpers.load_widget_options(self.default_opts)
self.feature_model = None
self.feature_target = None
@@ -177,7 +178,7 @@ class Handler:
fig.update_layout(
title=dict(x=0.5, xanchor="center", yanchor="top", y=0.99),
showlegend=True,
margin=dict(t=40),
margin=dict(t=40, l=30),
height=500,
legend=dict(
bgcolor="rgba(0,0,0,0.5)",
@@ -313,7 +314,9 @@ class Handler:
with col_order[1]:
target_widget = st.selectbox(
"Target",
options=st.session_state["widget_options"]["target_widget"],
options=st_helpers.get_widget_options(
self.default_opts, "target_widget"
),
)
with col_order[2]:
@@ -328,7 +331,9 @@ class Handler:
with col_order[0]:
past_covs_widget = st.multiselect(
"Past Covariates",
options=st.session_state["widget_options"]["past_covs_widget"],
options=st_helpers.get_widget_options(
self.default_opts, "past_covs_widget"
),
disabled=not enable_past_covs,
label_visibility="hidden" if not enable_past_covs else "visible",
)

View File

@@ -15,6 +15,7 @@ st.set_page_config(
page_title="Chains",
initial_sidebar_state="expanded",
)
st_helpers.set_current_page("Chains")
st_helpers.set_css()
st.sidebar.markdown(

View File

@@ -16,6 +16,8 @@ st.set_page_config(
page_title="Correlation",
initial_sidebar_state="expanded",
)
st_helpers.set_current_page("Correlation")
st_helpers.set_css()
st.sidebar.markdown(
"<h2 style='text-align: center;'>Correlation Analysis</h2>",

View File

@@ -21,6 +21,7 @@ st.set_page_config(
page_title="Futures",
initial_sidebar_state="expanded",
)
st_helpers.set_current_page("Futures")
st_helpers.set_css()
df = pd.read_csv(MISCELLANEOUS_DIRECTORY / "futures" / "futures.csv")
@@ -130,12 +131,12 @@ class Chart:
self.tickers = st_helpers.load_state("tickers", {})
self.last_ticker = st_helpers.load_state("last_ticker", TICKERS[0])
self.last_exchange = st_helpers.load_state("last_exchange", EXCHANGES[0])
default_opts = {
self.default_opts = {
"exch_widget": EXCHANGES,
"tickers_widget": TICKERS,
"cat_widget": CATEGORIES,
}
st_helpers.load_widget_options(default_opts, "Futures")
st_helpers.load_widget_options(self.default_opts)
def create_stock(self, chart_type, contracts, ticker):
if not ticker:
@@ -216,25 +217,25 @@ class Chart:
st.sidebar.multiselect(
"Category",
st.session_state["widget_options"]["cat_widget"],
st_helpers.get_widget_options(self.default_opts, "cat_widget"),
on_change=self.on_change,
key="cat_widget",
)
st.sidebar.multiselect(
"Exchange",
st.session_state["widget_options"]["exch_widget"],
st_helpers.get_widget_options(self.default_opts, "exch_widget"),
key="exch_widget",
on_change=self.on_change,
)
ticker_widget = st.sidebar.selectbox(
"Ticker",
st.session_state["widget_options"]["tickers_widget"],
st_helpers.get_widget_options(self.default_opts, "tickers_widget"),
key="tickers_widget",
index=0,
)
chart_widget = st.sidebar.multiselect(
"Chart Type", chart_type, key="chart_widget", default=chart_type[0]
chart_widget = st.sidebar.selectbox(
"Chart Type", chart_type, key="chart_widget", index=0
)
contracts_widget = st.sidebar.slider(
"Contracts", 1, 24, 6, key="contracts_widget"

View File

@@ -25,11 +25,13 @@ set_system_variable("LOGGING_SUPPRESS", True)
pd.options.plotting.backend = "plotly"
st.set_page_config(
layout="wide",
page_title="Indicators",
initial_sidebar_state="expanded",
)
st_helpers.set_current_page("Indicators")
st_helpers.set_css()
logger = st.empty()

View File

@@ -49,6 +49,7 @@ st.markdown(middle_html, unsafe_allow_html=True)
MAIN_LOOP: asyncio.AbstractEventLoop = None # type: ignore
st_helpers.set_current_page("Short Data")
st_helpers.set_css()
@@ -133,7 +134,7 @@ class FinraShortData:
)
fig.update_layout(
title=f"Top {self.count_slider} Short Volume in Last {self.days_slider} Days",
margin=dict(l=5),
margin=dict(l=30),
xaxis_title="Volume",
yaxis_title="Ticker",
barmode="stack",
@@ -171,7 +172,7 @@ class FinraShortData:
)
fig2.update_layout(
title=f"Stock Volume and Short Volume for {self.stock_input.upper()}",
margin=dict(l=5),
margin=dict(l=30),
xaxis_title="Date",
yaxis_title="Volume",
)

View File

@@ -24,6 +24,7 @@ st.set_page_config(
page_title="Stocks",
initial_sidebar_state="expanded",
)
st_helpers.set_current_page("Stocks")
logger = st.empty()
page_title = st.empty()

View File

@@ -25,6 +25,16 @@ STOCKS_CLEAN_DATA = {
}
def update_current_page() -> None:
"""Updates the current page to the set page"""
st.session_state["set_page"] = st.session_state["current_page"]
def set_current_page(page: str) -> None:
"""Sets the current page to the given page"""
st.session_state["current_page"] = page
def get_calc(item, df, rolling) -> pd.DataFrame:
return STOCKS_VIEWS[item](df, rolling)
@@ -67,20 +77,36 @@ def has_parameter(func: Callable[..., Any], parameter: str) -> bool:
def load_state(name: str, default: Any) -> Any:
if name not in st.session_state:
st.session_state[name] = default
elif st.session_state.get("current_page", None) != st.session_state.get(
"set_page", None
):
update_current_page()
st.session_state[name] = default
return st.session_state[name]
def load_widget_options(default: Any, page: str) -> Any:
def load_widget_options(default: Any) -> Any:
name = "widget_options"
if name not in st.session_state:
st.session_state[name] = default
elif st.session_state[name].get("page", "") != page:
elif st.session_state.get("current_page", None) != st.session_state.get(
"set_page", None
):
update_current_page()
st.session_state[name] = default
st.session_state[name]["page"] = page
return st.session_state[name]
def get_widget_options(default: dict, key: str) -> Any:
options = load_widget_options(default)
if key not in options:
options[key] = default.get(key, None)
return options[key]
def save_state(name: str, value: Any):
st.session_state[name] = value

View File

@@ -10,6 +10,7 @@ import pandas as pd
from darts import TimeSeries
from statsforecast.core import StatsForecast
from openbb_terminal.core.session.current_user import get_current_user
from openbb_terminal.decorators import log_start_end
from openbb_terminal.forecast import helpers
from openbb_terminal.rich_config import USE_COLOR, console
@@ -21,10 +22,14 @@ logger = logging.getLogger(__name__)
# pylint: disable=E1123,E1137
def precision_format(best_model: str, index: str, val: float) -> str:
if index == best_model and USE_COLOR:
def precision_format(best_model: str, index: str, val: float) -> Union[str, float]:
if (
index == best_model
and USE_COLOR
and not get_current_user().preferences.USE_INTERACTIVE_DF
):
return f"[#00AAFF]{val:.2f}% [/#00AAFF]"
return f"{val:.2f}%"
return val
@log_start_end(log=logger)
@@ -167,6 +172,7 @@ def get_autoselect_data(
helpers.mean_absolute_percentage_error(y_true, historical_fcast[model].values)
for model in model_names
]
precision: pd.DataFrame = pd.DataFrame(
{"precision": precision_per_model}, index=model_names
)
@@ -181,12 +187,18 @@ def get_autoselect_data(
for index, val in precision["precision"].iteritems()
]
console.print("\n")
title = (
f"[#00AAFF]{best_model}[/#00AAFF]"
if not get_current_user().preferences.USE_INTERACTIVE_DF
else best_model
)
helpers.print_rich_table(
precision,
show_index=True,
index_name="Model",
headers=["MAPE"],
title=f"Performance per model.\nBest model: [#00AAFF]{best_model}[/#00AAFF]",
title=f"Performance per model.\nBest model: {title}",
)
# transform outputs to make them compatible with

View File

@@ -335,11 +335,6 @@ def prepare_scale_train_valid_test(
)
def lambda_price_prediction_color(val: float) -> str:
"""Set prediction to be a colored string. This was changed to always shows blue"""
return f"[#00AAFF]{val:.2f} [/#00AAFF]"
def print_pretty_prediction(df_pred: pd.DataFrame, last_price: float):
"""Print predictions"""
@@ -348,7 +343,7 @@ def print_pretty_prediction(df_pred: pd.DataFrame, last_price: float):
df_pred.columns = ["pred"]
if not get_current_user().preferences.USE_INTERACTIVE_DF:
df_pred["pred"] = df_pred["pred"].apply(
lambda x: lambda_price_prediction_color(x)
lambda x: f"[#00AAFF]{x:.2f} [/#00AAFF]"
)
if check_dates(df_pred.index.to_series()):
df_pred.index = df_pred.index.date