简介

回测时往往想知道策略中间的运行情况,虽然可以通过最后的统计指标来一窥端倪,但对回测过程进行可视化是最符合人性的,同时通过观察回测过程也可以更好的设计&优化量化策略。Backtrader使用matplotlib库提供可视化能力

使用方法

Backtrader数据可视化非常简单,只需在run()之后调用plot()方法即可。

cerebro.run()
cerebro.plot()

plot(self, plotter=None, numfigs=1, iplot=True, **kwargs) 方法各参数含义如下:

  • plotter: 包含绘图属性的PlotScheme及其派生类对象。默认为None,如果为None,则默认的PlotScheme对象会被实例化

  • numfigs :将图形拆分成多幅图展示,默认为1

  • iplot : 在Jupyter Notebook运行则是否自动 plot inline,默认为True。如果不在jupyter中运行,该参数最好设置为False,否则容易出问题

  • *kwargs:args参数用于改变plotter属性值

可以通过两种办法来系统性控制可视化配置:

  1. 直接通过设置plot()方法的args参数,如下所示。

cerebro.plot(iplot=False,style='candel',  # 设置主图行情数据的样式为蜡烛图plotdist=0.1,    # 设置图形之间的间距barup = '#ff9896', bardown='#98df8a', # 设置蜡烛图上涨和下跌的颜色volup='#ff9896', voldown='#98df8a', # 设置成交量在行情上涨和下跌情况下的颜色)

2. 自定义 PlotScheme 类修改对应的参数

PlotScheme对象包括了所有的系统级绘图选项,选项如下所示。

class PlotScheme(object):def __init__(self):# to have a tight packing on the chart wether only the x axis or also# the y axis have (see matplotlib)self.ytight = False# y-margin (top/bottom) for the subcharts. This will not overrule the# option plotinfo.plotymarginself.yadjust = 0.0# Each new line is in z-order below the previous one. change it False# to have lines paint above the previous lineself.zdown = True# Rotation of the date labes on the x axisself.tickrotation = 15# How many "subparts" takes a major chart (datas) in the overall chart# This is proportional to the total number of subchartsself.rowsmajor = 5# How many "subparts" takes a minor chart (indicators/observers) in the# overall chart. This is proportional to the total number of subcharts# Together with rowsmajor, this defines a proportion ratio betwen data# charts and indicators/observers chartsself.rowsminor = 1# Distance in between subchartsself.plotdist = 0.0# Have a grid in the background of all chartsself.grid = True# Default plotstyle for the OHLC bars which (line -> line on close)# Other options: 'bar' and 'candle'self.style = 'line'# Default color for the 'line on close' plotself.loc = 'black'# Default color for a bullish bar/candle (0.75 -> intensity of gray)self.barup = '0.75'# Default color for a bearish bar/candleself.bardown = 'red'# Level of transparency to apply to bars/cancles (NOT USED)self.bartrans = 1.0# Wether the candlesticks have to be filled or be transparentself.barupfill = Trueself.bardownfill = True# Wether the candlesticks have to be filled or be transparentself.fillalpha = 0.20# Wether to plot volume or not. Note: if the data in question has no# volume values, volume plotting will be skipped even if this is Trueself.volume = True# Wether to overlay the volume on the data or use a separate subchartself.voloverlay = True# Scaling of the volume to the data when plotting as overlayself.volscaling = 0.33# Pushing overlay volume up for better visibiliy. Experimentation# needed if the volume and data overlap too muchself.volpushup = 0.00# Default colour for the volume of a bullish dayself.volup = '#aaaaaa'  # 0.66 of gray# Default colour for the volume of a bearish dayself.voldown = '#cc6073'  # (204, 96, 115)# Transparency to apply to the volume when overlayingself.voltrans = 0.50# Transparency for text labels (NOT USED CURRENTLY)self.subtxttrans = 0.66# Default font text size for labels on the chartself.subtxtsize = 9# Transparency for the legend (NOT USED CURRENTLY)self.legendtrans = 0.25# Wether indicators have a leged displaey in their chartsself.legendind = True# Location of the legend for indicators (see matplotlib)self.legendindloc = 'upper left'# Plot the last value of a line after the Object nameself.linevalues = True# Plot a tag at the end of each line with the last valueself.valuetags = True# Default color for horizontal lines (see plotinfo.plothlines)self.hlinescolor = '0.66'  # shade of gray# Default style for horizontal linesself.hlinesstyle = '--'# Default width for horizontal linesself.hlineswidth = 1.0# Default color scheme: Tableau 10self.lcolors = tableau10# strftime Format string for the display of ticks on the x axisself.fmt_x_ticks = None# strftime Format string for the display of data points valuesself.fmt_x_data = None

PlotScheme类定义了一个color(self, idx) 方法返回将要使用的颜色,子类可以重载,其idx参数为要绘制的line的当前index。 如MACD 绘制3条线,idx变量有0,1和2共3个值,新的指标idx会从0重新开始。默认的color scheme是Tableau 10 Color Palette ,对应的index是tab10_index = [3, 0, 2, 1, 2, 4, 5, 6, 7, 8, 9] 。可以通过在自定义 PlotScheme类重载color()方法或传递 lcolors 变量给plot 方法来改变要使用的颜色。

def color(self, idx):colidx = tab10_index[idx % len(tab10_index)]return self.lcolors[colidx]

可视化组件

Backtrader支持3大部分组件的可视化:

  • Data feeds数据源:通过 adddata、replaydata和resampledata方法导入cerebro的原始数据

  • Indicators指标:在策略类中声明或者通过 addindicator 添加的指标

  • Observers观测器对象:通过addobserver添加的观测器,如Cash和Value对象

在绘制图形时,默认是将data feeds数据源绘制在主图上,Indicators指标有的与 Data Feeds数据源一起绘制在主图上,比如均线,有的则以子图形式绘制;observers 通常绘制在子图上

可视化选项

除了上面说的通过plot()参数和自定义PlotScheme来系统控制可视化选项外,Indicators指标和Observers观测器有一些选项可以控制其绘图形式,一共有3种类型:

  • Object对象级的可视化选项 —可以影响整个对象的绘制行为,由plotinfo来控制

plotinfo = dict(plot=True, # 是否绘制subplot=True, # 是否绘制成子图plotname='', # 图形名称plotabove=False, # 子图是否绘制在主图的上方plotlinelabels=False, # 主图上曲线的名称plotlinevalues=True,plotvaluetags=True,plotymargin=0.0,plotyhlines=[],plotyticks=[],plothlines=[],plotforce=False,plotmaster=None,plotylimited=True,)

有2种方法来访问plotinfo的属性,如下所示:

# 通过参数来设置
sma = bt.indicators.SimpleMovingAverage(self.data, period=15, plotname='mysma')# 通过属性来设置
sma = bt.indicators.SimpleMovingAverage(self.data, period=15)
sma.plotinfo.plotname = 'mysma'
  • Line线相关的可视化选项 — 可以使用plotlines对象来控制lines对象的绘图行为,plotlines中的选项会在绘图时直接传给matplotlib,如下所示。

lines = ('histo',)
plotlines = dict(histo=dict(_method='bar', alpha=0.50, width=1.0))
  • 方法控制的可视化 — 当处理indicator指标和observer观测器时,_plotlabel(self), _plotinit(self)方法可以进一步控制可视化

结论 & 交流

关注微信公众号:诸葛说talk,获取更多内容。同时还能获取邀请加入量化投资群, 与众多投资爱好者、量化从业者、技术大牛一起交流、切磋,在实战中快速提升自己的投资水平。

写文章不易,觉得本文对你有帮助的话,帮忙点个在看吧。

参考

  • Plotting - Backtrader

  • https://github.com/mementum/backtrader/blob/master/backtrader/plot/plot.py

  • Indicators - Usage - Backtrader

量化框架backtrader之一文读懂可视化相关推荐

  1. 量化框架backtrader之一文读懂observer观测器

    简介 Backtrader observer观测器主要用于观察策略运行过程中的各个状态指标,如资金.买卖点等,在调用cerebro.plot()后可以方便地可视化状态指标的变化情况,如下图展示的Bro ...

  2. 量化框架backtrader之一文读懂Analyzer分析器

    诺贝尔奖获得者威廉夏普 简介 策略绩效评价是量化交易很重要的一环,投资不仅需要了解策略的收益率, 也需要了解策略的风险.backtrader提供多种analyzer分析器,可以输出多种绩效指标,用来分 ...

  3. 任务调度框架 Quartz 一文读懂

    1.Quartz 简介 Quartz是OpenSymphony开源组织在Job scheduling领域又一个开源项目,完全由Java开发,可以用来执行定时任务,类似于java.util.Timer. ...

  4. hdfs文档存储服务器,一文读懂HDFS分布式存储框架分析

    一文读懂HDFS分布式存储框架分析 HDFS是一套基于区块链技术的个人的数据存储系统,利用无处不在的私人PC存储空间及便捷的网络为个人提供数据加密存储服务,将闲置的存储空间利用起来,服务于正处于爆发期 ...

  5. hdfs读写流程_一文读懂HDFS分布式存储框架分析

    一文读懂HDFS分布式存储框架分析 HDFS是一套基于区块链技术的个人的数据存储系统,利用无处不在的私人PC存储空间及便捷的网络为个人提供数据加密存储服务,将闲置的存储空间利用起来,服务于正处于爆发期 ...

  6. 一文读懂程序化交易算法交易量化投资高频交易统计利

    转 一文读懂程序化交易.算法交易.量化投资.高频交易. 统计套利 在央行发布的<中国金融稳定报告(2016)>中,对于高频交易的解释为程序化交易的频率超过一定程度,就成为高频交易.而对程序 ...

  7. 一文读懂PQuant与QQuant量化易金工

    转 一文读懂P Quant与 Q Quant ,量化交易与金融工程 原标题:P Quant 和 Q Quant 到底哪个是未来?  来源:李老师与何老师的CFA学习课堂  作者:何璇 P-Quant ...

  8. ​一文读懂EfficientDet

    一文读懂EfficientDet. 今年年初Google Brain团队在 CVPR 2020 上发布了 EfficientDet目标检测模型, EfficientDet是一系列可扩展的高效的目标检测 ...

  9. 独家 | 一文读懂语音识别(附学习资源)

    原标题:独家 | 一文读懂语音识别(附学习资源) 一.前言 6月27日,美国权威科技杂志<MIT科技评论>公布2017全球最聪明50家公司榜单.科大讯飞名列中国第一.全球第六.全世界排在科 ...

  10. 一文读懂BERT(原理篇)

    一文读懂BERT(原理篇) 2018年的10月11日,Google发布的论文<Pre-training of Deep Bidirectional Transformers for Langua ...

最新文章

  1. python可以从事什么工作-学完Python开发可以从事哪些行业?
  2. 在线IDE之关键字另色显示
  3. lol服务器不稳定补偿地址,LOL9月4日更新bug补偿地址在哪里 9月4日更新bug补偿地址分享...
  4. JAVA 设计的七大原则
  5. pyqt5讲解10:布局管理讲解大全
  6. “数据驱动、智能引领”,打造未来智能小镇“样板间”
  7. 还是畅通工程(HDU-1233)
  8. A-古代汉语知识点整理大全
  9. SpringBoot测试类
  10. CSR8系列ROM版本芯片介绍
  11. 学习理论:理论联系实际--演绎归纳演绎
  12. movs 数据传送指令_深入理解计算机系统(3.3)---数据传送(或者说复制)指令详解...
  13. OpenCV-DoG
  14. user story的重要性
  15. java netty wss_netty实现websocket客户端(支持wss安全连接)
  16. DAS\NAS\SAN\IPSAN区别
  17. 突发!微软亚洲研究院副院长周明离职,将加入创新工场
  18. 随想录(工作中的常用软件)
  19. 传智播客 php培训 mysql 刘道成 word 文档,传智播客 刘道成PHP视频教程 mysql 数据库视频教程...
  20. 谈谈UVM中的uvm_info打印

热门文章

  1. postgresql 优势
  2. oracle判断除数为零,Oracle decode函数 除数为零
  3. java折线图_如何用java 画折线图
  4. 杀毒软件需要开源吗?
  5. Puppet nginx+passenger模式配置
  6. 可重入锁 ReentrantLock
  7. 《孙子兵法特殊战法之火攻篇》
  8. cidaemon.exe过程cpu入住率和关闭cidaemon.exe加工方法
  9. springboot整合容联云发短信验证码
  10. 国内Linux内核先驱者陈莉君教授领衔,业界首个产学研 eBPF技术探索SIG成立!