How to send multiple time series objects (created in Django view) to Dash Application for plot?

I have a Django application aiming to track my stock portfolio daily value (Time Series 1) and daily return (Time Series 2). These 2 Time Series are computed in Django based on custom models and methods.

On my homepage, I want to display these Time Series in a Dash app with 2 buttons: “Returns” and “Prices”. Depending on the button pressed, only one of the 2 time series will be plotted. I am using the django-plotly-dash package.

dash_app.py

import dash
from dash import dcc, html

from django_plotly_dash import DjangoDash

app = DjangoDash('Dashboard')
app.layout = html.Div(children=[
    # Price / Return mode
    dcc.RadioItems(
        id="radio-chart-mode", 
        options=["Prices", "Returns"],
        value="Returns",
        inline=True),

    # Buttons below for dates
    html.Div([
        html.Button(id='btn-horizon-1m', children="1m"),
        html.Button(id='btn-horizon-3m', children="3m"),
        html.Button(id='btn-horizon-6m', children="6m"),
        html.Button(id='btn-horizon-ytd', children="YTD"),
        html.Button(id='btn-horizon-1y', children="1Y"),
        html.Button(id='btn-horizon-3y', children="3Y"),
        html.Button(id='btn-horizon-max', children="Max")
        ]),

    # The Time Series chart
    html.Div(dcc.Graph(id='graph-ts', figure={})),
])

# Price/Return callback
@app.callback(
    dash.dependencies.Output('graph-ts', 'figure'),
    [dash.dependencies.Input('radio-chart-mode', 'value')],
    prevent_initial_call=False
)
def update_the_graph(chart_mode: str):
    if (chart_mode == "Prices"):
        # Draw Prices Graph based on ts_prices
        pass
    
    elif chart_mode == "Returns":
        # Draw Return Graph based on ts_returns 
        pass

My issue is that I cannot pass the 2 time series object from my Django view to the Dash application.

I have tried to take advantage of the initial_argument parameter in the HTML template of my homepage, namely

home.html

{%load plotly_dash%}
{%plotly_app name="Dashboard" initial_arguments=dash_context ratio=1%}

but cannot get it to work, as both time series are needed for the same graph object in the template. What could be the best way to do this?

Leave a Comment