mplfinancet绘制K线图
1、安装
安装速度快
pip install mplfinance -i https://pypi.tuna.tsinghua.edu.cn/simple
C:\Users>pip install mplfinance -i https://pypi.tuna.tsinghua.edu.cn/simple
Defaulting to user installation because normal site-packages is not writeable
Looking in indexes: https://pypi.tuna.tsinghua.edu.cn/simple
Collecting mplfinance
Downloading https://pypi.tuna.tsinghua.edu.cn/packages/5c/38/6e4a35f156efef1f2b0ebb18aaa5ea69d28b6f46584ebdb9e57dc59f1cb5/mplfinance-0.12.9b7-py3-none-any.whl (73 kB)
|████████████████████████████████| 73 kB 514 kB/s
Requirement already satisfied: pandas in c:\users\appdata\roaming\python\python38\site-packages (from mplfinance) (1.2.3)
Requirement already satisfied: matplotlib in c:\users\appdata\roaming\python\python38\site-packages (from mplfinance) (3.3.4)
Requirement already satisfied: python-dateutil>=2.1 in c:\users\appdata\roaming\python\python38\site-packages (from matplotlib->mplfinance) (2.8.1)
Requirement already satisfied: kiwisolver>=1.0.1 in c:\users\appdata\roaming\python\python38\site-packages (from matplotlib->mplfinance) (1.3.1)
Requirement already satisfied: pillow>=6.2.0 in c:\users\appdata\roaming\python\python38\site-packages (from matplotlib->mplfinance) (8.1.2)
Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.3 in c:\users\appdata\roaming\python\python38\site-packages (from matplotlib->mplfinance) (2.4.7)
Requirement already satisfied: numpy>=1.15 in c:\users\appdata\roaming\python\python38\site-packages (from matplotlib->mplfinance) (1.19.5)
Requirement already satisfied: cycler>=0.10 in c:\users\appdata\roaming\python\python38\site-packages (from matplotlib->mplfinance) (0.10.0)
Requirement already satisfied: pytz>=2017.3 in c:\users\appdata\roaming\python\python38\site-packages (from pandas->mplfinance) (2021.1)
Requirement already satisfied: six in c:\users\appdata\roaming\python\python38\site-packages (from cycler>=0.10->matplotlib->mplfinance) (1.15.0)
Installing collected packages: mplfinance
Successfully installed mplfinance-0.12.9b7
C:\Users>
2、测试绘图参数
通过数据库中的股票数据进行绘图。
(1)MySQL读入数据
通过pd.read_sql读入MySQL数据,直接设置好索引列:
- sql:sql命令字符串 con:连接sql数据库的engine,一般可以用sqlalchemy或者pymysql之类的包建立;
- index_col:选择某一列作为index; coerce_float:将数字形式的字符串直接以float型读入;
- parse_dates:将某一列日期型字符串转换为datetime型数据,与pd.to_datetime功能类似。可以直接提供需要转换的列名以默认的日期形式转换,也可以用字典的格式提供列名和转换的日期格式,比如{column_name:
format string}(format string:“%Y:%m:%H:%M:%S”); - columns:要选取的列,一般没啥用,因为在sql命令里面一般就指定要选择的列了;
- chunksize:如果提供了一个整数值,那么就会返回一个generator,每次输出的行数就是提供的值的大小。
(2)plot主要参数
参数 描述
- type 绘制图线的种类
- ylabel y轴标签
- style 风格样式
- title 图表标题
- mav 均线,格式为一个元组,如(5, 10)表示绘制5日均线和10日均线
- volume 是否绘制量柱图,默认为False,表示不绘制。
- figratio 图像横纵比,如(5,3)表示图像长比宽为5:3。
- ylabel_lower 表示底部图像的标签(一般是量柱图)
- savefig 如果需要将图像保存为一个图片文件,则通过该参数指定文件路径即名字即可。不指定则默认不保存,但是图像会显示出来。如果指定了则图像不会直接显示出来。
type 描述
candle 蜡烛图
ohlc OHLC图,也称“美国线”。即用一根垂直的线段表示一天的行情,在开盘和收盘价格处划一笔刻度。
line 直线,即近绘制收盘价曲线
renko 砖形图
pnf pnf图,由圈和叉构成
style 描述
‘binance’ 币安风格
‘blueskies’ 蓝天风格
‘brasil’ 巴西风格
‘charles’ 查理风格
‘checkers’ 跳棋风格
‘classic’ 古典风格
‘default’ 默认风格
‘mike’ 迈克风格
‘nightclouds’ 夜云风格
‘sas’ SAS风格
‘starsandstripes’ 星条旗风格
‘yahoo’ 雅虎风格
(3)测试程序
通过参数type修改绘图类型,默认是ohlc,可改成type=‘candle’ 或者 type=‘line’
关键字参数 mav=(2, 5, 10),多条均线使用元组,只绘制一条均线,可以mav=10
关键字参数volume=True,显示成交量
关键字参数show_nontrading,默认是False,设置为True,就可以看到停盘的时间段
def draw_day_k_test():
# 1、获取数据
# 返回一个 Connection 对象
db_conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='TEST',
database='test',
charset='utf8'
)
# 执行sql操作
sql = "select t.stock_date,t.open_stock,t.high_stock,t.low_stock,t.close_stock,volume_stock from tdx_daily t where t.stock_no='sh600000' and stock_date>'2023-01-01' order by t.stock_date"
stock_data = pd.read_sql(sql, con=db_conn, index_col="stock_date")
data = stock_data.rename(
columns={'stock_date': 'Date', 'open_stock': 'Open', 'close_stock': 'Close', 'high_stock': 'High',
'low_stock': 'Low',
'volume_stock': 'Volume'}) # 更换列名,为后面函数变量做准备
# data.set_index('Date', inplace=True) # 设置date列为索引,覆盖原来索引,这个时候索引还是 object 类型,就是字符串类型。
data.index = pd.DatetimeIndex(
data.index) # 将object类型转化成 DateIndex 类型,pd.DatetimeIndex 是把某一列进行转换,同时把该列的数据设置为索引 index。
data = data.sort_index(ascending=True)
mpf.plot(data, type='candle', title='Candle')
mpf.plot(data, type='line', title='Line')
mpf.plot(data, type='ohlc', mav=5, title='default type ohlc')
mpf.plot(data, type='candle', mav=(3, 6, 9), title='3 6 9 day moving average line')
mpf.plot(data, type='candle', mav=(3, 6, 9), volume=True, title='day moving average line and volume')
mpf.plot(data, type='candle', mav=(5, 10, 30), volume=True, show_nontrading=True,
title='day moving average line and volume')
# show_nontrading=True 关键字参数show_nontrading,默认是False,设置为True,就可以看到停盘的时间段
iday = data.loc['2023-02-01':'2023-02-28']
# print(iday)
# print(data)
mpf.plot(iday, type='candle', mav=(5, 10), title='Slice Query', figratio=(5, 3),
style='blueskies', ylabel_lower='Volume', volume=True)
mpf.plot(data, type='renko', volume=True, mav=(5, 10), title='Slice Query pnf')
db_conn.close()
(4)效果图
3、模拟股票软件
(1)代码
def draw_day_k():
# 返回一个 Connection 对象
db_conn = pymysql.connect(
host='127.0.0.1',
port=3306,
user='root',
password='TEST',
database='test',
charset='utf8'
)
# 执行sql操作
sql = "select t.stock_date,t.open_stock,t.high_stock,t.low_stock,t.close_stock,volume_stock from tdx_daily t where t.stock_no='sh600000' and stock_date>'2023-01-01' order by t.stock_date"
stock_data = pd.read_sql(sql, con=db_conn,index_col="stock_date")
data = stock_data.rename(columns={'stock_date': 'Date', 'open_stock': 'Open', 'close_stock': 'Close', 'high_stock': 'High', 'low_stock': 'Low',
'volume_stock': 'Volume'}) # 更换列名,为后面函数变量做准备
#data.set_index('Date', inplace=True) # 设置date列为索引,覆盖原来索引,这个时候索引还是 object 类型,就是字符串类型。
data.index = pd.DatetimeIndex(data.index) # 将object类型转化成 DateIndex 类型,pd.DatetimeIndex 是把某一列进行转换,同时把该列的数据设置为索引 index。
data = data.sort_index(ascending=True)
my_color = mpf.make_marketcolors(up='green', down='red', edge='i', wick='i', volume='in')
my_style = mpf.make_mpf_style(marketcolors=my_color, gridaxis='both', gridstyle='-.', y_on_right=False)
#data = data.loc('2020-01-01':'2022-12-31')
mpf.plot(data, type='candle', mav=(5, 10, 20), style=my_style, volume=True, show_nontrading=False)
db_conn.close()