Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I customize mplfinance.plot?

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

enter image description here

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: enter image description here
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 to all will spend time for reply me.

[EDIT]: this is an old question I've ade when mpl_finance was at It's first stage, now a lot of things are changed and this question is obsolete.

like image 815
Matteo_Sid Avatar asked Mar 09 '20 11:03

Matteo_Sid


3 Answers

The best way to do this is to define your own style using mpf.make_mpf_style() rather than using the default mpf styles.

If using external axes method in mplfinance, you can plot multiple charts as below:

# add your own style by passing in kwargs    
s = mpf.make_mpf_style(base_mpf_style='charles', rc={'font.size': 6})
fig = mpf.figure(figsize=(10, 7), style=s) # pass in the self defined style to the whole canvas
ax = fig.add_subplot(2,1,1) # main candle stick chart subplot, you can also pass in the self defined style here only for this subplot
av = fig.add_subplot(2,1,2, sharex=ax)  # volume chart subplot
mpf.plot(price_data, type='candle', ax=ax, volume=av)

The default mpf styles are as below. I believe 'mike' and 'nighclouds' have dark background, not 100% sure about others, you can choose to work on top of these two.

In [5]:
mpf.available_styles()
Out[5]:
['binance',
 'blueskies',
 'brasil',
 'charles',
 'checkers',
 'classic',
 'default',
 'mike',
 'nightclouds',
 'sas',
 'starsandstripes',
 'yahoo']

Link to visualize the default mplfinance styles enter image description here

The arguments that can be passed in mpf.make_mpf_style() are as below, you can use base_mpf_style, facecolor, gridcolor, gridstyle, gridaxis, rc to customise your own style, and give it a name by using style_name. You can play around with these arguments to see how they turn out.

def _valid_make_mpf_style_kwargs():
    vkwargs = {
        'base_mpf_style': { 'Default'     : None,
                            'Validator'   : lambda value: value in _styles.keys() },

        'base_mpl_style': { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) }, # and is in plt.style.available

        'marketcolors'  : { 'Default'     : None, # 
                            'Validator'   : lambda value: isinstance(value,dict)  },

        'mavcolors'     : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,list) },  # TODO: all([mcolors.is_color_like(v) for v in value.values()])

        'facecolor'     : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

        'edgecolor'     : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

        'figcolor'      : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

        'gridcolor'     : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

        'gridstyle'     : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

        'gridaxis'      : { 'Default'     : None,
                            'Validator'   : lambda value: value in [ 'vertical'[0:len(value)], 'horizontal'[0:len(value)], 'both'[0:len(value)] ] },

        'y_on_right'    : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,bool) },

        'rc'            : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,dict) },

        'style_name'    : { 'Default'     : None,
                            'Validator'   : lambda value: isinstance(value,str) },

    }
    _validate_vkwargs_dict(vkwargs)
    return vkwargs
like image 87
data2wealth Avatar answered Oct 08 '22 09:10

data2wealth


First you should upgrade your package to the latest version, then in your code, you can write: mpf.plot(......, axisoff= True) in my experience sometimes when using "axisoff= True", it is usefull to use figscale to obtain better results.

like image 40
Mehrnoush Haghighat Avatar answered Oct 08 '22 10:10

Mehrnoush Haghighat


To hide axes add this:

axisoff=True
like image 3
Moobi Cool Avatar answered Oct 08 '22 08:10

Moobi Cool