Comments (12)
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'))
from mplfinance.
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:
from mplfinance.
@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.
from mplfinance.
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
from mplfinance.
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.
from mplfinance.
See https://matplotlib.org/stable/tutorials/text/annotations.html for further information on how to use matplotlib annotations.
from mplfinance.
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
from mplfinance.
@henribu
Oyakunitatte yokatta
from mplfinance.
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.
from mplfinance.
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
from mplfinance.
@ateeq-code
Please describe your plan. Or fork this repository and modify the code in your fork so that we can see your work.
from mplfinance.
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()
from mplfinance.
Related Issues (20)
- Feature Request: Monthly Pivot Point Plot with Segmented Lines HOT 1
- When saving candle charts to file, the candles are red when should be green. why? HOT 13
- Minor enhancements on some simple plot handling HOT 2
- Feature Request: Alternating Background Color
- during save to image file to the disk, there are some noise...how to fix these issue? HOT 2
- Adding ConciseDateFormatter displays dates from 1970 HOT 10
- Bug Report: Is there a typo in src/mplfinance/plotting.py, line 946: fig.suptitle(title,**title_kwargs) HOT 1
- how to get OHLC return values and trend from renko plot HOT 1
- Issue while trying to get_ydata of an EMA from a fig or from the axes HOT 3
- Subplot and panel work fine when they use separately, but mix up when I try to use them in same figure, how can I solve? HOT 8
- Feature Request: HOT 2
- How do i get renko values without ploting the chart? HOT 2
- weird orange line appearing in axes' .plot() HOT 1
- Parabolic Sar and supertrend for renko
- Assist to draw Simple Moving Average. HOT 2
- I just don't know who to ask…. HOT 1
- mplfinance warn if user passes an empty data set. HOT 1
- Feature Request: The line width argument adding request for 'candlestick_ohlc' about the 'Wick/shadow' part(above/blow line) HOT 9
- Bug Report: marketcolors display error when open=close HOT 1
- Bug Report: Typo HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mplfinance.