Use Python pandas+matplotlib+mpl_finance to draw candlestick charts

 Python data analysis notes use Python pandas+matplotlib+mpl_finance to draw K-line graphs

1. First import the library

# coding=utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import mpl_finance as mpf
import warnings

2. Create data (the data is created by yourself, it is only for practice, just preprocess your own data when applying, and keep the format consistent)

d = {'最高':[132,135,136,137,139,136,132,130,130,134,135,132,132,137,138,136,136,140,122,138,135,142,141,144,144,139],
     '最低':[120,120,110,119,120,119,110,88,120,115,100,110,110,115,121,124,81,124,122,118,108,100,110,93,100,119],
     '开始':[127,126,124,133,126,120,119,125,123,122,127,123,127,128,127,128,81,132,127,129,125,129,132,93,133,119],
     '结束':[126,130,132,126,130,125,125,91,126,126,116,126,126,128,127,126,131,129,122,125,108,131,135,134,119,128]
    }
df = pd.DataFrame(d)

3. View data (first five lines)

df.head()

 Output result:

 

4. Draw K-line diagrams (by calling the mpf.candlestick2_ochl() function to draw K-line diagrams, the parameters of this function can be set according to the requirements. If you want to know more specifically, you can learn about it yourself on Baidu)

fig, ax= plt.subplots(1, 1, sharex=True, figsize=(15, 10))
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
mpf.candlestick2_ochl(ax,df["开始"], df["结束"], df["最高"], df["最低"], width=0.6, colorup='r',colordown='green',alpha=1.0)
plt.title('K线图')

Result graph: 

Full version code (local test can run):

# coding=utf-8
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import mpl_finance as mpf
import warnings
d = {'最高':[132,135,136,137,139,136,132,130,130,134,135,132,132,137,138,136,136,140,122,138,135,142,141,144,144,139],
     '最低':[120,120,110,119,120,119,110,88,120,115,100,110,110,115,121,124,81,124,122,118,108,100,110,93,100,119],
     '开始':[127,126,124,133,126,120,119,125,123,122,127,123,127,128,127,128,81,132,127,129,125,129,132,93,133,119],
     '结束':[126,130,132,126,130,125,125,91,126,126,116,126,126,128,127,126,131,129,122,125,108,131,135,134,119,128]
    }
df = pd.DataFrame(d)
fig, ax= plt.subplots(1, 1, sharex=True, figsize=(15, 10))
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
mpf.candlestick2_ochl(ax,df["开始"], df["结束"], df["最高"], df["最低"], width=0.6, colorup='r',colordown='green',alpha=1.0)
plt.title('K线图')

 

 

 

 

Guess you like

Origin blog.csdn.net/weixin_43155435/article/details/126709442