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)
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')
Black and white color is too monotonous, we can change to "Yahoo" color scheme:
mpf.plot(candle_chart, type='candle', style='yahoo')
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')
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:
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)
If you need multiple moving averages, just change mav to a tuple parameter and pass in the period parameter you need:
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)
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:
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:
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()
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: