Example #1
0
def Add_Dash(server):
    app = Dash(
        server=server,
        url_base_pathname=url_base,
        external_stylesheets=[dbc.themes.BOOTSTRAP],
        external_scripts=["https://cdn.plot.ly/plotly-locale-de-latest.js"],
        meta_tags=[{
            "name": "viewport",
            "content": "width=device-width, initial-scale=1"
        }])

    apply_layout_with_auth(app, layout)

    return app.server
Example #2
0
def Add_Dash(server):
    app = Dash(
        server=server,
        url_base_pathname=url_base,
        external_stylesheets=[dbc.themes.BOOTSTRAP],
        external_scripts=["https://cdn.plot.ly/plotly-locale-de-latest.js"],
        meta_tags=[{
            "name": "viewport",
            "content": "width=device-width, initial-scale=1"
        }])

    apply_layout_with_auth(app, layout)

    @app.callback([
        Output('graph', 'figure'),
        Output('graph', 'config'),
        Output("benchmark-output", "children"),
        Output("cheaper-output", "children"),
        Output("other-output", "children")
    ], [
        Input('edit_perf', 'value'),
        Input('edit_onetime_invest', 'value'),
        Input('edit_duration', 'value'),
        Input('edit_month_invest', 'value'),
        Input('edit_cheap_ter', 'value'),
        Input('edit_cheap_trans_fee_per', 'value'),
        Input('edit_cheap_other_per', 'value'),
        Input('edit_cheap_trans_fee_abs', 'value'),
        Input('edit_cheap_other_abs', 'value'),
        Input('edit_exp_ter', 'value'),
        Input('edit_exp_trans_fee_per', 'value'),
        Input('edit_exp_other_per', 'value'),
        Input('edit_outperf', 'value'),
        Input('edit_exp_trans_fee_abs', 'value'),
        Input('edit_exp_other_abs', 'value')
    ])
    def display_tickers(perf, onetime_invest, duration, month_invest,
                        cheap_ter, cheap_trans_fee_per, cheap_other_per,
                        cheap_trans_fee_abs, cheap_other_abs, exp_ter,
                        exp_trans_fee_per, exp_other_per, outperf,
                        exp_trans_fee_abs, exp_other_abs):

        perf = cast_float(perf)
        onetime_invest = cast_float(onetime_invest)
        duration = cast_int(duration)
        month_invest = cast_float(month_invest)

        cheap_ter = cast_float(cheap_ter)
        cheap_trans_fee_per = cast_float(cheap_trans_fee_per)
        cheap_other_per = cast_float(cheap_other_per)
        cheap_trans_fee_abs = cast_float(cheap_trans_fee_abs)
        cheap_other_abs = cast_float(cheap_other_abs)

        exp_ter = cast_float(exp_ter)
        exp_trans_fee_per = cast_float(exp_trans_fee_per)
        exp_other_per = cast_float(exp_other_per)
        outperf = cast_float(outperf)
        exp_trans_fee_abs = cast_float(exp_trans_fee_abs)
        exp_other_abs = cast_float(exp_other_abs)

        duration_months = duration * 12
        ref_up_months = pow(1.0 + (perf / 100.0), (1.0 / 12.0))
        cheap_up_months = pow(1.0 + ((perf - cheap_ter) / 100.0), (1.0 / 12.0))
        exp_up_months = pow(1.0 + ((perf - exp_ter + outperf) / 100.0),
                            (1.0 / 12.0))

        start_eval = datetime.now()
        start_eval = start_eval.replace(minute=0,
                                        hour=0,
                                        second=0,
                                        microsecond=0)

        dates = pd.date_range(start=start_eval,
                              periods=duration_months,
                              freq='M')

        resultReference = []
        resultCheap = []
        resultExp = []

        #Init the results
        for i in range(duration_months):
            resultReference.append(0.0)
            resultCheap.append(0.0)
            resultExp.append(0.0)

        for i in range(len(resultReference)):

            if i == 0:
                resultReference[0] += onetime_invest
                resultCheap[0] += onetime_invest
                resultExp[0] += onetime_invest
            else:
                resultReference[i] = resultReference[i - 1]
                resultCheap[i] = resultCheap[i - 1]
                resultExp[i] = resultExp[i - 1]

                if i % 12 == 0:
                    resultCheap[i] *= (1.0 - (cheap_other_per / 100.0))
                    resultExp[i] *= (1.0 - (exp_other_per / 100.0))

                    resultCheap[i] -= cheap_other_abs
                    resultExp[i] -= exp_other_abs

            resultReference[i] += month_invest
            resultCheap[i] += month_invest
            resultExp[i] += month_invest

            resultCheap[i] -= cheap_trans_fee_abs
            resultExp[i] -= exp_trans_fee_abs

            resultCheap[i] -= (month_invest * (cheap_trans_fee_per / 100.0))
            resultExp[i] -= (month_invest * (exp_trans_fee_per / 100.0))

            resultReference[i] *= ref_up_months
            resultCheap[i] *= cheap_up_months
            resultExp[i] *= exp_up_months

        request_locale = request.accept_languages.best_match(
            ['en_US', 'de_DE'])
        if (request_locale == 'en_US'):
            dash_locale = 'en'
            sep_locale = "."
            request_locale_utf8 = 'en_US.utf8'
        else:
            dash_locale = 'de'
            sep_locale = ","
            request_locale_utf8 = 'de_DE.utf8'
        locale.setlocale(locale.LC_ALL, request_locale_utf8)

        # print('dash_locale:')
        # print(dash_locale)
        # print('request_locale')
        # print(request_locale)

        # df = pd.Series(resultReference,index=dates)
        # df.insert(1,'Cheap', resultCheap)
        # df.insert(2,'Other', resultExp)

        # str_res_ref = "%.2f" % resultReference[len(resultReference)-1]
        # str_res_cheap =  "%.2f" % resultCheap[len(resultCheap)-1]
        # str_res_exp  =  "%.2f" %  resultExp[len(resultExp)-1]

        # print("{:n}".format(str_res_ref))

        str_res_ref = "{:n}".format(resultReference[len(resultReference) - 1])
        str_res_cheap = "{:n}".format(resultCheap[len(resultCheap) - 1])
        str_res_exp = "{:n}".format(resultExp[len(resultExp) - 1])

        resultReference = list(np.around(np.array(resultReference), 0))
        resultCheap = list(np.around(np.array(resultCheap), 0))
        resultExp = list(np.around(np.array(resultExp), 0))

        df = pd.DataFrame({
            'Dates': dates,
            'Reference': resultReference,
            'Cheap': resultCheap,
            'Other': resultExp
        })

        # df.set_index('Dates', inplace=True)
        # df['Cheap'] = resultCheap
        # df['Other'] = resultExp
        pd.set_option('display.max_rows', None)  # or 1000
        # print(df)

        # Build graph
        layoutGraph = go.Layout(
            title="Performance Comparison",
            plot_bgcolor="#FFFFFF",
            hovermode="x",
            hoverdistance=100,  # Distance to show hover label of data point
            spikedistance=1000,  # Distance to show spike
            xaxis=dict(
                title="time",
                linecolor="#BCCCDC",
                showspikes=True,  # Show spike line for X-axis
                # Format spike
                spikethickness=2,
                spikedash="dot",
                spikecolor="#999999",
                spikemode="across",
            ),
            yaxis=dict(title="value", linecolor="#BCCCDC", tickformat=",r"))

        fig = go.Figure(layout=layoutGraph)
        fig.add_trace(
            go.Scatter(x=dates,
                       y=resultReference,
                       mode='lines',
                       name='Benchmark'))
        fig.add_trace(
            go.Scatter(x=dates, y=resultCheap, mode='lines', name='Fund #1'))
        fig.add_trace(
            go.Scatter(x=dates, y=resultExp, mode='lines', name='Fund #2'))

        # print(str_res_ref)

        # fig = px.line(df, x='Dates')
        return fig, dict(
            locale=dash_locale), str_res_ref, str_res_cheap, str_res_exp

    return app.server
Example #3
0
def Add_Dash(server):
    app = Dash(
        server=server,
        url_base_pathname=url_base,
        external_stylesheets=[dbc.themes.BOOTSTRAP],
        external_scripts=["https://cdn.plot.ly/plotly-locale-de-latest.js"],
        meta_tags=[{
            "name": "viewport",
            "content": "width=device-width, initial-scale=1"
        }])

    apply_layout_with_auth(app, layout)

    @app.callback([
        Output('ty-figure', 'figure'),
        Output("slider-value", "children"),
    ], [Input(component_id='ty-slider', component_property='value')])
    def computeBalance(value_from_slider):

        # mask = (df['Date']==df['Date'].min())
        # df_toDraw=df.loc[mask].drop(['Date'], axis=1).transpose()
        df_toDraw = df.iloc[[value_from_slider]].drop(['Date'],
                                                      axis=1).transpose()

        df_toDraw['Color'] = np.array(df2['Color'].tolist())

        mask2 = (df_toDraw.iloc[:, 0] != 0)
        df_toDraw = df_toDraw.loc[mask2]
        df_toDraw.rename(columns={df_toDraw.columns[0]: "Percent"},
                         inplace=True)

        df_toDraw['Name'] = df_toDraw.index

        fig_toDraw = go.Figure(data=[
            go.Pie(labels=df_toDraw['Name'].tolist(),
                   values=df_toDraw['Percent'].tolist())
        ])

        fig_toDraw.update_traces(hoverinfo='label+percent',
                                 textposition='inside',
                                 textinfo='percent+label',
                                 marker=dict(
                                     colors=df_toDraw['Color'].tolist(),
                                     line=dict(color='#000000', width=2)))

        fig_toDraw.update_layout(showlegend=False,
                                 template=draft_template,
                                 annotations=[
                                     dict(
                                         templateitemname="draft watermark",
                                         text="www.blackandwhitedata.com",
                                     )
                                 ],
                                 title_xanchor="auto",
                                 height=800,
                                 margin=dict(l=0, r=0, b=0, t=20))

        return fig_toDraw, [str(marks_dict[value_from_slider])]

    # @app.callback(
    #     [Output('ty-figure', 'figure'),
    #     Output('ty-figure', 'config')],
    #     Input('ty-slider', 'value')
    # )
    # def update_graph(value):
    #     # print(value)

    #     request_locale  = request.accept_languages.best_match(['en_US','de_DE'])
    #     if (request_locale=='en_US'):
    #         dash_locale = 'en'
    #         sep_locale = "."
    #         request_locale_utf8 = 'en_US.utf8'
    #     else:
    #         dash_locale = 'de'
    #         sep_locale = ","
    #         request_locale_utf8 = 'de_DE.utf8'
    #     locale.setlocale(locale.LC_ALL, request_locale_utf8)

    #     # print(request_locale_utf8)

    #     mask = (df['Year']==value)
    #     df_toDraw=df.loc[mask]
    #     df_toDraw = df_toDraw.sort_values('Market Cap', ascending=True)
    #     fig_toDraw = go.Figure(go.Bar(
    #                 x=df_toDraw['Market Cap'].tolist(),
    #                 y=df_toDraw['Name'].tolist(),
    #                 marker=dict(color=df_toDraw['Color']),
    #                 orientation='h'))

    #     # fig_toDraw.update_traces(texttemplate='%{text:.2s}',textposition='outside',textfont_size=12)

    #     fig_toDraw.update_layout(
    #         height=800,
    #         margin=dict(
    #             l=50,
    #             r=0,
    #             b=100,
    #             t=100,
    #             pad=4
    #         )
    #     )

    #     fig_toDraw.update_xaxes(
    #         tickvals=[0,50000000000,100000000000,150000000000,200000000000],
    #         range=[0,200000000000]
    #     )

    #     return fig_toDraw,dict(locale=dash_locale)

    return app.server
Example #4
0
def Add_Dash(server):
    app = Dash(
        server=server,
        url_base_pathname=url_base,
        external_stylesheets=[dbc.themes.BOOTSTRAP],
        external_scripts=["https://cdn.plot.ly/plotly-locale-de-latest.js"],
        meta_tags=[{
            "name": "viewport",
            "content": "width=device-width, initial-scale=1"
        }])

    apply_layout_with_auth(app, layout)

    @app.callback(
        [Output('ty-figure', 'figure'),
         Output('ty-figure', 'config')], Input('ty-slider', 'value'))
    def update_graph(value):
        # print(value)

        request_locale = request.accept_languages.best_match(
            ['en_US', 'de_DE'])
        if (request_locale == 'en_US'):
            dash_locale = 'en'
            sep_locale = "."
            request_locale_utf8 = 'en_US.utf8'
        else:
            dash_locale = 'de'
            sep_locale = ","
            request_locale_utf8 = 'de_DE.utf8'
        locale.setlocale(locale.LC_ALL, request_locale_utf8)

        # print(request_locale_utf8)

        mask = (df['Year'] == value)
        df_toDraw = df.loc[mask]
        df_toDraw = df_toDraw.sort_values('Market Cap', ascending=True)
        fig_toDraw = go.Figure(
            go.Bar(x=df_toDraw['Market Cap'].tolist(),
                   y=df_toDraw['Name'].tolist(),
                   marker=dict(color=df_toDraw['Color']),
                   orientation='h'))

        # fig_toDraw.update_traces(texttemplate='%{text:.2s}',textposition='outside',textfont_size=12)

        fig_toDraw.update_layout(height=800,
                                 annotations=[
                                     dict(
                                         textangle=-30,
                                         opacity=0.1,
                                         font=dict(color="black", size=25),
                                         xref="paper",
                                         yref="paper",
                                         x=0.5,
                                         y=0.5,
                                         showarrow=False,
                                         text="www.blackandwhitedata.com",
                                     )
                                 ],
                                 margin=dict(l=50, r=0, b=100, t=100, pad=4))

        fig_toDraw.update_xaxes(tickvals=[
            0, 50000000000, 100000000000, 150000000000, 200000000000
        ],
                                range=[0, 200000000000])

        return fig_toDraw, dict(locale=dash_locale)

    return app.server
Example #5
0
def Add_Dash(server):
    app = Dash(
        server=server,
        url_base_pathname=url_base,
        external_stylesheets=[dbc.themes.BOOTSTRAP],
        external_scripts=["https://cdn.plot.ly/plotly-locale-de-latest.js"],
        meta_tags=[{
            "name": "viewport",
            "content": "width=device-width, initial-scale=1"
        }])
    apply_layout_with_auth(app, layout)

    @app.callback([
        Output(component_id={
            'type': 'dynamic-new_value',
            'index': ALL
        },
               component_property='children'),
        Output(component_id={
            'type': 'dynamic-change',
            'index': ALL
        },
               component_property='children'),
        Output(component_id={
            'type': 'dynamic-piece-exact',
            'index': ALL
        },
               component_property='children'),
        Output("compute-output", "children")
    ], [
        Input(component_id={
            'type': 'dynamic-quantity',
            'index': ALL
        },
              component_property='value'),
        Input(component_id={
            'type': 'dynamic-price',
            'index': ALL
        },
              component_property='value'),
        Input(component_id={
            'type': 'dynamic-percent',
            'index': ALL
        },
              component_property='value'),
    ])
    def computeBalance(quantities, prices, percents):

        request_locale = request.accept_languages.best_match(
            ['en_US', 'de_DE'])
        if (request_locale == 'en_US'):
            dash_locale = 'en'
            sep_locale = "."
            request_locale_utf8 = 'en_US.utf8'
        else:
            dash_locale = 'de'
            sep_locale = ","
            request_locale_utf8 = 'de_DE.utf8'
        locale.setlocale(locale.LC_ALL, request_locale_utf8)

        if len(quantities) == 1:
            return get_dummy_result(len(quantities),
                                    "You need at least 2 assets")

        if hasNoneType(quantities, prices, percents):
            return get_dummy_result(len(quantities), "A field is empty")

        if not sumsTo100(percents):
            return get_dummy_result(len(quantities),
                                    "Goal does not sum to 100%")

        portfolioSize = getPortfolioSize(quantities, prices)
        values = getValues(quantities, prices)
        new_Values = getNewValues(portfolioSize, percents)
        changes = getChanges(values, new_Values)
        pieces = getPieces(changes, prices)
        resutlText = []
        resutlText.append("The result is ready.")

        # "{:n}".format(result)
        # return "{:n}".format(convertToStringNoSign(new_Values)), "{:n}".format(convertToString(changes)), "{:n}".format(convertToString(pieces)), resutlText
        return convertToStringNoSign(new_Values), convertToString(
            changes), convertToString(pieces), resutlText

    @app.callback([
        Output(component_id={
            'type': 'dynamic-sum',
            'index': MATCH
        },
               component_property='children')
    ], [
        Input(component_id={
            'type': 'dynamic-quantity',
            'index': MATCH
        },
              component_property='value'),
        Input(component_id={
            'type': 'dynamic-price',
            'index': MATCH
        },
              component_property='value')
    ])
    def updateSumValue(quantity, price):

        request_locale = request.accept_languages.best_match(
            ['en_US', 'de_DE'])
        if (request_locale == 'en_US'):
            dash_locale = 'en'
            sep_locale = "."
            request_locale_utf8 = 'en_US.utf8'
        else:
            dash_locale = 'de'
            sep_locale = ","
            request_locale_utf8 = 'de_DE.utf8'
        locale.setlocale(locale.LC_ALL, request_locale_utf8)

        if quantity is not None:
            quantity = float(quantity)
        else:
            quantity = 0.0
        if price is not None:
            price = float(price)
        else:
            price = 0.0
        result = price * quantity

        conv_result = "{:n}".format(result)
        return [conv_result]
        # return ["%.2f" % result]

    @app.callback(Output('container_asset',
                         'children'), [Input('add_ticker_button', 'n_clicks')],
                  [State('container_asset', 'children')])
    def display_tickers(n_clicks, div_children):

        new_child = html.Div(children=[
            html.P("Asset #" + str(n_clicks), style={"color": "#000000"}),
            dbc.Row([
                dbc.Col(children=[
                    html.Div("Pieces:"),
                    dbc.Input(type="number",
                              value='126',
                              placeholder="Enter the number of pieces ",
                              id={
                                  'type': 'dynamic-quantity',
                                  'index': n_clicks
                              })
                ],
                        width=3),
                dbc.Col(children=[
                    html.Div("Price:"),
                    dbc.Input(type="number",
                              value='80.13',
                              placeholder="Enter price per piece",
                              id={
                                  'type': 'dynamic-price',
                                  'index': n_clicks
                              })
                ],
                        width=3),
                dbc.Col(children=[
                    html.Div("Value:"),
                    html.P(children='-',
                           id={
                               'type': 'dynamic-sum',
                               'index': n_clicks
                           })
                ],
                        width=3),
                dbc.Col(children=[
                    html.Div("Goal (%):"),
                    dbc.Input(type="number",
                              value='100',
                              placeholder="Enter percent of asset",
                              id={
                                  'type': 'dynamic-percent',
                                  'index': n_clicks
                              })
                ],
                        width=3)
            ],
                    style={'width': '100%'}),
            dbc.Toast([
                dbc.Row([
                    dbc.Col(children=[
                        html.Div("New Value:"),
                        html.P(children='4',
                               id={
                                   'type': 'dynamic-new_value',
                                   'index': n_clicks
                               })
                    ],
                            width=4),
                    dbc.Col(children=[
                        html.Div("Change:"),
                        html.P(children='-1000',
                               id={
                                   'type': 'dynamic-change',
                                   'index': n_clicks
                               })
                    ],
                            width=4),
                    dbc.Col(children=[
                        html.Div("Pieces:"),
                        html.P(children='-5.5',
                               id={
                                   'type': 'dynamic-piece-exact',
                                   'index': n_clicks
                               })
                    ],
                            width=4)
                ],
                        style={'width': '100%'}),
            ],
                      header="Change the asset to:",
                      style={"maxWidth": "450px"}),
            html.Br(),
        ])
        div_children.append(new_child)
        return div_children

    return app.server