Esempio n. 1
0
def format_columns(df):
    columns = df.columns
    type_dict = dict(
        df.iloc[0].map(lambda x: 'text' if isinstance(x, str) else 'numeric'))
    col_styles = [{"name": i, "id": i, "type": type_dict[i]} for i in columns]
    format_dict = {
        'price': FormatTemplate.money(0),
        'pct': FormatTemplate.percentage(1).sign(Sign.positive)
    }
    for i in col_styles:
        col_name = i['name']
        if any([x in col_name for x in ('pct', 'return')]):
            i['format'] = FormatTemplate.percentage(2).sign(Sign.positive)
        elif any([
                x in col_name
                for x in ('price', 'value', 'gain', 'wealth', 'cash')
        ]):
            i['format'] = FormatTemplate.money(2)
        elif 'weight' in col_name:
            i['format'] = FormatTemplate.percentage(2)
        elif 'quantity' in col_name:
            i['format'] = Format(
                precision=4,
                #                 scheme=Scheme.fixed,
                #                 symbol=Symbol.yes,
                #                 symbol_suffix=u'˚F'
            )

    return col_styles
Esempio n. 2
0
def update_yield_curve(n_clicks, value, md):
    model_data, test_data = strategy(value, md)

    blotter, ledger, test, sharp = backtest1(model_data, test_data)

    if test['Response'][-1] > 0.5:
        ac = 'BUY'
        tp = 'MKT'
    else:
        ac = 'SELL'
        tp = 'LMT'

    fig = go.Figure(data=[
        go.Scatter(x=ledger['Date'], y=ledger['Revenue'], name='Asset Return'),
        go.Scatter(x=ledger['Date'], y=ledger['IVV Yield'], name='IVV Return')
    ])
    fig.update_layout(title='Back-Test-Yield', yaxis={'hoverformat': '.2%'})
    #     data = df.dropna(axis=0)
    blotter.reset_index()
    blotter = blotter.to_dict('records')
    blotter_columns = [
        dict(id='Date', name='Date'),
        dict(id='ID', name='ID'),
        dict(id='Type', name='order type'),
        dict(id='actn', name='Action'),
        dict(id='Price',
             name='Order Price',
             type='numeric',
             format=FormatTemplate.money(2)),
        dict(id='size', name='Order Amount', type='numeric'),
        dict(id='symb', name='Symb')
    ]
    ledger = ledger.to_dict('records')
    ledger_columns = [
        dict(id='Date', name='Date'),
        dict(id='position', name='position'),
        dict(id='Cash', name='Cash'),
        dict(id='Stock Value',
             name='Stock Value',
             type='numeric',
             format=FormatTemplate.money(2)),
        dict(id='Total Value',
             name='Total Value',
             type='numeric',
             format=FormatTemplate.money(2)),
        dict(id='Revenue',
             name='Revenue',
             type='numeric',
             format=FormatTemplate.percentage(2)),
        dict(id='IVV Yield',
             name='IVV Yield',
             type='numeric',
             format=FormatTemplate.percentage(2))
    ]
    return ('Successfully trained model with window size ' + str(value), fig,
            blotter_columns, blotter, ledger_columns, ledger, ac, tp,
            test['Close'][-1])
def yrly_sum_stat_tbl_fmt(df):
    return DataTable(
        columns=[{'name': 'Year', 'id': 'Date'},
                 {'name': 'Average Daily Return', 'id': 'Average Daily Return', 'type': 'numeric',
                  'format': FormatTemplate.percentage(4)},
                 {'name': 'Standard Deviation of Daily Returns', 'id': 'Standard Deviation of Daily Returns',
                  'type': 'numeric', 'format': FormatTemplate.percentage(4)},
                 {'name': 'Annualized Average Daily Return', 'id': 'Annualized Average Daily Return',
                  'type': 'numeric', 'format': FormatTemplate.percentage(4)},
                 {'name': 'Annualized Standard Deviation of Daily Returns',
                  'id': 'Annualized Standard Deviation of Daily Returns',
                  'type': 'numeric', 'format': FormatTemplate.percentage(4)},
                 {'name': 'Annualized Sharpe Ratio',
                  'id': 'Annualized Sharpe Ratio',
                  'type': 'numeric', 'format': FormatTemplate.percentage(4)}
                 ],
        data=df.to_dict('records'),
        style_cell={
            'textAlign': 'center',
            'whiteSpace': 'normal',
            'height': 'auto',
            'color': 'white',
            'backgroundColor': '#696969',
        },
        style_header={'backgroundColor': '#000000'},
        style_data_conditional=[
            {
                'if': {
                    'filter_query': '{{Annualized Sharpe Ratio}} < {}'.format(0.00),
                },
                'backgroundColor': '#FF4136',
            },
            {
                'if': {
                    'filter_query': '{{Annualized Sharpe Ratio}} > {}'.format(0.00),
                },
                'backgroundColor': '#3cb371',
            },
            {
                'if': {
                    'state': 'active'  # 'active' | 'selected'
                },
                'backgroundColor': '#696969',
                'border': '#ffffff',
            }
        ],
        style_as_list_view=True,
        page_size=20,
        export_format='csv',
        style_table={'overflowX': 'auto'}
    )
Esempio n. 4
0
def present_customer_data_layout():
    '''This is the screen layout for the customer data. This has not been implemented yet.'''
    return html.Div([
    html.Br(),
    html.Br(),
    html.H5('Client Information',
        style = TEXT_ALIGN_CENTER ),
    html.Br(),
    dash_table.DataTable(
        id='record',
        columns = [
            {'name': 'Customer Name',
                'id' : 'name'},
            {'name': 'Account Number',
                'id': 'account number'},
            {'name': 'Account Balance',
                'id' : 'account balance',
                'type' : 'numeric',
                'format': FormatTemplate.money(2)},
            {'name': 'Date of Transaction',
                'id' : 'date of entry'},
            {'name': 'Transaction Type',
                'id' : 'transaction type'},
            {'name': 'Transaction Amount',
                'id' : 'transaction amount',
                'type' : 'numeric',
                'format': FormatTemplate.money(2)},
        ],
        style_header = {
            'backgroundColor': 'rgb(230,230,230)',
            'font-weight' : 'bold',
        },
        style_cell = {
            'textAlign' : 'center'
        },
        style_data_conditional=
        [
            {'if': {'row_index': 'odd'}, 'backgroundColor': 'rgb(248, 248, 248)'},
        ],
        style_table = {
            'maxHeight': '300px',
            'overflowY' : 'scroll',
            'font-family': 'sans-serif',
            'font-size': '24',
        }
    ),
    html.Div(id = 'customer_record')
])
def generic_tbl_fmt(df):
    return DataTable(
            columns=[{'name': i, 'id': i, 'type': 'numeric', 'format': FormatTemplate.percentage(4)} for i in
                     df.columns],
            data=df.to_dict('records'),
            style_cell={
                'textAlign': 'center',
                'whiteSpace': 'normal',
                'height': 'auto',
                'color': 'white',
                'backgroundColor': '#696969',
            },
            style_header={'backgroundColor': '#000000'},
            style_data_conditional=[
                {
                    'if': {
                        'state': 'active'  # 'active' | 'selected'
                    },
                    'backgroundColor': '#8140CF'
                }
            ],
            style_as_list_view=True,
            page_size=20,
            export_format='csv',
            style_table={'overflowX': 'auto'}
    )
Esempio n. 6
0
def selects_callback(node_status, session_id):

    if session_id in pyplan_sessions and pyplan_sessions[session_id].is_ready(
    ):
        pyplan = pyplan_sessions[session_id]

        # get values from Pyplan
        print(f"Get values from Pyplan for session: {session_id}")
        df_json = pyplan.getResult('p_l_report_for_dash')
        df = pd.read_json(df_json, orient='table')
        sorted_values = df.index.get_level_values(
            "Report index").unique().tolist()
        df = pd.pivot_table(df,
                            values="value",
                            index=["Report index"],
                            columns=["time"],
                            aggfunc="sum")
        #fix index order after pivot
        df = df.reindex(index=sorted_values).reset_index()

        # create columns for table
        columns = []
        for nn, col in enumerate(df.columns):
            column_definition = None
            if nn == 0:
                column_definition = {
                    "name": 'P&L Accounts',
                    "id": 'Report index',
                    "type": "text"
                }
            else:
                column_definition = {
                    "name": col,
                    "id": col,
                    "type": "numeric",
                    "format": FormatTemplate.money(0)
                }
            columns.append(column_definition)

        data = df.to_dict("records")

        value_columns = [cc for nn, cc in enumerate(df.columns) if nn > 0]
        df_chart = df.melt(id_vars=["Report index"],
                           value_vars=value_columns,
                           var_name='time')

        # create chart
        fig = px.line(df_chart,
                      x="time",
                      y="value",
                      color='Report index',
                      color_discrete_sequence=default_colors)

        default_layout(fig)
        fig.update_layout(height=390,
                          xaxis_type="category",
                          title_text=f"P&L Report")

        return columns, data, fig
    return dash.no_update, dash.no_update, dash.no_update
Esempio n. 7
0
def update_figure4(in_sample, period):

    in_sample = True if in_sample == 'in_sample' else False

    worst_periods = pd.read_csv('data/absorption_ratio_worst_return_periods_list.csv')

    # subset the data for the user specification
    df = worst_periods.copy()
    df = df[df['period'] == period]
    df = df[df['in_sample'] == in_sample]
    df = df[df['overlapping'] == True]
    if in_sample:
        df = df[df['rank'] >= 0.95]
    else:
        df = df[df['rank_oos'] >= 0.95]

    df.sort_values(by='^GSPC', inplace=True, ascending=True)
    df.reset_index(inplace=True, drop=True)
    df['rank'] = df.index + 1

    # set the columns to show in table
    df.rename(columns={'rank': 'Rank', '^GSPC': 'Return', 'ar': 'AR', 'ar_shift': 'AR Shift', 'date': 'Date'}, inplace=True)
    cols = [{'name': 'Rank', 'id': 'Rank'},
            {'name': 'Date', 'id': 'Date'},
            {'name': 'Return', 'id': 'Return', 'type': 'numeric', 'format': FormatTemplate.percentage(1)},
            {'name': 'AR', 'id': 'AR', 'type': 'numeric'},
            {'name': 'AR Shift', 'id': 'AR Shift', 'type': 'numeric'}]

    # format to 2 decimals places for presentation
    for var in ['AR', 'AR Shift']:
        df[var] = df[var].map(lambda x: round(x,2))


    return df.to_dict('records'), df.to_dict('records')
Esempio n. 8
0
def choose_libor_currency(currency):
    if currency:
        dfs = scrape_libor()[currency]
        cols = [{'id': dfs.columns[0], 'name': dfs.columns[0]}] + [
            {'id': col, 'name': col.title(), 'type': 'numeric',
             "format": FormatTemplate.percentage(4)} for col in dfs.columns[1:]]
        return cols, dfs.to_dict('records')
    else:
        return [], []
def number(decimals,
           sign=FormatTemplate.Sign.default,
           group=FormatTemplate.Group.yes):
    return FormatTemplate.Format(group=group,
                                 precision=decimals,
                                 scheme=FormatTemplate.Scheme.fixed,
                                 sign=sign,
                                 symbol=FormatTemplate.Symbol.no,
                                 group_delimiter='.',
                                 decimal_delimiter=',')
Esempio n. 10
0
def update_netric_table(days_since_d1, metric):
    df = update_df(metric, days_since_d1)
    cols=[
        {'name': 'Rank', 'id': 'Rank', 'type': 'numeric'},
        {'name': 'State', 'id': 'State'},
        {'name': metric, 'id': metric, 'type': 'numeric', 'format': Format(group=',')},
        {'name': '1D | # Delta', 'id': '1D | # Delta', 'type': 'numeric', 'format': Format(group=',')},
        {'name': '1W | # Delta', 'id': '1W | # Delta', 'type': 'numeric', 'format': Format(group=',')},
        {'name': '1D | % Delta', 'id': '1D | % Delta', 'type': 'numeric', 'format': FormatTemplate.percentage(1).sign(Sign.positive)},
        {'name': '1W | % Delta', 'id': '1W | % Delta', 'type': 'numeric', 'format': FormatTemplate.percentage(1).sign(Sign.positive)}
    ]
    da = df.to_dict('records')
    output = dash_table.DataTable(
        columns = cols,
        data = da,
        sort_action='native',
        filter_action='native',
        style_cell={'fontSize':15, 'font-family':'sans-serif', 'textAlign': 'left', 'padding':'8px'},
        style_header={'backgroundColor': 'white', 'fontWeight': 'bold'},
        style_as_list_view=True,
    )
    return output
Esempio n. 11
0
    def initalization(_):
        columns = [{
            'name': 'Period',
            'id': 'period',
            'type': 'numeric',
        }, {
            'name': 'Value',
            'id': 'value',
            'type': 'numeric',
            'format': FormatTemplate.money(2)
        }]

        return columns
Esempio n. 12
0
def budget_columns(cols):
    data = []
    for c in cols:
        if c == 'amount':
            data.append({
                "name": c,
                "id": c,
                'type': 'numeric',
                'format': FormatTemplate.money(0)
            })
        else:
            data.append({"name": c, "id": c})
    data.append({'deletable': True})
    return data
Esempio n. 13
0
    def update_table_columns(cols):
        if cols is None:
            raise PreventUpdate

        columns = []

        for i in range(cols + 1):
            columns.append({
                'name': str(i),
                'id': str(i),
                'type': 'numeric',
                'format': FormatTemplate.money(2)
            })

        return columns
Esempio n. 14
0
def column_prep(cols):
    data = []
    for c in cols:
        if c == 'date':
            data.append({"name": c, "id": c, "type": "datetime"})
        elif c == 'amount':
            data.append({
                "name": c,
                "id": c,
                'type': 'numeric',
                'format': FormatTemplate.money(0)
            })
        else:
            data.append({"name": c, "id": c})
    return data
Esempio n. 15
0
def make_dcc_country_tab(countryName, dataframe):
    '''This is for generating tab component for country table'''
    return dcc.Tab(label=countryName,
            value=countryName,
            className='custom-tab',
            selected_className='custom-tab--selected',
            children=[dash_table.DataTable(
                    id='datatable-interact-location-{}'.format(countryName),
                    # Don't show coordinates
                    columns=[{"name": i, "id": i, "type": "numeric","format": FormatTemplate.percentage(2)}
                             if i == 'Death rate' else {"name": i, "id": i}
                             for i in dataframe.columns[0:6]],
                    # But still store coordinates in the table for interactivity
                    data=dataframe.to_dict("rows"),
                    row_selectable="single" if countryName != 'Schengen' else False,
                    sort_action="native",
                    style_as_list_view=True,
                    style_cell={'font_family': 'Arial',
                                  'font_size': '1.1rem',
                                  'padding': '.1rem',
                                  'backgroundColor': '#f4f4f2', },
                    fixed_rows={'headers': True, 'data': 0},
                    style_table={'minHeight': '800px',
                                 'height': '800px',
                                 'maxHeight': '800px',
                                 #'overflowX': 'scroll'
                                 },
                    style_header={'backgroundColor': '#f4f4f2',
                                    'fontWeight': 'bold'},
                    style_cell_conditional=[{'if': {'column_id': 'Province/State'}, 'width': '26%'},
                                            {'if': {'column_id': 'Country/Region'}, 'width': '26%'},
                                            {'if': {'column_id': 'Active'}, 'width': '14.2%'},
                                            {'if': {'column_id': 'Confirmed'}, 'width': '15.8%'},
                                            {'if': {'column_id': 'Recovered'}, 'width': '15.8%'},
                                            {'if': {'column_id': 'Deaths'}, 'width': '14.2%'},
                                            {'if': {'column_id': 'Death rate'}, 'width': '14%'},
                                            {'if': {'column_id': 'Active'}, 'color':'#e36209'},
                                            {'if': {'column_id': 'Confirmed'}, 'color': '#d7191c'},
                                            {'if': {'column_id': 'Recovered'}, 'color': '#1a9622'},
                                            {'if': {'column_id': 'Deaths'}, 'color': '#6c6c6c'},
                                            {'textAlign': 'center'}],
                        )
            ]
          )
Esempio n. 16
0
def get_data_table(total_cities_for_table):
    dash_table_columns = []
    for col in total_cities_for_table.columns:

        if col == "unemployment_pct":
            f = FormatTemplate.percentage(2)
            t = "numeric"
        elif col == "people_count" or col == UNEMPLOYED_COL_NAME:
            f = Format(
                precision=0,
                scheme=Scheme.fixed,
            )
            t = "numeric"
        else:
            f = {}
            t = "text"

        col_info = dict(name=COLUMN_NAMES_MAPPING[col],
                        id=col,
                        type=t,
                        format=f)

        dash_table_columns.append(col_info)

    dash_t = dash_table.DataTable(
        id="table",
        columns=dash_table_columns,
        data=total_cities_for_table.to_dict("rows"),
        # row_selectable="multi",
        # selected_rows=[],
        filtering=False,
        sorting=True,
        editable=False,
        #style_as_list_view=True,
        pagination_mode="fe",
        pagination_settings={
            "displayed_pages": 1,
            "current_page": 0,
            "page_size": 35,
        },
        navigation="page",
    )
    return dash_t
Esempio n. 17
0
def total_money_table(data):
    table = DataTable(
        id='total_money_table',
        columns=[
            dict(id='Type', name='Type'),
            dict(id='Total',
                 name='Total',
                 type='numeric',
                 format=Format(scheme=Scheme.fixed,
                               precision=2,
                               group=Group.yes,
                               groups=3,
                               group_delimiter=' ',
                               decimal_delimiter=',',
                               symbol=Symbol.no)),
            dict(id='Percentage',
                 name='Percentage',
                 type='numeric',
                 format=FormatTemplate.percentage(2))
        ],
        data=data.to_dict('records'),
        style_cell={
            'fontFamily': 'Rubik',
            'textAlign': 'right',
            'height': 'auto',
            # all three widths are needed
            'minWidth': '120px',
            'width': '120px',
            'maxWidth': '120px',
            'whiteSpace': 'normal'
        },
        style_cell_conditional=[
            {
                'if': {
                    'column_id': 'Type'
                },
                'textAlign': 'left'
            },
        ],
        style_as_list_view=True,
        fill_width=False)
    return table
def update_processes_table(n):
    df = create_system_table(pi.get_current_processes())

    # format percentage currently defined for ALL columns. However only applied for numeric (as per DataTable
    # documentation)
    columns = [{
        "name":
        i,
        "id":
        i,
        "type":
        lambda i: 'numeric'
        if i in ['cpu_percent', 'memory_percent'] else 'text',
        "format":
        FormatTemplate.percentage(2)
    } for i in df.columns]

    # returns df in dict format
    data = df.to_dict("records")
    return (columns, data)
Esempio n. 19
0
def get_columns_for_summary():
    money = FormatTemplate.money(2)
    columns = [
        dict(id='type', name='Type'),
        dict(id='profit', name='Profit', type='numeric', format=money),
        dict(id='max_dd', name='Max Drawdown', type='numeric', format=money),
        dict(id='slippage_paid', name='Slippage', type='numeric', format=money),
        dict(id='np_maxdd', name='NP / Max DD', type='numeric'),
        dict(id='num_trades', name='Trades', type='numeric'),
        dict(id='avg_trade', name='Avg Trade', type='numeric'),
        dict(id='profit_factor', name='Profit Factor', type='numeric'),
        dict(id='k_ratio', name='K-Ratio', type='numeric'),
        dict(id='worst_trade', name='Worst Trade', type='numeric', format=money),
        dict(id='worst_month', name='Worst Month', type='numeric', format=money),
        dict(id='profit_1m', name='Profit 1 Month', type='numeric', format=money),
        dict(id='profit_3m', name='Profit 3 Month', type='numeric', format=money),
        dict(id='profit_6m', name='Profit 6 Month', type='numeric', format=money),
        dict(id='profit_9m', name='Profit 9 Month', type='numeric', format=money),
        dict(id='profit_1y', name='Profit 1 Year', type='numeric', format=money),
    ]
    return columns
def contrarian_portfolio_tbl_fmt(df):
    return DataTable(
            columns=[{'name': i, 'id': i, 'type': 'numeric', 'format': FormatTemplate.percentage(4)} for i in
                     df.columns],
            data=df.to_dict('records'),
            style_cell={
                'textAlign': 'center',
                'whiteSpace': 'normal',
                'height': 'auto',
                'color': 'white',
                'backgroundColor': '#696969',
            },
            style_header={'backgroundColor': '#000000'},
            style_data_conditional=[
                {
                    'if': {
                        'filter_query': '{{Strategy Daily Return}} < {}'.format(0.00),
                    },
                    'backgroundColor': '#FF4136',
                },
                {
                    'if': {
                        'filter_query': '{{Strategy Daily Return}} > {}'.format(0.00),
                    },
                    'backgroundColor': '#3cb371',
                },
                {
                    'if': {
                        'state': 'active'  # 'active' | 'selected'
                    },
                    'backgroundColor': '#696969',
                    'border': '#ffffff',
                }
            ],
            style_as_list_view=True,
            page_size=20,
            export_format='csv',
            style_table={'overflowX': 'auto'}
    )
def sum_stat_tbl_fmt(df):
    return DataTable(
        columns=[{'name': i, 'id': i, 'type': 'numeric', 'format': FormatTemplate.percentage(4)} for i in
                 df.columns],
        data=df.to_dict('records'),
        style_cell={
            'textAlign': 'center',
            'whiteSpace': 'normal',
            'height': 'auto',
            'color': 'white',
            'backgroundColor': '#696969',
        },
        style_header={'backgroundColor': '#000000'},
        style_data_conditional=[
            {
                'if': {
                    'filter_query': '{{Annualized Sharpe Ratio}} < {}'.format(0.00),
                },
                'backgroundColor': '#FF4136',
            },
            {
                'if': {
                    'filter_query': '{{Annualized Sharpe Ratio}} > {}'.format(0.00),
                },
                'backgroundColor': '#3cb371',
            },
            {
                'if': {
                    'state': 'active'  # 'active' | 'selected'
                },
                'backgroundColor': '#696969',
                'border': '#ffffff',
            }
        ],
        style_as_list_view=True,
    )
Esempio n. 22
0
def update_output(n_clicks, boro, spc_common):
    if n_clicks>0:
        url = "https://data.cityofnewyork.us/resource/nwxe-4ae8.json?$limit=1000000&$where=boroname='" + boro + "'"
        trees = pd.read_json(url)
        species_list = pd.Series(trees['spc_common'].unique()).dropna().sort_values().tolist()
        species_string = str(species_list)[2:-2].replace(" \'", " ").replace("\',", ",").replace('\",', ',')
        
        try:        
            df = trees.query('spc_common == "' + spc_common + '"')
            df_cont = pd.crosstab(df.health, df.steward, margins=True, normalize=True).round(3)
            df_cont.columns = df_cont.columns + ' Stewards'
            df_cont = df_cont.rename(columns={'All Stewards': 'All'})
            df_cont.index.name = 'Health'
            df_cont.reset_index(inplace = True)
            first_col_format = {"name": df_cont.columns[0], "id": df_cont.columns[0], "type": "text"}
            col_format = [{"name": i, "id": i, "type": "numeric", "format": FormatTemplate.percentage(1)} for i in df_cont.columns[1:]]
            col_format.insert(0, first_col_format)
    
            return (html.Iframe(srcDoc=boro.replace('%20', ' ') + " species choices: <br><br>" + species_string),
                    
                    html.H3("Two Way Contingency Table:"), 
                    
                    dash_table.DataTable(
                            id='table',
                            columns=col_format,
                            data=df_cont.to_dict('records'),
                            )
                    )
        
        except:
            return (dcc.Markdown('''
                                 *Error: Check syntax of tree species.*
                                 '''), 
                    
                    html.Iframe(srcDoc=boro.replace('%20', ' ') + " species choices: <br><br>" + species_string)
                    )
Esempio n. 23
0
from dash_bootstrap_components._components.Card import Card
from dash_bootstrap_components._components.CardBody import CardBody
from dash_bootstrap_components._components.CardHeader import CardHeader
from dash_bootstrap_components._components.Col import Col
from dash_bootstrap_components._components.Row import Row
import dash_html_components as html
import dash_bootstrap_components as dbc
import dash_core_components as dcc
from dash_table import DataTable, FormatTemplate

from app_server import main_service

main_service.top_investiment('Ação')

money = FormatTemplate.money(2)
percentage = FormatTemplate.percentage(2)

cols1 = [
    #dict(id='Tipo', name='Tipo'),
    dict(id='Nome', name='Nome'),
    dict(id='financeiro', name='Posição atual', type='numeric', format=money),
    dict(id='aporte', name='Aporte', type='numeric', format=money),
    dict(id='retirada', name='Retirada', type='numeric', format=money),
    dict(id='rendimento', name='Rendimento', type='numeric', format=money),
    dict(id='%', name='%', type='numeric', format=percentage)
]

top5_cols = [
    dict(id='Nome', name='Nome'),
    dict(id='rendimento', name='Rendimento', type='numeric', format=money),
    dict(id='%', name='%', type='numeric', format=percentage)
Esempio n. 24
0
def get_columns():

    the_date = "Return % as at {}".format(get_data_date())
    
    size_cols = [{
            'id': 'investment_name',
            'name': 'Investment Name',
            'type': 'text'
        }, {
            'id': 'superfund_type',
            'name': 'Super Fund Type',
            'type': 'text'
        }, {
            'id': 'asset_class',
            'name': 'Asset Class',
            'type': 'text'
        }, {
            'id': 'fund_assets',
            'name': 'Fund Assets ($)',
            'type': 'numeric',
            'format': FormatTemplate.money(2)
        }, {
            'id': 'investment_size',
            'name': 'Investment Size ($)',
            'type': 'numeric',
            'format': FormatTemplate.money(2)
        }]

    performance_cols = [{
            'id': 'investment_name',
            'name': ['', 'Fund'],
            'type': 'text'
        }, {
            'id': 'return_5yr',
            'name': [the_date, '5 Year'],
            'type': 'numeric',
            'format': FormatTemplate.percentage(2)
        }, {
            'id': 'return_3yr',
            'name': [the_date, '3 Year'],
            'type': 'numeric',
            'format': FormatTemplate.percentage(2)
        }, {
            'id': 'return_1yr',
            'name': [the_date, '1 Year'],
            'type': 'numeric',
            'format': FormatTemplate.percentage(2)
        }, {
            'id': 'fee',
            'name': ['Fee', '$'],
            'type': 'numeric',
            'format': FormatTemplate.money(0)
        }]

    # performance_cols = [{
    #         'id': 'investment_name',
    #         'name': 'Investment Name',
    #         'type': 'text'
    #     }, {
    #         'id': 'superfund_type',
    #         'name': 'Super Fund Type',
    #         'type': 'text'
    #     }, {
    #         'id': 'asset_class',
    #         'name': 'Asset Class',
    #         'type': 'text'
    #     }, {
    #         'id': 'fee',
    #         'name': 'Fee ($)',
    #         'type': 'numeric',
    #         'format': FormatTemplate.money(0)
    #     }, {
    #         'id': 'risk_label',
    #         'name': 'Risk',
    #         'type': 'text'
        
    #     }, {
    #         'id': 'targetreturn',
    #         'name': 'Target Return (%)',
    #         'type': 'numeric',
    #         'format': FormatTemplate.percentage(2)
        
    #     }, {
    #         'id': 'return_1yr',
    #         'name': '1 Year Return (%)',
    #         'type': 'numeric',
    #         'format': FormatTemplate.percentage(2)
    #     }, {
    #         'id': 'return_3yr',
    #         'name': '3 Year Return (%)',
    #         'type': 'numeric',
    #         'format': FormatTemplate.percentage(2)
    #     }, {
    #         'id': 'return_5yr',
    #         'name': '5 Year Return (%)',
    #         'type': 'numeric',
    #         'format': FormatTemplate.percentage(2)
    #     }, {
    #         'id': 'invfee',
    #         'name': 'Investment Fee (%)',
    #         'type': 'numeric',
    #         'format': FormatTemplate.percentage(4)
    #     }, {
    #         'id': 'admin_fee',
    #         'name': 'Admin Fee (%)',
    #         'type': 'numeric',
    #         'format': FormatTemplate.percentage(4)
    #     }]
    
    details_cols = [{
            'id': 'investment_name',
            'name': 'Fund',
            'type': 'text'
        }, {
            'id': 'superfund_type',
            'name': 'Fund Type',
            'type': 'text'
        }, {
            'id': 'asset_class',
            'name': 'Asset Class',
            'type': 'text'
        }, {
            'id': 'fund_assets',
            'name': 'Fund Assets',
            'type': 'numeric',
            'format': FormatTemplate.money(2)
        }]
    
    objective_cols = [{
            'id': 'investment_name',
            'name': 'Fund',
            'type': 'text'
        }, {
            'id': 'targetreturn',
            'name': 'Target Return',
            'type': 'numeric',
            'format': FormatTemplate.percentage(2)
        
        }, {
            'id': 'risk_label',
            'name': 'Risk',
            'type': 'text'
        
        }]

    return performance_cols, size_cols, details_cols, objective_cols
Esempio n. 25
0
def generate_pf_content():
    day, pf_sym_view = df_pf_symbol()
    pf_sym_view.reset_index(inplace=True)
    xirr_timeseries = get_xirr_timeseries()
    return_timeseries = get_returns_timeseries()

    xirr_traces = []
    for column in xirr_timeseries.columns:
        xirr_traces.append(
            go.Scatter(x=xirr_timeseries.index,
                       y=xirr_timeseries[column],
                       name=column))
    xirr_data = xirr_traces

    return_traces = []
    for column in return_timeseries.columns:
        return_traces.append(
            go.Scatter(x=return_timeseries.index,
                       y=return_timeseries[column],
                       name=column))
    return_data = return_traces

    xirr_fig = go.Figure(data=xirr_data, layout=get_table_layout())
    return_fig = go.Figure(data=return_data, layout=get_table_layout())

    tab1_content = html.Div(children=[
        html.H1(children=["Portfolio Data from " + day.strftime("%d.%m.%y")],
                style={'textAlign': 'center'}),
        html.Div(
            style={
                'width': '75%',
                'margin': 'auto'
            },
            children=[
                dash_table.DataTable(
                    id='table',
                    columns=[
                        {
                            'id': "Portfolio",
                            'name': "Portfolio",
                            'type': "text"
                        },
                        {
                            'id': "Symbol",
                            'name': "Symbol",
                            'type': "text"
                        },
                        {
                            'id': "Holdings",
                            'name': "Holdings",
                            'type': "numeric"
                        },
                        {
                            'id': "Price",
                            'name': "Price",
                            'type': "numeric",
                            'format': euro(2)
                        },
                        {
                            'id': "Value",
                            'name': "Value",
                            'type': "numeric",
                            'format': euro(2)
                        },
                        {
                            'id': "Turnover",
                            'name': "Turnover",
                            'type': "numeric",
                            'format': euro(2)
                        },
                        {
                            'id': "Fees",
                            'name': "Fees",
                            'type': "numeric",
                            'format': euro(2)
                        },
                        {
                            'id': "Return(tot)",
                            'name': "Return(tot)",
                            'type': "numeric",
                            'format': euro(2)
                        },
                        {
                            'id': "Return(rel)",
                            'name': "Return(rel)",
                            'type': "numeric",
                            'format': FormatTemplate.percentage(1)
                        },
                        {
                            'id': "XIRR",
                            'name': "XIRR",
                            'type': "numeric",
                            'format': FormatTemplate.percentage(1)
                        },
                    ],
                    data=pf_sym_view.round(2).to_dict("records"),
                    style_as_list_view=True,
                    style_cell={
                        "textAlign": 'right',
                        "padding": '5px',
                        'fontSize': 14,
                        'font-family': 'sans-serif'
                    },
                    style_header={
                        'backgroundColor': 'darkgrey',
                        'fontWeight': 'bold',
                        'color': 'white'
                    },
                    style_cell_conditional=[{
                        'if': {
                            'column_id': header
                        },
                        'textAlign': 'left',
                        'width': '50px'
                    } for header in ["Portfolio", "Symbol"]] + [{
                        'if': {
                            'column_id': data_header
                        },
                        'textAlign': 'right',
                        'width': '20px'
                    } for data_header in pf_sym_view.columns.drop(
                        ["Portfolio", "Symbol"])],
                    style_data_conditional=[{
                        'if': {
                            'filter_query': '{Symbol} = ""'
                        },
                        'backgroundColor': 'lightgrey',
                        'fontWeight': 'bold'
                    }],
                )
            ]),
        html.H4(children="Time Series"),
        html.H5(children="XIRR Chart"),
        dcc.Graph(figure=xirr_fig),
        html.H5(children="Total Returns Chart"),
        dcc.Graph(figure=return_fig)
    ])
    return tab1_content
Esempio n. 26
0
def main_table(tickers, start_date):
    columns = [
        {
            'name': ['', 'Stock'],
            'id': 'Stock',
            'type': 'text',
            # 'presentation':'markdown',
        },
        {
            'name': ['', 'ROI'],
            'id': 'ROI',
            'type': 'numeric',
            'format': FormatTemplate.percentage(1).sign(Sign.positive),
        },
        {
            'name': ['Forecast', 'Score'],
            'id': 'Score',
            'type': 'numeric',
            'format': Format(precision=2, scheme=Scheme.fixed),
        },
        # {
        # 	'name': ['Forecast','N'],
        # 	'id':'N',
        # 	'type':'numeric',
        # },
        {
            'name': ['Forecast', 'NTM ROI'],
            'id': 'NTM ROI',
            'type': 'numeric',
            'format': FormatTemplate.percentage(1).sign(Sign.positive),
        },
        {
            'name': ['Growth Estimate', 'Qrt'],
            'id': 'Quarter',
            'type': 'numeric',
            'format': FormatTemplate.percentage(2).sign(Sign.positive),
        },
        {
            'name': ['Growth Estimate', 'Next Qtr'],
            'id': 'NextQuarter',
            'type': 'numeric',
            'format': FormatTemplate.percentage(2).sign(Sign.positive),
        },
        {
            'name': ['Growth Estimate', 'Year'],
            'id': 'Year',
            'type': 'numeric',
            'format': FormatTemplate.percentage(2).sign(Sign.positive),
        },
        {
            'name': ['Growth Estimate', 'Next Year'],
            'id': 'NextYear',
            'type': 'numeric',
            'format': FormatTemplate.percentage(2).sign(Sign.positive),
        },
    ]
    data = []
    for t in tickers:
        if t not in STOCKS or t not in RATINGS:
            print('{} is not found.'.format(t))
            continue
        # start = determine_start_date(start_date)
        start = start_date
        end = datetime.datetime.today()
        stock_df = STOCKS[t][start:end]
        rating_df = RATINGS[t][start:end]
        trends = FINANCIALS[t]['trends']
        if len(stock_df) > 0:
            latest_price = stock_df.iloc[-1]['Adj Close']
            target_price = rating_df[rating_df.Price > 0].Price
            if len(target_price) == 0:
                med_roi = 0
                # min_roi, med_roi, max_roi = 0, 0, 0
            else:
                med_roi = target_price.median() / latest_price - 1
                # min_roi = target_price.min()/latest_price-1
                # max_roi = target_price.max()/latest_price-1

            # return_at_forecast = []
            gaps = []
            for i in range(len(target_price)):
                date = target_price.index[i]
                idx = min(np.searchsorted(stock_df.index, date),
                          len(stock_df) - 1)
                price_at_forecast = stock_df.iloc[idx]['Adj Close']
                # return_at_forecast.append(target_price.iloc[i]/price_at_forecast-1)

                t_at_forecast = stock_df.index[idx]
                t_latest = stock_df.index[-1]
                p_star = price_at_forecast + (
                    target_price.iloc[i] -
                    price_at_forecast) * (t_latest - t_at_forecast).days / 365
                gap = (latest_price - p_star) / latest_price
                gaps.append(gap)

            if len(rating_df[rating_df.Rating >= 0]) > 0:
                score = rating_df[rating_df.Rating >= 0].Rating.mean()
            else:
                score = -1
            data.append({
                'Stock':
                t,
                'ROI':
                stock_df.iloc[-1]['Adj Close'] / stock_df.iloc[0]['Adj Close']
                - 1,
                'Score':
                score,
                # 'N' : len(rating_df.Price),
                'NTM ROI':
                med_roi,
                'Quarter':
                trends['Growth_Quarter'] / 100,
                'NextQuarter':
                trends['Growth_NextQuarter'] / 100,
                'Year':
                trends['Growth_Year'] / 100,
                'NextYear':
                trends['Growth_NextYear'] / 100,
            })
        else:
            Debug('No data for', t, 'within range.')

    data.sort(key=lambda c: c['Score'], reverse=True)
    return data, columns, 'single'
Esempio n. 27
0
def secondary_table(ticker, start_date):
    rating_label = {
        0: '?',
        1: 'Sell',
        2: 'Hold',
        3: 'Buy',
        4: 'Outperform',
        5: 'Strong Buy'
    }
    columns = [
        {
            'name': 'Date',
            'id': 'Date',
        },
        {
            'name': 'Forecaster',
            'id': 'Forecaster',
        },
        {
            'name': 'Trust',
            'id': 'Trust',
            'type': 'numeric',
        },
        {
            'name': 'Rating',
            'id': 'Rating',
        },
        {
            'id': 'ROI',
            'name': 'ROI',
            'type': 'numeric',
            'format': FormatTemplate.percentage(1).sign(Sign.positive),
        },
    ]
    # start = determine_start_date(start_date)
    start = start_date
    end = datetime.datetime.today()

    stock = STOCKS[ticker]
    series = stock['Adj Close'][start:end]

    df = RATINGS[ticker][start:end]
    df = df.sort_index(ascending=False)
    data = []
    for i in range(len(df)):
        date = df.index[i]
        idx = min(np.searchsorted(series.index, date), len(series) - 1)
        date_nearest = series.index[idx]
        close_price = stock['Adj Close'].loc[date_nearest]

        item = df.iloc[i]
        trust = round(get_analyst_score(item.Analyst), 2)
        data.append({
            'Date':
            datetime.datetime.strftime(item.name, '%m.%d'),
            'Forecaster':
            item.Analyst,
            'Trust':
            trust,
            'Rating':
            rating_label[item.Rating],
            'ROI':
            0 if item.Price == 0 else item.Price / close_price - 1,
        })
    return data, columns
Esempio n. 28
0
 def publishers_table(self):
     return dash_table.DataTable(
         id='dataset_by_publisher_table',
         columns=[
             #{'name': '', 'id': 'index'},
             {
                 'name': 'Publisher',
                 'id': 'publisher'
             },
             #{'name': 'Score', 'id': 'weighted score', 'format': Format(precision=2, scheme=Scheme.decimal)},
             {
                 'name': 'Score',
                 'id': 'weighted score ratio',
                 'type': 'numeric',
                 'format': FormatTemplate.percentage(1)
             },
         ],
         data=self.df.groupby('publisher', as_index=False).mean().round({
             'weighted score':
             2
         }).to_dict('records'),
         sort_action='native',
         style_cell={
             'textAlign': 'left',
             'whiteSpace': 'normal'
         },
         # virtualization=True,
         style_cell_conditional=[
             {
                 'if': {
                     'column_id': 'weighted score ratio'
                 },
                 'fontWeight': 'bold',
                 'textAlign': 'center'
             },
             #{'if': {'row_index': 'odd'},'backgroundColor': 'rgb(248, 248, 248)'},
         ],
         style_data_conditional=[
             {
                 'if': {
                     'column_id': 'weighted score ratio',
                     'filter_query': '{weighted score ratio} > 0.5'
                 },
                 'backgroundColor': '#238823'
             },
             {
                 'if': {
                     'column_id': 'weighted score ratio',
                     'filter_query': '{weighted score ratio} > 0.2'
                 },
                 'backgroundColor': '#FFBF00'
             },
             {
                 'if': {
                     'column_id': 'weighted score ratio',
                     'filter_query': '{weighted score ratio} < 0.2'
                 },
                 'backgroundColor': '#D2222D',
                 'color': 'white'
             },
         ],
         style_as_list_view=True,
         style_table={
             'margin': 0,
             'padding': 0,
         },
         style_header={
             'backgroundColor': 'rgb(230, 230, 230)',
             'fontWeight': 'bold',
         })
Esempio n. 29
0
def update_chart(start_date, end_date, reporting_l1_dropdown,
                 reporting_l2_dropdown):
    start = dt.strptime(start_date, '%Y-%m-%d')
    end = dt.strptime(end_date, '%Y-%m-%d')

    # Filter based on the dropdowns
    isselect_all_l1 = 'Start'  #Initialize isselect_all
    isselect_all_l2 = 'Start'  #Initialize isselect_all
    ## L1 selection (dropdown value is a list!)
    for i in reporting_l1_dropdown:
        if i == 'All':
            isselect_all_l1 = 'Y'
            break
        elif i != '':
            isselect_all_l1 = 'N'
        else:
            pass
    # Filter df according to selection
    if isselect_all_l1 == 'N':
        sales_df_1 = sales_import.loc[
            sales_import[sales_fields['reporting_group_l1']].
            isin(reporting_l1_dropdown), :].copy()
    else:
        sales_df_1 = sales_import.copy()
    ## L2 selection (dropdown value is a list!)
    for i in reporting_l2_dropdown:
        if i == 'All':
            isselect_all_l2 = 'Y'
            break
        elif i != '':
            isselect_all_l2 = 'N'
        else:
            pass
    # Filter df according to selection
    if isselect_all_l2 == 'N':
        sales_df = sales_df_1.loc[
            sales_df_1[sales_fields['reporting_group_l2']].
            isin(reporting_l2_dropdown), :].copy()
    else:
        sales_df = sales_df_1.copy()
    del sales_df_1

    # Filter based on the date filters
    df_1 = sales_df.loc[(sales_df[sales_fields['date']] >= start) &
                        (sales_df[sales_fields['date']] <= end), :].copy()
    del sales_df

    # Aggregate df
    metrics = ['Sales (M u)', 'Revenues (M €)', 'Customers (M)']
    result = [
        df_1[sales_fields['sales']].sum() / 1000000,
        df_1[sales_fields['revenues']].sum() / 1000000,
        df_1[sales_fields['num clients']].sum() / 1000000
    ]
    target = [
        df_1[sales_fields['sales target']].sum() / 1000000,
        df_1[sales_fields['rev target']].sum() / 1000000, ''
    ]
    performance = [
        df_1[sales_fields['sales']].sum() /
        df_1[sales_fields['sales target']].sum(),
        df_1[sales_fields['revenues']].sum() /
        df_1[sales_fields['rev target']].sum(), ''
    ]
    df = pd.DataFrame({
        'KPI': metrics,
        'Result': result,
        'Target': target,
        'Target_Percent': performance
    })

    # Configure table data
    data = df.to_dict('records')
    columns = [{
        'id': 'KPI',
        'name': 'KPI'
    }, {
        'id':
        'Result',
        'name':
        'Result',
        'type':
        'numeric',
        'format':
        Format(scheme=Scheme.fixed,
               precision=2,
               group=Group.yes,
               group_delimiter=',',
               decimal_delimiter='.')
    }, {
        'id':
        'Target',
        'name':
        'Target',
        'type':
        'numeric',
        'format':
        Format(scheme=Scheme.fixed,
               precision=2,
               group=Group.yes,
               group_delimiter=',',
               decimal_delimiter='.')
    }, {
        'id': 'Target_Percent',
        'name': '% Target',
        'type': 'numeric',
        'format': FormatTemplate.percentage(2)
    }]

    # Configure conditional formatting
    conditional_style = [
        {
            'if': {
                'filter_query': '{Result} >= {Target} && {Target} > 0',
                'column_id': 'Target_Percent'
            },
            'backgroundColor': corporate_colors['light-green'],
            'color': corporate_colors['dark-green'],
            'fontWeight': 'bold'
        },
        {
            'if': {
                'filter_query': '{Result} < {Target} && {Target} > 0',
                'column_id': 'Target_Percent'
            },
            'backgroundColor': corporate_colors['pink-red'],
            'color': corporate_colors['dark-green'],
            'fontWeight': 'bold'
        },
    ]

    return data, columns, conditional_style
Esempio n. 30
0
==========================================================================
Tables
"""

total_returns_table = html.Div([
    dash_table.DataTable(
        id="total_returns",
        columns=[{
            "id": "Year",
            "name": "Year",
            "type": "text"
        }] + [{
            "id": col,
            "name": col,
            "type": "numeric",
            "format": FormatTemplate.money(0),
        } for col in ["Cash", "Bonds", "Stocks", "Total"]],
        style_table={
            "overflowY": "scroll",
            "border": "thin lightgrey solid",
            "maxHeight": "425px",
        },
        style_cell={
            "textAlign": "right",
            "font-family": "arial"
        },
        style_cell_conditional=[{
            "if": {
                "column_id": "Year"
            },
            "type": "text"