Exemple #1
0
def mean_pos(appareil):

    pos, temp, time, date = appareil.pos, appareil.temp, appareil.tdelta, appareil.date

    fig = go.Figure()
    POS_AXIS = 1
    # data :
    line = go.Line(x=date,
                   y=np.nanmean(temp, axis=POS_AXIS),
                   visible=True,
                   name='dts')
    fig.add_traces([line])
    fig.update_layout(
        title='Température moyenne (dans la fibre) en fonction du temps',
        width=1000,
        height=600,
        xaxis_title='Date',
        yaxis_title='Température (°C)',
    )

    # Add range slider
    fig.update_layout(xaxis=dict(rangeslider=dict(visible=True), type="date"))
    return fig
Exemple #2
0
def kpi_5(tipo = '-'):
    #df_pilatus = sql.psql_pilatusqtync()
    df_kpi_5 = df_pilatus[["campo_adicional", "contenido"]]
    df_kpi_5["contenido"] = df_kpi_5["contenido"].apply(pd.to_numeric, errors='coerce')
        
    kpi_5 = df_kpi_5.groupby(["campo_adicional"]).agg({'contenido':'sum'}).reset_index().rename(columns={"campo_adicional":"Tipo", "contenido":"Defectos"})
    kpi_5.sort_values(by=["Defectos"], ascending= False, inplace=True)
    #Calcular el porcentaje sobre el total en una columna, se puede con groupby
    kpi_5["Cumsum %"] = round(kpi_5["Defectos"].cumsum() / kpi_5["Defectos"].sum(), 2)
    
    fig_2 = make_subplots(specs=[[{"secondary_y": True}]])
    fig_2.add_trace(go.Bar(x=kpi_5["Tipo"], y=kpi_5["Defectos"], hovertext=kpi_5["Tipo"], name="TYPE", text=kpi_5["Defectos"], marker_color="rgb(0,73,131)"), secondary_y = False)#, log_x=True)
    fig_2.add_trace(go.Line(x=kpi_5["Tipo"], y=kpi_5["Cumsum %"], marker_color="red", name="%"), secondary_y = True)
    
    # Styling
    fig_2.update_traces(textfont=dict(color="#fff")) #, textposition="inside"
    fig_2.layout.plot_bgcolor = "#fff"
    fig_2.layout.paper_bgcolor = "#fff"
    fig_2.update_xaxes(title="Defectos", showline=True, linewidth=1, linecolor="#656565", showgrid=True, gridcolor="#E4E6E8", gridwidth=1, tickcolor="red", tickangle=315, tickfont=dict(size=7))
    fig_2.update_yaxes(showline=True, linewidth=1, linecolor="#656565", showgrid=True, gridcolor="#E4E6E8", gridwidth=1, tickcolor="#656565", secondary_y = False, showticklabels=True)
    fig_2.update_yaxes(showline=True, linewidth=1, linecolor="#656565", showgrid=False, gridcolor="#E4E6E8", gridwidth=1, tickcolor="#656565", secondary_y = True, range=[0,1.1], overlaying='y')
    
    return fig_2
Exemple #3
0
def first10cases():
    df4 = pd.read_csv("owid-covid-data.csv")
    df4 = df4[df4.date > '2020-02-29']
    df4 = df4[['location', 'date', 'total_cases']]
    df4 = df4[df4.location.isin([
        'Russia', 'United Kingdom', 'Spain', 'Italy', 'Germany', 'Turkey',
        'France', 'Iran', 'India', 'China'
    ])]
    df4['date'] = pd.to_datetime(df4['date'])
    df4.set_index(['date', 'location'], inplace=True)
    df4.sort_index(inplace=True)
    df4 = df4.unstack(level=[1])
    df4.columns = df4.columns.droplevel()
    df4col = df4.columns.values.tolist()
    graph4 = []
    for i in df4col:
        graph4.append(go.Line(name=i, x=df4.index, y=df4[i]))
    fig4 = go.Figure(data=graph4)
    fig4.update_layout(
        title="Total Cases v/s Timeline",
        xaxis_title="Timeline",
        yaxis_title="Total Cases",
    )
    return plotly.offline.plot(fig4, output_type='div')
Exemple #4
0
def third10tests():
    df9 = pd.read_csv('owid-covid-data.csv')
    df9 = df9[df9.date > '2020-02-29']
    df9 = df9[['location', 'date', 'total_tests_per_thousand']]
    df9 = df9[df9.location.isin([
        'Bangladesh', 'Poland', 'Indonesia', 'Romania', 'Israel', 'Japan',
        'Austria', 'South Korea'
    ])]
    df9['date'] = pd.to_datetime(df9['date'])
    df9.set_index(['date', 'location'], inplace=True)
    df9.sort_index(inplace=True)
    df9 = df9.unstack(level=[1])
    df9.columns = df9.columns.droplevel()
    df9col = df9.columns.values.tolist()
    graph9 = []
    for i in df9col:
        graph9.append(go.Line(name=i, x=df9.index, y=df9[i]))
    fig9 = go.Figure(data=graph9)
    fig9.update_layout(
        title="Total Tests per Thousand",
        xaxis_title="Timeline",
        yaxis_title="Total tests per thousand",
    )
    return plotly.offline.plot(fig9, output_type='div')
Exemple #5
0
def third10cases():
    df8 = pd.read_csv("owid-covid-data.csv")
    df8 = df8[df8.date > '2020-02-29']
    df8 = df8[['location', 'date', 'total_cases']]
    df8 = df8[df8.location.isin([
        'Bangladesh', 'Poland', 'Indonesia', 'Romania', 'Israel', 'Japan',
        'Austria', 'South Korea'
    ])]
    df8['date'] = pd.to_datetime(df8['date'])
    df8.set_index(['date', 'location'], inplace=True)
    df8.sort_index(inplace=True)
    df8 = df8.unstack(level=[1])
    df8.columns = df8.columns.droplevel()
    df8col = df8.columns.values.tolist()
    graph8 = []
    for i in df8col:
        graph8.append(go.Line(name=i, x=df8.index, y=df8[i]))
    fig8 = go.Figure(data=graph8)
    fig8.update_layout(
        title="Total Cases",
        xaxis_title="Timeline",
        yaxis_title="Total Cases",
    )
    return plotly.offline.plot(fig8, output_type='div')
Exemple #6
0
def second10tests():
    df7 = pd.read_csv('owid-covid-data.csv')
    df7 = df7[df7.date > '2020-02-29']
    df7 = df7[['location', 'date', 'total_tests_per_thousand']]
    df7 = df7[df7.location.isin([
        'Canada', 'Belgium', 'Mexico', 'Chile', 'Ecuador', 'Qatar',
        'Switzerland', 'Portugal'
    ])]
    df7['date'] = pd.to_datetime(df7['date'])
    df7.set_index(['date', 'location'], inplace=True)
    df7.sort_index(inplace=True)
    df7 = df7.unstack(level=[1])
    df7.columns = df7.columns.droplevel()
    df7col = df7.columns.values.tolist()
    graph7 = []
    for i in df7col:
        graph7.append(go.Line(name=i, x=df7.index, y=df7[i]))
    fig7 = go.Figure(data=graph7)
    fig7.update_layout(
        title="Total Tests per Thousand",
        xaxis_title="Timeline",
        yaxis_title="Total tests per thousand",
    )
    return plotly.offline.plot(fig7, output_type='div')
Exemple #7
0
def second10cases():
    df6 = pd.read_csv("owid-covid-data.csv")
    df6 = df6[df6.date > '2020-02-29']
    df6 = df6[['location', 'date', 'total_cases']]
    df6 = df6[df6.location.isin([
        'Canada', 'Belgium', 'Mexico', 'Chile', 'Ecuador', 'Qatar',
        'Switzerland', 'Portugal'
    ])]
    df6['date'] = pd.to_datetime(df6['date'])
    df6.set_index(['date', 'location'], inplace=True)
    df6.sort_index(inplace=True)
    df6 = df6.unstack(level=[1])
    df6.columns = df6.columns.droplevel()
    df6col = df6.columns.values.tolist()
    graph6 = []
    for i in df6col:
        graph6.append(go.Line(name=i, x=df6.index, y=df6[i]))
    fig6 = go.Figure(data=graph6)
    fig6.update_layout(
        title="Total Cases",
        xaxis_title="Timeline",
        yaxis_title="Total Cases",
    )
    return plotly.offline.plot(fig6, output_type='div')
Exemple #8
0
def first10tests():
    df5 = pd.read_csv('owid-covid-data.csv')
    df5 = df5[df5.date > '2020-02-29']
    df5 = df5[['location', 'date', 'total_tests_per_thousand']]
    df5 = df5[df5.location.isin([
        'Russia', 'United Kingdom', 'Spain', 'Italy', 'Germany', 'Turkey',
        'France', 'Iran', 'India', 'China'
    ])]
    df5['date'] = pd.to_datetime(df5['date'])
    df5.set_index(['date', 'location'], inplace=True)
    df5.sort_index(inplace=True)
    df5 = df5.unstack(level=[1])
    df5.columns = df5.columns.droplevel()
    df5col = df5.columns.values.tolist()
    graph5 = []
    for i in df5col:
        graph5.append(go.Line(name=i, x=df5.index, y=df5[i]))
    fig5 = go.Figure(data=graph5)
    fig5.update_layout(
        title="Total Tests per Thousand",
        xaxis_title="Timeline",
        yaxis_title="Total tests per thousand",
    )
    return plotly.offline.plot(fig5, output_type='div')
def update_figure(n): 

    #sent = time.time() + 1
    while receiver.poll(1): # Timeout of 1 ms checking for new data
        sent, new = msgpack.unpackb(receiver.recv())
        for i in range (16):
            dt[i] = np.delete(dt[i], 0)
            dt[i] = np.append(dt[i], new[i][0]) #new[1..16 sensors][0] is data  

    graph_number = 0
    for r in range (1,5):
        for c in range (1,5):
            fig.update_traces(go.Line(x=np.array(t), y=np.array(dt[graph_number])), row=r, col=c)
            graph_number += 1

    #fig.update_layout(transition_duration=500) #Adjusts frame

    #fig.update_layout(
    #    title="Test Layout",
    #    xaxis_title="Time",
    #    yaxis_title="Data"
    #)

    return fig
Exemple #10
0
def plot(functions, x1, x2, marker_mode, size, logX, logY):
    lines = list()

    for f in functions:
        lineX = list()
        lineY = list()
        for x in range(x1, x2):
            lineX.append(x)
            lineY.append(f(x))
        lines.append([lineX, lineY])

    fig = go.Figure()

    for line in lines:
        fig.add_trace(go.Line(x=line[0], y=line[1], mode=marker_mode))

    fig.update_traces(marker_size=size)

    if logX:
        fig.update_xaxes(type="log")
    if logY:
        fig.update_yaxes(type="log")

    return fig
Exemple #11
0
def main():
    st.title("Covid-19 Visualizer")
    st.sidebar.text("Author: Harrison Hoffman")
    st.sidebar.info("https://github.com/hfhoffman1144")
    st.sidebar.info("https://www.linkedin.com/in/harrison-hoffman-utd/")
    st.sidebar.info('https://raw.githubusercontent.com/datasets/covid-19/master/data/countries-aggregated.csv')
    data = get_timeseries_data()
    data_global = data.groupby('Date').sum()
    

    st.write(data_global.tail(1))
    st.write(f"Today's calculated daily rate of change: {np.diff(data_global['Confirmed'])[-1]}")

    fig0 = go.Figure()
    fig0.add_trace(go.Line(x=data_global.index,y=data_global.Confirmed,name=f'Confirmed global cases'))
    fig0.add_trace(go.Line(x=data_global.index,y=data_global.Recovered,name=f'Recovered global cases'))
    fig0.add_trace(go.Line(x=data_global.index,y=data_global.Deaths,name=f'Global Deaths'))
    fig0.update_layout(title=f'Global Covid-19 Cases')
    st.plotly_chart(fig0)
    
    country = st.selectbox("Select a country",data.Country.unique())
    data_country = data[data['Country'] == country]
    st.write(data_country.tail(1))
    st.write(f"Today's calculated daily rate of change for {country}: {np.diff(data_country['Confirmed'])[-1]}")

    fig = go.Figure()
    fig.add_trace(go.Line(x=data_country.Date,y=data_country.Confirmed,name=f'Confirmed {country} cases'))
    fig.add_trace(go.Line(x=data_country.Date,y=data_country.Recovered,name=f'Recovered {country} cases'))
    fig.add_trace(go.Line(x=data_country.Date,y=data_country.Deaths,name=f'Deaths {country}'))
    fig.update_layout(title=f'{country} Covid-19 Cases')
    st.plotly_chart(fig)

    fig1 = go.Figure()
    fig1.add_trace(go.Line(x=data_country.Date,y=np.diff(data_country.Confirmed),name=f'Confirmed {country} cases'))
    fig1.update_layout(title=f'Rate of Change {country} Covid-19 Cases')
    st.plotly_chart(fig1)
def trace_by_dep(dep):
    if dep == '75':
        fig = {
            'data': [
                #dep_name = df.loc[df['dep'] == dep],
                go.Line(x=df.loc[df['dep'] == '75'].index,
                        y=df.loc[df['dep'] == '75']['dc'])
            ],
            'layout':
            go.Layout(title='Nombre de décès en Ile de France',
                      xaxis={'title': 'Days'},
                      yaxis={'title': 'Number of death'},
                      hovermode='closest')
        }
    elif dep == '59':
        fig = {
            'data': [
                #dep_name = df.loc[df['dep'] == dep],
                go.Line(x=df.loc[df['dep'] == '59'].index,
                        y=df.loc[df['dep'] == '59']['dc'])
            ],
            'layout':
            go.Layout(title='Nombre de décès dans le Nord',
                      xaxis={'title': 'Days'},
                      yaxis={'title': 'Number of death'},
                      hovermode='closest')
        }
    elif dep == '94':
        fig = {
            'data': [
                #dep_name = df.loc[df['dep'] == dep],
                go.Line(x=df.loc[df['dep'] == '94'].index,
                        y=df.loc[df['dep'] == '94']['dc'])
            ],
            'layout':
            go.Layout(title='Nombre de décès au Val de Marne',
                      xaxis={'title': 'Days'},
                      yaxis={'title': 'Number of death'},
                      hovermode='closest')
        }
    elif dep == '69':
        fig = {
            'data': [
                #dep_name = df.loc[df['dep'] == dep],
                go.Line(x=df.loc[df['dep'] == '69'].index,
                        y=df.loc[df['dep'] == '69']['dc'])
            ],
            'layout':
            go.Layout(title='Nombre de décès à Rhon',
                      xaxis={'title': 'Days'},
                      yaxis={'title': 'Number of death'},
                      hovermode='closest')
        }
    elif dep == '57':
        fig = {
            'data': [
                #dep_name = df.loc[df['dep'] == dep],
                go.Line(x=df.loc[df['dep'] == '57'].index,
                        y=df.loc[df['dep'] == '57']['dc'])
            ],
            'layout':
            go.Layout(title='Nombre de décès a Moselle',
                      xaxis={'title': 'Days'},
                      yaxis={'title': 'Number of death'},
                      hovermode='closest')
        }

    return fig
Exemple #13
0
def calculate_benefits(results_df, json_data, fraction_wasted, unit_sell_price, unit_cost, currency_symbol):
	a = datetime.strptime(json_data['simulation_first_datetime'],"%Y-%m-%d")
	b = datetime.strptime(json_data['simulation_last_datetime'],"%Y-%m-%d")
	seconds_between = (b-a).total_seconds()
	days_between = (b-a).days +1
	seconds_in_week = 24*3600*7
	seconds_in_year = 24*3600*365
	months_in_year = 12
	seconds_in_month = seconds_in_year/months_in_year					

	fraction_wasted_array = np.arange(0,31,1)/100.
	percentage_wasted_array = np.arange(0,31,1)
	percentage_wasted_array = [str(int(x))+'%' for x in percentage_wasted_array]

	profit_change_array = []
	weekly_profit_change_array = []
	monthly_profit_change_array = []		


	historical_demand_units_total = json_data['historical_demand_units_total']
	historical_delivered_units_total = int(historical_demand_units_total/(1.-fraction_wasted))
	historical_wasted_units_total = historical_delivered_units_total - historical_demand_units_total
	
	historical_revenue = historical_demand_units_total * unit_sell_price
	historical_cost = (historical_delivered_units_total) * unit_cost
	historical_profit = historical_revenue - historical_cost
	
	
	simulation_satisfied_units_total = json_data['simulation_satisfied_units_total']					
	simulation_wasted_units_total = json_data['simulation_wasted_units_total']
	simulation_delivered_units_total = json_data['simulation_delivered_units_total']
	simulation_leftover_units_total = json_data['simulation_delivered_units_total'] - json_data['simulation_satisfied_units_total'] - json_data['simulation_wasted_units_total']
	
	simulation_revenue = simulation_satisfied_units_total * unit_sell_price
	simulation_cost = (simulation_delivered_units_total - simulation_leftover_units_total) * unit_cost
	simulation_profit = simulation_revenue - simulation_cost
	
	profit_change = simulation_profit - historical_profit
	
	n_weeks_in_simulation = seconds_between/seconds_in_week
	n_months_in_simulation = seconds_between/seconds_in_month

	weekly_benefit = profit_change / n_weeks_in_simulation
	monthly_benefit = profit_change / n_months_in_simulation

	st.write('Deploying the WasteNot Service on this item between ',json_data['simulation_first_datetime'],' & ',
			 json_data['simulation_last_datetime'],' (',days_between,' days) would have generated '+currency_symbol,int(monthly_benefit),'/month of business benefit, assuming historically',
				int(fraction_wasted*100.),'% of delivered units were wasted')


	simulation_satisfied_percentage = 100.*(simulation_satisfied_units_total/historical_demand_units_total)

	hist_kpi = [historical_profit, historical_revenue, historical_cost, json_data['historical_demand_units_total'], json_data['historical_wasted_units_total']]
	simulation_kpi = [simulation_profit, simulation_revenue, simulation_cost, json_data['simulation_satisfied_units_total'], json_data['simulation_wasted_units_total']]
	abs_change_in_kpi = [simulation_kpi[x] - hist_kpi[x] for x in range(len(simulation_kpi))]
	percentage_change_in_kpi = [100.*(simulation_kpi[x] - hist_kpi[x])/hist_kpi[x] for x in range(len(simulation_kpi))]
	percentage_change_in_kpi = [ '%.1f' % elem for elem in percentage_change_in_kpi ]

	if weekly_benefit > 0:
		benefit_colour = 'green'
	if weekly_benefit == 0:
		benefit_colour = 'orange'
	if weekly_benefit < 0:
		benefit_colour = 'red'	
	col1, col2 = st.beta_columns((2,1))
	with col1:
		fig_timeseries = go.Figure()
		fig_timeseries.update_layout(title="Demand vs Delivered Units",     
								 	 paper_bgcolor='rgba(0,0,0,0)',
					 			     plot_bgcolor='rgba(0,0,0,0)')
		fig_timeseries.add_trace(
			go.Line(x=results_df['timestamp_start'], 
				    y=results_df['actual_demand_units_unconstrained'],
				    name="Historical Demand",
				    marker_color='blue'))

		fig_timeseries.add_trace(
			go.Bar(x=results_df['timestamp_start'], 
				   y=results_df['simulation_delivered_units'],
				   name="Simulated Replenishments",
				   marker_color='lightblue'))
		fig_timeseries.update_layout(legend=dict(
			orientation="h",
			yanchor="bottom",
			y=1.02,
			xanchor="right",
			x=1
		))			
		st.plotly_chart(fig_timeseries, use_container_width=True)
		csv = results_df.to_csv(index=False)
		b64 = base64.b64encode(csv.encode()).decode()  # some strings <-> bytes conversions necessary here
		href = f'<a href="data:file/csv;base64,{b64}" download="backcast_timeseries_results.csv">Download Time-Series Results in CSV format</a>'
		st.markdown(href, unsafe_allow_html=True)
			
	with col2:
		fig = go.Figure()
		fig.add_trace(go.Indicator(
			mode = "number",
			value = profit_change,    
			title = {"text": "Business Savings"},    
			number = {'prefix': currency_symbol,
					  'font.color': benefit_colour},
			domain = {'x': [0.0,1.0]
					  , 'y': [0.75, 1.0]
					 }
		))

		fig.add_trace(go.Indicator(
			mode = "delta",
			value = json_data['simulation_wasted_units_total'],
			title = {"text": "Units Wasted"},
			delta = {'reference': json_data['historical_wasted_units_total'], 'relative': True, 'position' : "right",
					 'increasing.color':"red",
					 'decreasing.color':"green",},
			domain = {'x': [0.,1.0]
					  , 'y': [0.45, 0.65]
					 }
		))

		fig.add_trace(go.Indicator(
			mode = "number",
			value = simulation_satisfied_percentage,    
			title = {"text": "Demand Satisfied"},    
			number = {'suffix': '%',
					  'font.color': 'green'},
			domain = {'x': [0.,1.0]
					  , 'y': [0.0, 0.3]
					 }
		))
		


		st.plotly_chart(fig, use_container_width=True)
	
	kpi_df = pd.DataFrame(data={'KPI':['Profit','Revenue','Cost','Satisfied Units','Wasted Units'],
								'Without WasteNot':hist_kpi,
								'With WasteNot':simulation_kpi,
								'Change in KPI':abs_change_in_kpi,
								'% Change in KPI':percentage_change_in_kpi
								})
	st.dataframe(kpi_df)			
	csv = kpi_df.to_csv(index=False)
	b64 = base64.b64encode(csv.encode()).decode()  # some strings <-> bytes conversions necessary here
	href = f'<a href="data:file/csv;base64,{b64}" download="backcast_summary_results.csv">Download Summary Results in CSV format</a>'
	st.markdown(href, unsafe_allow_html=True)

	result_expander = st.beta_expander("Further Results", expanded=False)		
	with result_expander:

		fig_unmet_waste = go.Figure()
		fig_unmet_waste.update_layout(title="Backcast: Wasted & Unmet Units", 
									  legend=dict(orientation="h",
									  yanchor="bottom",
									  y=1.02,
									  xanchor="right",
									  x=1
									  ))
		fig_timeseries.update_layout()			
		
		fig_unmet_waste.add_trace(
			go.Bar(x=results_df['timestamp_start'], 
				   y=results_df['simulation_wasted_units'],
				   name="Wasted Units"))

		fig_unmet_waste.add_trace(
			go.Bar(x=results_df['timestamp_start'], 
				   y=results_df['simulation_unmet_units'],
				   name="Unmet Demand Units"))

		st.plotly_chart(fig_unmet_waste, use_container_width=True)	
		
		for fw in fraction_wasted_array:
			historical_demand_units_total = json_data['historical_demand_units_total']
			historical_delivered_units_total = int(historical_demand_units_total/(1.-fw))
			historical_wasted_units_total = historical_delivered_units_total - historical_demand_units_total
	
			historical_revenue = historical_demand_units_total * unit_sell_price
			historical_cost = (historical_delivered_units_total) * unit_cost
			historical_profit = historical_revenue - historical_cost
	
	
			simulation_satisfied_units_total = json_data['simulation_satisfied_units_total']					
			simulation_wasted_units_total = json_data['simulation_wasted_units_total']
			simulation_delivered_units_total = json_data['simulation_delivered_units_total']
			simulation_leftover_units_total = json_data['simulation_delivered_units_total'] - json_data['simulation_satisfied_units_total'] - json_data['simulation_wasted_units_total']
	
			simulation_revenue = simulation_satisfied_units_total * unit_sell_price
			simulation_cost = (simulation_delivered_units_total - simulation_leftover_units_total) * unit_cost
			simulation_profit = simulation_revenue - simulation_cost
	
			profit_change = simulation_profit - historical_profit
	
			n_weeks_in_simulation = seconds_between/seconds_in_week
			n_months_in_simulation = seconds_between/seconds_in_month

			weekly_benefit = profit_change / n_weeks_in_simulation
			monthly_benefit = profit_change / n_months_in_simulation	
			profit_change_array.append(profit_change)
			weekly_profit_change_array.append(weekly_benefit)
			monthly_profit_change_array.append(monthly_benefit)				
	
		fraction_wasted_colour_array = ['red' if x <=0 else 'green' for x in profit_change_array]
		fig_benefit_by_waste_fraction = go.Figure()
		fig_benefit_by_waste_fraction.update_layout(title="Business Benefit increases if the historical wastage is high", 
													legend=dict(orientation="h",
													yanchor="bottom",
													y=1.02,
													xanchor="right",
													x=1
													))
		fig_benefit_by_waste_fraction.update_traces(marker_colorbar_tickprefix="$", selector=dict(type='bar'))						
		fig_benefit_by_waste_fraction.add_trace(
			go.Bar(x=percentage_wasted_array, 
				   y=monthly_profit_change_array,
				   marker_color = fraction_wasted_colour_array,
				   hovertemplate = '<i>Historical Wastage</i>: %{x}'+'<br><b>Monthly Business Benefit</b>: %{y:$.2f}<br>',
				   name="Monthly Benefit"))
		st.plotly_chart(fig_benefit_by_waste_fraction, use_container_width=True)	
Exemple #14
0
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest'

json = requests.get(url, params=params, headers=headers).json()

cryptodata2 = json['data']

# for x in cryptodata:
#     crydata=[x['symbol'], x['quote']['USD']['price']]
dfline = pd.json_normalize(cryptodata2)
df2 = dfline[[
    'name', 'symbol', 'quote.USD.percent_change_24h', 'quote.USD.last_updated'
]]
fig = go.Figure()  # or any Plotly Express function e.g. px.bar(...)
fig.add_trace(
    go.Line(x=df2['name'],
            y=df2['quote.USD.percent_change_24h'],
            name="24 hour graph ",
            marker_color='rgb(162,162,162)'))

app = dash.Dash(__name__)
server = app.server

#---------------------------------------------------------------
#Taken from https://www.ecdc.europa.eu/en/geographical-distribution-2019-ncov-cases
# df = pd.read_csv("COVID-19-geographic-disbtribution-worldwide-2020-03-29.csv")

# dff = df.groupby('countriesAndTerritories', as_index=False)[['deaths','cases']].sum()
# print (dff[:5])
# df=pd.json_normalize(cryptodata)


# df= pd.DataFrame(cryptodata)
Exemple #15
0
def produce_charts(results_df):
    median = results_df.median()
    sum_data = {
        'Median': median,
        '10th': results_df.quantile(0.10) - median,
        '25th': results_df.quantile(0.25) - median,
        '75th': results_df.quantile(0.75) - median,
        '90th': results_df.quantile(0.90) - median
    }

    results_summary = pd.DataFrame(sum_data).reset_index().rename(
        {'index': 'Policy_Count'}, axis='columns')
    results_summary[
        '10thBC'] = results_summary['10th'] / results_summary['Policy_Count']
    results_summary[
        '25thBC'] = results_summary['25th'] / results_summary['Policy_Count']
    results_summary[
        '75thBC'] = results_summary['75th'] / results_summary['Policy_Count']
    results_summary[
        '90thBC'] = results_summary['90th'] / results_summary['Policy_Count']

    # Plot Results
    figure = go.Figure()
    figure.add_trace(
        go.Line(y=results_summary['10thBC'],
                x=results_summary['Policy_Count'],
                name='10th Percentile'))

    figure.add_trace(
        go.Line(y=results_summary['25thBC'],
                x=results_summary['Policy_Count'],
                name='25th Percentile'))
    figure.add_trace(
        go.Line(y=results_summary['75thBC'],
                x=results_summary['Policy_Count'],
                name='75th Percentile'))
    figure.add_trace(
        go.Line(y=results_summary['90thBC'],
                x=results_summary['Policy_Count'],
                name='90th Percentile'))

    min_bc = np.min(results_summary['10thBC'])
    max_bc = np.max(results_summary['90thBC'])
    figure.add_shape(
        dict(type="line",
             x0=15000,
             y0=min_bc,
             x1=15000,
             y1=max_bc,
             line=dict(color="Red", width=3)))
    figure.add_shape(
        dict(type="line",
             x0=35000,
             y0=min_bc,
             x1=35000,
             y1=max_bc,
             line=dict(color="RoyalBlue", width=3)))
    figure.add_shape(
        dict(type="line",
             x0=65000,
             y0=min_bc,
             x1=65000,
             y1=max_bc,
             line=dict(color="RoyalBlue", width=3)))

    figure.update_layout(title="Plot Title",
                         xaxis_title="Policy Exposure (Years)",
                         yaxis_title="Movement in Burn Cost",
                         annotations=[
                             dict(x=15000,
                                  y=max_bc,
                                  xref="x",
                                  yref="y",
                                  text="Class B",
                                  showarrow=False,
                                  ax=0,
                                  ay=50),
                             dict(x=35000,
                                  y=max_bc,
                                  text="Class A",
                                  showarrow=False,
                                  ax=0,
                                  ay=50),
                             dict(x=65000,
                                  y=max_bc,
                                  text="Class A (Max Exposure)",
                                  showarrow=False,
                                  ax=0,
                                  ay=50)
                         ])

    return figure
Exemple #16
0
import plotly.graph_objects as go
from plotly.subplots import make_subplots
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt

st.title('Amplitude Modulation')

A_m = st.sidebar.slider('Modulator Amplitude', 0, 10, 5)
f_m = st.sidebar.slider('Modulator Frequency', 0.0, 5.0, 1.5)
A_c = st.sidebar.slider('Carrier Amplitude', 0, 10, 5)
f_c = st.sidebar.slider('Carrier Frequency', 0, 100, 80)
modulation_index = st.sidebar.slider('Modulation Index', 0.0, 1.0, 0.5)

t = np.linspace(0, 1, 1000)
carrier = A_c * np.cos(2 * np.pi * f_c * t)
modulator = A_m * np.cos(2 * np.pi * f_m * t)
product = A_c * (1 + modulation_index * np.cos(2 * np.pi * f_m * t)) * np.cos(
    2 * np.pi * f_c * t)

f = make_subplots(rows=3, cols=1)
f.add_trace(go.Line(x=t, y=modulator), row=1, col=1)

f.add_trace(go.Line(x=t, y=carrier), row=2, col=1)

f.add_trace(go.Line(x=t, y=product), row=3, col=1)
st.plotly_chart(f)
Exemple #17
0
def plot_3d(combos, resolution, mem_size, order, coolwarm_cmap=True):
    from matplotlib import cm
    from mpl_toolkits.mplot3d import Axes3D
    import matplotlib as mpl

    use_plotly = True
    if not use_plotly:
        fig = plt.figure()
        ax = fig.gca(projection='3d')

    SOTA = 1.509

    fake_lines = []
    labels = []
    visibility = []
    surfaces = []

    #rax = plt.axes([0.05, 0.3, 0.2, 0.5])
    plotly_objects = []
    for combo in combos:
        vals = np.load(file_name(combo, resolution, mem_size, order))
        X = np.linspace(0.01, MAX_PROB, resolution)
        X, Y = np.meshgrid(X, X)
        means = np.mean(vals, axis=2)

        if use_plotly:
            import plotly.graph_objects as go
            plotly_objects.append(
                go.Surface(z=means, x=X, y=Y, colorscale='RdBu_r'))
            plotly_objects.append(
                go.Scatter3d(z=[means[x, x] + 0.005 for x in range(len(X[0]))],
                             x=X[0],
                             y=X[0],
                             line=go.Line(color="#000000", width=5.),
                             marker=dict(size=0, color='rgba(0,0,0,0)')))

            if True:
                z = np.zeros_like(X)
                z[:] = SOTA
                plotly_objects.append(
                    go.Surface(z=z,
                               x=X,
                               y=Y,
                               opacity=0.5,
                               colorscale=[[0, 'rgb(0,255,0)'],
                                           [1, 'rgb(0,255,0)']]))

            N = 50
            fig = go.Figure(data=plotly_objects)

            fig.update_layout(scene=dict(
                xaxis=dict(title="1-bit Probability - First Round",
                           gridcolor="grey",
                           showbackground=True,
                           zerolinecolor="black",
                           zerolinewidth=10,
                           ticktext=[
                               f'  {i}  '
                               for i in [0, 0.1, 0.2, 0.3, 0.4, 0.5]
                           ],
                           tickvals=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5],
                           ticks='outside',
                           range=[0.00, 0.5]),
                yaxis=dict(title="1-bit Probability - Second Round",
                           gridcolor="grey",
                           showbackground=True,
                           zerolinecolor="black",
                           zerolinewidth=10,
                           ticktext=[
                               f'  {i}  '
                               for i in [0, 0.1, 0.2, 0.3, 0.4, 0.5]
                           ],
                           tickvals=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5],
                           ticks='outside',
                           range=[0.00, 0.5]),
                zaxis=dict(
                    title="Compression Ratio",
                    gridcolor="grey",
                    showbackground=True,
                    zerolinecolor="white",
                    zerolinewidth=10,
                    ticks='outside',
                ),
            ),
                              scene_aspectmode='cube',
                              font=dict(size=17),
                              margin=dict(r=10, l=10, b=10, t=10))
            '''fig.update_layout(scene=dict(
                xaxis_title="1-bit Probability - First Round",
                yaxis_title="1-bit Probability - Second Round",
                zaxis_title="Compression Ratio"),
                scene_aspectmode='cube',
                xaxis_gridcolor='rgb(0,255,0)',
                yaxis_gridcolor='rgb(0,255,0)',
                xaxis=dict(
                    gridcolor="white",
                    zerolinecolor="white", ),
                yaxis=dict(
                    gridcolor="white",
                    zerolinecolor="white"),
                

            )'''
            fig.show()
        else:

            SOTA_z = np.empty_like(means)
            SOTA_z[:] = SOTA

            #surf.set_sort_zpos(1)
            SOTA_z_parital = SOTA_z.copy()
            SOTA_z_parital[means < SOTA] = np.nan
            SOTA_z[~(means < SOTA)] = np.nan
            surf3 = ax.plot_wireframe(X,
                                      Y,
                                      SOTA_z_parital,
                                      rstride=10,
                                      cstride=10,
                                      zorder=20,
                                      color='green')
            # surf2.set_sort_zpos(0)

            ax.plot(X[0],
                    X[0], [means[x, x] for x in range(len(X[0]))],
                    lw=5,
                    c='black',
                    zorder=10)

            surf = ax.plot_surface(X,
                                   Y,
                                   means,
                                   visible=True,
                                   cmap=cm.coolwarm if coolwarm_cmap else None,
                                   linewidth=0,
                                   zorder=2)

            import matplotlib.cm as cm
            m = cm.ScalarMappable(cmap=cm.coolwarm)
            m.set_array(means)
            plt.colorbar(m)

            surf2 = ax.plot_wireframe(X,
                                      Y,
                                      SOTA_z,
                                      rstride=10,
                                      cstride=10,
                                      zorder=20,
                                      color='green')

            surfaces.append(surf)
            labels.append(combinations.name(combo))
            visibility.append(True)

    if not use_plotly:

        ax.set_xlabel('1-bit Probability - First Round')
        ax.set_ylabel('1-bit Probability - Second Round')
        ax.set_zlabel('Compression Ratio')
        plt.xlim(0.02, 0.5)
        plt.ylim(0.02, 0.5)

        if False:
            if coolwarm_cmap:
                fig.colorbar(surf)

            check = CheckButtons(rax, labels, visibility)

            ax.legend(fake_lines, labels)

            def func(label):
                index = labels.index(label)
                surfaces[index].set_visible(not surfaces[index].get_visible())
                plt.draw()

            check.on_clicked(func)

        plt.show()
Exemple #18
0
    go.Scatter(x=weekends['x'],
               y=weekends['y'],
               mode='markers',
               name='Weekends',
               marker=dict(color='green'),
               visible='legendonly'))
fig.add_trace(
    go.Scatter(x=mondays['x'],
               y=mondays['y'],
               mode='markers',
               name='Mondays',
               marker=dict(color='blue'),
               visible='legendonly'))
fig.add_trace(
    go.Line(x=df['x'],
            y=df['moving_avg'],
            name='All Days moving avg',
            line=dict(color='black', dash='dash')))
fig.add_trace(
    go.Line(x=weekends['x'],
            y=weekends['moving_avg'],
            name='Weekends moving avg',
            line=dict(color='green', dash='dash')))
fig.add_trace(
    go.Line(x=mondays['x'],
            y=mondays['moving_avg'],
            name='Mondays moving avg',
            line=dict(color='blue', dash='dash')))
fig.update_layout(
    title="How happy were redditors on each day of 2019?",
    xaxis_title="Month",
    yaxis_title="Average Happiness /10",
Exemple #19
0
#################
# Chart w/ Overlay
fig = make_subplots(specs=[[{"secondary_y": True}]])
i=0
for col in ["v_upset", "upset", "v_happy","happy"]:
    # Add traces
    fig.add_trace(
        go.Bar(x=daily_counts["day"], y=daily_counts[col], name=col+" count",
               marker_color = colors[i]),
        secondary_y=False,
    )
    i+=1

fig.add_trace(
    go.Line(x=df_stock["day"], y=df_stock['PLTR'], name="PLTR", marker_color ='black'),
    secondary_y=True,
)

# Add figure title
fig.update_layout(
    title_text="Sentiment and Stock Price Overview",barmode='relative'
)

# Set x-axis title
fig.update_xaxes(title_text="Date")

# Set y-axes titles
fig.update_yaxes(title_text="<b>Count</b>", secondary_y=False)
fig.update_yaxes(title_text="<b>Price (USD)</b>", secondary_y=True)
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt

st.title('Frequency Modulation')

A_m = st.sidebar.slider('Modulator Amplitude', 0, 10, 5)
f_m = st.sidebar.slider('Modulator Frequency', 0, 30, 5)
A_c = st.sidebar.slider('Carrier Amplitude', 0, 10, 5)
f_c = st.sidebar.slider('Carrier Frequency', 0, 50, 30)
modulation_index = st.sidebar.slider('Modulation Index', 0.0, 5.0, 1.5)

t = np.linspace(0, 1, 1000)
carrier = A_c*np.cos(2*np.pi*f_c*t)
modulator = A_m*np.cos(2*np.pi*f_m*t)
product = A_c*np.cos(2*np.pi*f_c*t + modulation_index*np.sin(2*np.pi*f_m*t))

f = make_subplots(rows=3, cols=1)
f.add_trace(
    go.Line(x=t, y=modulator), row=1, col=1
)

f.add_trace(
    go.Line(x=t, y=carrier), row=2, col=1
)

f.add_trace(
    go.Line(x=t, y=product), row=3, col=1
)
st.plotly_chart(f)
Exemple #21
0
A_m = st.sidebar.slider('Message Amplitude', 0, 10, 5)
f_m1 = st.sidebar.slider('Message1 Frequency', 0.0, 5.0, 2.0)
f_m2 = st.sidebar.slider('Message2 Frequency', 0.0, 10.0, 8.0)
A_c = st.sidebar.slider('Carrier Amplitude', 0, 10, 5)
f_c = st.sidebar.slider('Carrier Frequency', 0, 100, 80)
modulation_index = st.sidebar.slider('Modulation Index', 0.0, 1.0, 0.5)

t = np.linspace(0, 1, 1000)
c_t = np.linspace(0, 1, 500)

carrier = A_c * np.cos(2 * np.pi * f_c * t)
carrier2 = A_c * np.sin(2 * np.pi * f_c * t)
message1 = A_m * np.sin(2 * np.pi * f_m1 * t)
message2 = A_m * np.sin(2 * np.pi * f_m2 * t)
p1 = message1 * carrier
p2 = message2 * carrier2
product = p1 + p2

f = make_subplots(rows=4, cols=1)
f.add_trace(go.Line(x=t, y=message1, name="Message Signal 1"), row=1, col=1)

f.add_trace(go.Line(x=t, y=message2, name="Message Signal 2"), row=2, col=1)

f.add_trace(go.Line(x=c_t, y=carrier, name="Carrier Signal"), row=3, col=1)

f.add_trace(go.Line(x=c_t, y=product, name="Generated QAM"), row=4, col=1)
f.update_layout(width=800, height=600)

st.plotly_chart(f)
Exemple #22
0
    1061778.0, 847866.0, 621884.0, 387050.0, 146706.0, -95726.0, -336795.0,
    -573070.0, -801188.0, -1017901.0, -1220124.0, -1404979.0, -1569835.0,
    -1712344.0, -1830478.0, -1922556.0, -1987267.0, -2023689.0, -2031305.0,
    -2010005.0, -1960093.0, -1882280.0, -1777673.0, -1647761.0, -1494394.0,
    -1319754.0, -1126328.0, -916869.0, -694358.0, -461964.0, -222993.0,
    19152.0, 261024.0, 499181.0, 730232.0, 950888.0, 1158009.0, 1348645.0,
    1520084.0, 1669885.0, 1795915.0, 1896381.0, 1969852.0, 2015283.0,
    2032027.0, 2019845.0, 1978911.0, 1909808.0, 1813519.0, 1691415.0,
    1545234.0, 1377057.0, 1189278.0, 984569.0, 765846.0, 536221.0, 298963.0,
    57449.0, -184882.0, -424582.0, -658238.0, -882524.0, -1094248.0,
    -1290395.0, -1468173.0, -1625053.0, -1758800.0, -1867511.0, -1949638.0,
    -2004013.0, -2029861.0, -2026814.0, -1994916.0, -1934621.0, -1846787.0,
    -1732664.0, -1593878.0, -1432402.0, -1250537.0, -1050871.0, -836245.0,
    -609716.0, -374508.0, -133969.0, 108478.0, 349380.0, 585309.0, 812906.0,
    1028931.0, 1230310.0, 1414176.0, 1577911.0, 1719185.0, 1835987.0,
    1926654.0, 1989895.0, 2024811.0, 2030904.0, 2008087.0, 1956686.0,
    1877431.0, 1771452.0, 1640256.0, 1485712.0, 1310019.0, 1115679.0, 905456.0,
    682345.0, 449521.0, 210298.0, -31919.0, -273681.0, -511548.0, -742133.0,
    -962153.0, -1168478.0, -1358169.0, -1528528.0, -1677128.0, -1801854.0,
    -1900932.0, -1972950.0, -2016883.0, -2032107.0, -2018404.0, -1975969.0,
    -1905407.0, -1807722.0, -1684304.0, -1536911.0, -1367640.0, -1178901.0,
    -973381.0, -754004.0, -523895.0, -286328.0, -44685.0, 197594.0, 437060.0,
    670305.0, 894008.0, 1104985.0, 1300233.0, 1476972.0, 1632687.0, 1765161.0,
    1872508.0, 1953200.0, 2006090.0, 2030422.0, 2025853.0, 1992445.0,
    1930676.0, 1841423.0, 1725959.0, 1585926.0, 1423317.0, 1240448.0,
    1039922.0, 824592.0, 597524.0, 361951.0
]

fig = go.Figure(data=[go.Line(x=list(np.arange(0.2, 100, 0.2)), y=fifteens)])
fig.show()
rholist = []
drholist = []
rhofig = go.Figure()
drhofig = go.Figure()
for index, row in Summary.iterrows():
    r = np.linspace(0, row['Distance (kpc)'] * 1000,
                    1000)  # Radius units for bayestar are pc.
    rho, drho = ComputeDustLine(r, row.lii, row.bii)
    st.write(
        f"E(B-V) for {row['Source Name']} at distance {row['Distance (kpc)']} kpc, is {np.max(rho):0.3g}."
    )
    Summary.loc[index, 'E(B-V)'] = np.max(rho)
    rlist.append(rho)
    rholist.append(rho)
    drholist.append(drho)
    rhofig.add_trace(go.Line(x=r, y=rho, name=row['Source Name']))
    drhofig.add_trace(go.Line(x=r, y=drho, name=row['Source Name']))
st.write(Summary)

# Add the total column density to the dataframe.
rho = np.max(rholist, axis=1)
Summary['rho'] = rho

rhofig.update_layout(
    title_text='E(B-V) as a function of distance to X-ray sources.',
    xaxis_title='parsec',
    yaxis_title='E(B-V)')
drhofig.update_layout(title_text='d(E(B-V))/dr, with r in parsec.',
                      xaxis_title='parsec',
                      yaxis_title='dE(B-V)/dr')
st.write(rhofig)
Exemple #24
0
def update_figure(sparam, center, span, window, mode):
    """
    Update figures given a change in s-parameter of interest, or
    gate parameters
    """

    if window == "kaiser":
        window = ("kaiser", 6)
    oneport = dut.__getattribute__(sparam)
    gated = oneport.time_gate(center=center, span=span, window=window, mode=mode)

    # time
    time_fig = go.Figure()
    time_fig.add_trace(
        go.Line(
            x=freq.t_ns, y=oneport.s_time_db.flatten(), line_color="#204a87", name="OG"
        )
    )

    time_fig.add_trace(go.Line(x=freq.t_ns, y=gated.s_time_db.flatten(), name="gated"))
    dat = oneport.s_time_db.flatten()
    span_height = (dat.min() * 1.5, dat.max() * 0.5)
    time_fig.update_layout(
        shapes=[
            dict(
                type="rect",
                xref="x",
                yref="y",
                x0=center - span / 2,
                y0=span_height[0],
                x1=center + span / 2,
                y1=span_height[1],
                fillcolor="lightgray",
                opacity=0.8,
                line_width=0,
                layer="below",
            )
        ]
    )

    time_fig.update_layout(
        legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01),
        margin=dict(l=20, r=20, t=40, b=20),
        title="Time Domain",
        xaxis_title="Time (ns)",
        yaxis_title="Magnitude (dB)",
        yaxis_range=(-80, 0),
    )

    # frequency
    freq_fig = go.Figure()
    freq_fig.add_trace(
        go.Line(
            x=freq.f_scaled, y=oneport.s_db.flatten(), name="OG", line_color="#204a87"
        )
    )

    freq_fig.add_trace(go.Line(x=freq.f_scaled, y=gated.s_db.flatten(), name="gated"))

    freq_fig.update_layout(
        legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01),
        margin=dict(l=20, r=20, t=40, b=20),
        title="Frequency",
        xaxis_title="Frequency (%s)" % dut.frequency.unit,
        yaxis_title="Magnitude (dB)",
        yaxis_range=(-60, 10),
    )
    return time_fig, freq_fig
Exemple #25
0
fig = go.Figure([go.Bar(x=salary_dist.index, y=salary_dist, marker_color='#5f4b8b')])

fig.update_layout(title="Salary Distribtuion ($USD)")
fig.show()
degree_order = ['No formal education past high school',
'Some college/university study without earning a bachelor’s degree',
'Bachelor’s degree',
'Master’s degree',
'Doctoral degree',
'Professional degree']

salary_degree = salary_career.groupby('Q4')['Q10'].value_counts().unstack().fillna(0)[salary_order]
fig = go.Figure()

for i in degree_order:
    fig.add_trace(go.Line(x=salary_order, y=salary_degree.loc[i], name=i ))

fig.update_layout(title="Salary Distribtuion by Educational ($USD)")
fig.show()
fig = go.Figure()

for i in degree_order:
    fig.add_trace(go.Line(x=salary_order, y=salary_degree.loc[i] / sum(salary_degree.loc[i] ), name=i ))

fig.update_layout(title="Salary Distribtuion by Educational / Ratio ($USD)")
fig.show()
salary_est = [500, 1500, 2500, 3500, 4500, 6250, 8750, 12500, 17500, 22500, 27500, 35000, 45000, 55000, 65000, 75000, 85000, 95000, 112500, 137500, 175000, 225000, 275000, 400000, 500000]

tmp_dict = dict()
for a, b in zip(salary_order, salary_est):
    tmp_dict.update({a:b})
# India
time_series_india = time_series[' Country'] == ('India')
time_series_india = time_series[time_series_india]

# Russia
time_series_russia = time_series[' Country'] == ('Russia')
time_series_russia = time_series[time_series_russia]

# Peru
time_series_peru = time_series[' Country'] == ('Peru')
time_series_peru = time_series[time_series_peru]
fig15 = go.Figure()

fig15.add_trace(
    go.Line(x=time_series_us['Date_reported'],
            y=time_series_us[' Cumulative_cases'],
            name='USA'))
fig15.add_trace(
    go.Line(x=time_series_brazil['Date_reported'],
            y=time_series_brazil[' Cumulative_cases'],
            name='Brazil'))
fig15.add_trace(
    go.Line(x=time_series_india['Date_reported'],
            y=time_series_india[' Cumulative_cases'],
            name='India'))
fig15.add_trace(
    go.Line(x=time_series_russia['Date_reported'],
            y=time_series_russia[' Cumulative_cases'],
            name='Russia'))
fig15.add_trace(
    go.Line(x=time_series_peru['Date_reported'],
Exemple #27
0
                     marker=dict(color="Red"),
                     showlegend=True),
              row=1,
              col=4)

fig.add_trace(go.Bar(name="Credit",
                     x=df_deposit_withdrawl["Txn Date"],
                     y=df_deposit_withdrawl["Credit"],
                     marker=dict(color="Green"),
                     showlegend=True),
              row=1,
              col=4)

fig.add_trace(go.Line(name="Balance",
                      x=df_balance["Txn Date"],
                      y=df_balance["Balance"],
                      marker=dict(color="Blue"),
                      showlegend=True),
              row=4,
              col=4)

fig.add_trace(go.Table(
    columnwidth=[0.8, 0.47, 0.48, 0.60],
    header=dict(
        values=['Txn Date', 'Debit(D)', 'Credit(C)', 'Gross Income(C - D)'],
        fill=dict(color='#C2D4FF'),
    ),
    cells=dict(
        values=[
            df_deposit_withdrawl[k].tolist()
            for k in df_deposit_withdrawl.columns
def home():
    # chosen values
    country = request.args.get('country')
    status = request.args.get('status')
    graph = request.args.get('graph')
    country_1 = request.args.get('country_1')
    country_2 = request.args.get('country_2')
    status_2 = request.args.get('status_2')
    chart = request.args.get('chart')
    country_chart = request.args.get('country_chart')
    date = request.args.get('date')
    # if user has chosen a value
    if status and country and graph:
        # request for the given data
        result = req.get('https://api.covid19api.com/total/country/' +
                         country + '/status/' + status)
        # prepare the X,Y of the graph
        dates = []
        cases = []
        for inADay in result.json():
            dates.append(inADay['Date'])
            cases.append(inADay['Cases'])
        # show the graph
        if graph == 'Line':
            (go.Figure(data=[go.Line(x=dates, y=cases)])).show()
        elif graph == 'Bars':
            (go.Figure(data=[go.Bar(x=dates, y=cases)])).show()

    elif country_chart and chart == "R":
        if country_chart == "World":
            days = []
            worlddays = []
            result = req.get(
                'https://pomber.github.io/covid19/timeseries.json')
            result = result.json()
            #        dates= []
            #        for date in result['Afghanistan']:
            #            dates.append(result['Afghanistan']['date'])
            for day in range(1, len(result['Afghanistan'])):
                worldcases = 0
                for country in result:
                    daily = result[country][day]['confirmed'] - result[
                        country][day - 1]['confirmed']
                    worldcases += daily
                worlddays.append(worldcases)
                days.append(day)
            for i in range(len(worlddays)):
                worlddays[i] = math.log(worlddays[i], 2)
            days = pylab.array(days)
            worlddays = pylab.array(worlddays)
            if date == "all":
                A, B = pylab.polyfit(days, worlddays, 1)
                worlddays_predicted = A * pylab.array(days) + B
                virusworldR = 2**(A * 6)
                fig = go.Figure()
                fig.add_trace(
                    go.Scatter(x=days,
                               y=worlddays,
                               name='log(world cases)',
                               mode='markers',
                               marker_color='red'))
                fig.add_trace(
                    go.Scatter(x=days,
                               y=worlddays_predicted,
                               name='log(world cases predicted)',
                               mode='markers',
                               marker_color='green'))
                fig.update_layout(title=virusworldR,
                                  xaxis_title="days",
                                  yaxis_title="log(cases)",
                                  font=dict(family="Courier New, monospace",
                                            size=18,
                                            color="#7f7f7f"))
                print(r2_score(worlddays_predicted, worlddays))
                fig.show()
            elif date == 'daily':
                two_weeks_cases = worlddays[-14:len(worlddays)]
                two_weeks = days[-14:len(days)]
                A, B = pylab.polyfit(two_weeks, two_weeks_cases, 1)
                two_weeks_cases_predicted = A * pylab.array(two_weeks) + B
                R_daily = 2**(A * 6)
                fig = go.Figure()
                fig.add_trace(
                    go.Scatter(x=two_weeks,
                               y=two_weeks_cases,
                               name='log(world cases)',
                               mode='markers',
                               marker_color='red'))
                fig.add_trace(
                    go.Scatter(x=two_weeks,
                               y=two_weeks_cases_predicted,
                               name='log(world cases predicted)',
                               mode='markers',
                               marker_color='green'))
                fig.update_layout(title=R_daily,
                                  xaxis_title="days",
                                  yaxis_title="log(cases)",
                                  font=dict(family="Courier New, monospace",
                                            size=18,
                                            color="#7f7f7f"))
                #            print(r2_score(R_daily, two_weeks_cases))
                fig.show()

        else:
            payload = {'country': country_chart}
            URL = 'https://api.statworx.com/covid'
            result = req.request("POST", url=URL, data=json.dumps(payload))
            discrete_cases = result.json()['cases']
            logn_t = []
            days_array = []
            firstday = 0
            for d in range(0, len(discrete_cases)):
                if discrete_cases[d] != 0:
                    firstday = d
                    break
            for i in range(firstday, len(discrete_cases)):
                if discrete_cases[i] == 0:
                    logn_t.append(0)
                else:
                    logn_t.append(int(math.log(float(discrete_cases[i]), 2)))
                days_array.append(i)
            dates = pylab.array(days_array)
            logn_t = pylab.array(logn_t)
            if date == "all":
                a, b = pylab.polyfit(dates, logn_t, 1)
                logn_t_predicted = a * pylab.array(dates) + b
                #slope
                virus_reproduction = 2**(a * 6)
                fig = go.Figure()
                fig.add_trace(
                    go.Scatter(x=dates,
                               y=logn_t,
                               name='log(cases)',
                               mode='markers',
                               marker_color='red'))
                fig.add_trace(
                    go.Scatter(x=dates,
                               y=logn_t_predicted,
                               name='log(cases predictec)',
                               mode='markers',
                               marker_color='green'))
                fig.update_layout(title=virus_reproduction,
                                  xaxis_title="days",
                                  yaxis_title="log(cases)",
                                  font=dict(family="Courier New, monospace",
                                            size=18,
                                            color="#7f7f7f"))
                print(r2_score(logn_t_predicted, logn_t))
                fig.show()
            elif date == 'daily':
                two_weeks_cases = logn_t[-14:len(logn_t)]
                two_weeks = dates[-14:len(dates)]
                A, B = pylab.polyfit(two_weeks, two_weeks_cases, 1)
                two_weeks_cases_predicted = A * pylab.array(two_weeks) + B
                R_daily = 2**(A * 6)
                fig = go.Figure()
                fig.add_trace(
                    go.Scatter(x=two_weeks,
                               y=two_weeks_cases,
                               name='log(world cases)',
                               mode='markers',
                               marker_color='red'))
                fig.add_trace(
                    go.Scatter(x=two_weeks,
                               y=two_weeks_cases_predicted,
                               name='log(world cases predicted)',
                               mode='markers',
                               marker_color='green'))
                fig.update_layout(title=R_daily,
                                  xaxis_title="days",
                                  yaxis_title="log(cases)",
                                  font=dict(family="Courier New, monospace",
                                            size=18,
                                            color="#7f7f7f"))
                #            print(r2_score(R_daily, two_weeks_cases))
                fig.show()

    elif country_1 and country_2 and status_2:
        result = req.get('https://api.covid19api.com/total/country/' +
                         country_1 + '/status/' + status_2)
        # prepare the X,Y of the graph
        dates = []
        cases = []
        for inADay in result.json():
            dates.append(inADay['Date'])
            cases.append(inADay['Cases'])
        fig = go.Figure()
        fig.add_trace(
            go.Bar(x=dates, y=cases, name=country_1, marker_color='red'))
        result = req.get('https://api.covid19api.com/total/country/' +
                         country_2 + '/status/' + status_2)
        # prepare the X,Y of the graph
        dates = []
        cases = []
        for inADay in result.json():
            dates.append(inADay['Date'])
            cases.append(inADay['Cases'])

        fig.add_trace(
            go.Bar(x=dates, y=cases, name=country_2, marker_color='green'))
        # Here we modify the tickangle of the xaxis, resulting in rotated labels.
        fig.update_layout(barmode='group', xaxis_tickangle=-45)
        fig.show()
    elif country == '' or status == '' or graph == '' or country_1 == '' or country_2 == '' or status_2 == '':
        error_message = {
            'country': country,
            'status': status,
            'graph': graph,
            'country_1': country_1,
            'country_2': country_2,
            'status_2': status_2,
        }
        return render_template("Index.html",
                               countries=response,
                               errorMessage=error_message)

    return render_template("Index.html", countries=response, errorMessage={})
Exemple #29
0
spy_covid = spy_covid.dropna()

news_count = pd.read_csv('./NYTnews_keyword_monthly.csv', index_col=0)
news_count['date'] = '2020-' + news_count['month'].astype(str) + '-15'
news_count['date'] = pd.to_datetime(news_count['date'])

spy_covid_correlation_all = spy_covid.corr()['COVID_search'][0] * 100
spy_covid_correlation_after_march = spy_covid['2020-03':].corr(
)['COVID_search'][0] * 100

fig3 = make_subplots(specs=[[{"secondary_y": True}]])

fig3.add_trace(
    go.Line(x=spy_covid.index,
            y=spy_covid['spy_return%'],
            name="spy return%",
            mode="markers+lines",
            marker_symbol="star"),
    secondary_y=False,
)

fig3.add_trace(
    go.Line(x=spy_covid.index,
            y=spy_covid['COVID_search'],
            name="covid search",
            mode="markers+lines",
            marker_symbol="star"),
    secondary_y=True,
)

fig3.add_trace(go.Bar(x=news_count.date,
Exemple #30
0
def state_details(request):

    state_name = request.POST["state"]

    check = False

    ind_dist = pd.read_json('https://api.covid19india.org/state_district_wise.json')
    for i in ind_dist.columns:
        if state_name.lower() in i.lower():
            check = True
            state_name = i
            temp_dist = pd.DataFrame(ind_dist[i].iloc[0])
            temp_dist.drop(['notes', 'delta'], inplace = True)
            temp_dist = temp_dist.transpose()
    
    if check:
        temp_dist.reset_index(inplace = True)
        temp_dist.rename(columns={'index':'Name of District', 'active':'Active','confirmed':'Confirmed cases', 
                                         'deceased':'Deaths', 'recovered':'Discharged'}, inplace = True)

        temp_dist = temp_dist.sort_values(by='Confirmed cases', ascending = False)

        rows = []
        for i in range(len(temp_dist)):
            inn = []
            inn.append(temp_dist.iloc[i,0])
            inn.append(temp_dist.iloc[i,2])
            inn.append(temp_dist.iloc[i,4])
            inn.append(temp_dist.iloc[i,3])
            rows.append(inn)


        fig_dist = px.bar(temp_dist, x = 'Name of District', y = 'Confirmed cases', hover_data=['Active', 'Discharged', 'Deaths'],
                template = 'plotly_dark')
        fig_dist = opy.plot(fig_dist, auto_open=False, output_type='div')
        fig_dist

        raw_daily = pd.read_json('https://api.rootnet.in/covid19-in/stats/history')

        regional_daily = raw_daily.iloc[0,1]['regional']
        regional_daily = pd.DataFrame(regional_daily)
        regional_daily['Date'] = raw_daily.iloc[0,1]['day']
        for j in range(1, len(raw_daily)):
            temp_df = raw_daily.iloc[j,1]['regional']
            temp_df = pd.DataFrame(temp_df)
            temp_df['Date'] = raw_daily.iloc[j,1]['day']
            regional_daily = pd.concat([regional_daily, temp_df])

        regional_daily.rename(columns = {'totalConfirmed':'Total Confirmed Cases', 'discharged':'Discharged', 'deaths':'Deaths', 'loc': 'Name of State / UT'}, inplace = True)
        regional_daily.drop(['confirmedCasesIndian', 'confirmedCasesForeign'], axis = 1, inplace = True)
        regional_daily = regional_daily[['Date', 'Name of State / UT', 'Total Confirmed Cases', 'Discharged', 'Deaths']]

        state_df = regional_daily[regional_daily['Name of State / UT'] == state_name]

        Date = state_df.iloc[-1,0]
        Total = int(state_df.iloc[-1,2])
        Discharged = int(state_df.iloc[-1,3])
        Deaths = int(state_df.iloc[-1,4])
        Active = int(Total - (Discharged + Deaths))

        fig_all = go.Figure()
        fig_all.add_trace(go.Line(x = state_df['Date'], y = state_df['Total Confirmed Cases'], mode = 'markers+lines', name = 'Daily Confirmed Cases'))
        fig_all.add_trace(go.Line(x = state_df['Date'], y = state_df['Deaths'], mode = 'markers+lines', name = 'Daily Deaths'))
        fig_all.add_trace(go.Line(x = state_df['Date'], y = state_df['Discharged'], mode = 'markers+lines', name = 'Daily Cured Cases'))
        fig_all.update_layout(title = '{} Daily Confirmed Cases vs Recoveries vs Deaths'.format(state_name), xaxis_title="Date", yaxis_title="Count", template = 'plotly_dark')
        fig_all = opy.plot(fig_all, auto_open=False, output_type='div')

        fig = [fig_dist, fig_all]

        return render(request, 'india_state.html', {'check': check, 'State': state_name, 'Date': Date, 'Total': Total, 'Active': Active, 'Discharged': Discharged,
                    'Deaths': Deaths, 'rows': rows, 'fig':fig})    

    else:
        return render(request, 'india_state.html', {'check': check})