Giter VIP home page Giter VIP logo

mplfinance's Introduction

mplfinance Checks

mplfinance

matplotlib utilities for the visualization, and visual analysis, of financial data

Installation

pip install --upgrade mplfinance


Contents and Tutorials


The New API

This repository, matplotlib/mplfinance, contains a new matplotlib finance API that makes it easier to create financial plots. It interfaces nicely with Pandas DataFrames.

More importantly, the new API automatically does the extra matplotlib work that the user previously had to do "manually" with the old API. (The old API is still available within this package; see below).

The conventional way to import the new API is as follows:

    import mplfinance as mpf

The most common usage is then to call

    mpf.plot(data)

where data is a Pandas DataFrame object containing Open, High, Low and Close data, with a Pandas DatetimeIndex.

Details on how to call the new API can be found below under Basic Usage, as well as in the jupyter notebooks in the examples folder.

I am very interested to hear from you regarding what you think of the new mplfinance, plus any suggestions you may have for improvement. You can reach me at [email protected] or, if you prefer, provide feedback or a ask question on our issues page.


Basic Usage

Start with a Pandas DataFrame containing OHLC data. For example,

import pandas as pd
daily = pd.read_csv('examples/data/SP500_NOV2019_Hist.csv',index_col=0,parse_dates=True)
daily.index.name = 'Date'
daily.shape
daily.head(3)
daily.tail(3)
(20, 5)
Open High Low Close Volume
Date
2019-11-01 3050.72 3066.95 3050.72 3066.91 510301237
2019-11-04 3078.96 3085.20 3074.87 3078.27 524848878
2019-11-05 3080.80 3083.95 3072.15 3074.62 585634570

...

Open High Low Close Volume
Date
2019-11-26 3134.85 3142.69 3131.00 3140.52 986041660
2019-11-27 3145.49 3154.26 3143.41 3153.63 421853938
2019-11-29 3147.18 3150.30 3139.34 3140.98 286602291

After importing mplfinance, plotting OHLC data is as simple as calling mpf.plot() on the dataframe

import mplfinance as mpf
mpf.plot(daily)

png


The default plot type, as you can see above, is 'ohlc'. Other plot types can be specified with the keyword argument type, for example, type='candle', type='line', type='renko', or type='pnf'

mpf.plot(daily,type='candle')

png

mpf.plot(daily,type='line')

png

year = pd.read_csv('examples/data/SPY_20110701_20120630_Bollinger.csv',index_col=0,parse_dates=True)
year.index.name = 'Date'
mpf.plot(year,type='renko')

png

mpf.plot(year,type='pnf')

png



We can also plot moving averages with the mav keyword

  • use a scalar for a single moving average
  • use a tuple or list of integers for multiple moving averages
mpf.plot(daily,type='ohlc',mav=4)

png

mpf.plot(daily,type='candle',mav=(3,6,9))

png


We can also display Volume

mpf.plot(daily,type='candle',mav=(3,6,9),volume=True)

png

Notice, in the above chart, there are no gaps along the x-coordinate, even though there are days on which there was no trading. Non-trading days are simply not shown (since there are no prices for those days).

  • However, sometimes people like to see these gaps, so that they can tell, with a quick glance, where the weekends and holidays fall.

  • Non-trading days can be displayed with the show_nontrading keyword.

    • Note that for these purposes non-trading intervals are those that are not represented in the data at all. (There are simply no rows for those dates or datetimes). This is because, when data is retrieved from an exchange or other market data source, that data typically will not include rows for non-trading days (weekends and holidays for example). Thus ...
    • show_nontrading=True will display all dates (all time intervals) between the first time stamp and the last time stamp in the data (regardless of whether rows exist for those dates or datetimes).
    • show_nontrading=False (the default value) will show only dates (or datetimes) that have actual rows in the data. (This means that if there are rows in your DataFrame that exist but contain only NaN values, these rows will still appear on the plot even if show_nontrading=False)
  • For example, in the chart below, you can easily see weekends, as well as a gap at Thursday, November 28th for the U.S. Thanksgiving holiday.

mpf.plot(daily,type='candle',mav=(3,6,9),volume=True,show_nontrading=True)

png


We can also plot intraday data:

intraday = pd.read_csv('examples/data/SP500_NOV2019_IDay.csv',index_col=0,parse_dates=True)
intraday = intraday.drop('Volume',axis=1) # Volume is zero anyway for this intraday data set
intraday.index.name = 'Date'
intraday.shape
intraday.head(3)
intraday.tail(3)
(1563, 4)
Open Close High Low
Date
2019-11-05 09:30:00 3080.80 3080.49 3081.47 3080.30
2019-11-05 09:31:00 3080.33 3079.36 3080.33 3079.15
2019-11-05 09:32:00 3079.43 3079.68 3080.46 3079.43

...

Open Close High Low
Date
2019-11-08 15:57:00 3090.73 3090.70 3091.02 3090.52
2019-11-08 15:58:00 3090.73 3091.04 3091.13 3090.58
2019-11-08 15:59:00 3091.16 3092.91 3092.91 3090.96

The above dataframe contains Open,High,Low,Close data at 1 minute intervals for the S&P 500 stock index for November 5, 6, 7 and 8, 2019. Let's look at the last hour of trading on November 6th, with a 7 minute and 12 minute moving average.

iday = intraday.loc['2019-11-06 15:00':'2019-11-06 16:00',:]
mpf.plot(iday,type='candle',mav=(7,12))

png

The "time-interpretation" of the mav integers depends on the frequency of the data, because the mav integers are the number of data points used in the Moving Average (not the number of days or minutes, etc). Notice above that for intraday data the x-axis automatically displays TIME instead of date. Below we see that if the intraday data spans into two (or more) trading days the x-axis automatically displays BOTH TIME and DATE

iday = intraday.loc['2019-11-05':'2019-11-06',:]
mpf.plot(iday,type='candle')

png


In the plot below, we see what an intraday plot looks like when we display non-trading time periods with show_nontrading=True for intraday data spanning into two or more days.

mpf.plot(iday,type='candle',show_nontrading=True)

png


Below: 4 days of intraday data with show_nontrading=True

mpf.plot(intraday,type='ohlc',show_nontrading=True)

png


Below: the same 4 days of intraday data with show_nontrading defaulted to False.

mpf.plot(intraday,type='line') 

png


Below: Daily data spanning across a year boundary automatically adds the YEAR to the DATE format

df = pd.read_csv('examples/data/yahoofinance-SPY-20080101-20180101.csv',index_col=0,parse_dates=True)
df.shape
df.head(3)
df.tail(3)
(2519, 6)
Open High Low Close Adj Close Volume
Date
2007-12-31 147.100006 147.610001 146.059998 146.210007 118.624741 108126800
2008-01-02 146.529999 146.990005 143.880005 144.929993 117.586205 204935600
2008-01-03 144.910004 145.490005 144.070007 144.860001 117.529449 125133300

...

Open High Low Close Adj Close Volume
Date
2017-12-27 267.380005 267.730011 267.010010 267.320007 267.320007 57751000
2017-12-28 267.890015 267.920013 267.450012 267.869995 267.869995 45116100
2017-12-29 268.529999 268.549988 266.640015 266.859985 266.859985 96007400
mpf.plot(df[700:850],type='bars',volume=True,mav=(20,40))

png

For more examples of using mplfinance, please see the jupyter notebooks in the examples directory.


Some History

My name is Daniel Goldfarb. In November 2019, I became the maintainer of matplotlib/mpl-finance. That module is being deprecated in favor of the current matplotlib/mplfinance. The old mpl-finance consisted of code extracted from the deprecated matplotlib.finance module along with a few examples of usage. It has been mostly un-maintained for the past three years.

It is my intention to archive the matplotlib/mpl-finance repository soon, and direct everyone to matplotlib/mplfinance. The main reason for the rename is to avoid confusion with the hyphen and the underscore: As it was, mpl-finance was installed with the hyphen, but imported with an underscore mpl_finance. Going forward it will be a simple matter of both installing and importing mplfinance.


Old API availability

With this new mplfinance package installed, in addition to the new API, users can still access the old API.
The old API may be removed someday, but for the foreseeable future we will keep it ... at least until we are very confident that users of the old API can accomplish the same things with the new API.

To access the old API with the new mplfinance package installed, change the old import statements

from:

    from mpl_finance import <method>

to:

    from mplfinance.original_flavor import <method>

where <method> indicates the method you want to import, for example:

    from mplfinance.original_flavor import candlestick_ohlc

mplfinance's People

Contributors

akgnah avatar alexpvpmindustry avatar amiaty avatar anbarief avatar aurumnpegasus avatar borgstrom avatar chanseathink avatar coffincw avatar danielgoldfarb avatar donbing avatar drchandrakant avatar fxhuhn avatar haybb avatar instrat avatar jbadiapa avatar jenshnielsen avatar jubapa avatar kenanharik avatar lfenzo avatar mattsta avatar nijek avatar simonthor avatar soellingeraj avatar synapticarbors avatar tacaswell avatar teddyrowan avatar ugorsahin avatar vedant-gawande avatar wgong avatar wsyxbcl avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mplfinance's Issues

Event Handling with mplfinance

Hey Daniel, love what you're doing with this package, it's absolutely fantastic.

I'm a pretty novice coder so excuse any code that might be unpreferred but I recently had an idea for a "point and click" technical indicator and wanted to try it out. The only issue is that I have absolutely no idea how to use event handling with the new mplfinance package.

I made a makeshift version using the old mpl_finance package. Attached is it (I'm using Alphavantage for intraday data, not sure I want to post my apikey here so I'll post everything but that):

import requests_html
import yahoo_fin.stock_info as yf
import pandas as pd
import numpy as np
import mpl_finance as mpf
import json
import requests
import datetime
import matplotlib as mpl
from mplfinance.original_flavor import candlestick_ohlc


ticker='SPY'
interval='60min'
apikey=''

r = requests.get("https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol={}&interval={}&outputsize=full&apikey={}".format(ticker,interval, apikey))
df = pd.DataFrame.from_dict(r.json()['Time Series ({})'.format(interval)]).T
df.columns=['Open','High','Low','Close','Volume']
df.index = pd.to_datetime(df.index)
df.sort_index(ascending=True, inplace=True)
df = df.apply(pd.to_numeric)

inital_data = df
inital_data.columns = map(str.title, inital_data.columns)


fig, ax = plt.subplots(figsize=(15,15))


candlestick_ohlc(ax, zip(mpl.dates.date2num(inital_data.index), inital_data['Open'], inital_data['High'], inital_data['Low'], inital_data['Close']))  


def onclick(event):
    date = mpl.dates.num2date(event.xdata)
    # print(datetime.datetime.strftime(date,"%Y-%m-%d %H:%M"))
    data = inital_data.loc[date:,:]
    vwap = []


    for x in range(len(data['Close'])):
        vwap.append(np.sum((data['Close'][0:(x+1)]*data['Volume'][0:(x+1)]))/np.sum(data['Volume'][0:(x+1)]))

    data[date] = vwap
    inital_data[date]=data[date]

    ax.plot(inital_data.index,inital_data[date])

    inital_data.drop(date, axis=1, inplace=True)
    event.canvas.draw()
    print(data.index[0])

cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()

The point and click functionality works incredible, exactly what I wanted, but it is so ugly. I made a non-point and click version using the new mplfinance and it looks beautiful but I want the point and click functionality for that.

Here's the ugly looking one:
https://imgur.com/a/VPa0SlH

Here's the beautiful looking one:
https://imgur.com/a/6s5gQSu

Any help in getting the event handling for the new package would be much appreciated.

support for matplotlib.animation?

I've been trying to use returnfig=True to replot live data with matplotlib.animation, but the new axes do not update on the original figure. I believe this is due to the fact that a new figure and axes are created in mplfinance.
A config setting for plot, or a new function, to update axes rather than return a new figure and axes would help with this I think.

how to plot more than 3 ma line?

now, i got an exception:
ValueError: kwarg "mav" with invalid value: "(5, 20, 60, 90)"
def _mav_validator(mav_value):
'''
Value for mav (moving average) keyword may be:
scalar int greater than 1, or tuple of ints, or list of ints (greater than 1).
tuple or list limited to length of 3 moving averages (to keep the plot clean).
'''
if isinstance(mav_value,int) and mav_value > 1:
return True
elif not isinstance(mav_value,tuple) and not isinstance(mav_value,list):
return False

if not len(mav_value) < 4:
    return False
for num in mav_value:
    if not isinstance(num,int) and num > 1:
        return False
return True

err = f'NOT is_color_like() for {key}[\'{updown}\'] = {colors[updown]}'

Hi,
Getting this error:
Debian, Python 3.5
import mplfinance as mpf
File "/usr/local/lib/python3.5/dist-packages/mplfinance/init.py", line 1, in
from mplfinance.plotting import plot, make_addplot
File "/usr/local/lib/python3.5/dist-packages/mplfinance/plotting.py", line 15, in
from mplfinance._utils import _construct_ohlc_collections
File "/usr/local/lib/python3.5/dist-packages/mplfinance/_utils.py", line 15, in
from mplfinance._styles import _get_mpfstyle
File "/usr/local/lib/python3.5/dist-packages/mplfinance/_styles.py", line 215
err = f'NOT is_color_like() for {key}['{updown}'] = {colors[updown]}'

mc = mpf.make_marketcolors(ohlc='black')
s  = mpf.make_mpf_style(marketcolors=mc)                                    
mpf.plot(item['Close'],type='bars',style=s)

This code works perfectly within the Anaconda Env.
I cannot run in on my VPS...

Thanks in advance...

Ability to label prices

This is just an idea of a little addition that I think can be useful. It would be nice to see what is the lastest value on the volume chart, price chart and also any addplots.
Example:

  • The arrows have their value as a label

  • Both charts have a white box that indicates the latest price value

show

output to buffer

i need to save to io.buffer
something like:

buf = io.BytesIO()
mpf.plot(
candles,
type='candle',
mav=(3, 6, 9),
volume=True,
show_nontrading=True,
figratio=(6, 6),
title="Graph",
style='yahoo',
savefig=buf
)
buf.seek(0)

Bug Report: skip zero value from Volumes

Describe the bug
if one of volume = 0

2020-02-12  54.41  56.36  54.39  55.79  305454      USD
2020-02-13  55.76  56.84  54.97  56.45       0      USD

then i get error when run:

    apds = [mpf.make_addplot(moexfl['non_com'], scatter=True, color='g', secondary_y='auto')]
    mpf.plot(stock_df, addplot=apds, type='candle', figratio=(25.6, 14.4),figscale=0.5, volume=True)
header: Content-Security-Policy: upgrade-insecure-requests; block-all-mixed-content
Traceback (most recent call last):
  File "C:\PycharmProjects\DataAnalysis\venv\lib\site-packages\mplfinance\plotting.py", line 34, in decorator
    return func(*args, **kwargs)
  File "C:\PycharmProjects\DataAnalysis\venv\lib\site-packages\mplfinance\plotting.py", line 352, in plot
    lo = math.log(math.fabs(min(volumes)),10) - 0.5
ValueError: math domain error
Backend TkAgg is interactive backend. Turning interactive mode on.

Trendlines

Hi Daniel,

Thanks for the work you put into this. I tried working with it and I want to do something that I'm not sure it's supported. I want to draw trendlines over the graph (just have list of values). Is this possible?

how to add text to figure

Hi,Denial:
thanks for your great work! and I want to know if there is a way to add a text to figure,thank you

Volume plot looks weird sometimes

Did somebody experience this kind of look in the volume plot? The volume bars are so thick, that they overlap each other and they also seem to not match the time stamps of the candle bars:

200205_1day

If I use no_xgaps, then it looks better, but that is not the behaviour I expected:
200205_1day

make drawing trend lines simpler

Is there anyway that I can get the matplotlib axes/figure object and add my custom plotting on top.

I currently want to draw trendlines like this

ac = ([dateA, dateC], [priceA, priceC])
l = mlines.Line2D(*ac)
ax.add_line(l)

The result look like
Screen Shot 2020-03-03 at 23 47 12

Bug Report:

Traceback (most recent call last):
File "d:/用户目录/Desktop/股票测试/MySql_rd.py", line 87, in
mpf.plot(iday,type='candle',mav=(5,13,21,34,55),volume=True)
File "D:\Anaconda3\lib\site-packages\mplfinance\plotting.py", line 35, in decorator
return func(*args, **kwargs)
File "D:\Anaconda3\lib\site-packages\mplfinance\plotting.py", line 154, in plot
dates,opens,highs,lows,closes,volumes = _check_and_prepare_data(data)
File "D:\Anaconda3\lib\site-packages\mplfinance_arg_validators.py", line 29, in _check_and_prepare_data
opens = data['Open'].values
File "D:\Anaconda3\lib\site-packages\pandas\core\frame.py", line 2800, in getitem
indexer = self.columns.get_loc(key)
File "D:\Anaconda3\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
return self._engine.get_loc(self._maybe_cast_indexer(key))
File "pandas_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
File "pandas_libs\hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item
File "pandas_libs\hashtable_class_helper.pxi", line 1622, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'Open'

??? Open -----must be upper case ???

Feature Request: Remove axes completely - show data only

Hi, I've made a python script to convert a csv file in a candlestick like this using mpl_finance, this is the script:

    import matplotlib.pyplot as plt
    from mpl_finance import candlestick_ohlc
    import pandas as pd
    import matplotlib.dates as mpl_dates

    plt.style.use('ggplot')

    # Extracting Data for plotting
    data = pd.read_csv('CSV.csv')
    ohlc = data.loc[:, ['Date', 'Open', 'High', 'Low', 'Close']]
    ohlc['Date'] = pd.to_datetime(ohlc['Date'])
    ohlc['Date'] = ohlc['Date'].apply(mpl_dates.date2num)
    ohlc = ohlc.astype(float)

    # Creating Subplots
    fig, ax = plt.subplots()
    plt.axis('off')
    fig.patch.set_facecolor('black')

    candlestick_ohlc(ax, ohlc.values, width=0.6, colorup='green', colordown='red', alpha=0.8)

    plt.show()

mario


Now I need to do the same thing but using mplfinance instead of mpl_finance and I've tried like this:

    import mplfinance as mpf
    # Load data file.
    df = pd.read_csv('CSV.csv', index_col=0, parse_dates=True)
 
    # Plot candlestick.
    # Add volume.
    # Add moving averages: 3,6,9.
    # Save graph to *.png.
    mpf.plot(df, type='candle', style='charles',
            title='',
            ylabel='',
            ylabel_lower='',
            volume=True, 
            mav=(3,6,9), 
            savefig='test-mplfiance.png')

And I have this result:
test-mplfiance


So, now I need to change background color from white to black, remove grid and remove axes but I have no idea how to do it.
Thanks for the replies.

Feature Reuest: more plots is needed

As far as I know, there are only two plots in mplfinance.
Sometime, I need other indicators that is simular with Volume.
I want to added them below the Vol plot.
How can I do it?

Double Y Axis... Is it possible?

Hi Daniel,

Is it possible to have 2nd Y-axis on the either side, along with the stock price? Basically, I am looking for the same feature, as I will plot some longitudes of planets to study the impact of these planets.

If you need a pic for what I am asking, here it is -
https://1.bp.blogspot.com/-3rN2z9PfuXE/XfyyxGjH_gI/AAAAAAAACRA/b6K06eP6h7w0_LLDJi6iN-C75H5mFHQXgCLcBGAsYHQ/s1600/NIFTY%2B-%2BDhuma-2.png

In the above pic, along with the candlestick chart you can see the planetary line, here only one is used, but I may require more.

Regards

Issues with addplot when adding scatter plot

Hi, I am very new to this Library. I enjoy the simplicity of it, but I am having some issues.
I simply want to draw arrows on my candlestick graph just like you did: https://github.com/matplotlib/mplfinance/blob/master/examples/addplot.ipynb

If I try to add a scatter plot it shrinks the Y-axis shrinks massively. I added pictures so you can see.
ScreenClip  2
ScreenClip

line = mpf.make_addplot(myData["High"],scatter=False) #No issues drawing a line
scatter = mpf.make_addplot(myData["High"],scatter=True) #Issues drawing scatter
    
mpf.plot(myData,
               type = 'candle',
               style='yahoo', 
               addplot= line,
               figscale=1.8)

Feature Request: Plot percent price change on the y-axis

Is your feature request related to a problem? Please describe.

When I want to compare two stocks, I'm interested in seeing the % changes in those two stocks over a period of time. Currently when I plot two stocks in mplfinance (using a secondary y-axis), I can't see the day-to-day percent changes, I only see the day-to-day price changes, which can be on different axes and thus inaccurate to compare directly.

For example, if I want to compare SPY and GOOG over a time period, I want to see the percent changes between the two (for easy comparison) rather than their stock prices which are almost an order of magnitude apart.

Describe the solution you'd like

A plot option that lets you plot the % change and lets you specify the start value that the percent changes should be compared against.

mpf and subplots

Hi Daniel!
Thank you for your work to improve mplfinance!
How can I use MPF in old code (I write it by analogy):
fig, (ax1, ax2, ax3) = plt.subplots(nrows=3, ncols=1)
mpf.plot(df, type='candle', ax=ax1)

How to Indicate Custom Column Names?

Is it possible to indicate custom column names for the OHLC data? I receive some candle data from Oanda as 'o','h','l','c', and volume: 'v'. However when trying to plot it will ask for names with uppercase as "Open","Low",etc.

I would like to know if there is a way I can pass an argument indicating the naming convention I am using so that I don't need to modify the dataframe or saved files.

Thanks for developing this library. It makes plotting financial data so much easier than the old mpl-finance module.

Point and Figure Chart Type

Another chart type similar to Renko Plots, are Point and Figure charts. They also don't take into account the passage of time. I think this chart type would be a good addition to the package.

Information:
https://www.dummies.com/personal-finance/investing/technical-analysis/how-to-create-a-point-and-figure-chart-of-trading-prices/
https://www.investopedia.com/terms/p/pointandfigurechart.asp

Existing Code:
https://stackoverflow.com/questions/8750648/point-and-figure-chart-with-matplotlib

If an option, I'd like to work on this feature.

Feature Request: support animation/live updating of OHLCV data plots.

Is your feature request related to a problem? Please describe.
I am trying to rewrite a live chart plotting function I had with the previous mpl-finance module by using matplotlib animation.FuncAnimation method (documentation here).

The function expects to be passed a figure where to draw. For the func argument, I am passing a simple function animate_plot:

class Plotter(object):
...
    def plot_live_chart(self,ohlc_data):
        def animate_plot(df_generator, *fargs):
            _type = fargs[0]
            mplfinance.plot(df_generator,type=_type)
     
        fig = plt.figure()
        ax1 = fig.add_subplot(1,1,1)
        #ani = animation.FuncAnimation(fig,animate_plot,interval=self.plot_refresh_rate,blit=True) #blit=True means to only re-draw parts that have changed
        ani = animation.FuncAnimation(fig,animate_plot,frames=ohlc_data.iterrows(),fargs=(self.type,),interval=self.plot_refresh_rate)

When I run my code, I only get a blank canvas at the end. I am thinking that it could be because on each call to mplfinance.plot a new figure is created but I am not really sure.
Describe the solution you'd like
I would like to have another parameter option for mplfinance.plot to provide a previously created figure. Then it could be checked internally to see if the parameter was provided then that figure is used. If not, then the normal code creates one.

I think it could also be useful to have the function return the figure so it can still be used later. If these are things that are already possible then could you point me in the right direction where to find it?

Describe alternatives you've considered
I think it would be great if a live plotter method were implemented with mplfinance so there is no need to build around it.
It could be a method that uses the already existing .plot() similar to what I am doing above but better. This method could either animate a full dataframe like historical data and it could also animate continuously updating data.

I think this fits better for another feature request. I may open one soon once I have more time to think of how it could be implemented.

Volume graph's peak Y-axis is too high

Sometimes the Volume subchart's peak y-axis is too high compared to the peak volume.

Here's an example:

image

The peak volume was ~30k. It's reasonable to stop the peak volume around 40k, but the chart above goes up to almost 60k. This wastes space in the chart and makes it harder to read the existing volume bars.

Show two plots side by side

I've been trying to create two plots and would like to show them side by side. I'm using jupyter but everytime I create the first plot, it stops. I have to close the window to show the second plot.

mynewdf = mynewdf[['Open', 'High', 'Low', 'Close', periodname1, periodname2]]
adpict = mpf.make_addplot(mynewdf[[periodname1, periodname2]])
mpf.plot(mynewdf,type='candle',addplot=adpict) #works

Here, it shows the plot with mynewdf dataset. So far so good. The window opens and even though the code continues with:

my5mdf = pd.read_csv(filenameM5, delimiter=";",index_col='Date', parse_dates=True, date_parser = mydateparser)
my5mdf = my5mdf[['Open', 'High', 'Low', 'Close']]
mpf.plot(my5mdf,type='candle')

I can only see this second plot, when closing the first window. What is the reason for that? I'm pretty sure, I'm doing something wrong here but I'm stuck. Thanks for any help!
regards,
Marco

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
image

or like this ( in left axis )
image

please help me :) thanks

Implement regression tests for the new API

Upon a Pull Request or Merge, the repository presently kicks off TravisCI tests for the old API. We should extend this for the new API as well. The new tests can easily be based off code in the jupyter notebooks in the examples folder.

Problems with candles color and bg color

I'm trying to make greyscale plots from a csv file, I need to have only 3 color in my images so I plot my graph like this:

mc = mpf.make_marketcolors(
    up='white',
    down='black',
    edge={'up':'white','down':'black'},
    wick={'up':'white','down':'black'},
    inherit=True
)
s  = mpf.make_mpf_style(base_mpf_style='classic', gridstyle = '', facecolor='grey', marketcolors=mc)

mpf.plot(df2,
        type = 'candle',
        style = s,
        title = '',
        ylabel = '',
        ylabel_lower = '',
        volume = False,
        show_nontrading=True,
        savefig = save_path + str(row) + flag
)

Then I delete all the edges with PIL and this is the result:
0_1
Apparently that's exactly what I wanted to get but zooming in we can see that the colors aren't correct.
Schermata 2020-03-22 alle 14 37 04

What would I have to do to get the uniform color in the candles?
Thanks a lot.

Error with candle style?

Nice package. But when I try to draw candles I get this error:

TypeError: '<' not supported between instances of 'numpy.ndarray' and 'str'

result.csv.txt

Works fine for line or ohlc.
mpf.plot(rawdf[['Open','High','Low','Close','Volume']].head(10), type='candle', volume=True)

The data looks like this (intraday e mini)
Also included as .txt file
Open High Low Close Volume
DateTime
2020-01-19 18:00:00 3325 3326.50 3323.25 3323.25 1815
2020-01-19 18:01:00 3323.25 3323.50 3323.25 3323.50 417
2020-01-19 18:02:00 3323.5 3323.50 3323.25 3323.50 231
2020-01-19 18:03:00 3323.25 3323.50 3323.25 3323.25 193
2020-01-19 18:04:00 3323.25 3323.50 3323.25 3323.50 147
2020-01-19 18:05:00 3323.5 3323.75 3323.50 3323.75 624
2020-01-19 18:06:00 3323.75 3324.25 3323.50 3324.25 148
2020-01-19 18:07:00 3324.25 3325.25 3324.00 3325.00 340
2020-01-19 18:08:00 3325 3325.50 3325.00 3325.50 217
2020-01-19 18:09:00 3325.75 3326.25 3325.25 3325.50 313

TypeError while plotting data for selected range?

Hi Daniel,

I am learning Python, to be very honest and trying to plot the chart simultaneously. I am trying to plot the chart of SPX (data taken from you) for selected time frame. Here's the code-

sDate = datetime(2008, 2, 1) #Start Date
eDate = datetime(2008, 9, 30) #End Date

#Data for Ephmeris
dfE = pdE.read_csv("eph.csv", parse_dates=['dt'])
dfE = dfE[(dfE['dt'] >= sDate) & (dfE['dt'] <= eDate)]

df1 = mpf.make_addplot(dfE['Sun'])

dfS = pdS.read_csv("SPX.csv", parse_dates=['Date'])
dfS = dfS[(dfS['Date'] >= sDate) & (dfS['Date'] <= eDate)]
mpf.plot(dfS, volume=False, addplot=df1)

I am getting TypeError - Expect data.index as DatetimeIndex, generated by the last line!!!

Regards

Implement y-scale (ex: log)

Hi Daniel, thanks for helping to develop this library. I was wondering if it'll be (or already is) possible to manipulate the resulting charts much like matplotlib charts, for example:

  • changing the y-scale
  • changing major/minor x-ticks
  • setting chart titles and legends

I'd love to be able to do this with the existing charts. Let me know if I can help. Thanks!

use tulipy and accept an array of technical indicators as an argument (feature request)

Hi Daniel, thank you for taking over the maintainance of mpl-finance. I agree with you about the new mission statement. Here is a feature request for you to consider. The tulipy project already implemented lots of technical indicators. It would be nice to be able to use them in mpl_finance. Here is a short piece showing how I would like to be able to pass my chosen technical indicators as arguments to candlestick_ohlc():

#!/usr/bin/python3

import numpy as np
import tulipy as ti
from datetime import datetime

def candlestick_ohlc(quotes, ti_array):
    close_prices = quotes['Close'].copy(order='C')
    for ti in ti_array:
        f = ti['f']
        del ti['f']
        print(f.full_name, f(close_prices, **ti))
        # of course in real code it should be plotting here.

dt = [float] * 6
dt[0] = 'datetime64[D]'
convertfunc = lambda x: datetime.strptime(x.decode('utf8'), '%m/%d/%Y')
daily = np.genfromtxt('SP500_NOV2019_Hist.csv',
    delimiter=',', autostrip=True, names=True, dtype=dt,
    converters = {'Date': convertfunc}
)
candlestick_ohlc(daily, [
    {'f':ti.sma, 'period':5},
    {'f':ti.sma, 'period':10},
    {'f':ti.macd, 'short_period':2, 'long_period':5, 'signal_period':9}
] )

Maybe we also need room for options telling candlestick_ohlc what colors and line width, etc. to use for each indicator line. And/or whether some of them should be displayed as solid bar and/or on a separate pane (so that volume can be processed using exactly this same interface without requiring a distinctive/separate interface). I don't have a very good suggestion yet as to how best to design that part of the interface.

More easily Plot Trades or Trade Signals

Is your feature request related to a problem? Please describe.
Your addplot.ipynb page is phenomenal and I was able to figure out that I can add scatter points by;

  1. Making a numpy array empty/zero
    trs = np.zeros((length_to_add, 1))
  2. Filling it with Nans
    trs.fill(np.nan)
  3. Setting my 2 scatter points as I know the index (x) and y values
    trs[x] = y
  4. Adding this to a dataframe
    toplot.insert(6, "trades", trs, True)
  5. Then using your well documented addplot:
    apdict = mpf.make_addplot(toplot['trades'],scatter=True,secondary_y=False)
    mpf.plot(toplot,type='candle',volume=True,addplot=apdict)

Describe the solution you'd like
While this is great it took a lot of energy - I'm moving from the plotpy (for the candles!) and there I simply wrote:
plt.scatter(trade_list_idx,trade_list_price,c='b')

Which was simpler than messing around with a dataframe and so on.

Regular intervals when using datetime instead of date

I'm currently using mplfinance with a dataframe that contains datetime/pandas.Timestamp instead of just date. When I plot this, the x-axis ends up having irregularly spaced timestamps.

See example:

image

Instead, it would be good if either there were intervals / timegaps that were user-provided or were regularly spaced (eg. 9:30am, 12pm, 4pm, etc). It would also be nice if the user can specify the date/time format to use when graphing.

Add option for plot function to return figure and not display the figure itself.

I desire to use mplfinance with tkinter.

To do this most straight forwardly I desire an option to return the figure.

So adding an option returnfig, using code something like the below:

Adding to vkwargs:

    'returnfig': {'Default': False,'Validator': lambda value: isinstance(value, bool)},

And extending the "savefig" code something like the below:
Code something like the below:

if config['savefig'] is not None:
    save = config['savefig']
    if isinstance(save,dict):
        plt.savefig(**save)
    else:
        plt.savefig(save)
else:
    if config['returnfig'] is not None:
        save = config['returnfig']
        if save:
            return (fig)            
    # https://stackoverflow.com/a/13361748/1639359 suggests plt.show(block=False)
    plt.show(block=config['block'])

Renko plot type

Great start so far, solid selection of plot types. There is a group of plot types that are not defined by consistent periods of time. One of these is Renko.

It would be a fantastic benefit having the ability to simply specify:
mpf.plot(df, type='renko')

Information
https://school.stockcharts.com/doku.php?id=chart_analysis:renko
https://avilpage.com/2018/01/how-to-plot-renko-charts-with-python.html

Existing code
https://github.com/chillaranand/stocktrends
https://github.com/mementum/backtrader/blob/master/backtrader/filters/renko.py

Get renko values

Hi, how can I get renko values that are calculated for plot ?
And also moving average values associated ?

Feature Request: Ability to overlay a candle chart over another (share axes)

Thank you for your work on updating mplfinance!

Using the deprecated mpl-finance, I was able to put 2 candlestick_ohlc() charts on top of each other (overlaid, sharing the same axes), and a table below the chart, all within a single figure that could be saved.

Now, I can use returnfig=True to export the figure and axes, but not sure how to actually use those later. ax is not a valid kwarg in plot(), as it was in candlestick_ohlc(). And not sure how to draw the chart inside a parent figure. Should fig be a kwarg for plot()?

Thank you.

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.