Exemplo n.º 1
0
def render_js_py():
    with st.echo("below"):
        st.markdown("""Overwrite chart colors with JS. 
        Under 50 : red. Between 50 - 100 : blue. Over 100 : green""")
        color_function = """
                function (params) {
                    if (params.value > 0 && params.value < 50) {
                        return 'red';
                    } else if (params.value > 50 && params.value < 100) {
                        return 'blue';
                    }
                    return 'green';
                }
                """
        c = (Bar().add_xaxis(Faker.choose()).add_yaxis(
            "商家A",
            Faker.values(),
            itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_function)),
        ).add_yaxis(
            "商家B",
            Faker.values(),
            itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_function)),
        ).add_yaxis(
            "商家C",
            Faker.values(),
            itemstyle_opts=opts.ItemStyleOpts(color=JsCode(color_function)),
        ).set_global_opts(title_opts=opts.TitleOpts(title="Bar-自定义柱状颜色")))
        st_pyecharts(c)
def calendar_plot(df):
    """[summary]

    Parameters
    ----------
    df : [type]
        [description]
    """

    #begin = datetime.date(2020, 2, 9)
    #end = datetime.date(2020,11,11)
    begin = df.Fecha.min()
    end = df.Fecha.max()

    c = (
        Calendar(init_opts=opts.InitOpts(width="1000px", height="300px"))
        .add(
            series_name="",
            yaxis_data=[[str(x),y] for x,y in zip(df.Fecha, df['Nuevos casos'])],
            calendar_opts=opts.CalendarOpts(
                pos_top="120",
                pos_left="30",
                pos_right="30",
                range_="2020",
                yearlabel_opts=opts.CalendarYearLabelOpts(is_show=False),
            ),
        )
        .set_global_opts(
            title_opts=opts.TitleOpts(pos_top="20", pos_left="center", title="2020: Evolución del Covid19 en Andalucía"),
            visualmap_opts=opts.VisualMapOpts(
                max_=df['Nuevos casos'].max(), min_=0, orient="horizontal", is_piecewise=False
            ),
        )
    )   
    st_pyecharts(c)
Exemplo n.º 3
0
def main():
    st.sidebar.title("Kalkula")
    action = st.sidebar.selectbox("Navigation", ["Productivity", "Planning", "Progress Report", "Chart"])
    if action == "Productivity":
        st.title("Productivity")
        report()
    elif action == "Planning":
        st.title("Planning")
        planning()
    elif action == "Progress Report":
        st.title("Progress Report")
        progress()
    elif action == "Chart":
        st.title("Sample Chart")
        b = (
            Bar()
            .add_xaxis(["Microsoft", "Amazon", "IBM", "Oracle", "Google", "Alibaba"])
            .add_yaxis(
                "2017-2018 Revenue in (billion $)", [21.2, 20.4, 10.3, 6.08, 4, 2.2]
            )
            .set_global_opts(
                title_opts=opts.TitleOpts(
                    title="Top cloud providers 2018", subtitle="2017-2018 Revenue"
                )
            )
        )
        st_pyecharts(b)
        st_echarts({"xAxis": {
            "type": "category",
            "data": ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"],
        },
        "yAxis": { "type": "value" },
        "series": [
            {"data": [820, 932, 901, 934, 1290, 1330, 1320], "type": "bar" }
        ],})
Exemplo n.º 4
0
def render_liquid_py():
    with st.echo("below"):
        c = (
            Liquid()
            .add("lq", [0.6, 0.7])
            .set_global_opts(title_opts=opts.TitleOpts(title="Liquid-基本示例"))
        )
        st_pyecharts(c)
Exemplo n.º 5
0
def render_basic_line_chart():
    c = (
        Line()
        .add_xaxis(Faker.choose())
        .add_yaxis("商家A", Faker.values())
        .add_yaxis("商家B", Faker.values())
        .set_global_opts(title_opts=opts.TitleOpts(title="Line-基本示例"))
    )
    st_pyecharts(c)
Exemplo n.º 6
0
def render_vertical_datazoom_py():
    with st.echo("below"):
        c = (Bar().add_xaxis(Faker.days_attrs).add_yaxis(
            "商家A", Faker.days_values,
            color=Faker.rand_color()).set_global_opts(
                title_opts=opts.TitleOpts(title="Bar-DataZoom(slider-垂直)"),
                datazoom_opts=opts.DataZoomOpts(orient="vertical"),
            ))
        st_pyecharts(c, height="400px")
Exemplo n.º 7
0
def render_filter_legend_py():
    with st.echo("below"):
        c = (Bar(init_opts=opts.InitOpts(animation_opts=opts.AnimationOpts(
            animation_delay=1000, animation_easing="elasticOut"))).add_xaxis(
                Faker.choose()).add_yaxis("商家A", Faker.values()).add_yaxis(
                    "商家B",
                    Faker.values()).set_global_opts(title_opts=opts.TitleOpts(
                        title="Bar-动画配置基本示例", subtitle="我是副标题")))
        st_pyecharts(c)
Exemplo n.º 8
0
def render_map():
    with open("./data/countries.geo.json", "r") as f:
        map = st_Map("world", json.loads(f.read()),)
    c = Map(init_opts=opts.InitOpts(bg_color="white"))
    c.add("Demo", [list(z) for z in zip(Faker.country, Faker.values())], "world")
    c.set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    c.set_global_opts(
        title_opts=opts.TitleOpts(title="Map world"),
        visualmap_opts=opts.VisualMapOpts(max_=200),
    )
    st_pyecharts(c, map=map, height=500)
Exemplo n.º 9
0
def render_map_py():
    with st.echo("below"):
        g = (Geo().add_schema(maptype="china").add(
            "geo",
            [list(z)
             for z in zip(Faker.provinces, Faker.values())]).set_series_opts(
                 label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                     visualmap_opts=opts.VisualMapOpts(),
                     title_opts=opts.TitleOpts(title="Geo-基本示例"),
                 ))
        st_pyecharts(g)
Exemplo n.º 10
0
def render_timeline_py():
    with st.echo("below"):
        x = Faker.choose()
        tl = Timeline()
        for i in range(2015, 2020):
            bar = (Bar().add_xaxis(x).add_yaxis(
                "商家A", Faker.values()).add_yaxis(
                    "商家B", Faker.values()).set_global_opts(
                        title_opts=opts.TitleOpts("某商店{}年营业额".format(i))))
            tl.add(bar, "{}年".format(i))
        st_pyecharts(tl)
Exemplo n.º 11
0
def render_bar_py():
    with st.echo("below"):
        b = (Bar().add_xaxis([
            "Microsoft", "Amazon", "IBM", "Oracle", "Google", "Alibaba"
        ]).add_yaxis("2017-2018 Revenue in (billion $)",
                     [21.2, 20.4, 10.3, 6.08, 4, 2.2]).set_global_opts(
                         title_opts=opts.TitleOpts(
                             title="Top cloud providers 2018",
                             subtitle="2017-2018 Revenue"),
                         toolbox_opts=opts.ToolboxOpts(),
                     ))
        st_pyecharts(b)
def plot_timeline(df, data1 = 'Nuevos casos', data2 = 'Hospitalizados'):
    """[summary]

    Parameters
    ----------
    df : [type]
        [description]
    data1 : str, optional
        [description], by default 'Nuevos casos'
    data2 : str, optional
        [description], by default 'Hospitalizados'
    """
    tl = Timeline()
    calendar_dict = {
    1:'Ene',
    2:'Feb',
    3:'Mar',
    4:'Abr',
    5:'May',
    6:'Jun',
    7:'Jul',
    8:'Ag',
    9:'Sep',
    10:'Oct',
    11:'Nov',
    12:'Dic'
}
    for i in range(3, df.Mes.max()+1):
        bar = (
            Bar()
            .add_xaxis(pd.unique(df.Territorio).tolist())
            .add_yaxis(data1, df[df.Mes == i][data1].tolist())
            .add_yaxis(data2, df[df.Mes == i][data2].tolist())
            .set_global_opts(
                title_opts=opts.TitleOpts("Covid19 mes a mes"),
                graphic_opts=[
                    opts.GraphicGroup(
                        graphic_item=opts.GraphicItem(
                            rotation=JsCode("Math.PI / 4"),
                            bounding="raw",
                            right=100,
                            bottom=110,
                            z=100,
                        ),
                    )
                ],
            )
        )
        tl.add(bar,calendar_dict[i])
    st_pyecharts(tl)
Exemplo n.º 13
0
def render_randomize_py():
    with st.echo("below"):
        b = (Bar().add_xaxis([
            "Microsoft", "Amazon", "IBM", "Oracle", "Google", "Alibaba"
        ]).add_yaxis("2017-2018 Revenue in (billion $)",
                     random.sample(range(100), 10)).set_global_opts(
                         title_opts=opts.TitleOpts(
                             title="Top cloud providers 2018",
                             subtitle="2017-2018 Revenue"),
                         toolbox_opts=opts.ToolboxOpts(),
                     ))
        st_pyecharts(
            b, key="echarts"
        )  # Add key argument to not remount component at every Streamlit run
        st.button("Randomize data")
Exemplo n.º 14
0
def render_custom_py():
    with st.echo("below"):
        b = (Bar().add_xaxis([
            "Microsoft", "Amazon", "IBM", "Oracle", "Google", "Alibaba"
        ]).add_yaxis(
            "2017-2018 Revenue in (billion $)",
            [21.2, 20.4, 10.3, 6.08, 4, 2.2]).set_global_opts(
                title_opts=opts.TitleOpts(title="Top cloud providers 2018",
                                          subtitle="2017-2018 Revenue")))
        st_pyecharts(b, theme=ThemeType.DARK)

        st_pyecharts(
            b,
            theme={
                "backgroundColor": "#f4cccc",
                "textStyle": {
                    "color": "rgba(255, 0, 0, 0.8)"
                },
            },
        )
Exemplo n.º 15
0
def pyechart_comunidad_bar(df, data1, data2):
    """Plot comparing those two charasteristics.

    Parameters
    ----------
    df : DataFrame
        [description]
    data1 : Series
        Column to plot between "nuevos casos", "hospitalizados", "UCI" y "fallecidos"
    data2 : Series
        Column to plot between "nuevos casos", "hospitalizados", "UCI" y "fallecidos"
    """

    bar = (Bar(init_opts=opts.InitOpts(theme=ThemeType.ESSOS)).add_xaxis([
        'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV'
    ]).add_yaxis(data1, df[data1].tolist()).add_yaxis(
        data2, df[data2].tolist()).set_global_opts(
            title_opts=opts.TitleOpts(
                title="Covid Andalucía",
                subtitle="Datos desde el inicio de la pandemia"),
            xaxis_opts=opts.AxisOpts(splitline_opts=opts.SplitLineOpts(
                is_show=True)),
            yaxis_opts=opts.AxisOpts(splitarea_opts=opts.SplitAreaOpts(
                is_show=True, areastyle_opts=opts.AreaStyleOpts(opacity=0))),
            toolbox_opts=opts.ToolboxOpts(is_show=True,
                                          orient='vertical',
                                          pos_left='95%'),
            datazoom_opts=[
                opts.DataZoomOpts(range_start=10,
                                  range_end=80,
                                  is_zoom_lock=False)
            ],
        ).set_series_opts(
            markpoint_opts=opts.MarkPointOpts(data=[
                opts.MarkPointItem(type_="max", name="MAX"),
                opts.MarkPointItem(type_="min", name="MIN"),
            ]),
            markline_opts=opts.MarkLineOpts(
                data=[opts.MarkLineItem(type_="average", name="AVG")]),
            label_opts=opts.LabelOpts(is_show=False)))
    st_pyecharts(bar)
Exemplo n.º 16
0
def render_liquid():
    with st.echo("below"):
        options = {
            "series": [
                {
                    "type": "liquidFill",
                    "data": [0.5, 0.4, 0.3],
                    "color": ["red", "#0f0", "rgb(0, 0, 255)"],
                    "itemStyle": {"opacity": 0.6},
                    "emphasis": {"itemStyle": {"opacity": 0.9}},
                }
            ]
        }
        st_echarts(options)

        c = (
            Liquid()
            .add("lq", [0.6, 0.7])
            .set_global_opts(title_opts=opts.TitleOpts(title="Liquid-基本示例"))
        )
        st_pyecharts(c)
def main():
    
    html_temp = """
		<div style="background-color:#45637d;padding:10px;border-radius:10px">
		<h1 style="color:white;text-align:center;">A-DAConsultancy</h1>
        <h4 style="color:white;text-align:center;text-decoration: underline">Semi Auto Machine Learning App</h4>
        <em style="color:white;text-align:center; margin-top:33px ">Using Streamlit = 0.78.0+</em>  
		</div>
		"""
    components.html(html_temp, height=300)

    # st.subheader('Semi Auto ML App ')
    # st.text('Using Streamlit == 0.78.0+')

    activities =[ 'EDA', 'Plot', 'Model Building', 'Other Projects','About']
    
    choice =  st.sidebar.selectbox('Select Activity', activities)
    if choice == 'EDA':
        st.subheader('Exploratory data analysis')
        data = getData()
        if data is not None:
            df = pd.read_csv(data)
            st.dataframe(df.head())
            
            if st.checkbox('show shape / Na(s) values'):
                
                col1, col2, col3 = st.beta_columns(3)
                
                col1.success('Shape of dataFrame')
                col1.write(df.shape)
              
                col2.success('Na(s) values')
                col2.write(df.isnull().sum().sum())
                
                
            if st.checkbox(' Show Columns /  Data types  '):
                col1, col2,  = st.beta_columns(2)
                
                col1.success('Show Columns')
                all_columns = df.columns.tolist()
                col1.write(all_columns)
                
                col2.success('Data type')
                col2.write(df.dtypes)
                     
            if st.checkbox('Show Summary'):
                st.write(df.describe())
            
    
            if st.checkbox('Last 5 columns'):
                st.write(df.tail())
        
            if st.checkbox('Pick Columns'):
                selected_columns = st.multiselect('Select Columns', df.columns.tolist())
                new_df = df[selected_columns]
                st.dataframe(new_df) 
                 
            if st.checkbox('Highlight_max'):
                st.dataframe(df.style.highlight_max(axis=0))
            
            if st.checkbox('Transform to table'):
                selected_columns = st.multiselect('Select Columns', df.columns.tolist())
                new_df = df[selected_columns]
                st.table(new_df) 
            
            
    
    elif choice == 'Plot':
        st.subheader('Data visualization')
       
        data = getData()
        if data is not None:
            df = pd.read_csv(data)
            st.dataframe(df.head())
            
        if  st.checkbox('Correlation  with seaborn'):
            if data is not None:
                fig, ax = plt.subplots(figsize=(20,15))
                st.write(sns.heatmap(df.corr(), annot=True))
                st.pyplot(fig) 
            else:
                st.warning('NO DATA')
        
        if  st.checkbox('Pairplot'):
            if data is not None:
                fig, ax = plt.subplots(figsize=(20,15))
                selected_columns = st.multiselect('Select Columns', df.columns)
                st.write(sns.pairplot(df[selected_columns]))
                st.pyplot(fig) 
            else:
                st.warning('NO DATA')
                      
        if  st.checkbox('Pie Chart'):
            if data is not None:
                pie = pieChart(df)        
                st.write(st_pyecharts(pie, height="1800px" ,theme={
                "backgroundColor": "#eeeee4",
                "textStyle": {"color": "#0080ff"},
            },
            ))              
            else:
                st.warning('NO DATA')
        
        if  st.checkbox('Bar Chart'):
            
            if data is not None:
                bar = barChart(df)
                st.write(st_pyecharts(bar ,height="1000px", width="1000px",theme={
                "backgroundColor": "#eeeee4",
                "textStyle": {"color": "#0080ff"},
            },))
            else:
                st.warning('NO DATA')
            
        if  st.checkbox('Polar Chart'):            
            if data is not None:
                polar = polarChart(df)
         
                st.write(st_pyecharts(polar ,height="900px" ,theme={
                "backgroundColor": "#eeeee4",
                "textStyle": {"color": "#0080ff"},
            },))
            else:
                st.warning('NO DATA')
        
        if  st.checkbox('HexagonLayer/ScatterplotLayer/light map'):
            
            if data is not None:
                map = mapChart(df)
                st.write((map ))
            else:
                st.warning('NO DATA')   
                
                 
        if  st.checkbox('TreeMap'):
            
            if data is not None:
               treemap = treeMapChart(df)
               st.write(st_pyecharts(treemap,height='700px',width='1920px' ,theme={
                "backgroundColor": "#eeeee4",
                "font_size":20
            },))
            
            else:
                st.warning('NO DATA') 
        
        if  st.checkbox('Tree'):
            
            if data is not None:
               tree = treeChart(df)
               st.write(st_pyecharts(tree,height='700px',width='1920px' ,theme={
                "backgroundColor": "#eeeee4",
                "font_size":20
            },))
            
            else:
                st.warning('NO DATA')     
         
         
        if  st.checkbox('Funnel'):
            
            if data is not None:
               funnel = funnelChart(df)
               st.write(st_pyecharts(funnel,height='700px',width='1920px' ,theme={
                "backgroundColor": "#eeeee4",
                "font_size":20
            },))
            
            else:
                st.warning('NO DATA')
        
        if  st.checkbox('Timeline_bar_with_graphic'):
                
            if data is not None:
               timeline = timelineChart(df)
               st.write(st_pyecharts(timeline,height='700px',width='1920px' ,theme={
                "backgroundColor": "#eeeee4",
                "font_size":20
            },))
            
            else:
                st.warning('NO DATA')     
        
            
    
    elif choice == 'Model Building':
        st.subheader('Model Building')
        data = st.file_uploader("Upload a Dataset", type=["csv", "txt"])
        if data is not None:
           df = pd.read_csv(data)
           st.dataframe(df.head())


			# Model Building
           X = df.iloc[:,0:-1]
           Y = df.iloc[:,-1]
           seed = 7
           # prepare models
           models = []
           models.append(('LR', LogisticRegression()))
           models.append(('LDA', LinearDiscriminantAnalysis()))
           models.append(('KNN', KNeighborsClassifier()))
           models.append(('CART', DecisionTreeClassifier()))
           models.append(('NB', GaussianNB()))
           models.append(('SVM', SVC()))
           # evaluate each model in turn
           model_names = []
           model_mean = []
           model_std = []
           all_models = []
           scoring = 'accuracy'
           for name, model in models:
               kfold = model_selection.KFold(n_splits=10, random_state=seed)
               cv_results = model_selection.cross_val_score(model, X, Y, cv=kfold, scoring=scoring)
               model_names.append(name)
               model_mean.append(cv_results.mean())
               model_std.append(cv_results.std())
               accuracy_results = {"model name":name,"model_accuracy":cv_results.mean(),"standard deviation":cv_results.std()}
               all_models.append(accuracy_results)
               if st.checkbox("Metrics As Table"):
                   st.dataframe(pd.DataFrame(zip(model_names,model_mean,model_std),columns=["Algo","Mean of Accuracy","Std"]))
               if st.checkbox("Metrics As JSON"):
                   st.json(all_models)

    
    
    elif choice == 'Others':
        st.subheader('some projects')
    
    elif choice == 'About':
        # st.subheader('About')
        
        footer_temp = """
	 <!-- CSS  -->
<!-- Font Awesome -->
<link
  href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css"
  rel="stylesheet"
/>
<!-- Google Fonts -->
<link
  href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700&display=swap"
  rel="stylesheet"
/>
<!-- MDB -->
<link
  href="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/3.3.0/mdb.min.css"
  rel="stylesheet"
/>
<script
  type="text/javascript"
  src="https://cdnjs.cloudflare.com/ajax/libs/mdb-ui-kit/3.3.0/mdb.min.js"
></script>
	 <footer style="background-color:#f0f2f6;padding:50px; border-radius:10px" class="page-footer grey darken-4">
	    <div class="container" id="aboutapp">
	      <div>
	        <div class="col l6 s12">
	          <h5 class="white-text">Simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.</h5>
	          <p class="grey-text text-lighten-4">Packages used: Streamlit,Pandas,Pyecharts, Echarts.</p>
	        </div>
	      
	   <div class="col l3 s12">
	        <h2>List of charts Used</h2>

                <ul>
                <li>BarChart</li>
                <li>TreeMap</li>
                <li>Rose Chart</li>
                <li>Map Chart</li>
                </ul>  
	    </div>
   
	    <div style="text-align:center"; class="footer-copyright">
	      <div class="container">
	     <div class="container p-4 pb-0">
    <!-- Section: Social media -->
    <section class="mb-4">
      <!-- Facebook -->
      <a
        class="btn btn-primary btn-floating m-1"
        style="background-color: #3b5998;"
        href="#!"
        role="button"
        ><i class="fab fa-facebook-f"></i
      ></a>

      <!-- Twitter -->
      <a
        class="btn btn-primary btn-floating m-1"
        style="background-color: #55acee;"
        href="#!"
        role="button"
        ><i class="fab fa-twitter"></i
      ></a>

      <!-- Google -->
      <a
        class="btn btn-primary btn-floating m-1"
        style="background-color: #dd4b39;"
        href="#!"
        role="button"
        ><i class="fab fa-google"></i
      ></a>

      <!-- Instagram -->
      <a
        class="btn btn-primary btn-floating m-1"
        style="background-color: #ac2bac;"
        href="#!"
        role="button"
        ><i class="fab fa-instagram"></i
      ></a>

      <!-- Linkedin -->
      <a
        class="btn btn-primary btn-floating m-1"
        style="background-color: #0082ca;"
        href="#!"
        role="button"
        ><i class="fab fa-linkedin-in"></i
      ></a>
      <!-- Github -->
      <a
        class="btn btn-primary btn-floating m-1"
        style="background-color: #333333;"
        href="#!"
        role="button"
        ><i class="fab fa-github"></i
      ></a>
    </section>
    <!-- Section: Social media -->
  </div>
  <!-- Grid container -->

  <!-- Copyright -->
  <div class="text-center p-3"; style="background-color: rgba(0, 0, 0, 0.2);  border-radius:10px;  padding-bottom:50px;">
    © 2021 Copyright
    <a class="text-white" href="https://mdbootstrap.com/"></a>
  </div>
	   
	    </div>
	  </footer>
	"""
        components.html(footer_temp, height=800)
Exemplo n.º 18
0
            pos_left="30",
            pos_right="30",
            range_="2020",
            yearlabel_opts=opts.CalendarYearLabelOpts(is_show=False),
        ),
    ).set_global_opts(
        title_opts=opts.TitleOpts(
            pos_top="30",
            pos_left="center",
            title=f"Número de tuits por día de {real_name}"),
        visualmap_opts=opts.VisualMapOpts(max_=25,
                                          min_=0,
                                          orient="horizontal",
                                          is_piecewise=False),
    ))
    st_pyecharts(c)

# =============================================================================
# Comparador
# =============================================================================
if selection == 'Comparador':
    perfil_1 = st.sidebar.selectbox('Elige un político', perfiles)
    perfil_2 = st.sidebar.selectbox('Elige un político',
                                    [p for p in perfiles if p != perfil_1])
    st.markdown(
        "<h1 style='text-align: center; color: #d84519;'>Política española en Twitter durante 2020</h1>",
        unsafe_allow_html=True)

    # =============================================================================
    # Variables globales
    # =============================================================================
Exemplo n.º 19
0
def render_wordcloud():
    with st.echo("below"):
        options = {
            "tooltip": {},
            "series": [
                {
                    "type": "wordCloud",
                    "gridSize": 2,
                    "sizeRange": [12, 50],
                    "rotationRange": [-90, 90],
                    "shape": "pentagon",
                    "width": 600,
                    "height": 400,
                    "drawOutOfBound": True,
                    "emphasis": {
                        "textStyle": {"shadowBlur": 10, "shadowColor": "#333"}
                    },
                    "data": [
                        {
                            "name": "Sam S Club",
                            "value": 10000,
                            "textStyle": {"color": "black"},
                            "emphasis": {"textStyle": {"color": "red"}},
                        },
                        {"name": "Macys", "value": 6181},
                        {"name": "Amy Schumer", "value": 4386},
                        {"name": "Jurassic World", "value": 4055},
                        {"name": "Charter Communications", "value": 2467},
                        {"name": "Chick Fil A", "value": 2244},
                        {"name": "Planet Fitness", "value": 1898},
                        {"name": "Pitch Perfect", "value": 1484},
                        {"name": "Express", "value": 1112},
                        {"name": "Home", "value": 965},
                        {"name": "Johnny Depp", "value": 847},
                        {"name": "Lena Dunham", "value": 582},
                        {"name": "Lewis Hamilton", "value": 555},
                        {"name": "KXAN", "value": 550},
                        {"name": "Mary Ellen Mark", "value": 462},
                        {"name": "Farrah Abraham", "value": 366},
                        {"name": "Rita Ora", "value": 360},
                        {"name": "Serena Williams", "value": 282},
                        {"name": "NCAA baseball tournament", "value": 273},
                        {"name": "Point Break", "value": 265},
                    ],
                }
            ],
        }
        st_echarts(options)

        data = [
            ("生活资源", "999"),
            ("供热管理", "888"),
            ("供气质量", "777"),
            ("生活用水管理", "688"),
            ("一次供水问题", "588"),
            ("交通运输", "516"),
            ("城市交通", "515"),
            ("环境保护", "483"),
            ("房地产管理", "462"),
            ("城乡建设", "449"),
            ("社会保障与福利", "429"),
            ("社会保障", "407"),
            ("文体与教育管理", "406"),
            ("公共安全", "406"),
            ("公交运输管理", "386"),
            ("出租车运营管理", "385"),
            ("供热管理", "375"),
            ("市容环卫", "355"),
            ("自然资源管理", "355"),
            ("粉尘污染", "335"),
            ("噪声污染", "324"),
            ("土地资源管理", "304"),
            ("物业服务与管理", "304"),
            ("医疗卫生", "284"),
            ("粉煤灰污染", "284"),
            ("占道", "284"),
            ("供热发展", "254"),
            ("农村土地规划管理", "254"),
            ("生活噪音", "253"),
            ("供热单位影响", "253"),
            ("城市供电", "223"),
            ("房屋质量与安全", "223"),
            ("大气污染", "223"),
            ("房屋安全", "223"),
            ("文化活动", "223"),
            ("拆迁管理", "223"),
            ("公共设施", "223"),
            ("供气质量", "223"),
            ("供电管理", "223"),
            ("燃气管理", "152"),
            ("教育管理", "152"),
            ("医疗纠纷", "152"),
            ("执法监督", "152"),
            ("设备安全", "152"),
            ("政务建设", "152"),
            ("县区、开发区", "152"),
            ("宏观经济", "152"),
            ("教育管理", "112"),
            ("社会保障", "112"),
            ("生活用水管理", "112"),
            ("物业服务与管理", "112"),
            ("分类列表", "112"),
            ("农业生产", "112"),
            ("二次供水问题", "112"),
            ("城市公共设施", "92"),
            ("拆迁政策咨询", "92"),
            ("物业服务", "92"),
            ("物业管理", "92"),
            ("社会保障保险管理", "92"),
            ("低保管理", "92"),
            ("文娱市场管理", "72"),
            ("城市交通秩序管理", "72"),
            ("执法争议", "72"),
            ("商业烟尘污染", "72"),
            ("占道堆放", "71"),
            ("地上设施", "71"),
            ("水质", "71"),
            ("无水", "71"),
            ("供热单位影响", "71"),
            ("人行道管理", "71"),
            ("主网原因", "71"),
            ("集中供热", "71"),
            ("客运管理", "71"),
            ("国有公交(大巴)管理", "71"),
            ("工业粉尘污染", "71"),
            ("治安案件", "71"),
            ("压力容器安全", "71"),
            ("身份证管理", "71"),
            ("群众健身", "41"),
            ("工业排放污染", "41"),
            ("破坏森林资源", "41"),
            ("市场收费", "41"),
            ("生产资金", "41"),
            ("生产噪声", "41"),
            ("农村低保", "41"),
            ("劳动争议", "41"),
            ("劳动合同争议", "41"),
            ("劳动报酬与福利", "41"),
            ("医疗事故", "21"),
            ("停供", "21"),
            ("基础教育", "21"),
            ("职业教育", "21"),
            ("物业资质管理", "21"),
            ("拆迁补偿", "21"),
            ("设施维护", "21"),
            ("市场外溢", "11"),
            ("占道经营", "11"),
            ("树木管理", "11"),
            ("农村基础设施", "11"),
            ("无水", "11"),
            ("供气质量", "11"),
            ("停气", "11"),
            ("市政府工作部门(含部门管理机构、直属单位)", "11"),
            ("燃气管理", "11"),
            ("市容环卫", "11"),
            ("新闻传媒", "11"),
            ("人才招聘", "11"),
            ("市场环境", "11"),
            ("行政事业收费", "11"),
            ("食品安全与卫生", "11"),
            ("城市交通", "11"),
            ("房地产开发", "11"),
            ("房屋配套问题", "11"),
            ("物业服务", "11"),
            ("物业管理", "11"),
            ("占道", "11"),
            ("园林绿化", "11"),
            ("户籍管理及身份证", "11"),
            ("公交运输管理", "11"),
            ("公路(水路)交通", "11"),
            ("房屋与图纸不符", "11"),
            ("有线电视", "11"),
            ("社会治安", "11"),
            ("林业资源", "11"),
            ("其他行政事业收费", "11"),
            ("经营性收费", "11"),
            ("食品安全与卫生", "11"),
            ("体育活动", "11"),
            ("有线电视安装及调试维护", "11"),
            ("低保管理", "11"),
            ("劳动争议", "11"),
            ("社会福利及事务", "11"),
            ("一次供水问题", "11"),
        ]

        c = (
            WordCloud()
            .add(series_name="热点分析", data_pair=data, word_size_range=[6, 66])
            .set_global_opts(
                title_opts=opts.TitleOpts(
                    title="热点分析", title_textstyle_opts=opts.TextStyleOpts(font_size=23)
                ),
                tooltip_opts=opts.TooltipOpts(is_show=True),
            )
        )
        st_pyecharts(c)
Exemplo n.º 20
0
from pyecharts.charts import Line

bTrends = (
    Line()
    #.add_xaxis(["Microsoft", "Amazon", "IBM", "Oracle", "Google", "Alibaba"])
    .add_xaxis(TrendsDateList).add_yaxis(
        "Revenue in B$",
        TrendsTerm01List,
        #category_gap = "10%"
        #is_large = True,
        #is_show_background = True,
    ).set_global_opts(title_opts=opts.TitleOpts(
        title="Top cloud providers 2018", subtitle="2017-2018 Revenue"),
                      #   toolbox_opts=opts.ToolboxOpts(),
                      ))
st_pyecharts(bTrends)

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

st.markdown('# LINE LINE WIP WIP - Google Trends test 02')

bTrends2 = (
    Line()
    #.add_xaxis([ "SEO" , "PPC" , "Social Media" , "Display" , "Direct" , "Affiliates" , "Else" ])
    .add_xaxis(TrendsDateList)
    #.add_yaxis( "Business A" , [ 114 , 55 , 27 , 101 , 125 , 27 , 105 ])
    .add_yaxis("Search Term A", TrendsTerm01List).add_yaxis(
        "Search Term B", TrendsTerm02List).add_yaxis("Search Term C",
                                                     TrendsTerm03List)
    #  .add_yaxis( "Business B" , [ 57 , 134 , 137 , 129 , 145 , 60 , 49 ])
    .set_global_opts(title_opts=opts.TitleOpts(title="Google Trends")))
Exemplo n.º 21
0
def render_wordcloud_py():
    with st.echo("below"):
        data = [
            ("生活资源", "999"),
            ("供热管理", "888"),
            ("供气质量", "777"),
            ("生活用水管理", "688"),
            ("一次供水问题", "588"),
            ("交通运输", "516"),
            ("城市交通", "515"),
            ("环境保护", "483"),
            ("房地产管理", "462"),
            ("城乡建设", "449"),
            ("社会保障与福利", "429"),
            ("社会保障", "407"),
            ("文体与教育管理", "406"),
            ("公共安全", "406"),
            ("公交运输管理", "386"),
            ("出租车运营管理", "385"),
            ("供热管理", "375"),
            ("市容环卫", "355"),
            ("自然资源管理", "355"),
            ("粉尘污染", "335"),
            ("噪声污染", "324"),
            ("土地资源管理", "304"),
            ("物业服务与管理", "304"),
            ("医疗卫生", "284"),
            ("粉煤灰污染", "284"),
            ("占道", "284"),
            ("供热发展", "254"),
            ("农村土地规划管理", "254"),
            ("生活噪音", "253"),
            ("供热单位影响", "253"),
            ("城市供电", "223"),
            ("房屋质量与安全", "223"),
            ("大气污染", "223"),
            ("房屋安全", "223"),
            ("文化活动", "223"),
            ("拆迁管理", "223"),
            ("公共设施", "223"),
            ("供气质量", "223"),
            ("供电管理", "223"),
            ("燃气管理", "152"),
            ("教育管理", "152"),
            ("医疗纠纷", "152"),
            ("执法监督", "152"),
            ("设备安全", "152"),
            ("政务建设", "152"),
            ("县区、开发区", "152"),
            ("宏观经济", "152"),
            ("教育管理", "112"),
            ("社会保障", "112"),
            ("生活用水管理", "112"),
            ("物业服务与管理", "112"),
            ("分类列表", "112"),
            ("农业生产", "112"),
            ("二次供水问题", "112"),
            ("城市公共设施", "92"),
            ("拆迁政策咨询", "92"),
            ("物业服务", "92"),
            ("物业管理", "92"),
            ("社会保障保险管理", "92"),
            ("低保管理", "92"),
            ("文娱市场管理", "72"),
            ("城市交通秩序管理", "72"),
            ("执法争议", "72"),
            ("商业烟尘污染", "72"),
            ("占道堆放", "71"),
            ("地上设施", "71"),
            ("水质", "71"),
            ("无水", "71"),
            ("供热单位影响", "71"),
            ("人行道管理", "71"),
            ("主网原因", "71"),
            ("集中供热", "71"),
            ("客运管理", "71"),
            ("国有公交(大巴)管理", "71"),
            ("工业粉尘污染", "71"),
            ("治安案件", "71"),
            ("压力容器安全", "71"),
            ("身份证管理", "71"),
            ("群众健身", "41"),
            ("工业排放污染", "41"),
            ("破坏森林资源", "41"),
            ("市场收费", "41"),
            ("生产资金", "41"),
            ("生产噪声", "41"),
            ("农村低保", "41"),
            ("劳动争议", "41"),
            ("劳动合同争议", "41"),
            ("劳动报酬与福利", "41"),
            ("医疗事故", "21"),
            ("停供", "21"),
            ("基础教育", "21"),
            ("职业教育", "21"),
            ("物业资质管理", "21"),
            ("拆迁补偿", "21"),
            ("设施维护", "21"),
            ("市场外溢", "11"),
            ("占道经营", "11"),
            ("树木管理", "11"),
            ("农村基础设施", "11"),
            ("无水", "11"),
            ("供气质量", "11"),
            ("停气", "11"),
            ("市政府工作部门(含部门管理机构、直属单位)", "11"),
            ("燃气管理", "11"),
            ("市容环卫", "11"),
            ("新闻传媒", "11"),
            ("人才招聘", "11"),
            ("市场环境", "11"),
            ("行政事业收费", "11"),
            ("食品安全与卫生", "11"),
            ("城市交通", "11"),
            ("房地产开发", "11"),
            ("房屋配套问题", "11"),
            ("物业服务", "11"),
            ("物业管理", "11"),
            ("占道", "11"),
            ("园林绿化", "11"),
            ("户籍管理及身份证", "11"),
            ("公交运输管理", "11"),
            ("公路(水路)交通", "11"),
            ("房屋与图纸不符", "11"),
            ("有线电视", "11"),
            ("社会治安", "11"),
            ("林业资源", "11"),
            ("其他行政事业收费", "11"),
            ("经营性收费", "11"),
            ("食品安全与卫生", "11"),
            ("体育活动", "11"),
            ("有线电视安装及调试维护", "11"),
            ("低保管理", "11"),
            ("劳动争议", "11"),
            ("社会福利及事务", "11"),
            ("一次供水问题", "11"),
        ]

        c = (
            WordCloud()
            .add(series_name="热点分析", data_pair=data, word_size_range=[6, 66])
            .set_global_opts(
                title_opts=opts.TitleOpts(
                    title="热点分析", title_textstyle_opts=opts.TextStyleOpts(font_size=23)
                ),
                tooltip_opts=opts.TooltipOpts(is_show=True),
            )
        )
        st_pyecharts(c)
Exemplo n.º 22
0
def main():
    global dps

    new_input = {}

    st.sidebar.markdown('## Set A DRFI Strategy:')

    for k in show_name:
        try:
            dvalue = dps[user_input][0][k] * 100 if k in input_pct else dps[
                user_input][0][k]
            nv = st.sidebar.text_input(show_name[k], dvalue, key=k)
            nv = float(nv) / 100.0 if k in input_pct else float(nv)
            new_input[k] = nv
        except:
            pass

    bg_params = st.sidebar.empty()
    bg_expander = bg_params.beta_expander('Other model settings')
    new_bg_input = {}
    for k in dps[bg_input][0]:
        new_bg_input[k] = float(
            bg_expander.text_input(k, value=dps[bg_input][0][k], key=k))

    st.sidebar.text('')
    st.sidebar.text('')
    if st.sidebar.button('Save this strategy'):
        dps[bg_input].append(new_bg_input)
        dps[user_input].append(new_input)

    if st.sidebar.button('reset the strategies'):
        reset()
        pass

    pses = []  # 计算过程的多组参数

    cb_AMTs = []
    for i in range(len(dps[user_input])):
        dps_ = copy.deepcopy(dps)
        uinp = copy.deepcopy(dps_[user_input][i])
        bginp = copy.deepcopy(dps_[bg_input][i])
        dps_.update(uinp)
        dps_.update(bginp)
        del dps_[user_input]
        bginp = copy.deepcopy(dps_[bg_input][i])
        dps_.update(bginp)
        del dps_[bg_input]

        dps_[cb_AMT] = dps_[cb_limit] - dps_[cb_att]
        cb_AMTs.append(dps_[cb_AMT])
        dps_[tier1_RL] = dps_[tier1_AMT] * dps_[tier1_BenRate]
        dps_[tier1_Int] = dps_[tier1_AMT] * dps_[tier1_IntRate]
        dps_[tier2_RL] = dps_[tier1_RL] * dps_[tier2_BenRate]
        dps_[tier2_Int] = dps_[tier2_RL] * dps_[tier2_IntRate]
        dps_[dataSR] = min(dps_[data_Invest] * dps_[dataSR_ImpRatio],
                           dps_[dataSR_Cap])
        dps_[dataCBLoad] = dps_[dataCBLoad_Base] * max(
            0, 1 - dps_[data_Invest] * dps_[dataCBLoad_ImpRatio])
        dps_[ipSR] = min(dps_[ip_Invest] * dps_[ipSR_ImpRate], dps_[ipSR_Cap])
        dps_[ipCBLoad] = dps_[ipCBLoad_Base] * max(
            0, 1 - dps_[ip_Invest] * dps_[ipCBLoad_ImpRatio])
        dps_[ipRLLoad] = dps_[ipRLLoad_Base] * max(
            0, 1 - min(dps_[ip_Invest] * dps_[ipRLLoad_ImpRatio],
                       dps_[ipRLLoad_ImpRatio_Cap]))
        dps_[inSize_Base] = dps_[GDP] * dps_[ip_Base] * dps_[cap_Converter]
        # dps_[inSize] = dps_[inSize_Base] * (1 + min(dps_[ip_Invest] * dps_[inSize_ImpRatio], dps_[inSize_ImpRatio_Cap]))
        dps_[inSize] = dps_[GDP] * dps_[ip_Revised] * dps_[cap_Converter]

        dps_[unit] = round(3 * dps_[L200Y] / dps_[no_cells], 0)
        dps_[SharpeRatio] = dps_[SharpeRatioBaseline] * (1 - dps_[dataSR]) * (
            1 - dps_[ipSR])

        pses.append(dps_)
        pass

    AnInt = np.array(range(0, int(dps[no_cells]) + 1, 1))
    Unit = round(3 * dps[L200Y] / dps[no_cells], 0)
    LossAmountMillion: np.ndarray = AnInt * Unit
    pencentile = [0.75, 0.9, 0.95, 0.975, 0.99, 0.995]
    pctile_year = [4, 10, 20, 40, 100, 200]

    # x axis
    EP_X = np.zeros(LossAmountMillion.size)

    S2 = 1 / 2 * (0.01 + 0.05) * (dps[L100Y] - dps[L20Y])
    S3 = 1 / 2 * (0.01 + 0.005) * (dps[L200Y] - dps[L100Y])
    S3 = 1 / 2 * (0.01 + 0.005) * (dps[L200Y] - dps[L100Y])
    S4 = dps[PctAELTail] * dps[AEL]
    S1 = dps[AEL] - S2 - S3 - S4
    f1 = S1 - dps[L20Y] * 0.05
    f2 = f1 / (dps[L0Y] - 0.05)
    b = 1 / f2
    r = S4 / 0.005

    t1 = LossAmountMillion < dps[L20Y]
    t2 = LossAmountMillion >= dps[L20Y]
    t3 = LossAmountMillion < dps[L100Y]
    t4 = LossAmountMillion >= dps[L100Y]
    t5 = LossAmountMillion < dps[L200Y]
    t6 = LossAmountMillion >= dps[L200Y]
    EP_X[t1] = func1(LossAmountMillion[t1], b, dps[L0Y])
    EP_X[t2 & t3] = func2(LossAmountMillion[t2 & t3], dps[L20Y], dps[L100Y])
    EP_X[t4 & t5] = func3(LossAmountMillion[t4 & t5], dps[L100Y], dps[L200Y])
    EP_X[t6] = func4(LossAmountMillion[t6], r, dps[L200Y])
    CDF = 1 - EP_X

    st.markdown('*****')
    st.markdown('### I. Exceedance Probablility Curve')
    linedata = [e for e in zip(LossAmountMillion, EP_X)]
    xdata = [e[0] for e in linedata]
    ydata = [e[1] for e in linedata]
    c2 = (Line(init_opts=opts.InitOpts()).add_xaxis(xdata).add_yaxis(
        'Exceedance Probablility',
        ydata,
        is_smooth=True,
        is_symbol_show=False,
        symbol_size=0).set_global_opts(
            tooltip_opts=opts.TooltipOpts(is_show=True,
                                          trigger='axis',
                                          axis_pointer_type='line'),
            xaxis_opts=opts.AxisOpts(type_='value', name='Loss Amount'),
            yaxis_opts=opts.AxisOpts(type_='value',
                                     name='Exceedance Probablility',
                                     is_scale=True),
            datazoom_opts=opts.DataZoomOpts(is_show=True,
                                            type_='slider',
                                            range_start=0,
                                            range_end=100),
            title_opts=opts.TitleOpts('')))
    st_pyecharts(c2, height='400%', width='100%')

    st.markdown('*****')
    st.markdown('### II. Loss by return year period ($M)')
    LossByReturnYearPeriod_empty = st.empty()

    st.markdown('*****')
    st.markdown('### III. Cost Comparison')
    CostComparison_empty = st.empty()

    st.markdown('****')
    st.markdown('### IV. Disaster Risk Layering')

    RetainedLossWithoutPolicy = LossAmountMillion / dps[natBdt]

    series_num = 1

    c = (Bar(init_opts=opts.InitOpts()).add_xaxis([
        str(y) + '-Year' for y in pctile_year
    ]).add_yaxis(
        'Without DRFI Strategy', [
            round(
                RetainedLossWithoutPolicy[np.argmin(np.abs(CDF - pctile))] *
                100, 2) for pctile in pencentile
        ],
        label_opts=opts.LabelOpts(
            is_show=True, formatter='{c}%')).set_global_opts(
                xaxis_opts=opts.AxisOpts(type_='category',
                                         name='\n\nReturn\nYear\nPeriod'),
                yaxis_opts=opts.AxisOpts(
                    type_='value',
                    name=' % of\nNational Budget',
                    is_scale=True,
                    axislabel_opts=opts.LabelOpts(
                        formatter=JsCode("function (x){return x + '%'}"))),
                legend_opts=opts.LegendOpts(),
                datazoom_opts=opts.DataZoomOpts(xaxis_index=[0, 1],
                                                type_='inside',
                                                range_start=0,
                                                range_end=100,
                                                pos_bottom='0%'),
                tooltip_opts=opts.TooltipOpts(is_show=True,
                                              trigger='axis',
                                              axis_pointer_type='shadow',
                                              is_show_content=True)))

    c1 = (Bar(init_opts=opts.InitOpts()).add_xaxis(
        [str(y) + '-Year' for y in pctile_year]).add_yaxis(
            '', [0] * len(pctile_year),
            label_opts=opts.LabelOpts(is_show=False)).set_global_opts(
                xaxis_opts=opts.AxisOpts(
                    type_='category',
                    name='',
                    axislabel_opts=opts.LabelOpts(is_show=False)),
                yaxis_opts=opts.AxisOpts(
                    type_='value',
                    name='Financing\nUtilization',
                    is_scale=True,
                    is_inverse=True,
                    axislabel_opts=opts.LabelOpts(
                        formatter=JsCode("function (x){return x + ' m'}"))),
                legend_opts=opts.LegendOpts(pos_top='3%'),
                tooltip_opts=opts.TooltipOpts(is_show=True,
                                              is_show_content=True),
            ))
    c1_label = opts.LabelOpts(
        is_show=True,
        position='inside',
        color='white',
        formatter=JsCode(
            "function(x) {d=x.data; if(d!==0.0){return d.toFixed() + ' m'}else{return ''};}"
        ))

    for i in range(len(pses)):
        ps = pses[i]
        if i == len(pses) - 1:
            funnel_data = [
                [
                    f'\n\n\nLayer 1:\n\nContingent budget or reserve\n\n0~{int(ps[tier1_UL])} m\n\n\nHigh{" " * 150}Low\nFrequency{" " * 140}Severity',
                    30
                ],
                [
                    f'Layer 2:\n\nContingent credit\n\n{int(ps[tier1_UL])}~{int(ps[tier2_UL])} m',
                    20
                ],
                [
                    f'Low Frequency{" " * 20}High Severity\n\n\n\nLayer 3:\n\nCapacity\nbuilding\nvehicles\n\n{int(ps[tier2_UL])}~{int(ps[tier3_UL])} m\n',
                    10
                ]
            ]
            layerc = (Funnel(init_opts=opts.InitOpts(theme='dark')).add(
                'layers',
                funnel_data,
                sort_='ascending',
                label_opts=opts.LabelOpts(
                    position='inside', color='black',
                    font_weight=['bold'])).set_global_opts(
                        legend_opts=opts.LegendOpts(is_show=False),
                        tooltip_opts=opts.TooltipOpts(is_show=False)))
            st_pyecharts(layerc, width='61.8%', height='600%')

        Limit = ps[inSize]

        RevisedLossRetainedRatio = ps[ipRLLoad]
        PctLossRetained = RevisedLossRetainedRatio
        LossTransfer = 1 - PctLossRetained

        InsurancePayout = (LossAmountMillion - ps[attachment]).clip(
            0, Limit) * LossTransfer

        CatbondSize = ps[cb_limit] - ps[cb_att]
        RetainedLossAfterInsurance = LossAmountMillion - InsurancePayout
        tier1_utilization = np.minimum(RetainedLossAfterInsurance,
                                       ps[tier1_AMT])
        Layer1FinancingBenefit = tier1_utilization * ps[tier1_BenRate]
        RetainedLossAfterLayer1Financing = np.maximum(
            0, RetainedLossAfterInsurance - tier1_utilization -
            Layer1FinancingBenefit)
        tier2_utilization = np.minimum(RetainedLossAfterLayer1Financing,
                                       ps[tier2_AMT])
        Layer2FinancingBenefit = tier2_utilization * ps[tier2_BenRate]
        RetainedLossAfterLayer2Financing = np.maximum(
            0, RetainedLossAfterLayer1Financing - tier2_utilization -
            Layer2FinancingBenefit)
        CatbondRecovery = (RetainedLossAfterLayer2Financing - ps[cb_att]).clip(
            0, CatbondSize)

        rl_pct_NB = (RetainedLossAfterLayer2Financing -
                     CatbondRecovery) / ps[natBdt]

        layer1_insurance_payout = np.minimum(LossAmountMillion, ps[tier1_UL])
        layer2_insurance_payout = np.maximum(
            np.minimum(LossAmountMillion, ps[tier2_UL]) - ps[tier1_UL], 0)
        layer3_insurance_payout = np.maximum(
            np.minimum(LossAmountMillion, ps[tier3_UL]) - ps[tier2_UL], 0)

        WT_CDF = np.zeros(CDF.size)
        WT_CDF[CDF != 0] = norm.cdf(norm.ppf(CDF[CDF != 0]) - ps[SharpeRatio])

        TransformedProbability = np.diff(WT_CDF)
        TransformedProbability = np.insert(TransformedProbability, 0,
                                           WT_CDF[0])
        InsurancePremium = (TransformedProbability * InsurancePayout).sum()
        InsurancePremiumAsPctNationalBudget = InsurancePremium / ps[natBdt]

        tier1_wtCost = (TransformedProbability * layer1_insurance_payout).sum()
        tier1_wtCost /= float(ps[tier1_UL])
        tier2_wtCost = (TransformedProbability * layer2_insurance_payout).sum()
        tier2_wtCost /= (ps[tier2_UL] - ps[tier1_UL])
        tier3_wtCost = (TransformedProbability * layer3_insurance_payout).sum()
        tier3_wtCost /= (ps[tier3_UL] - ps[tier2_UL])

        cc_df1 = pd.DataFrame([
            str(round(ps[tier1_IntRate] * 100, 0)) + '%',
            str(round(ps[tier2_IntRate] * 100, 0)) + '%'
        ],
                              index=['Debt', 'Credit Line'],
                              columns=[''])

        cc_df2 = pd.DataFrame([
            str(round(tier1_wtCost * 100, 1)) + '%',
            str(round(tier2_wtCost * 100, 1)) + '%',
            str(round(tier3_wtCost * 100, 1)) + '%'
        ],
                              index=[f'Layer {i}' for i in range(1, 4)],
                              columns=[''])
        sb, ertcc = CostComparison_empty.beta_columns(2)
        sb.markdown(
            '&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;**Sovereign Borrowing**'
        )
        ertcc.markdown(
            '&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;&emsp;**Estimated Risk Transfer Capacity Cost**'
        )
        sb.table(cc_df1.T)
        ertcc.table(cc_df2.T)

        PDF = np.diff(CDF)
        PDF = np.insert(PDF, 0, CDF[0])
        ExpectedLoss = (CatbondRecovery * PDF).sum()
        CatbondAnnualCost = ExpectedLoss * ps[hisMul] * (1 + ps[ipCBLoad]) * (
            1 + ps[dataCBLoad])
        CatbondCoupon = CatbondAnnualCost
        CatbondCostAsPctNationalBudget = CatbondCoupon / ps[natBdt]

        InsurancePenetrationCostAsPctNationalBudget = ps[ip_Invest]
        DataInfrastractureCostAsPctNationalBudget = ps[data_Invest]

        Layer1BorrowingCost = ps[tier1_Int]
        Layer1CostAsPctNationalBudget = Layer1BorrowingCost / ps[natBdt]
        Layer2BorrowingCost = ps[tier2_Int]
        Layer2CostAsPctNationalBudget = Layer2BorrowingCost / ps[natBdt]

        TotalDRFIStrategyCostAsPctNatlBudget = InsurancePremiumAsPctNationalBudget + CatbondCostAsPctNationalBudget \
                                               + DataInfrastractureCostAsPctNationalBudget + InsurancePenetrationCostAsPctNationalBudget \
                                               + Layer1CostAsPctNationalBudget + Layer2CostAsPctNationalBudget

        VaR_pct_NationalBudget = rl_pct_NB + TotalDRFIStrategyCostAsPctNatlBudget

        serie_name = f'DRFI Strategy {n2c[series_num]}'
        serie_data = []
        LossByReturnYearPeriod = []
        l1FUs, l2Fus, cbrs = [], [], []
        for pctile in pencentile:
            position = np.argmin(np.abs(CDF - pctile))
            var = VaR_pct_NationalBudget[position]
            var = round(var * 100, 2)
            serie_data.append(var)
            loss = LossAmountMillion[position]
            LossByReturnYearPeriod.append(loss)
            l1FU = tier1_utilization[position]
            l1FU = round(l1FU, 0)
            l1FUs.append(l1FU)
            l2FU = tier2_utilization[position]
            l2FU = round(l2FU, 0)
            l2Fus.append(l2FU)
            cbr = CatbondRecovery[position]
            cbr = round(cbr, 0)
            cbrs.append(cbr)

        c.add_yaxis(serie_name,
                    serie_data,
                    label_opts=opts.LabelOpts(is_show=True, formatter='{c}%'))
        c1.add_yaxis('Layer 1 Financing Utilization', l1FUs, stack=serie_name, label_opts=c1_label) \
            .add_yaxis('Layer 2 Financing Utilization', l2Fus, stack=serie_name, label_opts=c1_label) \
            .add_yaxis('Capacity Building Vehicles Recovery', cbrs, stack=serie_name, label_opts=c1_label)

        LossByReturnYearPeriod_df = pd.DataFrame(
            {
                'Loss ($m)': LossByReturnYearPeriod
            },
            index=[str(y) + '-year' for y in pctile_year]).T
        LossByReturnYearPeriod_empty.table(LossByReturnYearPeriod_df)

        series_num += 1

    grid = (Grid().add(c,
                       grid_opts=opts.GridOpts(pos_top='15%',
                                               pos_left='8%',
                                               height='43%',
                                               width='79%'),
                       grid_index=0).add(c1,
                                         grid_opts=opts.GridOpts(
                                             pos_bottom='8%',
                                             pos_left='8%',
                                             height='30%',
                                             width='79%'),
                                         grid_index=1))

    df = pd.DataFrame(dps[user_input])
    df[cb_AMT] = cb_AMTs
    params_df = df.copy(deep=True)

    rn = copy.deepcopy(show_name)
    for pname in change_to_amt:
        params_df[pname] = params_df[pname].map(
            lambda x: str(round(x * dps[natBdt], 1))[:3])

    for pname in pct_params:
        params_df[pname] = params_df[pname].map(
            lambda x: str(round(x * 100, 2)) + '%')
    rn.update(bg_show_name)
    params_df.rename(columns=rn, inplace=True)
    params_df = params_df.loc[:, [show_name[k] for k in show_name]]
    name_change = {}
    for pname in change_to_amt:
        if pname in show_name:
            name_change[show_name[pname]] = show_name[pname].replace(
                ' as % National Budget', '')
    params_df.rename(columns=name_change, inplace=True)
    params_df = pd.DataFrame(
        params_df.values.T,
        index=params_df.columns,
        columns=[f'DRFI Strategy {n2c[i + 1]}' for i in params_df.index])
    st.markdown('*****')
    st.markdown('### V. The DRFI Strategies')
    st.dataframe(params_df)

    st.markdown('*****')
    st.markdown(
        '### VI. Loss Impact as % of National Budget under Various Scenarios')
    st_pyecharts(grid, width='100%', height='618%', renderer='canvas')
Exemplo n.º 23
0
        if press_button:
            # any changes need to be performed in place
            is_pressed.update({"pressed": True})

        if is_pressed["pressed"]:  # saved between sessions
            c_positive, c_negative, data_positive, data_negative = dv.make_wordcloud_interactive(
                rest_name_input2, checked_pos_words, [])
            b_pos, b_neg = dv.make_barplot_interactive(rest_name_input2,
                                                       checked_pos_words, [])
    with col4:
        st.markdown("""## """)
    with col5:
        st_pyecharts(
            c_positive,
            theme={
                "width": "1000",
                "height": "800",
                "subtitle_text_size": "20",
            },
        )
        st_pyecharts(
            b_pos,
            theme={
                "backgroundColor": "#afc3a1c7",
                "textStyle": {
                    "color": "#F63366"
                },
                "yaxis_name_pos": "end",
                "subtitle_textstyle_opts": {
                    "color": "#F63366"
                },
            },
Exemplo n.º 24
0
    st.markdown('正在分析 **' + option1 + '** 与 **' + option2 + '** 的比赛')
    c = (Bar().add_xaxis([
        "控球率",
        "传球成功率",
        "场均关键传球",
        "绝佳机会",
        "场均争顶成功",
        "评分",
    ]).add_yaxis(option1, get_stats(team1, 0), color='#749f83').add_yaxis(
        option2, get_stats(team2, 0), color='#d48265').set_global_opts(
            xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(
                rotate=-10)),
            title_opts=opts.TitleOpts(title="球队概况"),
        ))
    st_pyecharts(c)

    MoreStats = st.multiselect('Select', ['进攻', '防守', '组织'])
    if '进攻' in MoreStats:
        c = (Bar().add_xaxis([
            "进球",
            "场均射门",
            "场均射正",
            "把握机会能力",
            "场均过人",
            "场均被侵犯",
        ]).add_yaxis(option1, get_stats(team1, 1)).add_yaxis(
            option2, get_stats(team2, 1)).set_global_opts(
                xaxis_opts=opts.AxisOpts(axislabel_opts=opts.LabelOpts(
                    rotate=-10)),
                title_opts=opts.TitleOpts(title="球队进攻对比"),