Exemple #1
0
def draw_income_statement(symbol, format="raw"):
  index = list_symbols.index(symbol)
  raw_df, percent_df = read_income_statement_with_cache(symbol)

  quarter_cols = raw_df.columns.tolist()

  if format == "raw":
    columns = [{"name": "fields", "id": "fields", "type": "text"}] + \
              [{"name": i, "id": i,
                'type': 'numeric',
                "format": Format(scheme=Scheme.fixed, group=',', precision=0)} for i in raw_df.columns]
    data = raw_df.to_dict("records")
  else:
    columns = [{"name": "fields", "id": "fields", "type": "text"}] + \
              [{"name": i, "id": i,
                'type': 'numeric',
                "format": Format(scheme=Scheme.percentage, precision=2)} for i in percent_df.columns]
    data = percent_df.to_dict("records")

  for f, r in zip(raw_df.index.tolist(), data):
    r["fields"] = f
  income_statement_table = html.Div([
    dbc.DropdownMenu([
      dbc.DropdownMenuItem("Raw", id={'type': f'dynamic-{card_name}-view-raw', 'index': index}),
      dbc.DropdownMenuItem("Percent", id={'type': f'dynamic-{card_name}-view-percent', 'index': index})
    ], label="View"),
    dtb.DataTable(
      id={
        'type': f'dynamic-{card_name}',
        'index': index
      },
      columns=columns,
      data=data,
      style_cell_conditional=[
        {'if': {'column_id': "fields"},
         'textAlign': 'left'},
        {'if': {'column_id': quarter_cols},
         'minWidth': '150px'}
      ],
      style_table={'overflowX': 'scroll', 'overflowY': 'scroll', 'height': '600px', 'minWidth': '100%'},
      style_header={
        'backgroundColor': 'rgb(230,230,230)',
        'fontWeight': 'bold'
      },
      style_cell={"marginLeft": "0px"},
      style_data_conditional=[
        {'if': {'row_index': [0, 21]}, 'fontWeight': 'bold'}],
      fixed_columns={'headers': True, 'data': 1},
      fixed_rows={'headers': True, 'data': 0},
      css=[{'selector': '.row', 'rule': 'margin: 0;flex-wrap: nowrap'}],

    ),
    html.Div(children="", style={'paddingBottom': '50px'}),
  ])

  return income_statement_table, columns, data
    def test_complex_and_valid_in_fluent(self):
        res = Format().align(f.Align.center).fill('.').group(
            f.Group.yes
        ).padding(True).padding_width(10).precision(6).scheme('s').sign(
            f.Sign.parantheses).symbol(
                f.Symbol.yes).symbol_prefix('a').symbol_suffix(
                    'bc').decimal_delimiter('x').group_delimiter('y').groups(
                        [2, 2, 2, 3]).nully('N/A').si_prefix(f.Prefix.none)

        self.validate_complex(res.to_plotly_json())
Exemple #3
0
def update_graph(num):
    # print("""update every 3 seconds""")
    if num == 0:
        raise PreventUpdate
    else:
        df_table = filter_prediction_df.copy()
        formato = Format(
            scheme=Scheme.fixed,
            precision=2,
            group=Group.yes,
            groups=3,
            group_delimiter=".",
            decimal_delimiter=",",
        )

        formato_int = Format(
            scheme=Scheme.fixed,
            precision=0,
            group=Group.yes,
            groups=3,
            group_delimiter=".",
            decimal_delimiter=",",
        )
        df_table.index.name = 'Cluster'
        df_table.reset_index(inplace=True)
        # cols = df_table.columns.drop("date_outage")
        cols = df_table.columns
        df_table[cols] = df_table[cols].apply(pd.to_numeric)
        df_numeric = df_table.select_dtypes(exclude=["object"])
        df_numeric.sort_values("Cluster", ascending=True, inplace=True)
        df_numeric.columns = df_numeric.columns.map(
            lambda x: x.replace("_", " "))
        cols = [{
            "name":
            i,
            "id":
            i,
            "type":
            "numeric",
            "format":
            formato_int if i in ["Cluster", "label", "line"] else formato,
        } for i in df_numeric.columns]
        style_data_conditional = [
            {
                "if": {
                    "filter_query": "{label} = 1"
                },
                "backgroundColor": "#FF4136",
                "color": "white",
                "fontWeight": "bold",
            },
        ]
        return (figure, dt.now().strftime("%H:%M:%S.%f")[:-4],
                "{:.1f}%".format(filter_prediction_df.prediction.max() * 100),
                df_numeric.to_dict("records"), cols, style_data_conditional)
Exemple #4
0
def makeColumns():
    desiredOrder = [
        ('Rang', ['Risiko', 'Rang'], 'numeric', FormatInt),
        ('Kontaktrisiko', ['Risiko', 'Risiko 1:N'], 'numeric', FormatInt),
        ('Landkreis', ['Kreis', 'Name'], 'text', Format()),
        ('Bundesland', ['Kreis', 'Bundesland'], 'text', Format()),
        ('LandkreisTyp', ['Kreis', 'Art'], 'text', Format()),
        ('Bevoelkerung', ['Kreis', 'Einwohner'], 'numeric', FormatInt),
        ('LetzteMeldung', ['Kreis', 'Letze Meldung'], 'numeric', FormatInt),
        ('AnzahlFallTrend', ['Fälle', 'Rw'], 'numeric', FormatFixed2),
        ('AnzahlFallLetzte7Tage', ['Fälle',
                                   'letzte Woche'], 'numeric', FormatInt),
        ('AnzahlFallLetzte7TageDavor', ['Fälle', 'vorletzte Woche'], 'numeric',
         FormatInt),
        ('AnzahlFall', ['Fälle', 'total'], 'numeric', FormatInt),
        ('FaellePro100kLetzte7Tage', ['Fälle je 100000', 'letzte Woche'],
         'numeric', FormatFixed1),
        ('FaellePro100kLetzte7TageDavor',
         ['Fälle je 100000', 'vorletzte Woche'], 'numeric', FormatFixed1),
        ('FaellePro100kTrend', ['Fälle je 100000',
                                'Differenz'], 'numeric', FormatFixed1),
        ('FaellePro100k', ['Fälle je 100000',
                           'total'], 'numeric', FormatFixed1),
        ('AnzahlTodesfallLetzte7Tage', ['Todesfälle',
                                        'letzte Woche'], 'numeric', FormatInt),
        ('AnzahlTodesfallLetzte7TageDavor', ['Todesfälle', 'vorletzte Woche'],
         'numeric', FormatInt),
        ('AnzahlTodesfall', ['Todesfälle', 'total'], 'numeric', FormatInt),
        ('TodesfaellePro100kLetzte7Tage',
         ['Todesfälle je 100000', 'letzte Woche'], 'numeric', FormatFixed2),
        ('TodesfaellePro100kLetzte7TageDavor',
         ['Todesfälle je 100000', 'vorletzte Woche'], 'numeric', FormatFixed2),
        ('TodesfaellePro100kTrend', ['Todesfälle je 100000',
                                     'Differenz'], 'numeric', FormatFixed2),
        ('TodesfaellePro100k', ['Todesfälle je 100000',
                                'total'], 'numeric', FormatFixed2),
    ]

    orderedCols, orderedNames, orderedTypes, orderFormats = zip(*desiredOrder)
    #orderedIndices = np.array(orderedIndices)+1
    #print(orderedIndices)

    columns = [{
        'name': L1,
        'id': L2,
        'type': L3,
        'format': L4
    } for (L1, L2, L3,
           L4) in zip(orderedNames, orderedCols, orderedTypes, orderFormats)]
    print("columns=", columns)
    return columns
Exemple #5
0
def select_table_columns(ts, values, data):
    """
    Select columns displayed in the table. A custom column is available and 
    filled with zero by default.
    """

    # get data from the Store component
    df = pd.DataFrame(data)

    if values is None:
        # initial set up
        return [], []
    else:
        # fill the table with the selected columns
        tab_df = df[values]
        data = tab_df.to_dict("records")

        # add format
        columns = list()
        for column in tab_df:
            if column in {"atom index", "species", "neighbors", "custom"}:
                columns.append({"name": column, "id": column})
            elif column[:4] == "prop":
                columns.append({"name": column, "id": column})
            else:
                columns.append({
                    "name": column, "id": column, "type": "numeric",
                    "format": Format(
                        precision=4,
                        scheme=Scheme.fixed,
                    )
                })

        return data, columns
Exemple #6
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': 'Percent', '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'}
         ],
         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})
Exemple #7
0
    def get_columns(self):
        """
        Returns
        -------
        columns : list of dicts
            List of column dictionaries in dash_table columns format.
        """
        format = Format(scheme=Scheme.fixed, precision=2)

        def get_dist_columns(id):
            return [{
                'id': id + 'pdf',
                'name': id,
                'editable': False,
                'type': 'numeric',
                'format': format
            }, {
                'id': id + 'cdf',
                'name': id + ' (cdf)',
                'editable': False,
                'type': 'numeric',
                'format': format
            }]

        columns = [{
            'id': 'bin-start',
            'name': 'Bin start',
            'type': 'numeric'
        }, {
            'id': 'bin-end',
            'name': 'Bin end',
            'type': 'numeric'
        }]
        [columns.extend(get_dist_columns(id)) for id in self._dist_ids]
        return columns
Exemple #8
0
def make_fft_table(df):
    """Return the speedup table for fft. For the speedup
    columns, formating is done to show the divergent from the
    midpoint.
    """
    columns = list(df.columns)
    interest_cols = [i for i in columns if 'over' in i]
    style_data_conditional = [
        data_bars_diverging(df, a) for a in interest_cols
    ]
    styles = [item for sublist in style_data_conditional for item in sublist]
    table = dash_table.DataTable(data=df.to_dict('records'),
                                 sort_action='native',
                                 columns=[{
                                     'name':
                                     i,
                                     'id':
                                     i,
                                     "type":
                                     'numeric',
                                     "format":
                                     Format(precision=6, scheme=Scheme.fixed)
                                 } for i in df.columns],
                                 style_data_conditional=(styles),
                                 style_cell={
                                     'minWidth': 105,
                                     'maxWidth': 105,
                                     'width': 105
                                 },
                                 style_header={
                                     'overflow': 'hidden',
                                     'textOverflow': 'ellipsis',
                                     'maxWidth': 0,
                                 })
    return table
Exemple #9
0
def create_table_columns(
    columns: list,
    volumemodel: Optional[InplaceVolumesModel] = None,
    format_columns: Optional[list] = None,
    use_si_format: Optional[bool] = None,
) -> List[dict]:

    format_columns = format_columns if format_columns is not None else []

    table_columns = []
    for col in columns:
        data = {"id": col, "name": col}
        if col in format_columns:
            data.update({
                "type": "numeric",
                "format": {
                    "locale": {
                        "symbol": ["", ""]
                    },
                    "specifier": "$.4s"
                } if use_si_format or volumemodel is not None
                and col in volumemodel.volume_columns else Format(precision=3),
            })
        table_columns.append(data)
    return table_columns
def table_graph(price, units, n_click):
    if n_click == None or n_click % 2 == 0:
        table_data = []  # empty table
        table_columns = []
        fig = go.Figure(data=[go.Mesh3d(x=[], y=[], z=[])])
        return (table_data, table_columns, fig)
    elif (n_click % 2 == 1):
        # build the table. data and styling goes here! Format() is a lifesaver.
        tbl = cost_table(price, units=units)
        table_data = tbl.to_dict('records')
        table_columns = [{
            "name": i,
            "id": i,
            "type": "numeric",
            "format": Format(precision=4)
        } for i in tbl.columns]
        # build the graph. data and styling goes here!
        fig = go.Figure(data=[
            go.Mesh3d(z=tbl['Cost'],
                      x=tbl['Number of Days'],
                      y=tbl['Total Number of Jobs'],
                      opacity=1,
                      intensity=tbl['Cost'],
                      colorscale="Inferno")
        ])
        fig.update_layout(title="Job cost over time and number of jobs",
                          scene=dict(xaxis_title="Number of Days (X)",
                                     yaxis_title="Total Number of Jobs (Y)",
                                     zaxis_title="Cost (Z)"))
    return (table_data, table_columns, fig)
Exemple #11
0
    def update_table_cols(interval, group, operation, *cols):
        ctx = dash.callback_context

        if ctx.triggered[0]['prop_id'] == 'interval1.n_intervals':
            local_data = pd.read_csv(Path(args['logdir'], 'results.csv'))
        else:
            local_data = df_data

        if group and operation:
            local_data = group_apply(df_data, group, operation)
        else:
            local_data = df_data

        cols_ = []
        for col in cols:
            cols_ = cols_ + [
                col_i for col_i in col if col_i in local_data.columns
            ]
        out_cols = [{
            "name": i,
            "id": i,
            'format': Format(precision=3),
            'type': 'numeric'
        } for i in cols_]

        return out_cols
Exemple #12
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
def table_from_dataframe(df,
                         id="table",
                         row_deletable=True,
                         row_selectable="multi"):
    return dt.DataTable(
        id=id,
        columns=[{
            "name": i,
            "id": i,
            "format": Format(precision=2)
        } for i in df.columns],
        data=df.iloc[::-1].to_dict("records"),
        sort_action="native",
        sort_mode="single",
        row_selectable=row_selectable,
        row_deletable=row_deletable,
        selected_rows=[],
        filter_action="native",
        page_action="native",
        page_current=0,
        page_size=16,
        style_table={"overflowX": "scroll"},
        export_format="csv",
        export_headers="display",
        merge_duplicate_headers=True,
        style_cell={
            "font_size": "10px",
            "padding-left": "5em",
            "padding-right": "5em"
        },
    )
Exemple #14
0
def simple_dash_table(input_gap, date_slider):
    # input_date = dt.strptime(re.split('T| ', input_date)[0], '%Y-%m-%d').date()
    start_date = date.fromordinal(min(date_slider))
    end_date = date.fromordinal(max(date_slider))
    df = api_data[(api_data['date'] == start_date) | (api_data['date'] == end_date)]
    pt = df.pivot_table(columns=['spot'], values='value', index=['date', 'plot_type'],
                        aggfunc=sum).reset_index()
    # pt = pt[(pt.plot_type != 'spot') & (pt.plot_type != 't')]
    for i in pt.columns:
        if isinstance(i, int):
            pt[i] = pd.to_numeric(pt[i])
    columns = [{'id': 'date', 'name': 'date', 'type': 'text'}] + \
              [{'id': 'plot_type', 'name': 'plot_type', 'type': 'text'}] + \
              [{'id': str(i),
                'name': str(i),
                'type': 'numeric',
                'format': Format(
                    nully='N/A',
                    precision=2,
                    scheme=Scheme.fixed,
                    sign=Sign.parantheses
                )}
               for i in pt.columns if isinstance(i, int) and i % int(input_gap) == 0]
    data = pt[[i for i in pt.columns if isinstance(i, str) or i % int(input_gap) == 0]].to_dict('records')
    style_data_conditional = [{'if': {'row_index': 'odd'}, 'backgroundColor': '#e2f2f6'}] + \
                             [{'if': {'column_id': col['id'], 'filter_query': '{}<0.0'.format("{" + col['id'] + "}")},
                               'color': 'red'}
                              for col in columns if col['type'] == 'numeric']
    return columns, data, style_data_conditional
Exemple #15
0
def get_pca_columns_settings(dataframe):
    """ Get display settings of columns for PC vs. UCM table.

    :param dataframe: Angles between principal components and ucm vectors.
    :type dataframe: pandas.DataFrame
    :return: List of dicts. Columns displaying float values have special formatting.
    :rtype: list
    """
    columns = list()
    for c in dataframe.columns:
        if dataframe[c].dtype == 'float':
            columns.append({
                'name':
                c.capitalize(),
                'id':
                c,
                'type':
                'numeric',
                'format':
                Format(nully='N/A',
                       precision=2,
                       scheme=Scheme.fixed,
                       symbol=Symbol.yes,
                       symbol_suffix=u'˚')
            })
        else:
            label = c.capitalize() if c != 'PC' else c
            columns.append({
                'name': label,
                'id': c,
                'type': table_type(dataframe[c])
            })
    return columns
Exemple #16
0
def get_columns_settings(dataframe, order=None):
    """ Get display settings of columns for tables.
    
    :param dataframe: Data
    :type dataframe: pandas.DataFrame
    :param order: Custom order for columns. Use position, in case names change.
    :type order: list[int]
    :return: List of dicts. Columns displaying float values have special formatting.
    :rtype: list
    """
    columns = list()
    if order is None:
        cols = dataframe.columns
    else:
        # Reorder columns.
        try:
            cols = [dataframe.columns[i] for i in order]
        except IndexError:
            logging.log(logging.WARNING, "Order of columns out of range.")
            cols = dataframe.columns
    for c in cols:
        # Nicer column names. Exclude df1 and df2 from renaming.
        if c == 'dV':
            label = '$\\Delta V$'
        elif c == 'dVz':
            label = '$\\Delta V_z$'
        elif c == 'p-unc':
            label = 'p'
        elif c.startswith('p-'):
            label = c
        elif c == 'SS':
            label = 'Sum of Squares'
        elif c == 'MS':
            label = 'Mean Square'
        elif c == 'np2':
            label = '$\\eta_{p}^{2}$'
        elif c == 'eps':
            label = '$\\epsilon$'
        else:
            label = c.replace("_", " ").title()
        if 'Df' in label:
            label = label.replace("Df1", "df1").replace("Df2", "df2")

        if dataframe[c].dtype == 'float':
            columns.append({
                'name': label,
                'id': c,
                'type': 'numeric',
                'format': Format(precision=2, scheme=Scheme.fixed)
            })
        else:
            columns.append({
                'name': label,
                'id': c,
                'type': table_type(dataframe[c])
            })
    return columns
Exemple #17
0
    def test_complex_and_valid_in_fluent(self):
        res = (Format().align(f.Align.center).fill(".").group(
            f.Group.yes).padding(True).padding_width(10).precision(6).scheme(
                "s").sign(f.Sign.parantheses).symbol(
                    f.Symbol.yes).symbol_prefix("a").symbol_suffix("bc").
               decimal_delimiter("x").group_delimiter("y").groups(
                   [2, 2, 2, 3]).nully("N/A").si_prefix(f.Prefix.none))

        self.validate_complex(res.to_plotly_json())
Exemple #18
0
 def make_table(df: pd.DataFrame) -> Tuple[List[Any], List[Any]]:
     df.columns = df.columns.map(" | ".join).str.strip(" | ")
     columns = [{
         "id": col,
         "name": col,
         "type": "numeric",
         "format": Format(precision=3)
     } for col in df.columns]
     return columns, df.iloc[::-1].to_dict("records")
Exemple #19
0
def update_topology(contents, filename):
    if not contents:
        return [{" ": " "}], [{"name": " ", "id": " "}]
    else:
        dff, _ = parse_contents(contents, filename)
        return dff.to_dict('records'), [{
            "name": i,
            "id": i,
            "format": Format(precision=4)
        } for i in dff.columns]
    def test_complex_and_valid_in_ctor(self):
        res = Format(align=f.Align.center,
                     fill='.',
                     group=f.Group.yes,
                     padding=True,
                     padding_width=10,
                     precision=6,
                     scheme='s',
                     sign=f.Sign.parantheses,
                     symbol=f.Symbol.yes,
                     symbol_prefix='a',
                     symbol_suffix='bc',
                     decimal_delimiter='x',
                     group_delimiter='y',
                     groups=[2, 2, 2, 3],
                     nully='N/A',
                     si_prefix=f.Prefix.none)

        self.validate_complex(res.to_plotly_json())
Exemple #21
0
 def make_table(df: pd.DataFrame) -> Tuple[List[Any], List[Any]]:
     """Return format needed for dash table"""
     col_order = ["PARAMETER", "Avg", "Stddev", "P90", "P10", "Min", "Max"]
     df = df.reindex(col_order, axis=1, level=0)
     df.columns = df.columns.map(" | ".join).str.strip(" | ")
     columns = [{
         "id": col,
         "name": col,
         "type": "numeric",
         "format": Format(precision=3)
     } for col in df.columns]
     return columns, df.to_dict("records")
Exemple #22
0
    def test_complex_and_valid_in_ctor(self):
        res = Format(
            align=f.Align.center,
            fill=".",
            group=f.Group.yes,
            padding=True,
            padding_width=10,
            precision=6,
            scheme="s",
            sign=f.Sign.parantheses,
            symbol=f.Symbol.yes,
            symbol_prefix="a",
            symbol_suffix="bc",
            decimal_delimiter="x",
            group_delimiter="y",
            groups=[2, 2, 2, 3],
            nully="N/A",
            si_prefix=f.Prefix.none,
        )

        self.validate_complex(res.to_plotly_json())
Exemple #23
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
Exemple #24
0
def show_wordlist(input0, input1, input2, lang):
    global DF
    DF = sheet_load()

    df = DF.get(lang)
    t = dash_table.DataTable(
        id='word-table',
        columns=[{
            "name": i.capitalize(),
            "id": i,
            "deletable": False,
            "selectable": True,
            "type":
            "text" if i in ["word", "phrase", "sentence"] else "numeric",
            "format": Format(precision=2, scheme=Scheme.fixed),
        } for i in df.columns],
        hidden_columns=['cell'],
        data=df.to_dict('records'),
        editable=True,
        filter_action="native",
        sort_action="native",
        sort_mode="single",
        row_selectable=False,
        row_deletable=False,
        selected_columns=[],
        selected_rows=[],
        page_action="native",
        page_current=0,
        page_size=15,
        style_cell={
            'font-size': '16pt',
        },
        style_cell_conditional=[{
            'if': {
                'column_id': c
            },
            'textAlign': 'left'
        } for c in ['Date', 'Region']],
        style_data_conditional=[{
            'if': {
                'row_index': 'odd'
            },
            'backgroundColor': 'rgb(248, 248, 248)'
        }],
        style_header={
            'backgroundColor': 'rgb(230, 230, 230)',
            'fontWeight': 'bold'
        })
    return [t]
Exemple #25
0
def view_percent_balance_sheet(n_clicks, id, tickers):
    if n_clicks is not None:
        raw_df, percent_df = balace_sheet_cache[tickers[id['index']]]

        columns = [{"name": "fields", "id": "fields", "type": "text"}] + \
                [{"name": i, "id": i,
                  'type': 'numeric',
                  "format": Format(scheme=Scheme.percentage, precision=2)} for i in percent_df.columns]
        data = percent_df.to_dict("records")
        for f, r in zip(percent_df.index.tolist(), data):
            r["fields"] = f

        return columns, data
    else:
        raise PreventUpdate
Exemple #26
0
def build_debt_table():
    """Build a table with current debts."""
    card = dbc.Card(children=[
        dbc.CardHeader(children=[
            html.H2("Ausstehende Zahlungen"),
        ]),
        dbc.CardBody(
            dash_table.DataTable(
                id='debt_table',
                columns=[{
                    'id': 'name',
                    'name': 'Name',
                    'type': 'text'
                }, {
                    'id': 'price',
                    'name': 'Schulden [EUR]',
                    'type': 'numeric',
                    'format': Format(scheme='f', precision=2),
                }],
                data=[],
                style_table={
                    'height': '450px',
                },
                style_header={
                    'backgroundColor': '#d1d1d1ff',
                    'fontWeight': 'bold',
                    'fontSize': '130%',
                    'textAlign': 'center',
                },
                style_cell={
                    'padding': '5px',
                    'textAlign': 'center',
                    'fontSize': '120%',
                    'fontFamily': 'Helvetica',
                    'height': '120%'
                },
                style_data_conditional=[{
                    'if': {
                        'row_index': 'odd'
                    },
                    'backgroundColor': '#f5f5f5ff'
                }],
                style_as_list_view=True,
                filter_action="none",
                sort_action="native",
            ))
    ])
    return card
Exemple #27
0
def make_blas_table(df):
    """Makes table specifying the problem being plotted for blas data suit"""
    df_p = df[['problem','transA','transB','M','N',
           'K','alpha','lda','beta','ldb','ldc','ldd','batch_count']]
    non_numeric = [{'name': i, 'id': i} for i in list(df_p.columns)[:3]]
    numeric = [{'name': i, 'id': i, "type": 'numeric',
         "format": Format(precision=6, scheme=Scheme.fixed)} for i in list(df_p.columns)[3:]]
    columns= non_numeric + numeric
    table = dash_table.DataTable(
        data=df_p.to_dict('records'),
        sort_action='native',
        columns=columns,
        fixed_rows={'headers': True},
        style_table={'height': '500px', 'overflowY': 'auto'}
    )
    return table
Exemple #28
0
def ghg_slider_callback(*values):
    sectors = [x.id.split('-')[1] for x in ghg_sliders]
    new_values = {s: val for s, val in zip(sectors, values)}
    set_variable('ghg_reductions_weights', new_values)
    df = get_ghg_emissions_forecast()
    fig = generate_ghg_emission_graph(df)

    df['Yhteensä'] = df.sum(axis=1)
    last_hist_year = df[~df.Forecast].index.max()
    data_columns = list(df.loc[df.index == last_hist_year].stack().sort_values(
        ascending=False).index.get_level_values(1))

    data_columns.remove('Forecast')
    data_columns.insert(0, 'Vuosi')
    data_columns.remove('Yhteensä')
    data_columns.append('Yhteensä')

    last_forecast_year = df[df.Forecast].index.max()
    table_df = df.loc[df.index.isin([
        last_hist_year, last_forecast_year - 5, last_forecast_year - 10,
        last_forecast_year
    ])]
    table_data = table_df.reset_index().to_dict('rows')
    table_cols = []
    for col_name in data_columns:
        col = dict(id=col_name, name=col_name)
        if col_name == 'Vuosi':
            pass
        else:
            col['type'] = 'numeric'
            col['format'] = Format(precision=0, scheme=Scheme.fixed)
        table_cols.append(col)
    table = dash_table.DataTable(
        data=table_data,
        columns=table_cols,
        # style_as_list_view=True,
        style_cell={'padding': '5px'},
        style_header={'fontWeight': 'bold'},
        style_cell_conditional=[{
            'if': {
                'column_id': 'Vuosi'
            },
            'fontWeight': 'bold',
        }])

    return [fig, table]
Exemple #29
0
def generate_district_heating_forecast_table(df):
    last_hist_year = df[~df.Forecast].index.max()
    df.index.name = 'Vuosi'

    data_columns = list(df.columns)
    data_columns.remove('Forecast')
    data_columns.insert(0, 'Vuosi')

    last_forecast_year = df[df.Forecast].index.max()
    table_df = df.loc[df.index.isin([
        last_hist_year, last_forecast_year - 5, last_forecast_year - 10,
        last_forecast_year
    ])]
    table_data = table_df.reset_index().to_dict('rows')
    table_cols = []
    for col_name in data_columns:
        col = dict(id=col_name, name=col_name)
        if col_name == 'Year':
            pass
        else:
            col['type'] = 'numeric'
            col['format'] = Format(precision=0, scheme=Scheme.fixed)
        table_cols.append(col)
    table = dash_table.DataTable(
        data=table_data,
        columns=table_cols,
        style_cell={
            'minWidth': '0px',
            'maxWidth': '70px',
            'whiteSpace': 'normal'
        },
        css=[{
            'selector':
            '.dash-cell div.dash-cell-value',
            'rule':
            'display: inline; white-space: inherit; overflow: inherit; text-overflow: inherit;'
        }],
        style_header={'fontWeight': 'bold'},
        style_cell_conditional=[{
            'if': {
                'column_id': 'Year'
            },
            'fontWeight': 'bold',
        }])
    return table
Exemple #30
0
def show_pivot_table(value):
    """ This function return a pivot Table """

    pivot_df = pd.pivot_table(data=df,
                              values=value,
                              columns="pos_simple",
                              index="height_bins")
    pivot_df = pivot_df.reset_index()
    pivot_df = pivot_df.astype({"height_bins": "str"})
    cols = [{
        "name": col,
        "id": col,
        "type": "numeric",
        "format": Format(precision=5)
    } for col in pivot_df.columns]
    data = pivot_df.to_dict("records")

    return data, cols