built on top of plotly javascript (plotly.js) library
referred to as “plotly.py”
enables python users to create interactive web-based visualisations that can be displayed in jupyter notebooks, saved to standalone html files or served as part of pure python-built web applications using Dash
built in feature for real-time updates of data objects
date sets the initial selected date; display_format controls how it is displayed.
Short-Term Moving Average Input
def STMA(id): instrument_input = html.Div([ html.Label('Enter the short term moving average', className='input-label'), ### dcc.Input( id=id, type='text', # placeholder='Enter MA', className='input', ) ], style={'width': '20%', 'display': 'inline-block'})
The slide ends after constructing instrument_input; add return instrument_input to use this helper in the layout.
Callbacks for Interactive Webpages
Output identifies the component property to update. Here, the callback updates the children of backtest-results.
Input triggers the callback when its value changes. Here, clicking the button changes n_clicks.
State supplies the current values without triggering the callback when those values change. Users can enter parameters first, then click the button to run the backtest.
# Define the callback to update backtest results@app.callback( Output('backtest-results', 'children'), [Input('rb-button', 'n_clicks')], [State('instrument-dropdown', 'value'), State('start_date', 'date'), State('end_date', 'date'), State('short_ma_period', 'value'), State('long_ma_period', 'value')])def update_backtest_results(n, instrument, start_date, end_date, short_ma_period, long_ma_period): if n == 0 or any(x is None for x in [instrument, start_date, end_date, short_ma_period, long_ma_period]): raise dash.exceptions.PreventUpdate # Fetch historical data data = pd.DataFrame(yf.download(instrument, start=start_date, end=end_date, progress=False)) # Create moving averages data['short_ma'] = data['Close'].rolling( window=int(float(short_ma_period))).mean() data['long_ma'] = data['Close'].rolling( window=int(float(long_ma_period))).mean()
PreventUpdate leaves the output unchanged when the button’s click count is zero or any required parameter is None.
yf.download fetches historical prices for the selected instrument and date range.
Rolling means of Close produce the short-term and long-term moving averages, using the entered window sizes.
The excerpt assumes imports for State (from dash), dash, pandas as pd, and yfinance as yf. The slide shows only part of the callback; the remaining backtest logic and returned output are not shown.