1

I am using matplotlib.animation right now I got some good result. I was looking to add some stuff to the chart but couldn't find how.

  1. adding "buy"/ "sell" arrow when button clicked let say '1' - for buy , '2' for sell.

  2. simple label/legend that will show current live values (open,high,low,close , volume)

This is my code below:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pandas as pd
import mplfinance as mpf
import matplotlib.animation as animation

idf = pd.read_csv('aapl.csv',index_col=0,parse_dates=True)



#df = idf.loc['2011-07-01':'2012-06-30',:]

pkwargs=dict(type='candle',mav=(20,200))

fig, axes = mpf.plot(idf.iloc[0:20],returnfig=True,volume=True,
                     figsize=(11,8),panel_ratios=(3,1),
                     title='\n\nS&P 500 ETF',**pkwargs,style='starsandstripes')
ax1 = axes[0]
ax2 = axes[2]
ax1.spines['top'].set_visible(True)
ax1.grid(which='major', alpha=0.1)
ax2.grid(which='major', alpha=0.1)




#fig = plt.figure()

def run_animation():
    ani_running = True

    def onClick(event):
        nonlocal ani_running
        
        if ani_running:
            ani.event_source.stop()
            ani_running = False
        else:
            ani.event_source.start()
            ani_running = True


    def animate(ival):
        if (20+ival) > len(idf):
            print('no more data to plot')
            ani.event_source.interval *= 3
            if ani.event_source.interval > 12000:
                exit()
            return
        #print("here")

    

        #mpf.plot(idf,addplot=apd)

        data = idf.iloc[100+ival:(250+ival)]
        print(idf.iloc[ival+250])

        ax1.clear()
        ax2.clear()

        mpf.plot(data,ax=ax1,volume=ax2,**pkwargs,style='yahoo')


    fig.canvas.mpl_connect('button_press_event', onClick)
    ani = animation.FuncAnimation(fig, animate, interval=240)
run_animation()
mpf.show()

enter image description here

1 Answer 1

1

I am not clear on what exactly you want when you say you want to add "buy"/ "sell" arrow, but I can answer your question on creating a legend.

I think the easiest thing is to build a custom legend by specifying the colors and labels. The labels will change as your animation proceeds, so you will need to update the legend in your animate function after you clear both axes and plot the latest data - I assume that the row of the DataFrame that you are printing is the one you want to display in the legend:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import pandas as pd
import mplfinance as mpf
import matplotlib.patches as mpatches

idf = pd.read_csv('https://raw.githubusercontent.com/matplotlib/sample_data/master/aapl.csv',index_col=0,parse_dates=True)

#df = idf.loc['2011-07-01':'2012-06-30',:]

pkwargs=dict(type='candle',mav=(20,200))

fig, axes = mpf.plot(idf.iloc[0:20],returnfig=True,volume=True,
                     figsize=(11,8),panel_ratios=(3,1),
                     title='\n\nS&P 500 ETF',**pkwargs,style='starsandstripes')
ax1 = axes[0]
ax2 = axes[2]

## define the colors and labels
colors = ["red","green","red","green"]
labels = ["Open", "High", "Low", "Close"]

#fig = plt.figure()

def run_animation():
    ani_running = True


    def onClick(event):
        nonlocal ani_running
        
        if ani_running:
            ani.event_source.stop()
            ani_running = False
        else:
            ani.event_source.start()
            ani_running = True


    def animate(ival):
        if (20+ival) > len(idf):
            print('no more data to plot')
            ani.event_source.interval *= 3
            if ani.event_source.interval > 12000:
                exit()
            return
        #print("here")

    

        #mpf.plot(idf,addplot=apd)

        data = idf.iloc[100+ival:(250+ival)]
        print(idf.iloc[ival+250])

        ## what to display in legend
        values = idf.iloc[ival+250][labels].to_list()
        legend_labels = [f"{l}: {str(v)}" for l,v in zip(labels,values)]
        handles = [mpatches.Patch(color=c, label=ll) for c,ll in zip(colors, legend_labels)]

        ax1.clear()
        ax2.clear()

        mpf.plot(data,ax=ax1,volume=ax2,**pkwargs,style='yahoo')

        ## add legend after plotting
        ax1.legend(handles=handles, loc=2)

    fig.canvas.mpl_connect('button_press_event', onClick)
    ani = animation.FuncAnimation(fig, animate, interval=240)
run_animation()
mpf.show()

enter image description here

Sign up to request clarification or add additional context in comments.

1 Comment

works great THANKS! I made a function for event click so I wanted to create a green arrow at the current candle, each time a button in the keyboard is clicked. the arrow if for visualizing a "entry point" on the stock. hope that make sense.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.