How to make an animation with Candlestick from plotly (Python)

Viewed 902

Esteemed,

I can make plots with candlestick from plotly. However, inside a loop, how to make these figures not be created one below the other, but to be all in one figure? Creating an animation effect. See the example where I plot candles with a window of 5 days ahead, successively, going through the entire DataFrame.

import plotly.graph_objects as go
import pandas as pd

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

#df
#i         Date   AAPL.Open   AAPL.High    AAPL.Low  AAPL.Close  AAPL.Volume  \
#0    2015-02-17  127.489998  128.880005  126.919998  127.830002     63152400   
#1    2015-02-18  127.629997  128.779999  127.449997  128.720001     44891700  
#....

for index, row in df.iterrows():

    FiveDaysBlock = df.iloc[index:(index+5),]

    fig = go.Figure(data=[go.Candlestick(
    x=FiveDaysBlock['Date'],
    open=FiveDaysBlock['AAPL.Open'], high=FiveDaysBlock['AAPL.High'],
    low=FiveDaysBlock['AAPL.Low'], close=FiveDaysBlock['AAPL.Close']
    )])
    fig.update_layout(xaxis_rangeslider_visible=False)
    fig.update_layout(autosize=False,width=700, height=250, margin=dict( l=1,r=1,b=20,  t=20, pad=2 ) )
    fig.update_xaxes(rangebreaks=[dict(bounds=["sat", "mon"])])
    fig.show()

See how the figure is generated under the other

Thank you,

2 Answers

Unfortunately, based on the following [answer][1], it seems that the x-axis and y-axis autoscaling is disabled with a go.Candlestick() object so the axes won't scale properly as the animation progresses.

import plotly.graph_objects as go
import datetime as dt
import pandas as pd
from ipywidgets import widgets
from IPython.display import display

df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/finance-charts-apple.csv')

#df
#i         Date   AAPL.Open   AAPL.High    AAPL.Low  AAPL.Close  AAPL.Volume  \
#0    2015-02-17  127.489998  128.880005  126.919998  127.830002     63152400   
#1    2015-02-18  127.629997  128.779999  127.449997  128.720001     44891700  
#....

# it might be useful to convert the Dates to datetime objects
df['Date'] = pd.to_datetime(df['Date'])

candlestick_data = []
for index, row in df.iterrows():
    FiveDaysBlock = df.iloc[index:(index+5),]
    candlestick_data.append(go.Candlestick(x=FiveDaysBlock['Date'],
        open=FiveDaysBlock['AAPL.Open'], high=FiveDaysBlock['AAPL.High'],
        low=FiveDaysBlock['AAPL.Low'], close=FiveDaysBlock['AAPL.Close'])
    )

def update_fig(i):
    fig = go.Figure(data=candlestick_data[i])

    fig.update_layout(xaxis_rangeslider_visible=False)
    fig.update_layout(transition_duration=2000)
    fig.update_layout(autosize=True,width=700, height=250, margin=dict(l=1,r=1,b=20,t=20,pad=2))

# this doesn't quite work but it's close
interact(update_fig, i=100)
fig.show()
Related