Esempio n. 1
0
import numpy as np
import datetime as dt
from datetime import datetime, date, time
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.ensemble import RandomForestRegressor

# In[2]:

st.title('Suyash App')
if st.checkbox("Show/Hide"):
    st.text("Coding With Mafia")

st.write("Covid-19 Cases Prediction")
predictdate = st.date_input('Input Date')
predictdate = pd.to_datetime(predictdate)
predictdate = predictdate.toordinal()

# In[3]:

df = pd.read_csv('state_wise_daily.csv')

# In[4]:

df.info()

# In[5]:

df.head()
Esempio n. 2
0
        size=alt.condition(~highlight, alt.value(1), alt.value(3))
    )
    return points+lines

usdata,usdata_diff = uscoviddata.load_data()

st.title("Hospitalizations by US state per 100,000 inhabitants")
st.markdown("""
Sources: [covidtracking.com](https://covidtracking.com/api), [census.gov](https://www.census.gov/data/datasets/time-series/demo/popest/2010s-state-total.html)

Hospitalization data is more normalized than case data because testing rates (and thus known cases) varies too much across states. 
While less of a leading indicator, the 7 day change gives a reasonable early sign of trouble.
""")

# Magic streamlit function that renders a date picker and assigns the picked value to picked_date
picked_date = st.date_input("Date", value=usdata_diff['date'].max()).strftime('%Y-%m-%d')

# 7 day change bar chart
st.subheader('Change last 7 days')
# The reason why picked_date was converted to string above is otherwise the data
# selection would not work in this line below.
st.write(alt.Chart(usdata_diff[usdata_diff['date'] == picked_date]).mark_bar().encode(
    y=alt.Y('state', sort='-x'),
    x=alt.X('hospitalizedPer100k7daychange:Q', axis=alt.Axis(orient='top')),
    tooltip=[alt.Tooltip("hospitalizedPer100k7daychange:Q", title="7 day change", format=',.0d')]
    ).properties(
        width=800
    )
)

st.subheader('Total')
Esempio n. 3
0
# Variables

v1 = st.radio("Variable 1", v1_vals)
v2 = st.selectbox("Variable 2", v2_vals)
v3 = st.multiselect("Variable 3", v3_vals)

if len(v3) == 0:
    st.error(f'Nothing is selected')

v4 = st.slider("Variable 4", v4_range_start, v4_range_end)

v5 = st.text_input("Variable 5")
v6 = st.text_area("Variable 6")

v7 = st.date_input("Variable 7", datetime.now())
v8 = st.time_input("Variable 8", time())


if st.button("Submit and Predict"):
    values_list = [v1, v2, v3, v4, v5, v6, v7, v8]
    X = []
    for element in values_list:
        if type(element) == list:
            for value in element:
                X.append(value)
        else:
            X.append(element)

    if '' in X:
        st.error(f"Empty values submitted")
Esempio n. 4
0
    def show_search(self):
        with st.beta_container():
            self.current_option = st.selectbox("Select table to search: ",
                                               self.tables)
            col1, col2 = st.beta_columns(2)

            if self.current_option == "Customer":
                with col1:
                    st.info("""
                        Input name to search for customer in the database.
                        If there is no input, all entries be shown.\n
                        *Limit to 1000 rows.*
                    """)
                    customer_name = ''
                    choice = st.radio("Search by id/name: ",
                                      options=['id', 'name'])
                    if choice == "id":
                        customer_id = st.number_input(
                            "Input customer id: ",
                            step=1,
                            value=0,
                            min_value=0,
                            max_value=Customer.max_id(self.connection))
                    elif choice == "name":
                        customer_name = st.text_input(
                            "Input customer name (* to search all): ",
                            value=customer_name)
                    columns = st.multiselect("Select columns to show: ",
                                             self.customer_columns)

                if not columns:
                    columns = self.customer_columns
                if choice == "id":
                    data = Customer.search_by_id(self.connection, customer_id,
                                                 columns)
                elif choice == "name":
                    data = Customer.search_by_name(self.connection,
                                                   customer_name, columns)
                df = pd.DataFrame.from_records(data, columns=columns)[:1000]

                with col2:
                    with st.beta_expander(
                            "Show customer with selected column(s)",
                            expanded=True):
                        st.dataframe(df)

            elif self.current_option == "ItemCategory":
                with col1:
                    st.info("""
                        Input name to search for category in the database.
                        If there is no input, all entries be shown.\n
                        *Limit to 1000 rows.*
                    """)
                    category_name = ''
                    choice = st.radio("Search by id/name: ",
                                      options=['id', 'name'])
                    if choice == "id":
                        category_id = st.number_input(
                            "Input category id: ",
                            step=1,
                            value=0,
                            min_value=0,
                            max_value=ItemCategory.max_id(self.connection))
                    elif choice == "name":
                        category_name = st.text_input(
                            "Input category name (* to search all): ",
                            value=category_name)
                    columns = st.multiselect("Select columns to search: ",
                                             self.category_columns)

                if not columns:
                    columns = self.category_columns
                if choice == "id":
                    data = ItemCategory.search_by_id(self.connection,
                                                     category_id, columns)
                elif choice == "name":
                    data = ItemCategory.search_by_name(self.connection,
                                                       category_name, columns)
                df = pd.DataFrame.from_records(data, columns=columns)[:1000]

                with col2:
                    with st.beta_expander(
                            "Show category with selected column(s)",
                            expanded=True):
                        st.dataframe(df)

            elif self.current_option == "Buyer":
                pass

            elif self.current_option == "Shop":
                with col1:
                    st.info("""
                        Input name to search for shop in the database.
                        If there is no input, all entries be shown.\n
                        *Limit to 1000 rows.*
                    """)
                    shop_name = ''
                    choice = st.radio("Search by id/name: ",
                                      options=['id', 'name'])
                    if choice == "id":
                        shop_id = st.number_input("Input shop id: ",
                                                  step=1,
                                                  value=0,
                                                  min_value=0,
                                                  max_value=Shop.max_id(
                                                      self.connection))
                    elif choice == "name":
                        shop_name = st.text_input(
                            "Input shop name (* to search all): ",
                            value=shop_name)
                    columns = st.multiselect("Select columns to show: ",
                                             self.shop_columns)

                if not columns:
                    columns = self.shop_columns
                if choice == "id":
                    data = Shop.search_by_id(self.connection, shop_id, columns)
                elif choice == "name":
                    data = Shop.search_by_name(self.connection, shop_name,
                                               columns)
                df = pd.DataFrame.from_records(data, columns=columns)[:1000]

                with col2:
                    with st.beta_expander("Show shop with selected column(s)",
                                          expanded=True):
                        st.dataframe(df)

            elif self.current_option == "Imports":
                with col1:
                    st.info("""
                        Input name to search for import record in the database.
                        If there is no input, all entries be shown.\n
                        *Limit to 1000 rows.*
                    """)
                    choice = st.radio(
                        "Search by id/date/shop: ",
                        options=['id', 'date', 'shop', 'get all records'])
                    if choice == "id":
                        import_id = st.number_input("Input import id: ",
                                                    step=1,
                                                    value=0,
                                                    min_value=0,
                                                    max_value=Imports.max_id(
                                                        self.connection))
                    elif choice == "date":
                        import_date = datetime.fromordinal(
                            st.date_input(
                                "Input date: ",
                                min_value=Imports.get_min_max_date(
                                    self.connection)[0],
                                max_value=Imports.get_min_max_date(
                                    self.connection)[1],
                                value=Imports.get_min_max_date(
                                    self.connection)[0],
                            ).toordinal()).strftime('%Y-%m-%d')
                    elif choice == "shop":
                        try:
                            shop_id = st.selectbox(
                                "Input shop id: ",
                                options=[
                                    i for i in range(
                                        Shop.max_id(self.connection))
                                ])
                        except TypeError:
                            shop_id = None
                    columns = st.multiselect("Select columns to show: ",
                                             self.imports_columns)

                if not columns:
                    columns = self.imports_columns
                if choice == "id":
                    data = Imports.search_by_id(self.connection, import_id,
                                                columns)
                elif choice == "date":
                    data = Imports.search_by_date(self.connection, import_date,
                                                  columns)
                elif choice == "shop":
                    data = Imports.search_by_shop_id(self.connection, shop_id,
                                                     columns)
                elif choice == "get all records":
                    data = Imports.search_all(self.connection, columns)
                df = pd.DataFrame.from_records(data, columns=columns)[:1000]

                with col2:
                    with st.beta_expander(
                            "Show import with selected column(s)",
                            expanded=True):
                        st.dataframe(df)
                    with st.beta_expander("Search for import details"):
                        selected_id = int(
                            st.selectbox(
                                "Choose which import record to search: ",
                                options=df["importID"].unique().tolist()))
                        data = ImportDetail.search_by_import_id(
                            self.connection, selected_id)
                        st.dataframe(
                            pd.DataFrame.from_records(
                                data,
                                columns=ImportDetail.columns_names(
                                    self.connection)))

            elif self.current_option == "Transactions":
                with col1:
                    st.info("""
                        Input name to search for transaction record in the database.
                        If there is no input, all entries be shown.\n
                        *Limit to 1000 rows.*
                    """)
                    choice = st.radio(
                        "Search by id/date/status/customer/shop: ",
                        options=[
                            'id', 'date', 'status', 'customer', 'shop',
                            'get all records'
                        ])
                    if choice == "id":
                        transaction_id = st.number_input(
                            "Input transaction id: ",
                            step=1,
                            value=0,
                            min_value=0,
                            max_value=Transactions.max_id(self.connection))
                    elif choice == "date":
                        transaction_date = datetime.fromordinal(
                            st.date_input(
                                "Input date: ",
                                min_value=Transactions.get_min_max_date(
                                    self.connection)[0],
                                max_value=Transactions.get_min_max_date(
                                    self.connection)[1],
                                value=Transactions.get_min_max_date(
                                    self.connection)[0],
                            ).toordinal()).strftime('%Y-%m-%d')
                    elif choice == "status":
                        transaction_status = st.radio(
                            "Transaction status: ",
                            options=['Pending', 'Completed']).upper()
                    elif choice == "customer":
                        customer_id = st.number_input(
                            "Input customer id: ",
                            step=1,
                            value=0,
                            min_value=0,
                            max_value=Customer.max_id(self.connection))
                    elif choice == "shop":
                        try:
                            shop_id = st.selectbox(
                                "Input shop id: ",
                                options=[
                                    i for i in range(
                                        Shop.max_id(self.connection))
                                ])
                        except TypeError:
                            shop_id = None
                    columns = st.multiselect("Select columns to show: ",
                                             self.transactions_columns)
                if not columns:
                    columns = self.transactions_columns
                if choice == "id":
                    data = Transactions.search_by_id(self.connection,
                                                     transaction_id, columns)
                elif choice == "date":
                    data = Transactions.search_by_date(self.connection,
                                                       transaction_date,
                                                       columns)
                elif choice == "status":
                    data = Transactions.search_by_status(
                        self.connection, transaction_status, columns)
                elif choice == "customer":
                    data = Transactions.search_by_customer_id(
                        self.connection, customer_id, columns)
                elif choice == "shop":
                    data = Transactions.search_by_shop_id(
                        self.connection, shop_id, columns)
                elif choice == "get all records":
                    data = Transactions.search_all(self.connection, columns)
                df = pd.DataFrame.from_records(data, columns=columns)[:1000]

                with col2:
                    with st.beta_expander(
                            "Show transaction with selected column(s)",
                            expanded=True):
                        st.dataframe(df)
                    with st.beta_expander("Search for transaction details"):
                        try:
                            selected_id = int(
                                st.selectbox(
                                    "Choose which transaction record to search: ",
                                    options=df["transactionID"].unique(
                                    ).tolist()))
                        except TypeError:
                            selected_id = None
                        data = TransactionDetail.search_by_transaction_id(
                            self.connection, selected_id)
                        st.dataframe(
                            pd.DataFrame.from_records(
                                data,
                                columns=TransactionDetail.columns_names(
                                    self.connection)))

            elif self.current_option == "Item":
                with col1:
                    st.info("""
                        Input name to search for item in the database.
                        If there is no input, all entries be shown.\n
                        *Limit to 1000 rows.*
                    """)
                    item_name = ''
                    choice = st.radio(
                        "Search by id/name/category/shop: ",
                        options=['id', 'name', 'category', 'shop'])
                    if choice == "id":
                        item_id = st.number_input("Input item id: ",
                                                  step=1,
                                                  value=0,
                                                  min_value=0,
                                                  max_value=Item.max_id(
                                                      self.connection))
                    elif choice == "name":
                        item_name = st.text_input(
                            "Input item name (* to search all): ",
                            value=item_name)
                    elif choice == "category":
                        category_id = st.number_input(
                            "Input category id: ",
                            step=1,
                            value=0,
                            min_value=0,
                            max_value=ItemCategory.max_id(self.connection))
                    elif choice == "shop":
                        shop_id = st.number_input("Input shop id: ",
                                                  step=1,
                                                  value=0,
                                                  min_value=0,
                                                  max_value=Shop.max_id(
                                                      self.connection))
                    columns = st.multiselect("Select columns to show: ",
                                             self.item_columns)

                if not columns:
                    columns = self.item_columns
                if choice == "id":
                    data = Item.search_by_id(self.connection, item_id, columns)
                elif choice == "name":
                    data = Item.search_by_name(self.connection, item_name,
                                               columns)
                elif choice == "category":
                    data = Item.search_by_category_id(self.connection,
                                                      category_id, columns)
                elif choice == "shop":
                    data = Item.search_by_shop_id(self.connection, shop_id,
                                                  columns)
                df = pd.DataFrame.from_records(data, columns=columns)[:1000]

                with col2:
                    with st.beta_expander("Show item with selected column(s)",
                                          expanded=True):
                        st.dataframe(df)
Esempio n. 5
0
import streamlit as st
import yfinance as yf
import pandas as pd

st.title("Asset performance - Dashboard")

tickers = ('TSLA', 'AAPL', 'MSFT', 'BTC-USD', 'ETH-USD')

dropdown = st.multiselect('Pick your investment assets', tickers)

start = st.date_input('Start', value=pd.to_datetime('2021-01-01'))
end = st.date_input('End', value=pd.to_datetime('today'))


def relativeret(df):
    rel = df.pct_change()
    cumret = (1 + rel).cumprod() - 1
    cumret = cumret.fillna(0)
    return cumret


if len(dropdown) > 0:
    df = relativeret(yf.download(dropdown, start, end)['Adj Close'])
    st.header('Returns of {}'.format(dropdown))
    st.line_chart(df)
Esempio n. 6
0
first_name = st.text_input("이름을 입력하세요.", "Type Here ...")
if st.button("Submit", key='first_name'):
    result = first_name.title()
    st.success(result)

# Text Area
message = st.text_area("메세지를 입력하세요.", "Type Here ...")
if st.button("Submit", key='message'):
    result = message.title()
    st.success(result)

st.markdown("* * *")  # 구분선 생성

## Date Input
import datetime
today = st.date_input("날짜를 선택하세요.", datetime.datetime.now())
the_time = st.time_input("시간을 입력하세요.", datetime.time())

st.markdown("* * *")  # 구분선 생성

# Display Raw Code - one line
st.subheader("Display one-line code")
st.code("import numpy as np")

# Display Raw Code - snippet 두 줄 이상
st.subheader("Display code snippet")
with st.echo():
    # 여기서부터 아래의 코드를 출력합니다.
    import pandas as pd
    df = pd.DataFrame()
    df.head()
Esempio n. 7
0
st.title("Liu Algo Trading Framework")
st.markdown("## **Back-testing & Analysis tools**")

app = st.sidebar.selectbox("select app", ("back-test", "analyzer"))

new_bid: str = ""
est = pytz.timezone("America/New_York")

if app == "back-test":
    env = st.sidebar.selectbox(
        "Select environment", ("PAPER", "BACKTEST", "PROD")
    )
    new_bid = ""
    st.text("Back-testing a past trading day, or a specific batch-id.")

    day_to_analyze = st.date_input("Pick day to analyze", value=date.today())

    selection = st.sidebar.radio(
        "Select back-testing mode",
        (
            "back-test a specific batch",
            # "back-test against the whole day",
        ),
    )

    async def back_test():
        uploaded_file: UploadedFile = st.file_uploader(
            label="Select tradeplan file", type=["toml", "TOML"]
        )
        if uploaded_file:
            byte_str = uploaded_file.read()
Esempio n. 8
0
def run():
    symbols = st.sidebar.text_input(
        "Enter symbol or list of symbols (comma separated)", value="aapl")
    symbols = [x.strip() for x in symbols.split(',')]
    yq = Ticker(symbols)

    page = st.sidebar.selectbox("Choose a page", [
        "Homepage", "Dictionaries", "Dataframes", "Option Chain",
        "Historical Pricing", "Mutual Funds"
    ])

    st.title("Welcome to YahooQuery")

    if page == "Homepage":
        st.write("""
            Enter a symbol or list of symbols and select a page from the left
            to the data available to you.""")
        st.markdown(
            "[View code here](https://github.com/dpguthrie/yahooquery)")
    elif page == "Dictionaries":
        st.header("Dictionaries")
        st.write("""
            Some data is returned as python dictionaries; use the dropdown
            below to view some of the data available to you through yahooquery.
        """)
        d_endpoint = st.selectbox("Select Dictionary Endpoint",
                                  options=list(AVAILABLE_DICTIONARIES.keys()),
                                  format_func=format_func_dicts)
        with st.spinner():
            data = get_data(yq, d_endpoint)
            st.json(data)
    elif page == "Dataframes":
        st.header("Dataframes")
        st.write("""
            Some data is returned as pandas DataFrames; use the dropdown
            below to view some of the data available to you through yahooquery.
        """)
        df_endpoint = st.selectbox("Select DataFrame Endpoint",
                                   options=list(AVAILABLE_DATAFRAMES.keys()),
                                   format_func=format_func_df)
        with st.spinner():
            data = get_data(yq, df_endpoint)
            st.write(data)
    elif page == "Option Chain":
        st.header("Option Chain")
        st.write("""
            Yahooquery also gives you the ability to view option chain data
            for all expiration dates for a given symbol(s)
        """)
        with st.spinner():
            data = get_data(yq, 'option_chain')
            st.write(data)
    elif page == "Historical Pricing":
        st.header("Historical Pricing")
        st.write("""
            Retrieve historical pricing data for a given symbol(s)
        """)
        st.markdown("""
            1. Select a period **or** enter start and end dates.  **This
               application defaults both start and end dates at today's
               date.  If you don't change them, None will be used for both.**
            2. Select interval (**note:  some intervals are not available for
                certain lengths of time**)
        """)
        period = st.selectbox("Select Period",
                              options=Ticker._PERIODS,
                              index=5)
        st.markdown("**OR**")
        start = st.date_input("Select Start Date")
        end = st.date_input("Select End Date")
        st.markdown("**THEN**")
        interval = st.selectbox("Select Interval",
                                options=Ticker._INTERVALS,
                                index=8)
        print(start == datetime.datetime.today().date())

        with st.spinner("Retrieving data..."):
            today = datetime.datetime.today().date()
            if start == today:
                start = None
            if end == today:
                end = None
            df = yq.history(period=period,
                            interval=interval,
                            start=start,
                            end=end)

        if isinstance(df, dict):
            st.write(df)
        else:
            if len(symbols) > 1:
                chart = (alt.Chart(df.reset_index()).mark_line().encode(
                    alt.Y('close:Q', scale=alt.Scale(zero=False)),
                    x='dates',
                    color='symbol'))
            else:
                chart = (alt.Chart(df.reset_index()).mark_line().encode(
                    alt.Y('close:Q', scale=alt.Scale(zero=False)),
                    x='dates:T',
                ))
            st.write("", "", chart)
            st.dataframe(df)
    else:
        st.header("Mutual Funds")
        st.write("""
            There's additional data available to mutual funds, etfs, etc.
            Use the dropdown below to view additional data available to these
            security types.
        """)
        fund_endpoint = st.selectbox("Select Fund Endpoint",
                                     options=list(FUND_SPECIFIC.keys()),
                                     format_func=format_fund)
        with st.spinner():
            data = get_data(yq, fund_endpoint)
            st.write(data)
def page(main_list, name):

    ###############################################################################

    full_info_ss = SessionState.get(new_df=0)
    full_info_ss.new_df = pd.read_csv('patients/' + name.replace(' ', '') +
                                      '.csv',
                                      header=0,
                                      index_col=False)

    ###############################################################################

    # Início

    expander_inicio_UC = st.beta_expander('Início', expanded=False)

    with expander_inicio_UC:
        select_inicio = st.date_input(
            'Qual foi a data em que começou a urticária?', date.today())
        for i in range(full_info_ss.new_df.shape[0], -1, -1):
            if full_info_ss.new_df.shape[0] == 0:
                break
            elif pd.isnull(full_info_ss.new_df.iloc[i - 1]['Início_UC']):
                continue
            else:
                current_time = full_info_ss.new_df.iloc[i - 1]['Início_UC']
                current_time = str(current_time)
                #st.text(current_time)
                current_time = date(int(current_time[0:4]),
                                    int(current_time[6:7]),
                                    int(current_time[9:10]))
                today = date.today()
                monday1 = (today - timedelta(days=today.weekday()))
                monday2 = (current_time -
                           timedelta(days=current_time.weekday()))
                weeks = (monday1 - monday2).days / 7
                st.text('Começou o tratamento há ' + str(weeks) + ' semanas.')
                break

    df_inicio_UC = pd.DataFrame({'Início_UC': [select_inicio]})

    ###############################################################################

    # Características e Fatores Prognósticos

    expander_caract = st.beta_expander(
        'Características e Fatores Prognósticos', expanded=False)

    with expander_caract:

        caract = writereadlists('características_UC', 'read', '')

        select_caract = st.multiselect(
            'Quais as características e fatores prognóstico mais relevantes?',
            caract)

        for i in range(full_info_ss.new_df.shape[0], -1, -1):
            if full_info_ss.new_df.shape[0] == 0:
                break
            elif full_info_ss.new_df.iloc[i - 1]['Características_UC'] == '[]':
                continue
            else:
                last_date = full_info_ss.new_df.iloc[i - 1]['Data']
                last_caract = full_info_ss.new_df.iloc[i -
                                                       1]['Características_UC']
                st.text(last_date + ' - ' + last_caract[1:-1])
                break

        text_caract = st.text_area('Outros')

    df_caract = pd.DataFrame({'Características_UC': [select_caract]})

    ###############################################################################

    # Controlo

    expander_contr_UC = st.beta_expander('Controlo', expanded=False)

    with expander_contr_UC:

        controlo = writereadlists('controlo_UC', 'read', '')

        select_contr = st.multiselect('Controlo', controlo)

        for i in range(full_info_ss.new_df.shape[0], -1, -1):
            if full_info_ss.new_df.shape[0] == 0:
                break
            elif full_info_ss.new_df.iloc[i - 1]['Controlo_UC'] == '[]':
                continue
            else:
                last_date = full_info_ss.new_df.iloc[i - 1]['Data']
                last_contr = full_info_ss.new_df.iloc[i - 1]['Controlo_UC']
                st.text(last_date + ' - ' + last_contr[1:-1])
                break

    df_controlo = pd.DataFrame({'Controlo_UC': [select_contr]})

    ###############################################################################
    # Save new info into csv file

    # O IDEAL SERÁ UMA CONCAT FINAL NO DIAGNOSIS_MAIN PARA JUNTAR A DATA DA CONSULTA
    concat_df_UC = pd.concat([df_inicio_UC, df_caract, df_controlo],
                             ignore_index=False,
                             axis=1)

    return concat_df_UC
Esempio n. 10
0
import streamlit as st
import numpy as np
import pandas as pd
from datetime import datetime
import base64

st.title('AFFINITY Share of Search Calculator')

startDate = st.date_input("Start Date", min_value=datetime(2004, 1, 1))
endDate = st.date_input("End Date", min_value=datetime(2004, 1, 1))

user_input = st.text_input("Enter search terms separated by a comma")

button = st.button(label='Fetch Share of Search')

keyword_list = user_input.split(", ")


# function defined
def share_of_search(kw_list, start_date, end_date):
    def calculate_rolling(
            df):  #calculate 12 month rolling average of search index
        columns = list(df)  #create list of column names
        for column in columns:
            col_name = str(column) + '_rolling'
            df[col_name] = df.rolling(window=12)[column].mean()
        df = df.drop(columns=columns)
        return df

    def add_total(df):  #add all columns together to get the rolling total
        df['rolling_total'] = df.sum(axis=1)
Esempio n. 11
0
def main():

    html_temp = """   
    <div style="background-color:#025246 ;padding:1px">
    <h2 style="color:white;text-align:center;">Restaurant Revenue Prediction </h2>
    </div>
    """

    st.markdown("""
    <style>
    body {
        color: #fff;
        background-color: #5F9EA0;

        
    } .stButton>button {
    color: #000000;
    border-radius: 50%;
    height: 4em;
    width: 5em;
    } 
    </style>
        """,
                unsafe_allow_html=True)

    img = 'https://storage.googleapis.com/kaggle-competitions/kaggle/4272/media/TAB_banner2.png'
    st.image(img, width=700)
    st.markdown(html_temp, unsafe_allow_html=True)

    option = st.sidebar.selectbox("Select any option",
                                  ("Predict", "Load Dataset", "Summary"))

    if option == 'Predict':
        if st.checkbox('Show Description'):
            st.subheader(
                ' To predict revenue of the restaurant in a given year ')

        city = st.selectbox(
            'Location',
            ('İstanbul', 'Ankara', 'Diyarbakır', 'Tokat', 'Gaziantep',
             'Afyonkarahisar', 'Edirne', 'Kocaeli', 'Bursa', 'İzmir',
             'Sakarya', 'Elazığ', 'Kayseri', 'Eskişehir', 'Şanlıurfa',
             'Samsun', 'Adana', 'Antalya', 'Kastamonu', 'Uşak', 'Muğla',
             'Kırklareli', 'Konya', 'Karabük', 'Tekirdağ', 'Denizli',
             'Balıkesir', 'Aydın', 'Amasya', 'Kütahya', 'Bolu', 'Trabzon',
             'Isparta', 'Osmaniye'))

        date = st.date_input('Restaurant opening Date')

        citygroup = st.selectbox('City Group', ("Big City", "Other"))
        type1 = st.selectbox('Restaurant Type',
                             ('Food Court', 'In line', 'Mobile', 'Drive Thru'))

        year = date.year
        month = date.month
        years_old = 2021 - year

        if citygroup == 'Big City' and (city == 'İstanbul' or city == 'Ankara'
                                        or city == 'İzmir'):
            citygroup = 0
        else:
            citygroup = 1

        if type1 == 'Food Court':
            type1 = 1
        elif type1 == 'In line':
            type1 = 2
        elif type1 == 'Mobile':
            type1 = 3
        else:
            type1 = 0

        if st.button("Predict"):
            output = predict_price(year, month, citygroup, type1, years_old)
            predicted = int(output)
            st.success('Approximate Annual Revenue is $ {}'.format(predicted))

    data = pd.read_csv('train.csv')

    if option == "Load Dataset":
        st.text(" ")
        st.text('Read first 100 rows...!')
        st.subheader(' Raw data ')
        st.write(data.head(100))

    if option == "Summary":
        st.text(" ")
        st.write("Introduction :")
        st.write(
            "Food industry plays a crucial part in the enhancement of the country’s economy.  This mainly plays a key role in metropolitan cities. Where restaurants are essential parts of social gatherings and in recent days there are different varieties of quick-service restaurants like food trucks and takeaways. With this recent rise in restaurant types, it is difficult to decide when and where to open a new restaurant."
        )
        st.write("Overview :")
        st.write(
            "Over 1,200 quick service restaurants across the globe, TFI is the company where it owns several well-known restaurants across different parts of the Europe and Asia.They employ over 20,000 people in Europe and Asia and make significant daily investments in developing new restaurant sites. We have been encountered with four different types of restaurants. They are inline, mobile, drive-thru, and food court. So deciding to open a new restaurant is challenging with these emerging quick-service restaurants. In recent days, even restaurant sites also include a large investment of time and capital. Geographical locations and cultures also impact the long-time survival of the firm. With the subjective data, it is difficult to extrapolate the place where to open a new restaurant. So TF1 needs a model such that they can effectively invest in new restaurant sites. This competition is to predict the annual restaurant sales of 100,000 regional locations."
        )
        st.write("Data Overview :")
        st.write("Id: Restaurant ID")
        st.write("Open Date: Opening date of a restaurant")
        st.write("City: City where restaurant is located")
        st.write("City Group: Type of the city. Big cities, or Other.")
        st.write(
            "Type: Type of the restaurant. FC: Food Court, IL: Inline, DT: Drive Thru, MB: Mobile"
        )
        st.write(
            "P1- P37: There are three categories of these obfuscated data.")
        st.write(
            "Demographic data are gathered from third party providers with GIS systems. These include population in any given area, age and gender distribution, development scales. Real estate data mainly relate to the m2 of the location, front facade of the location, car park availability. Commercial data mainly include the existence of points of interest including schools, banks, other QSR operators."
        )
        st.write(
            "Revenue: The revenue column indicates transformed revenue of the restaurant in a given year and is the target of predictive analysis"
        )
Esempio n. 12
0
    href = f'<a href="data:file/csv;base64,{b64}" download="class_calendar.csv">Download the Calendar CSV file</a>'
    return href


# END FUNCTION DEFINITION

uploaded_file = st.file_uploader("Upload Timetable PDF", type='pdf')
"""
#### This app does not work for every timetable pdf file, currently available for:

- Universiti Putra Malaysia

## Date Section
"""
start_date = st.date_input("Semester Start Date",
                           datetime.datetime.now(),
                           key="sem_start")
end_date = st.date_input("Semester End Date",
                         datetime.datetime.now(),
                         key="sem_end")

start_break = st.date_input("Mid Semester Break Start Date",
                            datetime.datetime.now(),
                            key="break_start")
end_break = st.date_input("Mid Semester Break End Date",
                          datetime.datetime.now(),
                          key="break_end")

start_study_week = st.date_input("Study Week Start Date",
                                 datetime.datetime.now(),
                                 key="study_start")
Esempio n. 13
0
def history_view(tickers: Ticker, symbols: List[str]):
    """Provides an illustration of the `Ticker.history` method

    Arguments:
        tickers {Ticker} -- A yahaooquery Ticker object
        symbols {List[str]} -- A list of symbols
    """
    st.header("Historical Pricing")
    st.write("""
        Retrieve historical pricing data for a given symbol(s)
    """)
    st.help(getattr(Ticker, "history"))
    st.markdown("""
        1. Select a period **or** enter start and end dates.
        2. Select interval (**note:  some intervals are not available for
            certain lengths of time**)
    """)
    history_args = {
        "period": "1y",
        "interval": "1d",
        "start": datetime.datetime.now() - datetime.timedelta(days=365),
        "end": None,
    }
    option_1 = st.selectbox("Select Period or Start / End Dates",
                            ["Period", "Dates"], 0)
    if option_1 == "Period":
        history_args["period"] = st.selectbox(
            "Select Period",
            options=Ticker._PERIODS,
            index=5  # pylint: disable=protected-access
        )

        history_args["start"] = None
        history_args["end"] = None
    else:
        history_args["start"] = st.date_input("Select Start Date",
                                              value=history_args["start"])
        history_args["end"] = st.date_input("Select End Date")
        history_args["period"] = None

    st.markdown("**THEN**")
    history_args["interval"] = st.selectbox(
        "Select Interval",
        options=Ticker._INTERVALS,
        index=8  # pylint: disable=protected-access
    )
    args_string = [
        str(k) + "='" + str(v) + "'" for k, v in history_args.items()
        if v is not None
    ]
    st.code(f"Ticker({symbols}).history({', '.join(args_string)})",
            language="python")
    dataframe = tickers.history(**history_args)

    if isinstance(dataframe, dict):
        st.write(dataframe)
    else:
        if len(symbols) > 1:
            chart = (alt.Chart(dataframe.reset_index()).mark_line().encode(
                alt.Y("close:Q", scale=alt.Scale(zero=False)),
                x="dates",
                color="symbol"))
        else:
            chart = (alt.Chart(dataframe.reset_index()).mark_line().encode(
                alt.Y("close:Q", scale=alt.Scale(zero=False)), x="dates:T"))
        st.write("", "", chart)
        st.dataframe(dataframe)
#Input
email=st.text_input("Enter your Email","Type here")
if st.button("Submit"):
	result=email.title()
	st.success(result)

#Text Area
message=st.text_area("Enter your query here","Type here...")
if st.button("Done"):
	result=message.title()
	st.success(result)

#Data Input
import datetime
today=st.date_input("Today is",datetime.datetime.now())

#Time
the_time=st.time_input('The time is',datetime.time())

#Display JSON
st.text("Display JSON")
st.json({'name':'dhruv','gender':'M'})

# Display Python Code
st.text('Display Raw Code')
st.code('import numpy as np')

#Display row code
with st.echo():
	#this will also show as comment
Esempio n. 15
0
    def add_doctor(self):
        st.write('Enter doctor details:')
        self.name = st.text_input('Full name')
        gender = st.radio('Gender', ['Female', 'Male', 'Other'])
        if gender == 'Other':
            gender = st.text_input('Please mention')
        self.gender = gender
        dob = st.date_input('Date of birth (YYYY/MM/DD)')
        st.info('If the required date is not in the calendar, please type it in the box above.')
        self.date_of_birth = dob.strftime('%d-%m-%Y')       # converts date of birth to the desired string format
        self.age = calculate_age(dob)
        self.blood_group = st.text_input('Blood group')
        department_id = st.text_input('Department ID')
        if department_id == '':
            st.empty()
        elif not department.verify_department_id(department_id):
            st.error('Invalid Department ID')
        else:
            st.success('Verified')
            self.department_id = department_id
            self.department_name = get_department_name(department_id)
        self.contact_number_1 = st.text_input('Contact number')
        contact_number_2 = st.text_input('Alternate contact number (optional)')
        self.contact_number_2 = (lambda phone : None if phone == '' else phone)(contact_number_2)
        self.aadhar_or_voter_id = st.text_input('Aadhar ID / Voter ID')
        self.email_id = st.text_input('Email ID')
        self.qualification = st.text_input('Qualification')
        self.specialisation = st.text_input('Specialisation')
        self.years_of_experience = st.number_input('Years of experience', value = 0, min_value = 0, max_value = 100)
        self.address = st.text_area('Address')
        self.city = st.text_input('City')
        self.state = st.text_input('State')
        self.pin_code = st.text_input('PIN code')
        self.id = generate_doctor_id()
        save = st.button('Save')

        # executing SQLite statements to save the new doctor record to the database
        if save:
            conn, c = db.connection()
            with conn:
                c.execute(
                    """
                    INSERT INTO doctor_record
                    (
                        id, name, age, gender, date_of_birth, blood_group,
                        department_id, department_name, contact_number_1,
                        contact_number_2, aadhar_or_voter_id, email_id,
                        qualification, specialisation, years_of_experience,
                        address, city, state, pin_code
                    )
                    VALUES (
                        :id, :name, :age, :gender, :dob, :blood_group, :dept_id,
                        :dept_name, :phone_1, :phone_2, :uid, :email_id, :qualification,
                        :specialisation, :experience, :address, :city, :state, :pin
                    );
                    """,
                    {
                        'id': self.id, 'name': self.name, 'age': self.age,
                        'gender': self.gender, 'dob': self.date_of_birth,
                        'blood_group': self.blood_group,
                        'dept_id': self.department_id,
                        'dept_name': self.department_name,
                        'phone_1': self.contact_number_1,
                        'phone_2': self.contact_number_2,
                        'uid': self.aadhar_or_voter_id, 'email_id': self.email_id,
                        'qualification': self.qualification,
                        'specialisation': self.specialisation,
                        'experience': self.years_of_experience,
                        'address': self.address, 'city': self.city,
                        'state': self.state, 'pin': self.pin_code
                    }
                )
            st.success('Doctor details saved successfully.')
            st.write('Your Doctor ID is: ', self.id)
            conn.close()
Esempio n. 16
0
# -*- coding: utf-8 -*-
# Copyright 2018-2019 Streamlit Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import streamlit as st
from datetime import datetime
from datetime import date

w1 = st.date_input("Label 1", date(1970, 1, 1))
st.write("Value 1:", w1)

w2 = st.date_input("Label 2", datetime(2019, 7, 6, 21, 15))
st.write("Value 2:", w2)
Esempio n. 17
0
def main():
    view = st.sidebar.selectbox("Choose Report:",
                                ["Monthly Segments", "Daily Pickup", "Matrix"])

    actuals, current_df, yesterday_df, past_df = get_data()

    st.header('Arlo Hotels')
    if view == 'Daily Pickup':
        st.write('Select Data:')
        col1, col2 = st.beta_columns(2)
        with col1:
            st.date_input('As of:', value=pd.to_datetime('11/30/20'))
            year = st.selectbox('Year:', [2019, 2020, 2021], index=2)
        with col2:
            length = st.selectbox('Pickup Length:', [1, 7])
            month = MONTHS[st.selectbox('Month:',
                                        list(MONTHS.keys()),
                                        index=TODAY.month - 6)]

        if length == 1:
            pickup_df = create_pickup(current_df, yesterday_df)
        if length == 7:
            pickup_df = create_pickup(current_df, past_df)

        current_year = pickup_df[pickup_df.Date.dt.year == year]
        current_year = create_month_view(current_year, year)

        st.subheader('Current On The Books by Month')
        st.dataframe(current_year.astype('object'), width=800, height=500)

        day_df = pickup_df[(pickup_df.Date.dt.month == month)
                           & (pickup_df.Date.dt.year == year)]

        st.subheader('Current On The Books by Day')

        day_df = create_day_view(day_df)

        st.dataframe(day_df, width=800, height=800)

    if view == 'Monthly Segments':
        st.write('Select Data:')
        col1, col2 = st.beta_columns(2)
        with col1:
            st.date_input('As of', value=pd.to_datetime('11/30/20'))
            year = st.selectbox('Year', [2019, 2020, 2021], index=2)
        with col2:
            length = st.selectbox('Pickup Length', [1, 7])
            month = MONTHS[st.selectbox('Month',
                                        list(MONTHS.keys()),
                                        index=TODAY.month - 6)]

        st.subheader('Current On The Books by Segment')
        condensed = st.checkbox('Condensed Segment View')

        if length == 1:
            pickup_df = create_pickup(current_df, yesterday_df)
        if length == 7:
            pickup_df = create_pickup(current_df, past_df)

        current_month = pickup_df[(pickup_df.Date.dt.month == month)
                                  & (pickup_df.Date.dt.year == year)]

        if condensed:
            current_month['Code'] = current_month['Code'].map(CONDENSED_SEG)
        else:
            current_month['Code'] = current_month['Code'].map(FULL_SEG)

        current_month = seg_pickup(current_month)

        st.dataframe(current_month)

    if view == 'Matrix':
        st.write('Work in Progress')
        year = st.selectbox('Year', [2019, 2020, 2021], index=2)
        month = MONTHS[st.selectbox('Month',
                                    list(MONTHS.keys()),
                                    index=TODAY.month - 6)]
        data = st.radio('Select View',
                        ('On The Books', '1 Day P/U', '7 Day P/U', 'Pace',
                         'Vs. Budget', 'Vs. Forecast'))
        condensed = st.checkbox('Condensed Segment View')

        if data == '7 Day P/U':
            pickup_df = create_pickup(current_df, past_df)
        else:
            pickup_df = create_pickup(current_df, yesterday_df)

        current_month = pickup_df[(pickup_df.Date.dt.month == month)
                                  & (pickup_df.Date.dt.year == year)]
        if condensed:
            current_month['Code'] = current_month['Code'].map(CONDENSED_SEG)
        else:
            current_month['Code'] = current_month['Code'].map(FULL_SEG)

        if data == 'On The Books':
            current_month = current_month.groupby(['Code', 'Date'])[[
                'Res', 'Rev'
            ]].sum().unstack().swaplevel(0, 1, axis=1).sort_index(axis=1)
        else:
            current_month = current_month.groupby(['Code', 'Date'])[[
                'Res p/u', 'Rev p/u'
            ]].sum().unstack().swaplevel(0, 1, axis=1).sort_index(axis=1)

        st.dataframe(current_month)
Esempio n. 18
0
    aoi_location = st.selectbox('Which area of interest?',
                                ["Berlin", "Washington"])
    aoi = up42.get_example_aoi(location=aoi_location, as_dataframe=True)
    # expander_aoi = st.beta_expander("Show aoi feature")
    # expander_aoi.json(aoi)

with col1_params:
    uploaded_file = st.file_uploader("Or upload a geojson file:",
                                     type=["geojson"])
    if uploaded_file is not None:
        aoi = gpd.read_file(uploaded_file, driver="GeoJSON")
        st.success("Using uploaded geojson as aoi!")

with col1_params:
    st.text("")
    start_date = st.date_input("Start date", parse("2019-01-01"))
    end_date = st.date_input("End date", parse("2020-01-01"))

with col1_params:
    limit = st.number_input(label='limit',
                            min_value=1,
                            max_value=10,
                            value=1,
                            step=1)

with col1_params:
    cloud_cover = st.slider('Select Cloud Cover 0-100:', 0, 100, 50)

with col1_params:
    sharpening_strength = st.radio("Sharpening strength:",
                                   ('light', 'medium', 'strong'),
Esempio n. 19
0
@st.cache(persist=True)
def District_counts(police_district):
    df = pd.read_csv(url_count)
    df['Date'] = pd.to_datetime(df['Date'])

    Temp = df[(df['PoliceDistrict'] == police_district)]
    dfSum = Temp.groupby(pd.Grouper(key='Date', freq='W'))['Count'].sum()
    dfWeekDistrict = pd.DataFrame(dfSum)
    dfWeekDistrict['Date'] = dfSum.index
    dfWeekDistrict['PoliceDistrict'] = police_district
    dfWeekDistrict = dfWeekDistrict[1:]
    dfWeekDistrict = dfWeekDistrict[0:-2]
    return (dfWeekDistrict)


date = st.date_input("Pick a week between 2013 and 2018",
                     datetime.date(2018, 10, 5))


@st.cache(persist=True)
def Weekly_rate(year, week):
    df = pd.read_csv(url_count)
    df['Date'] = pd.to_datetime(df['Date'])
    Temp = df[(df['Date'].dt.year == year) & (df['Date'].dt.week == week)]
    return (Temp)


week = date.isocalendar()[1]
year = date.year

if (year < 2013) | (year > 2018):
    '## That date is not in range'
Esempio n. 20
0
    
    # Add a placeholder
    latest_iteration = st.empty()
    bar = st.progress(0)
    
    for i in range(100):
      # Update the progress bar with each iteration.
      latest_iteration.text(f'Iteration {i+1}')
      bar.progress(i + 1)
      time.sleep(0.05)
    
    '...and now we\'re done!'



st.button('Button click me')
st.checkbox('Checkbox Check me out')
radiovalue = st.radio('Radio', [1,2,3])
'You picked ', radiovalue
st.selectbox('Selectbox', [1,2,3])
st.multiselect('Multiselect', ['A','B','C'])
st.slider('Slider', min_value=0, max_value=100)
st.select_slider('Select slider individual options', options=[1,20,'test','bob'])
st.text_input('Text input')
st.number_input('Number input')
st.text_area('Text area')
st.date_input('Date input')
st.time_input('Time entry')
st.file_uploader('File uploader')
st.color_picker('Pick a color')
# select box
selected = st.selectbox('select', ['yes', 'no', 'dont know'])
st.write('option selected: ', selected)

# multiselect
st.multiselect('select shape: ', ('Square', 'Triangle', 'Circle'))

# slider
st.slider('Select number between 1 and 10: ', 1, 10)

# text input
st.text_input('Input text here: ', 'type here')

# date
st.date_input('The date is ', datetime.datetime.now())

# time input
st.time_input('The time is ', datetime.time())


# progress bar
bar = st.progress(0)
for i in range(100):
    time.sleep(0.01)
    bar.progress(i+1)

# display data
# single line code
st.code('import pandas as pd')
Esempio n. 22
0
def main():
    st.set_page_config(layout="wide") 
    st.markdown('<style>#vg-tooltip-element{z-index: 1000051}</style>',
             unsafe_allow_html=True)

    confirmed_df, death_df, recovery_df = wwConfirmedDataCollection()
    st.title("Covid-19 ­Ъда Pandemic Data Visualization")
    displayRawData(confirmed_df, death_df, recovery_df)
    confirmed_df, death_df, recovery_df = dataMassaging(
        confirmed_df, death_df, recovery_df
    )
    full_table = mergeDataAndDataCorrection(confirmed_df, death_df, recovery_df)

    st.write('\nData from "CSSEGISandData POST data massaging"')
    
    user_selectionbox_input = st.selectbox(
        "Select an option", ["Global", "Select from list of countries"]
    )
    min_date_found = full_table["date"].min()
    max_date_found = full_table["date"].max()

    selected_date = st.date_input(
        "Pick a date",
        (min_date_found, max_date_found)
    )
    if len(selected_date) == 2:
        
        if user_selectionbox_input == "Select from list of countries":
            full_table = full_table[(full_table['date'] >= selected_date[0]) & (full_table['date'] <= selected_date[1])]
            
            # full_table = full_table[full_table["date"] == (between(selected_date[0], selected_date[1]))]
            list_of_countries = full_table["location"].unique()
            selected_country = st.selectbox("Select country", list_of_countries)

            mask_countries = full_table["location"] == (selected_country)
            full_table = full_table[mask_countries]

            # Adding new cases to the table for graphing
            full_table["new_confirmed"] = full_table["confirmed"].diff(1).fillna(0)
            full_table["new_recovered"] = full_table["recovered"].diff(1).fillna(0)
            full_table["new_deaths"] = full_table["deaths"].diff(1).fillna(0)
            

            user_input = st.selectbox(
                "Select an option", ["Total Number of Cases", "New Cases Per Day"]
            )
            st.write(full_table)
            if user_input == "New Cases Per Day":
                source = pd.DataFrame(full_table, columns=["date", "new_confirmed", "new_recovered", "new_deaths"])
                title = f"New Cases Per Day for {selected_country}"
            else:
                source = pd.DataFrame(
                    full_table, columns=["date", "confirmed", "deaths", "recovered"]
                )
                title = f"Total reported cases for {selected_country}"
            
            st.altair_chart(altairLineChartGraphing(title, source), use_container_width=True)    

        else:
            full_table = full_table[full_table["date"] == selected_date[1]]
            confirmed_source = pd.DataFrame(full_table, columns=["location", "lat", "lon", "confirmed"])
            

            #Readable values
            confirmed_source["confirmed_readable"] = confirmed_source["confirmed"].apply(human_format)
            display_confirmed_source = pd.DataFrame(confirmed_source, columns=["location", "lat", "lon", "confirmed_readable"]).reset_index(drop=True)
            display_confirmed_source = display_confirmed_source.rename(columns={"confirmed_readable": "confirmed"})
            st.dataframe(display_confirmed_source)

            INITIAL_VIEW_STATE = pdk.ViewState(
                latitude=55.3781,
                longitude=-3.436,
                zoom=1,
                pitch=25,
            )

            column_layer = pdk.Layer(
                "ColumnLayer",
                data=confirmed_source,
                get_position=["lon", "lat"],
                radius=50000,
                get_elevation="confirmed",
                elevation_scale=0.25,
                get_fill_color=["255,255, confirmed*.01"],
                get_line_color=[255, 255, 255],
                filled=True,
                pickable=True,
                extruded=True,
                auto_highlight=True,
            )
            TOOLTIP = {
                "html": "{location}<br> <b>{confirmed_readable}</b> Confirmed Cases",
                "style": {
                    "background": "grey",
                    "color": "white",
                    "font-family": '"Helvetica Neue", Arial',
                    "z-index": "10000",
                },
            }

            r = pdk.Deck(
                column_layer,
                map_style="mapbox://styles/mapbox/satellite-streets-v11",
                map_provider="mapbox",
                initial_view_state=INITIAL_VIEW_STATE,
                tooltip=TOOLTIP,
            )
            st.write("## Total Number of Confirmed Cases All Time")
            st.pydeck_chart(r)
    else:
        st.write("Select Valid Dates to continue")
Esempio n. 23
0
"""

indented_code_tooltip = """
Code:

    for i in range(10):
        x = i * 10
        print(x)
    """

no_indent_tooltip = "thisisatooltipwithnoindents. It has some spaces but no idents."

st.text_input("some input text", "default text", help=default_tooltip)
st.number_input("number input", value=1, help=leading_indent_code_tooltip)
st.checkbox("some checkbox", help=leading_indent_regular_text_tooltip)
st.radio("best animal", ("tiger", "giraffe", "bear"), 0, help=indented_code_tooltip)
st.selectbox("selectbox", ("a", "b", "c"), 0, help=default_tooltip)
st.time_input("time", datetime(2019, 7, 6, 21, 15), help=leading_indent_code_tooltip)
st.date_input(
    "date", datetime(2019, 7, 6, 21, 15), help=leading_indent_regular_text_tooltip
)
st.slider("slider", 0, 100, 50, help=indented_code_tooltip)
st.color_picker("color picker", help=no_indent_tooltip)
st.file_uploader("file uploader", help=default_tooltip)
st.multiselect(
    "multiselect", ["a", "b", "c"], ["a", "b"], help=leading_indent_code_tooltip
)
st.text_area("textarea", help=leading_indent_regular_text_tooltip)
st.select_slider("selectslider", options=["a", "b", "c"], help=indented_code_tooltip)
st.button("some button", help=no_indent_tooltip)
Esempio n. 24
0
# Put your widgets in an expander and then in that lay out your widgets in a grid
with st.beta_expander("Adjust chart values"):
    widget_col1, widget_col2, widget_col3 = st.beta_columns(3)

    with widget_col1:
        st.multiselect("Choose data", ["a", "b", "c"],
                       help="An example tooltip you can add")
        st.slider("Select value", 1, 100)

    with widget_col2:
        st.number_input("Select number", 1, 10)
        st.text_input("Add text")

    with widget_col3:
        st.date_input("Select another date")
        st.time_input("Pick a time")

st.write("#")

# Lay out your data and visualizations.

# We will use 3 columns. You should pick whichever column layout works best.
col1, col2 = st.beta_columns((2, 1))

with col1:
    st.area_chart(data, height=610)

with col2:
    st.line_chart(data)
    st.bar_chart(data)
Esempio n. 25
0
# '''
# ## Here we would like to add some controllers in order to ask the user to select the parameters of the ride

# 1. Let's ask for:
# - date and time
# - pickup longitude
# - pickup latitude
# - dropoff longitude
# - dropoff latitude
# - passenger count
# '''

# DAY
pickup_day = st.date_input(
    "On which day would you like to travel?",
    )
st.write('You will travel on:', pickup_day)


# TIME
pickup_time = st.time_input(
    'At what time?',
    )
st.write('You will travel at:', pickup_time)


# DEPARTURE ADDRESS
pickup_longitude = st.number_input('Insert your pick-up longitude')
pickup_latitude = st.number_input('Insert your pick-up latitude')
Esempio n. 26
0
    data_load_state = st.text('Loading data...')
    rawdata = load_data(file) # call load data function
    data_load_state.text('Loading data...done!')
    filecheck = 0

# If valid file
if filecheck == 0:
    st.write('The raw data contains ', len(rawdata.index), ' searches.')

    # Default values for date range inputs
    daterangestart = rawdata.index.min().date()
    daterangeend = dt.date.today()

    # User input to set date range
    st.subheader('Date Configuration')
    startdate = st.date_input('Start date: ', daterangestart)
    enddate = st.date_input('End date: ', daterangeend)

    # Checks date range validity
    if (startdate == daterangestart or startdate > daterangestart) & (startdate < enddate) & (enddate == daterangeend or enddate < daterangeend):
        datecheck = 0
    else:
        st.error('Error: End date must fall after start date.')
        datecheck = 1

    # If dates are valid, selects data from inputted range
    if datecheck == 1:
        st.write("Please fix the dates above.")
    elif datecheck == 0:
        datedf = rawdata.loc[startdate:enddate]
Esempio n. 27
0
first_name = st.text_input("First Name: ", "Type Here ...")
last_name = st.text_input("Last Name: ", "Type Here...")
name = first_name + " " + last_name
if st.button("Submit", key="name"):
    st.success(name)

# Text Area
st.markdown("#### Text Area")
message = st.text_input("Your Message: ", "Type Here ...")
if st.button("Submit", key="message"):
    st.success(message)

# Date and Time Input
st.subheader('Date and Time Inputs')
import datetime
date = st.date_input("today is: ", datetime.datetime.now())
time = st.time_input("time right now", datetime.time())

# Displaying JSON
st.subheader('Displaying JSON')
json_1 = {'Name': "Akshay Uppal", 'Gender': "Male", 'Age': 26}
st.json(json_1)

# Displaying Code
st.subheader('Displaying Code')
st.code("import numpy as np")
with st.echo():
    # this is a code block
    # Import Statements
    import numpy as np
    import pandas as pd
choice = st.selectbox("Which analysis do you want to perform?",
                      ["Text Analysis", "Twitter analysis"])
if choice == "Text Analysis":
    text = st.text_area("Enter your text here", "Type here...")
    #Converting text to lower case
    if st.button("Enter"):

        if len(text) != 0:
            with st.spinner("Please wait while we process your text"):
                process_text(text)

        else:
            st.warning("Please enter some text")
else:
    query = st.text_input("Enter your search query", "Twitter")
    startTime = st.date_input(
        "Enter the date from which you want your analysis to start")
    endTime = st.date_input(
        "Enter the ending date till which you want to search")
    No_of_tweets = st.text_input("Enter the no. of tweets you want to search",
                                 "50")

    start_Time = startTime.strftime('%Y-%m-%d')
    end_Time = endTime.strftime('%Y-%m-%d')
    if st.button("Enter"):

        if (len(query) != 0 and len(No_of_tweets) != 0
                and No_of_tweets.isnumeric() == True):
            no_of_tweets = int(No_of_tweets)
            with st.spinner('Please wait while we get you the graph'):
                tweets = get_tweets()
            if len(tweets) == 0:
Esempio n. 29
0
 def test_value_in_range(self, value, min_date, max_date):
     st.date_input("the label",
                   value=value,
                   min_value=min_date,
                   max_value=max_date)
Esempio n. 30
0
    col2.button('20201212002BET')
    col2.button('20201212003BET')

    col3.subheader('待反馈')
    col3.button('20201212001XPS')
    '''

    ## 订单查询
    历史订单查询
    '''
    option = st.selectbox('订单状态', ['已完成', '进行中', '待确认', '待反馈'])

    #df=pd.read_sql('select * from order where status=""')

    st.date_input(label='查询日期',
                  value=(datetime.date(2020, 12,
                                       1), datetime.date(2020, 12, 30)))

    st.balloons()


#Your script writes to your Streamlit app from within a cached function. This code will only be called when we detect a cache "miss"
@st.cache(allow_output_mutation=True, show_spinner=True)
def generate_data():
    chart_data = pd.DataFrame(abs(np.random.randn(20, 3) * 50 + 100),
                              columns=['SEM', 'XPS', 'BET'])
    date = pd.date_range('2020-12-01', periods=20, freq='D')
    chart_data.index = date
    return chart_data