当前位置:网站首页>One article of the quantification framework backtrader read observer
One article of the quantification framework backtrader read observer
2022-06-26 14:16:00 【Zhuge said talk】
brief introduction
Backtrader observer The observer is mainly used to observe each state index during the operation of the strategy , Such as funds 、 Trading point, etc , Calling cerebro.plot() After that, it can easily visualize the changes of status indicators , As shown in the figure below Broker、Trades and BuySell 3 individual observer Observers can be used to look at cash and market value 、 Trading profit and loss as well as the change of trading point in the back testing process .

Usage method
adopt cerebro.addobserver() add to observer The observer
import backtrader as bt
# View revenue series
cerebro.addobserver(bt.observers.TimeReturn)
# View the fallback sequence
cerebro.addobserver(bt.observers.DrawDown)
addobserver(obscls, args, **kwargs): Parameters obscls Corresponding observer The observer ,args, **kwargs Corresponding to the parameters supported by the observer
cerebro = bt.Cerebro(stdstats=False)
cerebro.addobserver(bt.observers.Broker)
cerebro.addobserver(bt.observers.Trades)
cerebro.addobserver(bt.observers.BuySell)
cerebro Will default to add Broker(Cash & Value)、Trades、BuySell 3 An observer (stdstats=True), You can instantiate cerebro when , adopt bt.Cerebro(stdstats=False) To control the default display
observers Observer execution time : observers The observer is in all indicators and strategies next Method is run and the data is counted , So in strategy next Read in the method observer The latest data [0] be relative to next The current moment of is a little late bar Of
How to read observer Data in the observer
observers The observer belongs to lines object , Historical back test data is stored , It can be like the market lines Object . Policy properties self.stats To visit observers The observer
class MyStrategy(bt.Strategy):
def next(self):
# Available cash of the previous day at the current time point
self.stats.broker.cash[0]
self.stats.broker.value[0]
# Get the benefit of the day before the current moment
self.stats.timereturn.line[0]
How to save observer Data in the observer
backtrader Currently there is no direct save observer Observer data to file mechanism , We need to do it ourselves .backtrader The recommended implementation method is :
At the strategic level start Method
At the strategic level next、stop Method
With DrawDown The observer mode is an example , The sample code is as follows :
class MyStrategy(bt.Strategy):
def start(self):
self.mystats = open('mystats.csv', 'wb')
self.mystats.write('datetime,drawdown, maxdrawdown\n')
def next(self):
self.mystats.write(self.data.datetime.date(-1).strftime('%Y-%m-%d'))
self.mystats.write(',%.2f' % self.stats.drawdown.drawdown[0])
self.mystats.write(',%.2f' % self.stats.drawdown.maxdrawdown[0])
self.mystats.write('\n')
def stop(self):
self.mystats.write(self.data.datetime.date(0).strftime('%Y-%m-%d'))
self.mystats.write(',%.2f' % self.stats.drawdown.drawdown[0])
self.mystats.write(',%.2f' % self.stats.drawdown.maxdrawdown[0])
self.mystats.write('\n')
backtrader Self contained observer The observer
Self contained observers Observer yes :
Benchmark: A revenue series that records performance benchmarks , Performance benchmark data must be passed in advance adddata、resampledata、replaydata And so on cerebro, During visualization, the revenue series of the strategy itself and the revenue curve of the performance benchmark will be drawn at the same time
Broker、Cash、Value: Broker The observer records the broker broker Available funds and total assets at each point in time , Visualization will also show cash and values curve ; If you want to show it separately cash and values, Can be called separately backtrader.observers.Cash and backtrader.observers.Value
BuySell: The buy and sell signals during the back test are recorded , During visualization, the buying and selling points will be marked on the price curve
DrawDown: The fallback sequence of the backtesting process is recorded , Draw the fallback curve during visualization
TimeReturn: The return series in the back testing process is recorded , When visualizing, it will draw TimeReturn The yield curve
Trades: The profit and loss of each transaction in the back test process are recorded , Profit and loss points will be drawn during visualization
LogReturns: The policy is documented log Return
LogReturns2: Expanded LogReturns Support 2 Data ,data0 and data1
FundValue: Record the results of the back test fund value
FundShares: Record the results of the back test fund share
among , frequently-used observers Observer yes :Broker、BuySell、Trades、TimeReturn、DrawDown、Benchmark etc. .
newly build observers The observer
Broker Observer yes 2 individual lines object :cash、value. The implementation is similar to the following :
class Broker(Observer):
alias = ('CashValue',)
lines = ('cash', 'value')
plotinfo = dict(plot=True, subplot=True)
def next(self):
self.lines.cash[0] = self._owner.broker.getcash()
self.lines.value[0] = value = self._owner.broker.getvalue()
It can be seen that , Customize observer The observer steps are as follows :
Customize observer The observer is inherited from bt.observer.Observer; You can also inherit that you have other observers
Declare what is needed lines And parameters , Parameters can be chosen . stay next Method
Statement plotinfo、plotlines attribute , be used for cerebro.plot() Visual display
There is an automatic attribute _owner Means holding the observer The strategy of
further , We can customize it OrderObserver( Refer to the official website ): The standard BuySell The observer only cares about the operations that have been performed , We can create one observer Observers view order creation and expiration , As shown below .
class OrderObserver(bt.observer.Observer):
lines = ('created', 'expired',)
plotinfo = dict(plot=True, subplot=True, plotlinelabels=True)
plotlines = dict(
created=dict(marker='*', markersize=8.0, color='lime', fillstyle='full'),
expired=dict(marker='s', markersize=8.0, color='red', fillstyle='full')
)
def next(self):
for order in self._owner._orderspending:
if order.data is not self.data:
continue
if not order.isbuy():
continue
# Only interested in "buy" orders, because the sell orders
# in the strategy are Market orders and will be immediately
# executed
if order.status in [bt.Order.Accepted, bt.Order.Submitted]:
self.lines.created[0] = order.created.price
elif order.status in [bt.Order.Expired]:
self.lines.expired[0] = order.created.price
Of course , We can also inherit from other existing observers , Reference code :
class MyBuySell(bt.observers.BuySell):
# take barplot The default value is changed to True
params = (('barplot', True), ('bardist', 0.015))
# Change triangle to arrow
plotlines = dict(
buy=dict(marker=r'$\Uparrow$', markersize=8.0, color='#d62728' ),
sell=dict(marker=r'$\Downarrow$', markersize=8.0, color='red')
)
Conclusion & communication
Pay attention to WeChat public number : Zhuge said talk, Get more . At the same time, you can also get an invitation to join the investment exchange group 、 Quantitative investment seminar group , With many investment lovers 、 Quantitative practitioners 、 Technical leaders communicate with each other 、 Compare notes , Quickly improve your investment level .
It's not easy to write , If you think this article can help you , Help me. Let's see .
Reference resources
边栏推荐
- Hard (magnetic) disk (II)
- Related knowledge of libsvm support vector machine
- [jsoi2015] string tree
- 8.Ribbon负载均衡服务调用
- On insect classes and objects
- Hard (magnetic) disk (I)
- Hands on data analysis unit 3 model building and evaluation
- [wc2006] director of water management
- Knowledge about the determination coefficient R2 and the relationship with the correlation coefficient
- CF676C Vasya and String
猜你喜欢

windows版MySQL软件的安装与卸载

Build your own PE manually from winpe of ADK

Hard (magnetic) disk (I)

How to call self written functions in MATLAB

Sword finger offer 06.24.35 Linked list

New specification of risc-v chip architecture

Pycharm远程连接服务器来跑代码

Gartner 2022年顶级战略技术趋势报告

9项规定6个严禁!教育部、应急管理部联合印发《校外培训机构消防安全管理九项规定》

Use performance to see what the browser is doing
随机推荐
Wechat applet SetData dynamic variable value sorting
Wechat applet -picker component is repackaged and the disabled attribute is added -- below
虫子 内存管理 下 内存注意点
Solutions to the failure of last child and first child styles of wechat applet
Mathematical design D12 according to string function
Applicable and inapplicable scenarios of mongodb series
同花顺股票开户选哪个证券公司是比较好,比较安全的
Sword finger offer 09.30 Stack
Lucky numbers in the matrix
Wechat applet -picker component is repackaged and the disabled attribute is added -- above
C language | file operation and error prone points
[hnoi2010] flying sheep
Wechat applet - bind and prevent event bubble catch
mysql配置提高数据插入效率
7.consul service registration and discovery
8. Ribbon load balancing service call
hands-on-data-analysis 第三单元 模型搭建和评估
Reprint - easy to use wechat applet UI component library
GEE——全球人类居住区网格数据 1975-1990-2000-2014
Wechat applet Registration Guide