Hide sidebar menu

I create a login page with navigation menu in sidebar. Below is the code:

import streamlit as st

from streamlit_option_menu import option_menu


import login, signup, forgot_us, forgot_pass
# Set page configuration
st.set_page_config(page_title="Stock Trend App", page_icon="πŸ’Ή")


class MultiApp:

    def __init__(self):
        self.apps = []

    def add_app(self, title, func):

        self.apps.append({
            "title": title,
            "function": func
        })

    def run():
        # Navigation sidebar
        with st.sidebar:        
            app = option_menu(
                menu_title='Navigation',
                options=['Sign-In','Sign-Up','Forgot Username','Forgot Password'],
                icons=['person-circle','person-add','trophy-fill','chat-fill','info-circle-fill'],
                menu_icon='list',
                default_index=1,
                styles={
                    "container": {"padding": "5!important","background-color":'black'},
        "icon": {"color": "white", "font-size": "23px"}, 
        "nav-link": {"color":"white","font-size": "20px", "text-align": "left", "margin":"0px", "--hover-color": "blue"},
        "nav-link-selected": {"background-color": "#02ab21"},}
                
                )

        
        if app == "Sign-In":
            login.app()
        if app == "Sign-Up":
            signup.app()
        if app == "Forgot Username":
            forgot_us.app()
        if app == "Forgot Password":
            forgot_pass.app()
                    
             
    run()            
         

Below is the login.py script:

login.py

import streamlit as st
import streamlit_authenticator as stauth
import yaml
from yaml.loader import SafeLoader
import app



def app():

    with open('config.yaml') as file:
         config = yaml.load(file, Loader=SafeLoader)

    # Initialize Streamlit authenticator
    authenticator = stauth.Authenticate(
        config['credentials'],
        config['cookie']['name'],
        config['cookie']['key'],
        config['cookie']['expiry_days'],
        config['pre-authorized']
    )

    # Attempt to authenticate the user
    #name, authentication_status, username = authenticator.login('Login', 'main')


    authenticator.login()

    if st.session_state["authentication_status"]:
        
        authenticator.logout()
        st.write(f'Welcome *{st.session_state["name"]}*')
        # Execute the app.py
        import app
        app.main()
    elif st.session_state["authentication_status"] is False:
        st.error('Username/password is incorrect')
    elif st.session_state["authentication_status"] is None:
        st.warning('Please enter your username and password')

Below is the app.py script

app.py

def main():

    import numpy as np
    import pandas as pd
    import matplotlib.pyplot as plt
    from keras.models import load_model
    import streamlit as st
    import datetime
    import yfinance as yf
    import pickle
    import plotly.express as px
    import plotly.graph_objs as go
    from neuralprophet import NeuralProphet

    # Display a message with the bot icon
    st.title("Welcome to Stock Trend App πŸ’Ή")
    st.write("This is a simple Streamlit app to forecast the stock close price.")

    tickerSymbol = st.sidebar.text_input('Enter Stock Ticker')

    # Display a date input widget
    start_date = st.sidebar.date_input("Select Start Date", min_value=datetime.date(2000, 1, 1), max_value=datetime.date.today(), value=datetime.date(2012, 1, 1))
    end_date = st.sidebar.date_input("Select End Date", min_value=datetime.date(2000, 1, 1), max_value=datetime.date.today(), value=datetime.date.today())

    # Get number of days to forecast
    future_days = st.sidebar.number_input("Enter Days to Forecast", min_value=1, value=100, step=1)

    button = st.sidebar.button("Submit")

    if button:
        if not tickerSymbol:
            st.write("Please enter a valid Stock Ticker")
        elif start_date > end_date:
            st.write("Please enter valid dates. Start Date cannot exceed the End Date.")
        else:
            
                # Get data on this ticker
                tickerData = yf.Ticker(tickerSymbol)

                # Get the historical prices for this ticker
                df = tickerData.history(period='1d', start=start_date, end=end_date)
                df = df.reset_index()

                # Get company information
                company_name = tickerData.info['longName']
                st.sidebar.write(f"Company Name: {company_name}")

                # describing data
                st.subheader(f'Data from {start_date} to {end_date}')
                st.write(df.describe())

                ## Visualization
                st.subheader(f'{tickerSymbol.upper()} Close Price vs Time')
                st.line_chart(df, x="Date", y="Close", color="#0514C0")
                
                stock = df[['Date', 'Close']]

                # the NeuralProphet model expects the input DataFrame to have two columns: 'ds' (datetime) and 'y' (target variable).
                stock.columns = ['ds', 'y']

                # Train the model
                NP_model = NeuralProphet()
                NP_model.fit(stock)

                # Evaluate the model
                future = NP_model.make_future_dataframe(stock, periods=future_days)

                prediction = NP_model.predict(stock)
                forecast = NP_model.predict(future)
                

                # Plot the future forecast
                st.subheader(f'{future_days} Days Forecasting')
                fig3 = px.line(forecast, x="ds", y="yhat1", color_discrete_sequence=['red'])
                fig3.update_layout(xaxis_title='Day', yaxis_title='Close Price')
                # Plot!
                st.plotly_chart(fig3, use_container_width=True)
              
                st.subheader("Components of Forecast")
                fig_components = NP_model.plot_components(forecast)
                st.plotly_chart(fig_components)

                # Calculate the trend component of the forecast
                trend = forecast['trend'].values

                # Calculate the change in trend
                trend_change = np.diff(trend)

                # Check if the trend is positive, negative, or flat
                if all(change > 0 for change in trend_change):
                    trend_status = "Sold"
                elif all(change < 0 for change in trend_change):
                    trend_status = "Buy"
                else:
                    trend_status = "Hold"

                # Display a bot icon and the trend status to the right side of the icon
                st.write(f"<div style='display: flex; align-items: center;'>"
                         f"<p style='font-size: 48px;'>πŸ€–</p>"
                         f"<div style='margin-left: 20px; font-size: 24px; font-weight: bold;'>{trend_status}</div>"
                         f"</div>", unsafe_allow_html=True)
            

I want that when the login is successful, the Navigation sidebar should be disable. After successfully signed in, the web page should look like this:

But in my case, it look like this:

Maybe try setting a token on successful login and only draw the navigation section when that token value is not set? Or even apply a CSS display:none when the token value is set.

@shawngiese I find an another way to fixed it. Instead of use login.app(), I used st.switch_page('pages/login.py'). And I removed the app() function from login.py and the code inside the app() function are placed outside the function, i.e., write the same code in login.py without app() function.

1 Like

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.