Here is my code. My last callback contains my datatable.
import dash
import dash_table as dt
import dash_bootstrap_components as dbc
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import plotly.express as px
import plotly.graph_objs as go
from dash.exceptions import PreventUpdate
import pandas as pd
from connect import *
from dash_tables import *
stock_ids = execute_query(conn, "SELECT DISTINCT id FROM security_price;")
stock_ids = [i[0] for i in stock_ids]
options = [{'label': i, 'value': i} for i in stock_ids]
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.LUX], meta_tags=[
{"name": "viewport", "content": "width=device-width, initial-scale=1"}])
body = html.Div(
[dbc.Jumbotron(
[
dbc.Container(
[
html.H1("SP500", className="display-4"),
html.P(
"Compare equities in the SP500 "
"before you buy.",
className="lead",
),
html.P(
"Enter the symbols that interest you "
"and view how they compare",
),
],
fluid=True,
)
],
fluid=True,
)
, dbc.Row(dbc.Container(dcc.Dropdown(id="dynamic-dropdown", options=options, multi=True, placeholder="Select a Symbol", style={'margin-left': '20px', 'margin-right':'45px'}),fluid=True))
, dbc.Row(dbc.Col(html.Div(children = [dcc.Graph(id='output-graph', config={'displayModeBar': False}, animate=True)], style={'padding': 10})))
, dbc.Row([
(html.Div(dbc.Container(dt.DataTable(id='table_stats', style_table={'margin-left': '20px', 'margin-right':'45px'}))))], justify="center")
# lg=9, md=6, xs=4, style={'margin-left': '5px','padding': 10})
#dbc.Col(html.Div(dbc.Alert("One of three columns", color="primary")), lg=3, md=4, xs=12, style={'padding' : 10})
# # , dbc.Col(html.Div(dbc.Alert("One of three columns", color="primary")), lg=3, md=4, xs=12,style={'margin-right': '5px','padding': 10})
# ], justify="center")
, dbc.Row(dbc.Col(html.Div(dbc.Alert("This is one column", color="primary", style={'margin-top' : '25px' ,'margin-bot' : '25px'}))),style={'margin-left' : '25px' ,'margin-right' : '25px'}, justify="center")
])
app.layout = html.Div([body])
@app.callback(
dash.dependencies.Output('output-graph', 'figure'),
[dash.dependencies.Input('dynamic-dropdown', 'value')])
def tickers(symbols):
if symbols == None:
raise PreventUpdate
trace1 = [] #lines for stocks
d = {} #dates
p = {} #prices
stock_info = {}
df = pd.DataFrame()
for stock in symbols:
stock_info[stock] = get_dict_resultset(f"SELECT date, close FROM security_price WHERE security_price.id = '{stock}' ;")
d[stock] = [rec['date'] for rec in stock_info[stock]]
p[stock] = [rec['close'] for rec in stock_info[stock]]
trace1.append(go.Scatter(x=d[stock],
y=p[stock],
mode='lines',
opacity=0.7,
name=stock,
textposition='bottom center'))
traces = [trace1]
data = [val for sublist in traces for val in sublist]
figure = {'data': data,
'layout': go.Layout(
colorway=["#5E0DAC", '#FF4F00', '#375CB1', '#FF7400', '#FFF400', '#FF0056'],
paper_bgcolor='rgba(0, 0, 0, 0)',
plot_bgcolor='rgba(0, 0, 0, 0)',
margin={'b': 15},
hovermode='x',
autosize=True,
title={'text': 'Stock Prices', 'font': {'color': 'black'}, 'x': 0.5},
#xaxis={'range': [df_sub.index.min(), df_sub.index.max()]},
),
}
return figure
@app.callback(
dash.dependencies.Output('table_stats', 'data'),
[dash.dependencies.Input('dynamic-dropdown', 'value')])
def statsTable(symbols):
print(symbols)
if symbols == None:
raise PreventUpdate
placeholders = ", ".join(['%s' for _ in symbols])
# PREPARED STATEMENT WITH PARAM PLACEHOLDERS
sql = f"""SELECT id, companyname, marketcap
, to_char(100.0*week52change,'999D99%%'), week52high, week52low
, to_char(dividend_yield * 100, '99D99%%'), next_earnings_date
, pe_ratio, ROUND(beta,2)
FROM security_stats
WHERE security_stats.id IN ({placeholders})
"""
print(sql)
df = postgresql_to_dataframe_v1(conn, sql, symbols, stats_col)
columns = df.columns
data = df.to_dict('rows')
table = dt.DataTable(data=data, columns=columns)
print(table)
return table
if __name__ == "__main__":
app.run_server(debug = True)
This is how print(data)
looks like.
data=[{'Symbol': 'RSG', 'Company': 'Republic Services Inc.', 'Market Cap': 31604176866, '1yr-Change': ' 13.21%', '52-Week High': Decimal('102.58'), '52-Week Low': Decimal('65.78'), 'Dividend Yield': ' 1.70%', 'Next Earnings Report': datetime.date(2020, 10, 25), 'PE-Ratio': Decimal('29.9'), 'Beta': Decimal('0.87')}])
My Dash app console says:
Invalid argument `data` passed into DataTable with ID "table_stats".
Expected an array.
Was supplied type `object`.
Would greatly appreciate help.