Example #1
0
def kpi_escuela(df):
    streamlit_metrics.metric_row({
        'Nº Alumnos':
        df.shape[0],
        'Nº Promociones':
        len(df['Promoción'].unique()),
        '% Alumnos Graduados':
        round(
            df['Estado de matrícula'].value_counts(normalize=True)['Graduado']
            * 100, 0),
    })
def getOrderBookInfo(coinName):
    bidOrderBookDF = pd.DataFrame()
    askOrderBookDF = pd.DataFrame()
    result = requests.get('https://api1.binance.com/api/v3/depth?symbol=' +
                          str(coinName) + '&limit=5000')
    json_data = json.loads(result.text)
    for i in range(0, len(json_data['bids'])):
        bidPrice = float(json_data['bids'][i][0])
        Qty = float(json_data['bids'][i][1])

        bidData = {'Bid': bidPrice, 'Qty': Qty}
        bidOrderBookDF = bidOrderBookDF.append(bidData, ignore_index=True)

    bidOrderBookDF[
        'Total price'] = bidOrderBookDF['Bid'] * bidOrderBookDF['Qty']
    bidOrderBookDF = bidOrderBookDF[(bidOrderBookDF['Total price'] >= 10000)]
    bidOrderBookDF['Qty'] = bidOrderBookDF['Qty'].round()
    bidOrderBookDF['Total price'] = bidOrderBookDF['Total price'].round()

    for i in range(0, len(json_data['asks'])):
        askPrice = float(json_data['asks'][i][0])
        Qty = float(json_data['asks'][i][1])

        askData = {'Ask': askPrice, 'Qty': Qty}
        askOrderBookDF = askOrderBookDF.append(askData, ignore_index=True)

    askOrderBookDF[
        'Total price'] = askOrderBookDF['Ask'] * askOrderBookDF['Qty']
    askOrderBookDF = askOrderBookDF[(askOrderBookDF['Total price'] >= 10000)]
    askOrderBookDF['Qty'] = askOrderBookDF['Qty'].round()
    askOrderBookDF['Total price'] = askOrderBookDF['Total price'].round()

    col1, col2 = st.beta_columns(2)
    with col1:
        st.info("__Support__ - " + getBestBidPriceQty(coinName))
        bidOrderBookDF = bidOrderBookDF.reset_index(drop=True)
        st.dataframe(bidOrderBookDF.sort_values(by=['Bid'], ascending=False))
        totalBids = bidOrderBookDF['Total price'].sum()
    with col2:
        st.info("__Resistance__ - " + getBestAskPriceQty(coinName))
        askOrderBookDF = askOrderBookDF.reset_index(drop=True)
        st.dataframe(askOrderBookDF.sort_values(by=['Ask']))
        totalAsks = askOrderBookDF['Total price'].sum()

    metric_row({
        "Total Bids": millify(totalBids, precision=2),
        "Total Asks": millify(totalAsks, precision=2)
    })
Example #3
0
def kpi_busqueda_empleo(df):

    tipo = '3 Continua su búsqueda de trabajo'

    a_180 = kpi_empleo(df, 'Estado 180 días post-graduación', tipo)
    a_90 = kpi_empleo(df, 'Estado 90 días post-graduación', tipo)
    actual = kpi_empleo(df, 'Estado actual', tipo)

    streamlit_metrics.metric_row({
        '% Alumnos que Continuan buscando trabajo':
        actual,
        '% Alumnos que Continuan buscando trabajo a 90 días de graduarse':
        a_90,
        '% Alumnos que Continuan buscando trabajo a 180 días de graduarse':
        a_180
    })
def changes24Hours(coinName):
    result = requests.get(
        'https://api1.binance.com/api/v3/ticker/24hr?symbol=' + str(coinName))
    json_data = json.loads(result.text)
    priceChange = json_data["priceChange"]
    percentChange = json_data["priceChangePercent"]
    lowPrice = json_data["lowPrice"]
    highPrice = json_data["highPrice"]
    weightedAvgPrice = json_data["weightedAvgPrice"]
    volume = int((float(json_data["volume"])))

    st.info("__24 hours change statistics__")
    metric_row({
        "Price Change": millify(priceChange, precision=2),
        "Percent Change": millify(percentChange, precision=2) + "%",
        "Low Price": millify(lowPrice, precision=2),
        "High Price": millify(highPrice, precision=2),
        "Average Price (24 hrs)": millify(weightedAvgPrice, precision=2),
        "Volume (24 hrs)": millify(volume, precision=0)
    })
Example #5
0
def show_results(counts, reset_callback, unsafe_password=None):
    """Show analytics results in streamlit, asking for password if given."""

    # Show header.
    st.title("Analytics Dashboard")
    st.markdown("""
        Psst! 👀 You found a secret section generated by 
        [streamlit-analytics](https://github.com/jrieke/streamlit-analytics). 
        If you didn't mean to go here, remove `?analytics=on` from the URL.
        """)

    # Ask for password if one was given.
    show = True
    if unsafe_password is not None:
        password_input = st.text_input("Enter password to show results",
                                       type="password")
        if password_input != unsafe_password:
            show = False
            if len(password_input) > 0:
                st.write("Nope, that's not correct ☝️")

    if show:
        # Show traffic.
        st.header("Traffic")
        st.write(f"since {counts['start_time']}")
        st.write(
            f"""
            <sup>pageview = user (re-)loads site | 
            script run = streamlit re-runs upon changes | 
            time spent = from page load to last widget interaction (summed across users)</sup>
            """,
            unsafe_allow_html=True,
        )
        st_metrics.metric_row({
            "Pageviews":
            counts["total_pageviews"],
            "Script runs":
            counts["total_script_runs"],
            "Time spent":
            utils.format_seconds(counts["total_time_seconds"]),
        })

        # Total: {counts['total_pageviews']} pageviews, {counts['total_script_runs']} script runs
        # <br>

        # st.header("Traffic per day")
        # Plot altair chart with pageviews and script runs.
        df = pd.DataFrame(counts["per_day"])
        base = alt.Chart(df).encode(
            x=alt.X("monthdate(days):O", axis=alt.Axis(title="", grid=True)))
        line1 = base.mark_line(point=True, stroke="#5276A7").encode(
            alt.Y(
                "pageviews:Q",
                axis=alt.Axis(
                    titleColor="#5276A7",
                    tickColor="#5276A7",
                    labelColor="#5276A7",
                    format=".0f",
                    tickMinStep=1,
                ),
                scale=alt.Scale(domain=(0, df["pageviews"].max() + 1)),
            ))
        line2 = base.mark_line(point=True, stroke="#57A44C").encode(
            alt.Y(
                "script_runs:Q",
                axis=alt.Axis(
                    title="script runs",
                    titleColor="#57A44C",
                    tickColor="#57A44C",
                    labelColor="#57A44C",
                    format=".0f",
                    tickMinStep=1,
                ),
            ))
        layer = (alt.layer(line1, line2).resolve_scale(
            y="independent").configure_axis(titleFontSize=15,
                                            labelFontSize=12,
                                            titlePadding=10))
        st.altair_chart(layer, use_container_width=True)

        # Show widget interactions.
        st.header("Widget interactions")
        st.markdown(
            """
            Find out how users interacted with your app!
            <br>
            Numbers indicate how often a button was clicked, how often a specific text 
            input was given, ...
            <br>
            <sub>Note: Numbers only increase if the state of the widget
            changes, not every time streamlit runs the script.</sub>
            """,
            unsafe_allow_html=True,
        )
        st.write(counts["widgets"])

        # Show button to reset analytics.
        st.header("Danger zone")
        with st.beta_expander("Here be dragons 🐲🔥"):
            st.write("""
                Here you can reset all analytics results.
                
                **This will erase everything tracked so far. You will not be able to 
                retrieve it. This will also overwrite any results synced to Firestore.**
                """)
            reset_prompt = st.selectbox(
                "Continue?",
                [
                    "No idea what I'm doing here",
                    "I'm absolutely sure that I want to reset the results",
                ],
            )
            if reset_prompt == "I'm absolutely sure that I want to reset the results":
                reset_clicked = st.button("Click here to reset")
                if reset_clicked:
                    reset_callback()
                    st.write("Done! Please refresh the page.")
expander_bar2 = st.beta_expander("Click to explore raw data table")
expander_bar2.write(filtered_df)
#st.subheader('Listing prices data')
#st.write(filtered_df)
'''
## Step 2: Create KPI cards
'''
# Calculate KPIs
listings_count = len(pd.unique(filtered_df['listing_id']))
avg_listed_days = round(filtered_df['days_on_site'].mean())

# Create visuals
st.subheader('Vancouver Housing Inventory')
metric_row({
    "Number of listings": listings_count,
    "Average days listed on site": avg_listed_days
})
'''
## Step 3: Create graphs
'''
# Create dataframe with count of unique listings by date
df_inventory = filtered_df[['scrape_date', 'listing_id'
                            ]].groupby(['scrape_date']).agg(['nunique'
                                                             ]).reset_index()
df_inventory.columns = ['scrape_date', 'listings_count']

st.subheader('Number of listings over time')
st.line_chart(df_inventory.set_index('scrape_date'))
'''
## Step 4: Create summary tables
'''