Mplfinance

Recently, we found that many of our partners have the need to draw K-line charts, and some of them even write their own code to draw charts without using third-party modules, which is actually a completely repetitive task.

Mplfinance is part of the Matplotlib open source project. Compared to Matplotlib, Mplfinance, a module in the financial industry vertical, has received less attention, so many of you are not aware of its existence, but in fact it is very practical and useful.

1.Preparation

Before you start, you need to make sure that Python and pip are successfully installed on your computer, if not, you can visit this article: Super Detailed Python Installation Guide to install them.

(Option 1) If your purpose of using Python is data analysis, you can directly install Anaconda: Python Data Analysis and Mining Helper - Anaconda, which has Python and pip built in.

Please enter the command to install the dependency in one of the following ways
1. Windows environment Open Cmd (Start - Run - CMD).
2. MacOS environment Open Terminal (command+space type Terminal).
3. If you are using the VSCode editor or Pycharm, you can use the Terminal directly below the interface.

pip install --upgrade mplfinance

 

2.Basic Use

First look at the data structure:

import pandas as pd
mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
print(mins)


The structure is as follows:

day      open      high       low     close     volume
0 2022-03-07 10:47:00  4406.223  4406.352  4405.662  4405.922   54345400
1 2022-03-07 10:48:00  4406.172  4406.175  4403.834  4403.918   70803100
2 2022-03-07 10:49:00  4403.333  4403.333  4402.235  4402.340   49632500
3 2022-03-07 10:50:00  4402.330  4402.519  4401.838  4402.519   48159200

 

The data we use for mplfinance must be a Pandas DataFrame. The fields are provided on demand, with at least a time field and a column of data. In addition the original data has to be converted to DataFrame format if it is of another data type.

In addition, the time field must be converted to a DatetimeIndex:

import pandas as pd
import mplfinance as mpf
mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
mins["day"] = pd.to_datetime(mins["day"])
mins = mins.set_index("day")
mins.index.name = 'Time'
print(mins)

 

The effect is as follows:

open      high       low     close     volume
Time
2022-03-07 10:47:00  4406.223  4406.352  4405.662  4405.922   54345400
2022-03-07 10:48:00  4406.172  4406.175  4403.834  4403.918   70803100
2022-03-07 10:49:00  4403.333  4403.333  4402.235  4402.340   49632500
2022-03-07 10:50:00  4402.330  4402.519  4401.838  4402.519   48159200

 

Once you are ready, you can draw the chart:

import pandas as pd
import mplfinance as mpf
mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
mins["day"] = pd.to_datetime(mins["day"])
mins = mins.set_index("day")
mins.index.name = 'Time'

# Draw default image (US line)
mpf.plot(mins)

 

Mplfinance

 

Plot the candlestick (K-line chart), to avoid the chart being too large, I only took 240 K-lines here:

import pandas as pd
import mplfinance as mpf
mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
mins["day"] = pd.to_datetime(mins["day"])
mins = mins.set_index("day")
mins.index.name = 'Time'

candle_chart = mins.tail(240)
mpf.plot(candle_chart, type='candle')

 

Mplfinance

 

Black and white color is too monotonous, we can change to "Yahoo" color scheme:

mpf.plot(candle_chart, type='candle', style='yahoo')

Mplfinance

Drawing line diagrams:

import pandas as pd
import mplfinance as mpf
mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
mins["day"] = pd.to_datetime(mins["day"])
mins = mins.set_index("day")
mins.index.name = 'Time'
mpf.plot(mins, type='line')

Mplfinance

 

In addition to US lines, candlestick (K-line) and line charts, mplfinance also supports renko, pnf and other graphics. Interested students can change the type and see the results:

Mplfinance

3.Add technical specifications

To plot the simple moving average MA5, we just need to add one more parameter:

import pandas as pd
import mplfinance as mpf
mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
mins["day"] = pd.to_datetime(mins["day"])
mins = mins.set_index("day")
mins.index.name = 'Time'
candle_chart = mins.tail(240)
mpf.plot(candle_chart, type='candle', mav=5)

Mplfinance

 

If you need multiple moving averages, just change mav to a tuple parameter and pass in the period parameter you need:

Mplfinance

 

If you also need to display volume, mplfinance can also do that:

import pandas as pd
import mplfinance as mpf
mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
mins["day"] = pd.to_datetime(mins["day"])
mins = mins.set_index("day")
mins.index.name = 'Time'
candle_chart = mins.tail(240)
mpf.plot(candle_chart, type='candle', mav=(5, 10, 20), volume=True)

Mplfinance

 

If you still want to color the candles, want to change the line colors, want to add other indicators, see the third section Advanced Use.

4.Advanced Use

Coloring is very easy, as we changed to the Yahoo color scheme before, you just need to add the style parameter to change to our traditional technical indicator colors.

If you want to customize the color is also possible to do, here I will set the first 120 columns to blue and yellow, after 120 columns to retain the original shape:

import pandas as pd
import mplfinance as mpf
mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
mins["day"] = pd.to_datetime(mins["day"])
mins = mins.set_index("day")
mins.index.name = 'Time'
candle_chart = mins.tail(240)
mco = ['yellow','blue'] * 60 + [None] * 120
mpf.plot(candle_chart, volume=True, style='yahoo', type='candle', marketcolor_overrides=mco)

 

The effect is as follows:Mplfinance

Some students also want to be able to plot their own technical indicators, which mplfinance can also do:



import pandas as pd
import mplfinance as mpf
import matplotlib.animation as animation

mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
mins["day"] = pd.to_datetime(mins["day"])
mins = mins.set_index("day")
mins.index.name = 'Time'
candle_chart = mins.tail(240)

df = candle_chart

exp12 = df['close'].ewm(span=12, adjust=False).mean()
exp26 = df['close'].ewm(span=26, adjust=False).mean()
macd = exp12 - exp26
signal = macd.ewm(span=9, adjust=False).mean()
histogram = macd - signal

apds = [mpf.make_addplot(exp12,color='lime'),
        mpf.make_addplot(exp26,color='c'),
        mpf.make_addplot(histogram,type='bar',width=0.7,panel=1,
                         color='dimgray',alpha=1,secondary_y=False),
        mpf.make_addplot(macd,panel=1,color='fuchsia',secondary_y=True),
        mpf.make_addplot(signal,panel=1,color='b',secondary_y=True),
       ]

s = mpf.make_mpf_style(base_mpf_style='classic',rc={'figure.facecolor':'lightgray'})

fig, axes = mpf.plot(df,type='candle',addplot=apds,figscale=1.5,figratio=(7,5),title='\n\nMACD',
                     style=s,volume=True,volume_panel=2,panel_ratios=(6,3,2),returnfig=True)

mpf.show()


mpf.make_addplot supports adding any plot to any panel, the panel parameter defaults to 0, if set to 1, the plot will be added to the second plot, the color parameter sets the color of the plot, and secondary_y sets the value of the plot to the y-axis. The effect is as follows:

 

Mplfinance

 

In addition, if you want to see the whole drawing process dynamically, just add an animation:

 

import pandas as pd
import mplfinance as mpf
import matplotlib.animation as animation

mins = pd.read_csv('sh300_1min.csv',index_col=0,parse_dates=True)
mins["day"] = pd.to_datetime(mins["day"])
mins = mins.set_index("day")
mins.index.name = 'Time'
candle_chart = mins.tail(240)

df = candle_chart

exp12 = df['close'].ewm(span=12, adjust=False).mean()
exp26 = df['close'].ewm(span=26, adjust=False).mean()
macd = exp12 - exp26
signal = macd.ewm(span=9, adjust=False).mean()
histogram = macd - signal

apds = [mpf.make_addplot(exp12,color='lime'),
        mpf.make_addplot(exp26,color='c'),
        mpf.make_addplot(histogram,type='bar',width=0.7,panel=1,
                         color='dimgray',alpha=1,secondary_y=False),
        mpf.make_addplot(macd,panel=1,color='fuchsia',secondary_y=True),
        mpf.make_addplot(signal,panel=1,color='b',secondary_y=True),
       ]

s = mpf.make_mpf_style(base_mpf_style='classic',rc={'figure.facecolor':'lightgray'})

fig, axes = mpf.plot(df,type='candle',addplot=apds,figscale=1.5,figratio=(7,5),title='\n\nMACD',
                     style=s,volume=True,volume_panel=2,panel_ratios=(6,3,2),returnfig=True)

mpf.show()

ax_main = axes[0]
ax_emav = ax_main
ax_hisg = axes[2]
ax_macd = axes[3]
ax_sign = ax_macd
ax_volu = axes[4]


def animate(ival):
    if (20+ival) > len(df):
        print('no more data to plot')
        ani.event_source.interval *= 3
        if ani.event_source.interval > 12000:
            exit()
        return
    data = df.iloc[0:(30+ival)]
    exp12 = data['close'].ewm(span=12, adjust=False).mean()
    exp26 = data['close'].ewm(span=26, adjust=False).mean()
    macd = exp12 - exp26
    signal = macd.ewm(span=9, adjust=False).mean()
    histogram = macd - signal
    apds = [mpf.make_addplot(exp12,color='lime',ax=ax_emav),
            mpf.make_addplot(exp26,color='c',ax=ax_emav),
            mpf.make_addplot(histogram,type='bar',width=0.7,
                             color='dimgray',alpha=1,ax=ax_hisg),
            mpf.make_addplot(macd,color='fuchsia',ax=ax_macd),
            mpf.make_addplot(signal,color='b',ax=ax_sign),
           ]

    for ax in axes:
        ax.clear()
    mpf.plot(data,type='candle',addplot=apds,ax=ax_main,volume=ax_volu)

ani = animation.FuncAnimation(fig,animate,interval=100)

mpf.show()

 

Mplfinance

 

 

There are many more interesting ways to play with it and you can read the examples of mplfinance to learn more about how to use it:

matplotlib github

Related articles

Python invoke task automation tool

Invoke is a spin-off from the well-known remote deployment tool Fabric, and together with paramiko are the two most core foundational components of the Fabric.

alive-progress example

I don't know if you have ever had the experience that you have written a program and it takes a long time to run each time. While waiting for the program to run you press enter again and again to prevent the program from getting stuck.

python fire examples

Python Fire, which can generate command-line interfaces from any Python code,Simply call the Fire function in any Python program to automatically convert that program to a CLI.

Pytype Usage and Examples

Pytype checks and infers the type of Python code:Use lint to check pure Python code, flag common errors such as misspelled property names, incorrect function calls, and much more, and it can even span files.

Encrypting files with Python

In life, sometimes we need to encrypt some important files,Python provides easy-to-use cryptographic libraries such as hashlib, base64, etc.

Quickly test your Python code with Hypothesis

Testing is important no matter which programming language or framework you use. hypothesis is an advanced testing library for Python. It allows writing test cases with parameters, and then generating easy-to-understand test data that makes the test fail.

mplcyberpunk tutorials

Cyberpunk 2077" is a very popular single-player game ~ The game is set in the year 2077, a highly developed technology but chaotic and disorderly "cyberpunk" city. In this world, although the technology is highly developed, but the standard of living of

Heartrate: Real-time Visualization for Python Execution

Heartate - Track programs like a heart rate,Heartrate is a Python tool library that allows you to visualize the execution of Python programs in real time. Monitoring a running Python program is shown in the following figure.

Implementing reverse proxies with Django only

When you think of reverse proxies, you say nginx. nginx is the ideal reverse proxy tool. But now the conditions are tough. The server doesn't have nginx and doesn't have root privileges, which means you can't compile and install nginx, and only one port,