在 Dash 中将动态文本返回到 html.P

Returning dynamic text to html.P in Dash

我正在使用 Python 和 Dash 创建财务仪表板。我正在使用 Python 3.7、Dash 1.18.1 和 Yahoo Finance 0.1.55。我能够从 Yahoo Finance API 中提取股票数据并创建相关矩阵,并提取相关性最高的符号对和相关性最低的符号对。我有一个带选项卡的仪表板,我正在尝试 return 在仪表板的第一个选项卡上并排显示相关矩阵和动态文本。我的应用程序的一部分是这样设置的:

app.layout = html.Div([
     dcc.Tabs(id='tabs', value='corr_matrix', children=[
     dcc.Tab(label='Correlation Matrix', value='corr_matrix', style=tab_style, selected_style=tab_selected_style),
     dcc.Tab(label='Compare Performance', value='performance', style=tab_style, selected_style=tab_selected_style)
    ], style=tabs_styles),

    html.Div(id='tabs-content')
])

这是我处理选项卡选择的第一个回调

@app.callback(
    Output('tabs-content', 'children'),
    [Input('tabs', 'value')]
)
def render_content(tab):
    if tab == 'corr_matrix':
        return html.Div([
            html.H1('Stock Correlation Matrix'),
            dbc.Row(
                [
                    dbc.Col(dcc.Graph(id='corr_chart')),
                    dbc.Col(html.P(id='corr_desc'))
                ]
            )

        ])

    elif tab == 'performance':
        return html.Div([
            html.H1('Stock Performance Chart')
        ])

这是我对相关矩阵和相关对语句的回调。在下面的函数中,我获取代码并从 Yahoo Finance 中提取收盘价并生成相关矩阵。我采用相关矩阵并提取最高相关性及其值的标签,以及最低相关性及其值的标签。我使用此代码构建了一个语句以放置在 html.P() 元素中。

@app.callback(
    [Output('corr_chart', 'figure'),
     Output('corr_desc', 'description')],
    [Input('tickers', 'value')]
)
def correlation_analysis(tickers):

    # list of tickers
    tickers = tickers.replace(' ', '').split(',')
    # converts list to uppercase
    for ticker in range(len(tickers)):
        tickers[ticker] = tickers[ticker].upper()

    # validate output
    # print(tickers)
    # print(type(tickers))

    # create empty dataframe
    stocks = pd.DataFrame()

    # iterate through tickers and grab
    # all historical closing prices
    # and append to dataframe
    for ticker in tickers:
        symbol = yf.Ticker(ticker)
        stock_close = symbol.history(period='max')['Close']
        stocks = stocks.append(stock_close)

    # reshape dataframe and rename columns
    stocks = stocks.transpose()
    stocks.columns = tickers

    # create correlation matrix
    corr_matrix = px.imshow(stocks.corr()[tickers])

    # define function to get lower part of correlation matrix
    def get_redundant_pairs(df):
        pairs_to_drop = set()
        cols = df.columns
        for i in range(0, df.shape[1]):
            for j in range(0, i + 1):
                pairs_to_drop.add((cols[i], cols[j]))
        return pairs_to_drop

    # reshape dataframe
    au_corr = stocks.corr().abs().unstack()
    labels_to_drop = get_redundant_pairs(stocks)

    # get the top correlated pair
    au_corr_top = au_corr.drop(labels=labels_to_drop).sort_values(ascending=False)
    top_corr_label_1 = au_corr_top.index[0][0]
    top_corr_label_2 = au_corr_top.index[0][1]
    top_corr_value = round(au_corr_top[0], 2)

    # get the bottom correlated pair
    au_corr_low = au_corr.drop(labels=labels_to_drop).sort_values(ascending=True)
    low_corr_label_1 = au_corr_low.index[0][0]
    low_corr_label_2 = au_corr_low.index[0][1]
    low_corr_value = round(au_corr_low[0], 2)

    # create statement to return to dashboard
    statement = 'The two symbols with the highest correlation are ' + top_corr_label_1 + ' and ' \
                + top_corr_label_2 + '. They have a correlation of ' + str(top_corr_value) + '. The two symbols' \
                ' with the lowest correlation are ' + low_corr_label_1 + ' and ' + low_corr_label_2 + '. They have' \
                ' a correlation of ' + str(low_corr_value) + '.'

    return corr_matrix, statement

html.P() 元素不呈现我的语句。相关矩阵正确显示。我可以使用 print(statement) 并且 return 是预期的语句。我哪里错了?

您的回调必须设置为呈现 children,因为这是将呈现到屏幕的内容。

改变这个

@app.callback(
    [Output('corr_chart', 'figure'),
     Output('corr_desc', 'description')],
    [Input('tickers', 'value')]

对此

@app.callback(
    [Output('corr_chart', 'figure'),
     Output('corr_desc', 'children')],
    [Input('tickers', 'value')]

有效