Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Plotly Candlestick updated and shown dynamically in a loop

I would like to dynamically update a Candlestick chart from plotly:

import time
import plotly.graph_objects as go

while True:
  candle_df = candle_handler.get_dataframe()
  candlestick = go.Candlestick(x=candle_df['Time'], open=candle_df['Open'], high=candle_df['High'], low=candle_df['Low'], close=candle_df['Close'])  
  fig = go.Figure(data=[candlestick])
  fig.show()
  time.sleep(3)

where candle_handler.get_dataframe() pull the data from an API and updates the data in the candle_df pandas dataframe.

However, the chart is shown only very briefly at every iteration of the loop (much less than for 3 seconds).

I have found a snippet that works for a scatter plot:

import time
import plotly.graph_objects as go

data = [1,3,2,4,3,3,2,3]

fig = go.FigureWidget()
fig.add_scatter()

for i in range(len(data)):
  time.sleep(3)
  fig.data[0].y = data[:i]
  fig.show()

and I would like to do something similar for the Candlestick chart.

like image 435
Newbie Avatar asked Dec 11 '25 04:12

Newbie


1 Answers

Your code worked perfectly fine for me. As an aside, I mocked up some data for your series - it's good practice when asking a question like this to provide some sample data

    import time
    
    import numpy as np
    import pandas as pd
    import plotly.graph_objects as go
    import datetime
    
    class Handler:
      def get_dataframe(self):
        start = datetime.datetime(2011, 1, 1)
        tim_col = pd.date_range(start, periods=500, freq="D")
        tim_col.name = "Time"
        prices_df = pd.DataFrame(data=np.random.rand(500,4), columns=['Open','High','Low','Close'], index=tim_col).reset_index()
        prices_df['Open'] = prices_df['Open']+ prices_df['Low']
        prices_df['Close'] = prices_df['Close']+ prices_df['Low']
        prices_df['High'] = prices_df['High']+ prices_df[['Open','Close']].max(axis=1)
        return prices_df
    
    candle_handler = Handler()
    
    while True:
      candle_df = candle_handler.get_dataframe()
      candlestick = go.Candlestick(x=candle_df['Time'], open=candle_df['Open'], high=candle_df['High'], low=candle_df['Low'], close=candle_df['Close'])
      fig = go.Figure(data=[candlestick])
      fig.show()
      time.sleep(3)

This does indeed ahow a graph every 3 seconds. Exact behaviour is going to depend on your graph renderer. If you run it in the terminal, it will probably pop up a tab in your browser looking at localhost on every loop - probably not what you want. If you run it in a Jupyter Notebook, it will change a figure dynamically, which might be closer to what you want.

If you want to dynamically update a figure in the browser, you might consider looking at dash

like image 175
J Richard Snape Avatar answered Dec 13 '25 23:12

J Richard Snape



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!