亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何正確地為 Dash Web 應用程序執行回調和函數

如何正確地為 Dash Web 應用程序執行回調和函數

POPMUISE 2022-10-06 16:13:51
非常感謝有關如何為我的 Dash Web 應用程序進行正確回調的一些幫助。我在下面有以下代碼。它應該返回一個圖表,其中包含有關股票財務狀況的各種線條。它從 API 獲取數據。但我不確定如何為應用回調定義我的函數。我嘗試過遵循在線教程,但取得了任何成功。如果它太混亂或效率低下,我深表歉意,我是新手。'''#!/usr/bin/env pythonimport pandas as pdimport requestsimport jsonimport plotlyimport chart_studio.plotly as pyimport plotly.graph_objs as goimport plotly.express as pximport dashimport dash_core_components as dccimport dash_html_components as htmlfrom dash.dependencies import Output, Inputticker = input("Insert company ticker: ")qoy = input("QUARTERLY or YEARLY: ")if qoy == "Yearly" or qoy == "yearly" or qoy == "YEARLY":    IS = requests.get("https://financialmodelingprep.com/api/v3/financials/income-statement/" + ticker)elif qoy == "Quarterly" or qoy == "quarterly" or qoy == "QUARTERLY":    IS = requests.get(        "https://financialmodelingprep.com/api/v3/financials/income-statement/" + ticker + "?period=quarter")IS = IS.json()IS = IS['financials']IS = pd.DataFrame.from_dict(IS)IS = IS.set_index("date")if qoy == "Yearly" or qoy == "yearly" or qoy == "YEARLY":    BS = requests.get("https://financialmodelingprep.com/api/v3/financials/balance-sheet-statement/" + ticker)elif qoy == "Quarterly" or qoy == "quarterly" or qoy == "QUARTERLY":    BS = requests.get(        "https://financialmodelingprep.com/api/v3/financials/balance-sheet-statement/" + ticker + "?period=quarter")BS = BS.json()BS = BS['financials']BS = pd.DataFrame.from_dict(BS)BS = BS.set_index("date")if qoy == "Yearly" or qoy == "yearly" or qoy == "YEARLY":    CF = requests.get("https://financialmodelingprep.com/api/v3/financials/cash-flow-statement/" + ticker)elif qoy == "Quarterly" or qoy == "quarterly" or qoy == "QUARTERLY":    CF = requests.get(        "https://financialmodelingprep.com/api/v3/financials/cash-flow-statement/" + ticker + "?period=quarter")CF = CF.json()CF = CF['financials']CF = pd.DataFrame.from_dict(CF)CF = CF.set_index("date")df_FS = pd.concat([IS, BS, CF], axis=1, sort=True)Date = df_FS.indexdf_FS.fillna(0, inplace=True)print(df_FS)
查看完整描述

1 回答

?
慕碼人2483693

TA貢獻1860條經驗 獲得超9個贊

您必須在回調中執行所有數據處理,因為它們需要輸入和按鈕值。有多種方法可以解決此問題,具體取決于您希望應用程序如何響應輸入。一種方法是這樣。在這里,主要輸入是qoy,回調使用stock input. 因此,在您選擇 之前,輸入股票輸入不會更新應用程序qoy。


#!/usr/bin/env python

from plotly.subplots import make_subplots

import pandas as pd

import requests

import json

import plotly

import chart_studio.plotly as py

import plotly.graph_objs as go

import plotly.express as px

import dash

import dash_core_components as dcc

import dash_html_components as html

from dash.dependencies import Output, Input, State

from dash.exceptions import PreventUpdate


external_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']


app = dash.Dash(__name__, external_stylesheets=external_stylesheets)


app.layout = html.Div([

    # Input the stock ticker

    html.Div([

        dcc.Input(id="stock-input",

                  placeholder='Please insert stock', type="text"),

        dcc.RadioItems(

            id="quarterlyoryearly",

            options=[

                {'label': 'Quarterly', 'value': 'quarterly'},

                {'label': 'Yearly', 'value': 'yearly'}

            ]

        )

    ]),



    # Banner of app

    html.Div([

        html.H2("Stock App")

    ], className="banner"),


    # Graphs

    html.Div([


        # Earnings & Revenue Graph

        html.Div([

            dcc.Graph(

                id="Earnings & Revenue",

                # figure=fig

            )

        ], className="six columns"),

    ], className="row")


])


@app.callback(Output("quarterlyoryearly", "value"),

              [Input("stock-input", "n_submit")],

              [State("quarterlyoryearly", "value")])

def enter_key(n_sub, qoy):

    if n_sub:

        return qoy


@app.callback(dash.dependencies.Output("Earnings & Revenue", "figure"),

              [dash.dependencies.Input("quarterlyoryearly", "value")],

              [dash.dependencies.State("stock-input", "value")]

              )

def update_fig(*args):


    if not any(args):

        raise PreventUpdate

    else:

        qoy, ticker = args


        if qoy.lower() == "yearly":

            IS = requests.get(

                "https://financialmodelingprep.com/api/v3/financials/income-statement/" + ticker)

        elif qoy.lower() == "quarterly":

            IS = requests.get(

                "https://financialmodelingprep.com/api/v3/financials/income-statement/" + ticker + "?period=quarter")


        IS = IS.json()

        IS = IS['financials']

        IS = pd.DataFrame.from_dict(IS)

        IS = IS.set_index("date")


        if qoy == "Yearly" or qoy == "yearly" or qoy == "YEARLY":

            BS = requests.get(

                "https://financialmodelingprep.com/api/v3/financials/balance-sheet-statement/" + ticker)

        elif qoy == "Quarterly" or qoy == "quarterly" or qoy == "QUARTERLY":

            BS = requests.get(

                "https://financialmodelingprep.com/api/v3/financials/balance-sheet-statement/" + ticker + "?period=quarter")


        BS = BS.json()

        BS = BS['financials']

        BS = pd.DataFrame.from_dict(BS)

        BS = BS.set_index("date")


        if qoy == "Yearly" or qoy == "yearly" or qoy == "YEARLY":

            CF = requests.get(

                "https://financialmodelingprep.com/api/v3/financials/cash-flow-statement/" + ticker)

        elif qoy == "Quarterly" or qoy == "quarterly" or qoy == "QUARTERLY":

            CF = requests.get(

                "https://financialmodelingprep.com/api/v3/financials/cash-flow-statement/" + ticker + "?period=quarter")


        CF = CF.json()

        CF = CF['financials']

        CF = pd.DataFrame.from_dict(CF)

        CF = CF.set_index("date")


        df_FS = pd.concat([IS, BS, CF], axis=1, sort=True)

        Date = df_FS.index

        df_FS.fillna(0, inplace=True)


        # EARNINGS & REVENUE

        fig = make_subplots(specs=[[{"secondary_y": True}]])

        fig.add_trace(go.Scatter(x=Date, y=df_FS['Revenue'],

                                 mode='lines+markers',

                                 name='Revenue'), secondary_y=False, )

        fig.add_trace(go.Bar(x=Date, y=df_FS['Profit Margin'],

                             opacity=0.2,

                             name='Profit Margin'), secondary_y=True, )


        fig.add_trace(go.Scatter(x=Date, y=df_FS['Consolidated Income'],

                                 mode='lines+markers',

                                 name='Earnings'), secondary_y=False, )

        fig.add_trace(go.Scatter(x=Date, y=df_FS['Operating Cash Flow'],

                                 mode='lines+markers',

                                 name='Operating Cash Flow'), secondary_y=False, )

        fig.add_trace(go.Scatter(x=Date, y=df_FS['Free Cash Flow'],

                                 mode='lines+markers',

                                 name='Free Cash Flow'), secondary_y=False, )

        fig.add_trace(go.Scatter(x=Date, y=df_FS['Operating Expenses'],

                                 mode='lines+markers',

                                 name='Operating Expenses'), secondary_y=False, )


        fig.update_layout(title="EARNINGS & REVENUE",

                          barmode='group', hovermode='x')

        fig.update_yaxes(title_text="in USD", secondary_y=False)

        fig.update_yaxes(title_text="Profit Margin", secondary_y=True)

        fig.update_xaxes(rangeslider_visible=True)

        return fig



if __name__ == '__main__':

    app.run_server(debug=False)

你可以玩轉輸入和狀態選項,看看應用程序是如何響應的。干杯!


PS:我添加了另一個回調,所以在第一個qoy和ticker值之后,您可以簡單地更改ticker輸入字段并點擊輸入按鈕(因為qoy已經選擇了)來更新您的應用程序。希望這能讓您更深入地了解回調是如何工作的。


查看完整回答
反對 回復 2022-10-06
  • 1 回答
  • 0 關注
  • 94 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號