mplfinance
mplfinance copied to clipboard
Label for the last price in plot
heii, i want to ask, how to show price label from the last candle and the last price of MA in right axis??
maybe in left top
or like this ( in left axis )
please help me :) thanks
@albertusfreddi
Albertus,
- This feature is not yet available.
- At some point this will be available. (hard to say when; maybe a month, maybe two months; other features are higher priority at this time).
- We also want, ideally, to make a similar feature available, when you mouse-over any candle/bar you would see the ohlc price labels on the side.
- In the meantime, as a work-around, within approximately one week we will be releasing the ability for
mpf.plot()
to return the Figure and Axes that it created. With that, if you are familiar with matplotlib, you should be able to add the labels yourself and then display the figure.
Thank you for your question. I hope you enjoy using mplfinance. If you would like also to contribute writing code for mplfinance, and/or working on the documentation, please let me know. Much appreciated. --Daniel
Hello Daniel, would you have any update on this? I am not quite sure on how to do this with fig and axes. Thanks for your help! I have been using your library for the past week and i love it, charts are super clean.
I do hope one day to integrate this feature into mplfinace. It is, for now, a relatively low priority, because it can be handled using returnfig=True
and matplotlib annotations. Here is an example:
This example uses a csv data file that can be found in this repository, and arbitrarily selects only 50 dates (rows of data) from that file just to keep the plot small and simple.
This example uses matplotlib annotations.
#!/usr/bin/env python
# coding: utf-8
import pandas as pd
import mplfinance as mpf
#print('pandas version=',pd.__version__)
#print('mplfinance version=',mpf.__version__)
df = pd.read_csv('data/SPY_20110701_20120630_Bollinger.csv',index_col=0,parse_dates=True)
df = df[['Open','High','Low','Close','Volume']].iloc[40:90] # Arbitrarily choose a 50 row subset of the data
cvals={}
fig, axlist = mpf.plot( df, type='candle', style='yahoo', mav=(8,16), volume=True,
return_calculated_values=cvals,
returnfig=True )
last = df.iloc[-1,:]
text = (f" {last.name.date().strftime('%m/%d/%Y'):}\n"+
f"O: {last['Open']:.2f}\n"+
f"H: {last['High']:.2f}\n"+
f"L: {last['Low']:.2f}\n"+
f"C: {last['Close']:.2f}\n"+
f"V: {last['Volume']:.0f}\n"+
f"mav( 8): {cvals['mav8'][-1]:.2f}\n"+
f"mav(16): {cvals['mav16'][-1]:.2f}"
)
axlist[0].annotate(text, xy=(len(df),last['Close']), textcoords='axes fraction', xytext=(1.13,0.4),
arrowprops=dict(facecolor='cyan',width=3),bbox=dict(boxstyle="round",fc="cyan"))
mpf.show()
Here is the resulting plot:
See https://matplotlib.org/stable/tutorials/text/annotations.html for further information on how to use matplotlib annotations.
I do hope one day to integrate this feature into mplfinace. It is, for now, a relatively low priority, because it can be handled using
returnfig=True
and matplotlib annotations. Here is an example:This example uses a csv data file that can be found in this repository, and arbitrarily selects only 50 dates (rows of data) from that file just to keep the plot small and simple.
This example uses matplotlib annotations.
#!/usr/bin/env python # coding: utf-8 import pandas as pd import mplfinance as mpf #print('pandas version=',pd.__version__) #print('mplfinance version=',mpf.__version__) df = pd.read_csv('data/SPY_20110701_20120630_Bollinger.csv',index_col=0,parse_dates=True) df = df[['Open','High','Low','Close','Volume']].iloc[40:90] # Arbitrarily choose a 50 row subset of the data cvals={} fig, axlist = mpf.plot( df, type='candle', style='yahoo', mav=(8,16), volume=True, return_calculated_values=cvals, returnfig=True ) last = df.iloc[-1,:] text = (f" {last.name.date().strftime('%m/%d/%Y'):}\n"+ f"O: {last['Open']:.2f}\n"+ f"H: {last['High']:.2f}\n"+ f"L: {last['Low']:.2f}\n"+ f"C: {last['Close']:.2f}\n"+ f"V: {last['Volume']:.0f}\n"+ f"mav( 8): {cvals['mav8'][-1]:.2f}\n"+ f"mav(16): {cvals['mav16'][-1]:.2f}" ) axlist[0].annotate(text, xy=(len(df),last['Close']), textcoords='axes fraction', xytext=(1.13,0.4), arrowprops=dict(facecolor='cyan',width=3),bbox=dict(boxstyle="round",fc="cyan")) mpf.show()
Here is the resulting plot:
Arigato Daniel Sensei m(_ _)m
@henribu Oyakunitatte yokatta
putting the same comment here on this duplicate, hope it helps...
I got close by doing the following:
y_min, y_max = ax1.get_ylim()
#annotate
if yest_close > last_close:
ax1.annotate(str(round(last_close,2)), xycoords='axes fraction', xy=(1.02, (last_close - y_min)/(y_max - y_min) ), size=8,
bbox=dict(boxstyle="larrow",pad=0.3, fc='red', ec='red'))
else:
ax1.annotate(str(round(last_close,2)), xycoords='axes fraction', xy=(1.02, (last_close - y_min)/(y_max - y_min) ), size=8,
bbox=dict(boxstyle="larrow",pad=0.3, fc='green', ec='green'))
It took a bit of wrangling to get the arrow in the correct location, but this is close enough for me.
look like I know the issue being.....I can fix this just assign me the work and then ta-da it's done in the blink of an eye
@ateeq-code Please describe your plan. Or fork this repository and modify the code in your fork so that we can see your work.
just incase. fwiw....i did change my code slightly due to the way numbers are rounded. see the detail of the string to round to two characters after the decimal. Previously it would not show this value with the trailing zero:
ax1.annotate("%.2f" % round(last_close, 2), xycoords='axes fraction', xy=(1.02, (last_close - y_min)/(y_max - y_min) ), size=8, bbox=dict(boxstyle="larrow",pad=0.3, fc='forestgreen', ec='forestgreen'))
I'm trying to follow the instructions on this site and on [Customizing annotation arrows] but i seems that I'm struggling placing a simple arrow at specific coordinates on the chart. The arrow is not visible. Did i miss something essential? To my understanding the arrow head in below example should point to 1681207203000,110
import pandas as pd
import mplfinance as mpf
data = {'Date': [1681203603000, 1681207203000, 1681210803000],
'Open': [100, 110, 105],
'High': [120, 115, 108],
'Low': [95, 105, 100],
'Close': [110, 108, 102]}
df = pd.DataFrame(data)
df['Date'] = pd.to_datetime(df['Date'], unit='ms')
df.set_index('Date', inplace=True)
fig, axlist = mpf.plot(df, type='candle', style='yahoo', returnfig=True)
axlist[0].annotate("",
xy=(df.index[1], 110), xycoords='data',
xytext=(df.index[1], 115), textcoords='data',
arrowprops=dict(arrowstyle="->", connectionstyle="arc3"))
mpf.show()
@sweb1 Try one of the following choices:
- set
show_nontrading=True
when callingmpf.plot()
, and convert the dataframe index value (used forx
in the annotation call) to a matplotlib date, or ... - pass in the dataframe row number instead of the index (datetime) value.
To understand why this works this way, see https://github.com/matplotlib/mplfinance/wiki/Mplfinance-Time-Axis-Concerns,-and-Internals-of-Displaying-or-Not-Displaying-Non-Trading-periods
Notice that in this example above I used the dataframe row number as the x-value for the annotation. That is usually the simpler solution.