Quantcast
Channel: 🎛️ Dash - Plotly Community Forum
Viewing all articles
Browse latest Browse all 6271

Update candlestick via callback

$
0
0

Hey everybody!
Is there a way to transfer the current position of the window to the callback or make an event if the user has reached the start value of figure for loading data?

What I have now:

import datetime as dt
import time
import dash_core_components as dcc
import dash_html_components as html
import pandas as pd
import plotly.graph_objects as go
from dash.dependencies import Output, Input
from dateutil.relativedelta import relativedelta
from django_plotly_dash import DjangoDash

inc_color = '#15aaba'
dec_color = '#7F7F7F'


config = {
    'scrollZoom': True,
    'displayModeBar': True,
    'displaylogo': False,
    'responsive': True,
    'modeBarButtonsToRemove': ['toImage',
                               'select2d',
                               'lasso2d',
                               'resetScale2d',
                               'hoverCompareCartesian',
                               'hoverClosestCartesian',
                               'toggleSpikelines',
                               ],
}

ohlc = DjangoDash('Plot',
                  add_bootstrap_links=True)

mn = (dt.datetime.today() - relativedelta(days=12)).strftime('%Y%m%d')
mx = dt.datetime.today().strftime('%Y%m%d')
daterange = pd.date_range(start=mn, end=mx, freq='D')


def unix_time_millis(date):
    """ Convert datetime to unix timestamp """
    return int(time.mktime(date.timetuple()))


def unix_to_datetime(unix):
    """ Convert unix timestamp to datetime. """
    return pd.to_datetime(unix, unit='s')


def get_marks(start, end):
    """ Returns the marks for labeling.
        Every Nth value will be used.
    """
    result = {}
    for i, date in enumerate(daterange):
        # Append value to dict
        result[unix_time_millis(date)] = str(date.strftime('%Y-%m-%d'))

    return result


def generate_layout():
    return html.Div([
        dcc.Graph(id='graph',
                  animate=True,
                  config=config),
        dcc.RangeSlider(id='graph-range-slider',
                        min=unix_time_millis(daterange.min()),
                        max=unix_time_millis(daterange.max()),
                        value=[unix_time_millis(daterange.max())],
                        marks=get_marks(daterange.min(),
                                        daterange.max()),
                        step=1,
                        updatemode='drag',
                        allowCross=False),
        html.Div(id='data-frame',
                 style={'display': 'none'}),
    ])


ohlc.layout = generate_layout()


@ohlc.expanded_callback(Output('graph', 'figure'),
                        [Input('data-frame', 'children')],
                        )
def load_graph(*args, **kwargs):
    df = pd.read_json(kwargs['session_state']['django_to_dash_context'], orient='split')

    return go.Figure(
        data=[go.Candlestick(
            x=df['x_axis'],
            open=df['open'], high=df['high'], low=df['low'], close=df['close'],
            increasing_line_color=inc_color, decreasing_line_color=dec_color,
        )],
        layout=dict(
            xaxis=dict(
                autorange=True,
                rangeslider=dict(
                    visible=False,
                ),
            ),
            yaxis=dict(
                overlaying="y",
                side="right",
                position=1,  # An int or float in the interval [0, 1]
                tickformat=".2f",
                ticksuffix="₽",
            ),
            margin=dict(
                t=0, b=0, r=40, l=0
            ),
            autosize=False,
            hovermode='x',
            dragmode='pan',
        ),
    )

1 post - 1 participant

Read full topic


Viewing all articles
Browse latest Browse all 6271

Latest Images

Trending Articles



Latest Images