Backtrader timer

use

You can add a timer for the policy in the init or start method

def add_timer(self, when,
                  offset=datetime.timedelta(), repeat=datetime.timedelta(),
                  weekdays=[], weekcarry=False,
                  monthdays=[], monthcarry=True,
                  allow=None,
                  tzdata=None, cheat=False,
                  *args, **kwargs):

example:

     def __init__(self):
        self.add_timer(
            when=self.p.when,# datetime.time(15, 30)
            offset=self.p.offset,# datetime.timedelta()
            repeat=self.p.repeat,# datetime.timedelta()
            weekdays=self.p.weekdays
        )# [1]

Explanation:

when

Here, when is set to 15:30, weekday=[1], that is, it is required to trigger once a week, and the trigger event is 15:30.
If when is set to bt.timer SESSION_ Start is the opening time

offset

If you set the policy offset = datetime Timedelta (minutes = 30), i.e. 30 minutes offset from when, then the trigger event is 16:00

repeat

If you set the parameter repeat = datetime Timedelta (minutes = 30), the timer is required to trigger repeatedly every 30 minutes. If the data is minute level data, it can be realized, and other data levels are invalid

be careful:
Currently, the feed read by PandasData is used. It cannot be triggered at 15:30. GenericCSVData needs to be used.
Convert pandas data to fedd data of GenericCSVData:

def dataframe_to_csv_feed(df, file='cache.csv'):
    '''
    take AKshare of dataframe Data conversion to csv of datafeed
    :param df: AKshare of dataframe data
    :param file: csv Cache file
    :return:
    '''
    date_list = df['date'].to_list()
    begin_date = datetime.datetime.strptime(str(date_list[0]), "%Y-%m-%d %H:%M:%S")  # Start date of data
    end_date = datetime.datetime.strptime(str(date_list[-1]), "%Y-%m-%d %H:%M:%S")  # Start date of data

    df.to_csv(file)

    feed = bt.feeds.GenericCSVData(
        dataname=file,
        datetime=1,  # Column of date row
        open=2,  # Column of opening price
        high=4,  # Highest price column
        low=5,  # Lowest price column
        close=3,  # Column of closing price
        volume=6,  # Column of trading volume
        openinterest=-1,  # No open position column
        dtformat=('%Y-%m-%d'),  # Date format
        fromdate=begin_date,  # Start date
        todate=end_date,  # End date
        timeframe=bt.TimeFrame.Days,
        compression=1,
        sessionstart=datetime.time(9, 0),
        sessionend=datetime.time(17, 30),
    )
    return feed
About sessionstart and sessionend parameters when loading datafeed
feed = bt.feeds.PandasData(
        dataname=stock_zh_a_hist_df_daily,
        datetime=0,  # Column of date row
        open=1,  # Column of opening price
        high=3,  # Highest price column
        low=4,  # Lowest price column
        close=2,  # Column of closing price
        volume=5,  # Column of trading volume
        openinterest=-1,  # There is no open position column (openinterest is used for futures trading)
        fromdate=begin_date,  # Start date
        todate=end_date,
        timeframe=bt.TimeFrame.Days,  # Data granularity
        compression=1,
        sessionstart=datetime.time(9, 0),
        sessionend=datetime.time(17, 30)
    )

Their meanings are the start time of daily bar and the end time of bar (equivalent to the opening and closing time of a day). The processing process of a bar is a session. By default, their values are 00:00:00.00000 and 23:59:59.999989. Here they are set to start at 9:00 and end at 17:30.

notify_timer trigger timing

When through add_ After adding a timer to the timer method, this timer will trigger notify on a certain day_ Timer event method. The triggering rules are as follows:
1. If cheat parameter = False:

  • After the data of the current bar has been loaded
  • After the broker has evaluated the order (that is, the order that should be executed has been executed, and the order that should be rejected has been rejected), and recalculated the market value of the portfolio (that is, the market value has been recalculated according to today's closing price)
  • Before recalculation of technical indicators (that is, if you access the current technical indicator value at this time, the actual value is still the value of the previous day)
  • Before the policy next method is called

2. If cheat parameter = True:

  • After the data of the current bar has been loaded
  • Before the broker evaluates the order and recalculates the market value of the portfolio (therefore, the actual market value obtained by the notify_timer accessing the market value of the current account at this time is the market value of yesterday. When the notify_timer occurs, the order to be executed today has not been executed, and will not be executed until the notify_timer is executed)
  • Before recalculation of technical indicators
  • Before the policy next method is called

Tips:
When cheat=True, for daily line data, the following situations are legal

  • Technical indicators are also based on the closing price of the previous day and can be used to generate signals to enter or exit the market
  • Since the data of the new bar has been loaded, the opening price can be used to calculate the number of shares purchased

Keywords: Python

Added by laurajohn89 on Fri, 04 Feb 2022 15:15:43 +0200