Python数据可视化:mplfinance创建蜡烛图(三)

1.make_mpf_style()函数
make_mpf_style(base_mpf_style,base_mpl_style,marketcolors,mavcolors,facecolor,edgecolor,figcolor,gridcolor,gridaxis,gridstyle,y_on_right,rc)

函数部分参数如下:

1).base_mpf_style设置需要继承的系统样式;

2).base_mpl_style设置同时使用matplotlib中的式样seaborn;

3).marketcolor设置K线的颜色,可以使用make_marketcolors()函数进行定义;

4).mavcolors设置均线的颜色,必须使用列表传参;

5).facecolor设置前景色;

6).edgecolor设置边缘线颜色;

7).figcolor设置图像外周围填充色;

8).gridcolor设置网格线颜色;

9).gridaxis设置网格线的位置,gridaxis=‘both’/‘horizontal’/‘vertical’;

10).gridstyle设置网格线线型,gridstyle=‘solid’/‘dashed’/‘dashdot’/‘dotted’;

11).y_on_right设置y轴位置是否在右,y_on_right=True设为右边;

12).rc使用rcParams的dict设置格式;

2.关于make_mpf_style()函数中的marketcolors参数,经常make_marketcolors()函数进行设置,
make_marketcolors(up,down,edge,wick,volume,ohlc,inherit)

函数部分参数如下:

1).up设置阳线柱填充颜色;

2).down设置阴线线柱填充颜色;

3).edge设置蜡烛线边缘颜色,edge='i’代表继承K线主体颜色;

4).wick设置蜡烛线上下影线的颜色,wick='i’代表继承K线主体的颜色;

5).volume设置成交量的颜色,volume='i’代表继承K线主体颜色;

6).ohlc设置均线颜色,代表继承K线主体的颜色;

7).inherit设置是否继承,如果设置了继承inherit=True,那么edge/wick/volume/ohlc 四个参数即便设置了颜色也会无效,其中edge/wick/volume/ohlc四个参数除了设置’i’ 自动继承up和down的颜色外,也可以使用dict模式定义。

3.解决中文输出乱码
1).首先解决matplotlib中文输出乱码: plt.rcParams[‘font.sans-serif’]=[‘simHei’] # 以黑体显示中文 plt.rcParams[‘axes.unicode_minus’]=False # 解决保存图像符号“-”显示为放块的问题 2.其次在mpf.plot()函数的style参数,添加rc={‘font.family’:‘SimHei’}。

import pandas as pd
import tushare as ts # tushare版本需大于1.2.10
import talib as tb
import matplotlib.pyplot as plt
import mplfinance as mpf
plt.rcParams['font.sans-serif']=['simHei'] # 以黑体显示中文
plt.rcParams['axes.unicode_minus']=False # 解决保存图像符号“-”显示为放块的问题
pd.set_option('max_rows', None)
pd.set_option('max_columns', None)
pd.set_option('expand_frame_repr', False)
pd.set_option('display.unicode.ambiguous_as_wide', True)
pd.set_option('display.unicode.east_asian_width', True)

def ts_candle_kline(ts_code=None,adj=None,start_date=None,end_date=None):

    # 输入your token,初始化pro接口
    pro=ts.pro_api('your token')

    # 后复权行情
    df = ts.pro_bar(ts_code=ts_code, adj=adj, start_date=start_date, end_date=end_date)


    df=df.drop(columns=['change','pct_chg'])
    df['trade_date']=pd.to_datetime(df['trade_date'],format='%Y-%m-%d')

    df.rename(columns={'vol': 'volume'},inplace=True)
    df=df[['trade_date','open','high','low','close','volume']]
    df.set_index('trade_date',drop=True,inplace=True)
    df.sort_values(by=['trade_date'],axis=0,ascending=True,inplace=True)
    # mpf.plot(df,type='candle',mav=(5,10,30),volume=True)
    return df


def find_signal(df):
    # 收盘价上穿布林带上轨做多
    df.loc[(df['close'].shift(1) <= df['upper'].shift(1)) & (df['close'] > df['upper']), 'signal_long'] = 1
    # 收盘价下穿布林带中轨平仓
    df.loc[(df['close'].shift(1) >= df['middler'].shift(1)) & (df['close'] < df['middler']), 'signal_short'] = -1


    return df

df=ts_candle_kline(ts_code='001227.SZ', adj='hfq', start_date='20000101', end_date='20220426')
df['upper'], df['middler'], df['lower'] = tb.BBANDS(df['close'], timeperiod=5, nbdevup=2, nbdevdn=2, matype=0)
df.fillna(method='bfill',inplace=True) # 用下一个非空值向上填充
df=find_signal(df)
df.loc[df['signal_short'].notna(),'signal_short']=df['high']

my_color=mpf.make_marketcolors(up='red',down='green',edge='black',wick='i',volume={'up':'red','down':'green'},ohlc='black',inherit=False)
my_style=mpf.make_mpf_style(base_mpf_style='sas',marketcolors=my_color,gridaxis='both',gridstyle='-.',y_on_right=False,rc={'font.family':'SimHei'})
add_plot=[mpf.make_addplot(df[['upper']],linestyle='dashdot'),
          mpf.make_addplot(df[['middler']],linestyle='dashdot'),
          mpf.make_addplot(df[['lower']],linestyle='dashdot'),
          mpf.make_addplot(df['signal_short'].values,type='scatter',markersize=20,marker='v',color='g'),
          mpf.make_addplot(df['close'].values,panel=2,color='y',secondary_y='auto')]


mpf.plot(df,type='candle',volume=True,addplot=add_plot,main_panel=0,volume_panel=1,num_panels=3,panel_ratios=(2,1,1),style=my_style,
         title='兰州银行k线图',ylabel='价格',ylabel_lower='成交量',figratio=(9,6),figscale=1.2,show_nontrading=False)

在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值