Giter Club home page Giter Club logo

Comments (12)

stevenm100 avatar stevenm100 commented on May 21, 2024 3

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'))

image

from mplfinance.

DanielGoldfarb avatar DanielGoldfarb commented on May 21, 2024 1

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:

image

from mplfinance.

DanielGoldfarb avatar DanielGoldfarb commented on May 21, 2024 1

@sweb1 Try one of the following choices:

  • set show_nontrading=True when calling mpf.plot(), and convert the dataframe index value (used for x 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.

DanielGoldfarb avatar DanielGoldfarb commented on May 21, 2024

@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

from mplfinance.

Maurice-D-Elbee avatar Maurice-D-Elbee commented on May 21, 2024

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.

DanielGoldfarb avatar DanielGoldfarb commented on May 21, 2024

See https://matplotlib.org/stable/tutorials/text/annotations.html for further information on how to use matplotlib annotations.

from mplfinance.

Maurice-D-Elbee avatar Maurice-D-Elbee commented on May 21, 2024

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:

image

Arigato Daniel Sensei m(_ _)m

from mplfinance.

DanielGoldfarb avatar DanielGoldfarb commented on May 21, 2024

@henribu
Oyakunitatte yokatta

from mplfinance.

stevenm100 avatar stevenm100 commented on May 21, 2024

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.

ateeq-code avatar ateeq-code commented on May 21, 2024

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.

DanielGoldfarb avatar DanielGoldfarb commented on May 21, 2024

@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.

sweb1 avatar sweb1 commented on May 21, 2024

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)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.