当前位置:网站首页>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

  1. 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

  1. 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

  2. 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]
  1. 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

原网站

版权声明
本文为[Zhuge said talk]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261317556687.html