本小章节对mplfinance的画图进行简单的说明
画出k线图和唐奇安通道线(同一幅图片内)
首先需要求解唐奇安通道线的各个指标,包括上轨线,下轨线和中轨线。
计算代码如下:
# 通过数据库获取数据
def get_data(security,start_date,end_date):
df = get_price(security, start_date, end_date, frequency='daily')
df['ret']=df.close.pct_change()
close=df.close
high=df.high
low=df.low
up=pd.Series(0.0,index=close.index)
down=pd.Series(0.0,index=low.index)
middle=pd.Series(0.0,index=close.index)
for i in range(20,len(close)):
up[i]=max(high[(i-20):i])
down[i]=min(low[(i-20):i])
middle[i]=(up[i]+down[i])/2
df['up']=up
df['down']=down
df['middle']=middle
df=df[20:]
df1=df.copy()
df1 = ta.add_all_ta_features(df1, "open", "high", "low", "close", "volume", fillna=True)
atr=df1.volatility_atr
df['atr']=atr
df=df[20:]
df['openinterest']=0
df.index=pd.to_datetime(df.index)
df=df[['open','high','low','close','volume','openinterest','ret','up','down','middle','atr']]
return df
security='600071.XSHG'
start_date='2018-01-01'
end_date='2020-10-01'
stock_df=get_data(security,start_date,end_date)
stock_df
结果如下所示
open high low close volume openinterest ret up down middle atr
2018-03-06 17.40 17.48 17.17 17.23 800200.0 0 -0.009770 17.84 15.30 16.570 0.516375
2018-03-07 17.49 17.49 17.12 17.20 429100.0 0 -0.001741 17.84 15.30 16.570 0.501738
2018-03-08 17.25 17.69 17.25 17.63 1685050.0 0 0.025000 17.84 15.30 16.570 0.500564
2018-03-09 17.60 17.60 17.00 17.47 1737678.0 0 -0.009075 17.84 15.30 16.570 0.513507
2018-03-12 17.41 17.70 17.37 17.66 1623748.0 0 0.010876 17.84 15.30 16.570 0.495157
... ... ... ... ... ... ... ... ... ... ... ...
2020-09-24 10.47 10.59 10.33 10.41 1578200.0 0 -0.022535 11.88 10.32 11.100 0.344765
2020-09-25 10.42 10.46 10.27 10.31 1198000.0 0 -0.009606 11.88 10.32 11.100 0.329289
2020-09-28 10.31 10.35 10.02 10.04 1144904.0 0 -0.026188 11.88 10.27 11.075 0.329360
2020-09-29 10.00 10.23 10.00 10.09 1365967.0 0 0.004980 11.88 10.02 10.950 0.319424
2020-09-30 10.06 10.18 10.00 10.07 1015515.0 0 -0.001982 11.88 10.00 10.940 0.305482
mc = mpf.make_marketcolors(
up="red", # 上涨K线的颜色
down="green", # 下跌K线的颜色
edge="black", # 蜡烛图箱体的颜色
volume="blue", # 成交量柱子的颜色
wick="black" # 蜡烛图影线的颜色
)
# 调用make_mpf_style函数,自定义图表样式
# 函数返回一个字典,查看字典包含的数据,按照需求和规范调整参数
style = mpf.make_mpf_style(base_mpl_style="ggplot", marketcolors=mc)
# print(style)
进行可视化
import mplfinance as mpf
# 调用make_marketcolors函数,定义K线颜色
mc = mpf.make_marketcolors(
up="red", # 上涨K线的颜色
down="green", # 下跌K线的颜色
edge="black", # 蜡烛图箱体的颜色
volume="blue", # 成交量柱子的颜色
wick="black" # 蜡烛图影线的颜色
)
# 调用make_mpf_style函数,自定义图表样式
# 函数返回一个字典,查看字典包含的数据,按照需求和规范调整参数
style = mpf.make_mpf_style(base_mpl_style="ggplot", marketcolors=mc)
# print(style)
add_plot=[
mpf.make_addplot(stock_df.up),
mpf.make_addplot(stock_df.middle),
mpf.make_addplot(stock_df.down)]
mpf.plot(data=stock_df,
type="candle",
title="Candlestick for fhgx",
addplot=add_plot,
ylabel="price",
style=style,
volume=True,
figratio=(20,14))