python:mplfinance 画K线图+布林线
pip install mplfinance ;
python 安装使用 TA-lib
安装主要在 http://www.lfd.uci.edu/~gohlke/pythonlibs/
这个网站找到
TA_Lib-0.4.24-cp310-cp310-win_amd64.whl
pip install /pypi/TA_Lib-0.4.24-cp310-cp310-win_amd64.whl
编写 mpf_kline_boll.py 如下
# -*- coding: utf-8 -*-
import os
import sys
import matplotlib.pyplot as plt
import mplfinance as mpf
import pandas as pd
import tushare as ts
import talib
if len(sys.argv) ==2:
code = sys.argv[1]
else:
print('usage: python mpf_kline_boll.py stockcode ')
sys.exit(1)
if len(code) !=6:
print('stock code length: 6')
sys.exit(2)
# help(ts.get_k_data) 了解参数
df = ts.get_k_data(code, start='2023-01-01')
if len(df) <30:
print(" len(df) <30 ")
sys.exit(2)
# 取收盘价
close = df['close'].values
# 计算布林线
df['upper'], df['mid20'], df['lower'] = talib.BBANDS(close,
timeperiod=20, nbdevup=2, nbdevdn=2, matype=0)
df.index = pd.to_datetime(df.date)
# 取样 近期的数据
df2 = df[ df['date'] >'2023-05-01']
print(df2.tail(5))
my_color = mpf.make_marketcolors(up='red', down='green', edge='black', wick='black')
my_style = mpf.make_mpf_style(marketcolors=my_color, gridaxis='both', gridstyle='-.', y_on_right=True)
#fig = mpf.figure(style=my_style, figsize=(12,6), facecolor=(0.82, 0.83, 0.85))
# 加画3条布林线
ap = mpf.make_addplot(df2[['upper','mid20','lower']])
# 绘画K线图
mpf.plot(df2, type='candle', style='charles', addplot=ap, volume=True, title=code)
#mpf.plot(df2, type='candle', style=my_style, addplot=ap, volume=True, title=code)
运行 python mpf_kline_boll.py 002594
参考:mplfinance最佳实践:动态交互式高级K线图(蜡烛图)