You are here:  Home » 量化交易与机器学习 » backtrader » Timers- backtrader中文教程

Timers

Release1.9.44.116timers到的可用工具阿森纳backtrader。此功能允许接到一个电话回notify_timer(在可用的CerebroStrategy)在给定的点时间,具有细粒度终端用户control.

Note

Some校正已在由1.9.46.116

Options

  • Timer基于在绝对时间输入或至于会议的开始/结束对于时间指定times
  • Timezone说明书中,直接或经由其是pytz兼容的对象或经由数据馈送会话结束times
  • Starting与问候到指定time
  • Repetitions intervals
  • Weekdays滤波器(带结转选项)偏移
  • Monthdays滤波器(带进位在选项)
  • 自定义回调filter

Usage pattern

Both在CerebroStrategy子类的计时器回调将是在下面的method.

def notify_timer(self, timer, when, *args, **kwargs):
    """Receives a timer notification where ``timer`` is the timer which was
    returned by ``add_timer``, and ``when`` is the calling time. ``args``
    and ``kwargs`` are any additional arguments passed to ``add_timer``

    The actual ``when`` time can be later, but the system may have not be
    able to call the timer before. This value is the timer value and not the
    system time.
    """

Adding定时器收到 – 通过Strategy

Done与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):
    """

It返回创建的Timerinstance.

见下面的parameters.

Adding定时器的解释 – 通过Cerebro

Done用同样的方法,只是添加参数strats的。如果设置为True计时器不仅将通知cerebro,它会也可以通知到system.

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

It运行的所有策略返回创建的Timerinstance.

When都定时器called

Ifcheat=False

这是默认的。在这种情况下,定时器将被称为:

  • 后的数据馈送已加载的新值当前bar
  • After经纪人评估了订单,并重新计算投资组合value
  • 之前指标已重新计算(因为这是由触发策略)
  • 之前任何next任何战略的方法是called

Ifcheat=True

在这种情况下,定时器将被称为:

  • 之后,数据馈送已加载的新值当前bar
  • Before经纪人评估了订单,并重新计算投资组合value
  • 因此前指标已重新计算和next任何战略的方法是called

Which允许例如每日条以下情形:

  • 新的律师是由经纪人进行评估前,定时器called
  • The指标有来自前一天的值在关闭和可用来产生一个进入/退出信号(或标志可以在已经设置的next
  • 因为新价格。,可以计算出股份使用上次评测开盘价。这是假定一个是例如获得良好指示关于open从看与每日bars

The样品

默认开口auction.scheduled.pyRunning与每日标准杆运行在backtrader分布可用。该参数的strategy

class St(bt.Strategy):
    params = dict(
        when=bt.timer.SESSION_START,
        timer=True,
        cheat=False,
        offset=datetime.timedelta(),
        repeat=datetime.timedelta(),
        weekdays=[],
    )

And数据具有以下会议时间:

  • 开始:09:00
  • end:17:与30

Running只是time

$ ./scheduled.py --strat when="datetime.time(15,30)"

strategy notify_timer with tid 0, when 2005-01-03 15:30:00 cheat False
1, 2005-01-03 17:30:00, Week 1, Day 1, O 2952.29, H 2989.61, L 2946.8, C 2970.02
strategy notify_timer with tid 0, when 2005-01-04 15:30:00 cheat False
2, 2005-01-04 17:30:00, Week 1, Day 2, O 2969.78, H 2979.88, L 2961.14, C 2971.12
strategy notify_timer with tid 0, when 2005-01-05 15:30:00 cheat False
3, 2005-01-05 17:30:00, Week 1, Day 3, O 2969.0, H 2969.0, L 2942.69, C 2947.19
strategy notify_timer with tid 0, when 2005-01-06 15:30:00 cheat False
...

As指定定时器在15:30。没有意外出现。让我们添加的30的偏移minutes.

$ ./scheduled.py --strat when="datetime.time(15,30)",offset="datetime.timedelta(minutes=30)"

strategy notify_timer with tid 0, when 2005-01-03 16:00:00 cheat False
1, 2005-01-03 17:30:00, Week 1, Day 1, O 2952.29, H 2989.61, L 2946.8, C 2970.02
strategy notify_timer with tid 0, when 2005-01-04 16:00:00 cheat False
2, 2005-01-04 17:30:00, Week 1, Day 2, O 2969.78, H 2979.88, L 2961.14, C 2971.12
strategy notify_timer with tid 0, when 2005-01-05 16:00:00 cheat False
...

And的时间已经从15:3016:00的定时器。没有惊喜。让我们做相同的,但瞧引用session.

$ ./scheduled.py --strat when="bt.timer.SESSION_START",offset="datetime.timedelta(minutes=30)"

strategy notify_timer with tid 0, when 2005-01-03 09:30:00 cheat False
1, 2005-01-03 17:30:00, Week 1, Day 1, O 2952.29, H 2989.61, L 2946.8, C 2970.02
strategy notify_timer with tid 0, when 2005-01-04 09:30:00 cheat False
2, 2005-01-04 17:30:00, Week 1, Day 2, O 2969.78, H 2979.88, L 2961.14, C 2971.12
...

Et的开始!在其调用回调的时间是09:30。而会议开始时,见上面,就是09:00。这使得简单地说能力一个要执行动作30 minutes后的开始session.

Let添加一个重复:

$ ./scheduled.py --strat when="bt.timer.SESSION_START",offset="datetime.timedelta(minutes=30)",repeat="datetime.timedelta(minutes=30)"

strategy notify_timer with tid 0, when 2005-01-03 09:30:00 cheat False
1, 2005-01-03 17:30:00, Week 1, Day 1, O 2952.29, H 2989.61, L 2946.8, C 2970.02
strategy notify_timer with tid 0, when 2005-01-04 09:30:00 cheat False
2, 2005-01-04 17:30:00, Week 1, Day 2, O 2969.78, H 2979.88, L 2961.14, C 2971.12
strategy notify_timer with tid 0, when 2005-01-05 09:30:00 cheat False
...

没有repetition。原因是,房价的分辨率每天。计时器在呼吁1st09:30时间`像前面的例子。但是,当系统中获取下一批价格时,他们是发生在第二天。和定时器只能显然,被调用一次。一种较低的分辨率needed.

But上移动到一个较低的分辨率之前,让我们具有定时器作弊以前称作session.

$ ./scheduled.py --strat when="bt.timer.SESSION_START",cheat=True

strategy notify_timer with tid 1, when 2005-01-03 09:00:00 cheat True
-- 2005-01-03 Create buy order
strategy notify_timer with tid 0, when 2005-01-03 09:00:00 cheat False
1, 2005-01-03 17:30:00, Week 1, Day 1, O 2952.29, H 2989.61, L 2946.8, C 2970.02
strategy notify_timer with tid 1, when 2005-01-04 09:00:00 cheat True
strategy notify_timer with tid 0, when 2005-01-04 09:00:00 cheat False
-- 2005-01-04 Buy Exec @ 2969.78
2, 2005-01-04 17:30:00, Week 1, Day 2, O 2969.78, H 2979.88, L 2961.14, C 2971.12
strategy notify_timer with tid 1, when 2005-01-05 09:00:00 cheat True
strategy notify_timer with tid 0, when 2005-01-05 09:00:00 cheat False
...

The战略的末尾添加一个2nd定时器cheat=True。这是加入2nd和意志因此接收到的2nd tidtimer id),其是1(请参阅上述实施例所分配的tid0

1之前0,因为那计时器cheating和正在所谓系统中的多个事件发生之前(见上面的说明)

由于daily价格的决议它没有太大的除了差异:

  • 该战略还发出前右开放的订单……它正在与开盘价在下day

    这一点,即使通过前开演技欺骗,仍在正常行为,因为cheating-on-open也没有在激活broker.

The相同,但与coo=True为broker

$ ./scheduled.py --strat when="bt.timer.SESSION_START",cheat=True --broker coo=True

strategy notify_timer with tid 1, when 2005-01-03 09:00:00 cheat True
-- 2005-01-03 Create buy order
strategy notify_timer with tid 0, when 2005-01-03 09:00:00 cheat False
-- 2005-01-03 Buy Exec @ 2952.29
1, 2005-01-03 17:30:00, Week 1, Day 1, O 2952.29, H 2989.61, L 2946.8, C 2970.02
strategy notify_timer with tid 1, when 2005-01-04 09:00:00 cheat True
strategy notify_timer with tid 0, when 2005-01-04 09:00:00 cheat False
2, 2005-01-04 17:30:00, Week 1, Day 2, O 2969.78, H 2979.88, L 2961.14, C 2971.12
strategy notify_timer with tid 1, when 2005-01-05 09:00:00 cheat True
strategy notify_timer with tid 0, when 2005-01-05 09:00:00 cheat False
...

而有些事情changed.

  • 该命令2005-01-03在作弊timer
  • 该命令是2005-01-03与开口price

    有效就像如果一个人在开幕拍卖价格秒钟行动所述market.

Running与5分钟的样品bars

The真正开口之前scheduled-min.py默认为与该标准的5分钟运行在backtrader分布可用酒吧。该参数的策略被扩展为包括monthdayscarryoptions

class St(bt.Strategy):
    params = dict(
        when=bt.timer.SESSION_START,
        timer=True,
        cheat=False,
        offset=datetime.timedelta(),
        repeat=datetime.timedelta(),
        weekdays=[],
        weekcarry=False,
        monthdays=[],
        monthcarry=True,
    )

该数据具有相同的会议时间:

  • 开始:09:00
  • end:17:30

Let的做一些实验。作为请求的第一单timer.

$ ./scheduled-min.py --strat when="datetime.time(15, 30)"

1, 2006-01-02 09:05:00, Week 1, Day 1, O 3578.73, H 3587.88, L 3578.73, C 3582.99
2, 2006-01-02 09:10:00, Week 1, Day 1, O 3583.01, H 3588.4, L 3583.01, C 3588.03
...
77, 2006-01-02 15:25:00, Week 1, Day 1, O 3599.07, H 3599.68, L 3598.47, C 3599.68
strategy notify_timer with tid 0, when 2006-01-02 15:30:00 cheat False
78, 2006-01-02 15:30:00, Week 1, Day 1, O 3599.64, H 3599.73, L 3599.0, C 3599.67
...
179, 2006-01-03 15:25:00, Week 1, Day 2, O 3634.72, H 3635.0, L 3634.06, C 3634.87
strategy notify_timer with tid 0, when 2006-01-03 15:30:00 cheat False
180, 2006-01-03 15:30:00, Week 1, Day 2, O 3634.81, H 3634.89, L 3634.04, C 3634.23
...

The计时器踢在15:30。日志显示它怎么说在1st2个days.

添加了repeat`15 minutes到mix

$ ./scheduled-min.py --strat when="datetime.time(15, 30)",repeat="datetime.timedelta(minutes=15)"

...
74, 2006-01-02 15:10:00, Week 1, Day 1, O 3596.12, H 3596.63, L 3595.92, C 3596.63
75, 2006-01-02 15:15:00, Week 1, Day 1, O 3596.36, H 3596.65, L 3596.19, C 3596.65
76, 2006-01-02 15:20:00, Week 1, Day 1, O 3596.53, H 3599.13, L 3596.12, C 3598.9
77, 2006-01-02 15:25:00, Week 1, Day 1, O 3599.07, H 3599.68, L 3598.47, C 3599.68
strategy notify_timer with tid 0, when 2006-01-02 15:30:00 cheat False
78, 2006-01-02 15:30:00, Week 1, Day 1, O 3599.64, H 3599.73, L 3599.0, C 3599.67
79, 2006-01-02 15:35:00, Week 1, Day 1, O 3599.61, H 3600.29, L 3599.52, C 3599.92
80, 2006-01-02 15:40:00, Week 1, Day 1, O 3599.96, H 3602.06, L 3599.76, C 3602.05
strategy notify_timer with tid 0, when 2006-01-02 15:45:00 cheat False
81, 2006-01-02 15:45:00, Week 1, Day 1, O 3601.97, H 3602.07, L 3601.45, C 3601.83
82, 2006-01-02 15:50:00, Week 1, Day 1, O 3601.74, H 3602.8, L 3601.63, C 3602.8
83, 2006-01-02 15:55:00, Week 1, Day 1, O 3602.53, H 3602.74, L 3602.33, C 3602.61
strategy notify_timer with tid 0, when 2006-01-02 16:00:00 cheat False
84, 2006-01-02 16:00:00, Week 1, Day 1, O 3602.58, H 3602.75, L 3601.81, C 3602.14
85, 2006-01-02 16:05:00, Week 1, Day 1, O 3602.16, H 3602.16, L 3600.86, C 3600.96
86, 2006-01-02 16:10:00, Week 1, Day 1, O 3601.2, H 3601.49, L 3600.94, C 3601.27
...
strategy notify_timer with tid 0, when 2006-01-02 17:15:00 cheat False
99, 2006-01-02 17:15:00, Week 1, Day 1, O 3603.96, H 3603.96, L 3602.89, C 3603.79
100, 2006-01-02 17:20:00, Week 1, Day 1, O 3603.94, H 3605.95, L 3603.87, C 3603.91
101, 2006-01-02 17:25:00, Week 1, Day 1, O 3604.0, H 3604.76, L 3603.85, C 3604.64
strategy notify_timer with tid 0, when 2006-01-02 17:30:00 cheat False
102, 2006-01-02 17:30:00, Week 1, Day 1, O 3604.06, H 3604.41, L 3603.95, C 3604.33
103, 2006-01-03 09:05:00, Week 1, Day 2, O 3604.08, H 3609.6, L 3604.08, C 3609.6
104, 2006-01-03 09:10:00, Week 1, Day 2, O 3610.34, H 3617.31, L 3610.34, C 3617.31
105, 2006-01-03 09:15:00, Week 1, Day 2, O 3617.61, H 3617.87, L 3616.03, C 3617.51
106, 2006-01-03 09:20:00, Week 1, Day 2, O 3617.24, H 3618.86, L 3616.09, C 3618.42
...
179, 2006-01-03 15:25:00, Week 1, Day 2, O 3634.72, H 3635.0, L 3634.06, C 3634.87
strategy notify_timer with tid 0, when 2006-01-03 15:30:00 cheat False
180, 2006-01-03 15:30:00, Week 1, Day 2, O 3634.81, H 3634.89, L 3634.04, C 3634.23
...

正如预期的1st呼叫触发的15:30然后开始重复每隔15分钟,直到会话的17:30结束。当新的会话踢,计时器已被重置为15:30again.

而现在与会话start

$ ./scheduled-min.py --strat when="bt.timer.SESSION_START",cheat=True

strategy notify_timer with tid 1, when 2006-01-02 09:00:00 cheat True
-- 2006-01-02 09:05:00 Create buy order
strategy notify_timer with tid 0, when 2006-01-02 09:00:00 cheat False
1, 2006-01-02 09:05:00, Week 1, Day 1, O 3578.73, H 3587.88, L 3578.73, C 3582.99
-- 2006-01-02 09:10:00 Buy Exec @ 3583.01
2, 2006-01-02 09:10:00, Week 1, Day 1, O 3583.01, H 3588.4, L 3583.01, C 3588.03
...

Order创建之前欺骗为t09:05:00和执行的09:10:00因为经纪人是不是在cheat-on-open模式。让我们把它…

$ ./scheduled-min.py --strat when="bt.timer.SESSION_START",cheat=True --broker coo=True

strategy notify_timer with tid 1, when 2006-01-02 09:00:00 cheat True
-- 2006-01-02 09:05:00 Create buy order
strategy notify_timer with tid 0, when 2006-01-02 09:00:00 cheat False
-- 2006-01-02 09:05:00 Buy Exec @ 3578.73
1, 2006-01-02 09:05:00, Week 1, Day 1, O 3578.73, H 3587.88, L 3578.73, C 3582.99
2, 2006-01-02 09:10:00, Week 1, Day 1, O 3583.01, H 3588.4, L 3583.01, C 3588.03
...

与开证时间和执行时间是09:05:00与执行价作为开盘价在09:05:00.

附加scenarios

Timers允许指定在其上天,他们必须通过使执行(根据ISO规范,其中星期一= 1和Sun = 7的整数)作为in

  • weekdays=[5]这将要求定时器只有有效上Fridays

    In情况下,周五是天名单非交易日和定时器应该踢在上下一个交易日,可以添加weekcarry=True

相似吧,一个可以决定作用于每个月的15th一天:

  • monthdays=[15]

    万一15th恰好是为非交易日和定时器应该踢入在接下来的交易日,可以添加monthcarry=True

没有喜欢的事情的实现:the 3rd Friday of March, June,
September and December
(期货/期权到期),但有一个可能通过传递实施细则:

  • allow=callable在调用接受datetime.date实例。请注意,这不是一个datetime.datetime情况下,由于allow可调用的只是为了决定是否某一天是适合定时器或not.

    要实现类似上述布局规则:

    class FutOpExp(object):
        def __init__(self):
            self.fridays = 0
            self.curmonth = -1
    
        def __call__(self, d):
            _, _, isowkday = d.isocalendar()
    
            if d.month != self.curmonth:
                self.curmonth = d.month
                self.fridays = 0
    
            # Mon=1 ... Sun=7
            if isowkday == 5 and self.curmonth in [3, 6, 9, 12]:
                self.fridays += 1
    
                if self.friday == 3:  # 3rd Friday
                    return True  # timer allowed
    
            return False  # timer disallowed
    

    还有一将通过allow=FutOpeExp()到timer

    This的建立将允许定时器来踢上3rd周五的两个月,可以是期货expire.

Parameters到add_timer

* `when`: can be

  * `datetime.time` instance (see below `tzdata`)

  * `bt.timer.SESSION_START` to reference a session start

  * `bt.timer.SESSION_END` to reference a session end
  • offset必须是一个datetime.timedeltainstance

    Used抵消值when之前接近的位置`。它以一种有意义的使用与SESSION_STARTSESSION_END,以组合来表示做事像计时器被称为15 minutes在会议结束后start.

    • repeat必须是datetime.timedeltainstance

    Indicates如果1st电话后,进一步的调用将被安排在同一会话中定repeatdelta

    Once定时器越过会议结束时就被复位到用于when

    • weekdays原始值:一个sorted迭代与指示对整数这天(ISO代码,星期一是1,星期日是7)定时器可以实际上是不invoked

    If规定,定时器将在所有days

    • weekcarry有效(默认:False)。如果True和平日是没有看到(例如:交易假期),定时器会在执行第二天(即使在新的一周)
    • monthdays:一sorted迭代的用于指示整数其中一个定时器,必须执行该月的日子。例如总是在一天15不指定month

    If,定时器将在所有days

    • monthcarry有效(默认:True)。如果一天中没有发现有(周末,假期交易),定时器将在接下来的执行可day.
    • allow(默认:None)。其接收的回调datetime.date`实例,并返回True如果日期允许定时器或否则返回False
    • tzdata其可以是None(默认值),一个pytz实例或data feedinstance.

    Nonewhen的表面价值被解释(这相当于以处理它,如果它在那里UTC即使它不是)

    pytz比如:when将被解释为指定由时区指定instance.

    data feed实例的本地时间:when会被解释为在通过的tz参数指定的本地时间规定数据馈送instance.

    !note

      If `when` is either `SESSION_START` or `SESSION_END` and `tzdata` is
      `None`, the 1st *data feed* in the system (aka `self.data0`) will be
      used as the reference to find out the session times.
    
    • strats(默认:False)调用也是notify_timer的strategies
    • cheat(默认False)如果True定时器将被称为代理之前,有机会评估订单。这将打开根据开盘价例如合适的机会来发布命令会议starts
    • *args:任何额外的参数将被传递给notify_timer
    • **kwargs:任何额外kwargs将被传递给notify_timer

使用范例scheduled.py

$ ./scheduled.py --help
usage: scheduled.py [-h] [--data0 DATA0] [--fromdate FROMDATE]
                    [--todate TODATE] [--cerebro kwargs] [--broker kwargs]
                    [--sizer kwargs] [--strat kwargs] [--plot [kwargs]]

Sample Skeleton

optional arguments:
  -h, --help           show this help message and exit
  --data0 DATA0        Data to read in (default:
                       ../../datas/2005-2006-day-001.txt)
  --fromdate FROMDATE  Date[time] in YYYY-MM-DD[THH:MM:SS] format (default: )
  --todate TODATE      Date[time] in YYYY-MM-DD[THH:MM:SS] format (default: )
  --cerebro kwargs     kwargs in key=value format (default: )
  --broker kwargs      kwargs in key=value format (default: )
  --sizer kwargs       kwargs in key=value format (default: )
  --strat kwargs       kwargs in key=value format (default: )
  --plot [kwargs]      kwargs in key=value format (default: )

使用范例scheduled-min.py

$ ./scheduled-min.py --help
usage: scheduled-min.py [-h] [--data0 DATA0] [--fromdate FROMDATE]
                        [--todate TODATE] [--cerebro kwargs] [--broker kwargs]
                        [--sizer kwargs] [--strat kwargs] [--plot [kwargs]]

Timer Test Intraday

optional arguments:
  -h, --help           show this help message and exit
  --data0 DATA0        Data to read in (default: ../../datas/2006-min-005.txt)
  --fromdate FROMDATE  Date[time] in YYYY-MM-DD[THH:MM:SS] format (default: )
  --todate TODATE      Date[time] in YYYY-MM-DD[THH:MM:SS] format (default: )
  --cerebro kwargs     kwargs in key=value format (default: )
  --broker kwargs      kwargs in key=value format (default: )
  --sizer kwargs       kwargs in key=value format (default: )
  --strat kwargs       kwargs in key=value format (default: )
  --plot [kwargs]      kwargs in key=value format (default: )

示例源scheduled.py

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import argparse
import datetime

import backtrader as bt


class St(bt.Strategy):
    params = dict(
        when=bt.timer.SESSION_START,
        timer=True,
        cheat=False,
        offset=datetime.timedelta(),
        repeat=datetime.timedelta(),
        weekdays=[],
    )

    def __init__(self):
        bt.ind.SMA()
        if self.p.timer:
            self.add_timer(
                when=self.p.when,
                offset=self.p.offset,
                repeat=self.p.repeat,
                weekdays=self.p.weekdays,
            )
        if self.p.cheat:
            self.add_timer(
                when=self.p.when,
                offset=self.p.offset,
                repeat=self.p.repeat,
                cheat=True,
            )

        self.order = None

    def prenext(self):
        self.next()

    def next(self):
        _, isowk, isowkday = self.datetime.date().isocalendar()
        txt = "{}, {}, Week {}, Day {}, O {}, H {}, L {}, C {}".format(
            len(self), self.datetime.datetime(),
            isowk, isowkday,
            self.data.open[0], self.data.high[0],
            self.data.low[0], self.data.close[0])

        print(txt)

    def notify_timer(self, timer, when, *args, **kwargs):
        print("strategy notify_timer with tid {}, when {} cheat {}".
              format(timer.p.tid, when, timer.p.cheat))

        if self.order is None and timer.p.cheat:
            print("-- {} Create buy order".format(self.data.datetime.date()))
            self.order = self.buy()

    def notify_order(self, order):
        if order.status == order.Completed:
            print("-- {} Buy Exec @ {}".format(
                self.data.datetime.date(), order.executed.price))


def runstrat(args=None):
    args = parse_args(args)

    cerebro = bt.Cerebro()

    # Data feed kwargs
    kwargs = dict(
        timeframe=bt.TimeFrame.Days,
        compression=1,
        sessionstart=datetime.time(9, 0),
        sessionend=datetime.time(17, 30),
    )

    # Parse from/to-date
    dtfmt, tmfmt = "%Y-%m-%d", "T%H:%M:%S"
    for a, d in ((getattr(args, x), x) for x in ["fromdate", "todate"]):
        if a:
            strpfmt = dtfmt + tmfmt * ("T" in a)
            kwargs[d] = datetime.datetime.strptime(a, strpfmt)

    # Data feed
    data0 = bt.feeds.BacktraderCSVData(dataname=args.data0, **kwargs)
    cerebro.adddata(data0)

    # Broker
    cerebro.broker = bt.brokers.BackBroker(**eval("dict(" + args.broker + ")"))

    # Sizer
    cerebro.addsizer(bt.sizers.FixedSize, **eval("dict(" + args.sizer + ")"))

    # Strategy
    cerebro.addstrategy(St, **eval("dict(" + args.strat + ")"))

    # Execute
    cerebro.run(**eval("dict(" + args.cerebro + ")"))

    if args.plot:  # Plot if requested to
        cerebro.plot(**eval("dict(" + args.plot + ")"))


def parse_args(pargs=None):
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description=(
            "Sample Skeleton"
        )
    )

    parser.add_argument("--data0", default="../../datas/2005-2006-day-001.txt",
                        required=False, help="Data to read in")

    # Defaults for dates
    parser.add_argument("--fromdate", required=False, default="",
                        help="Date[time] in YYYY-MM-DD[THH:MM:SS] format")

    parser.add_argument("--todate", required=False, default="",
                        help="Date[time] in YYYY-MM-DD[THH:MM:SS] format")

    parser.add_argument("--cerebro", required=False, default="",
                        metavar="kwargs", help="kwargs in key=value format")

    parser.add_argument("--broker", required=False, default="",
                        metavar="kwargs", help="kwargs in key=value format")

    parser.add_argument("--sizer", required=False, default="",
                        metavar="kwargs", help="kwargs in key=value format")

    parser.add_argument("--strat", required=False, default="",
                        metavar="kwargs", help="kwargs in key=value format")

    parser.add_argument("--plot", required=False, default="",
                        nargs="?", const="{}",
                        metavar="kwargs", help="kwargs in key=value format")

    return parser.parse_args(pargs)


if __name__ == "__main__":
    runstrat()

示例源scheduled-min.py

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import argparse
import datetime

import backtrader as bt


class St(bt.Strategy):
    params = dict(
        when=bt.timer.SESSION_START,
        timer=True,
        cheat=False,
        offset=datetime.timedelta(),
        repeat=datetime.timedelta(),
        weekdays=[],
        weekcarry=False,
        monthdays=[],
        monthcarry=True,
    )

    def __init__(self):
        bt.ind.SMA()
        if self.p.timer:
            self.add_timer(
                when=self.p.when,
                offset=self.p.offset,
                repeat=self.p.repeat,
                weekdays=self.p.weekdays,
                weekcarry=self.p.weekcarry,
                monthdays=self.p.monthdays,
                monthcarry=self.p.monthcarry,
                # tzdata=self.data0,
            )
        if self.p.cheat:
            self.add_timer(
                when=self.p.when,
                offset=self.p.offset,
                repeat=self.p.repeat,
                weekdays=self.p.weekdays,
                weekcarry=self.p.weekcarry,
                monthdays=self.p.monthdays,
                monthcarry=self.p.monthcarry,
                # tzdata=self.data0,
                cheat=True,
            )

        self.order = None

    def prenext(self):
        self.next()

    def next(self):
        _, isowk, isowkday = self.datetime.date().isocalendar()
        txt = "{}, {}, Week {}, Day {}, O {}, H {}, L {}, C {}".format(
            len(self), self.datetime.datetime(),
            isowk, isowkday,
            self.data.open[0], self.data.high[0],
            self.data.low[0], self.data.close[0])

        print(txt)

    def notify_timer(self, timer, when, *args, **kwargs):
        print("strategy notify_timer with tid {}, when {} cheat {}".
              format(timer.p.tid, when, timer.p.cheat))

        if self.order is None and timer.params.cheat:
            print("-- {} Create buy order".format(
                self.data.datetime.datetime()))
            self.order = self.buy()

    def notify_order(self, order):
        if order.status == order.Completed:
            print("-- {} Buy Exec @ {}".format(
                self.data.datetime.datetime(), order.executed.price))


def runstrat(args=None):
    args = parse_args(args)
    cerebro = bt.Cerebro()

    # Data feed kwargs
    kwargs = dict(
        timeframe=bt.TimeFrame.Minutes,
        compression=5,
        sessionstart=datetime.time(9, 0),
        sessionend=datetime.time(17, 30),
    )

    # Parse from/to-date
    dtfmt, tmfmt = "%Y-%m-%d", "T%H:%M:%S"
    for a, d in ((getattr(args, x), x) for x in ["fromdate", "todate"]):
        if a:
            strpfmt = dtfmt + tmfmt * ("T" in a)
            kwargs[d] = datetime.datetime.strptime(a, strpfmt)

    # Data feed
    data0 = bt.feeds.BacktraderCSVData(dataname=args.data0, **kwargs)
    cerebro.adddata(data0)

    # Broker
    cerebro.broker = bt.brokers.BackBroker(**eval("dict(" + args.broker + ")"))

    # Sizer
    cerebro.addsizer(bt.sizers.FixedSize, **eval("dict(" + args.sizer + ")"))

    # Strategy
    cerebro.addstrategy(St, **eval("dict(" + args.strat + ")"))

    # Execute
    cerebro.run(**eval("dict(" + args.cerebro + ")"))

    if args.plot:  # Plot if requested to
        cerebro.plot(**eval("dict(" + args.plot + ")"))


def parse_args(pargs=None):
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description=(
            "Timer Test Intraday"
        )
    )

    parser.add_argument("--data0", default="../../datas/2006-min-005.txt",
                        required=False, help="Data to read in")

    # Defaults for dates
    parser.add_argument("--fromdate", required=False, default="",
                        help="Date[time] in YYYY-MM-DD[THH:MM:SS] format")

    parser.add_argument("--todate", required=False, default="",
                        help="Date[time] in YYYY-MM-DD[THH:MM:SS] format")

    parser.add_argument("--cerebro", required=False, default="",
                        metavar="kwargs", help="kwargs in key=value format")

    parser.add_argument("--broker", required=False, default="",
                        metavar="kwargs", help="kwargs in key=value format")

    parser.add_argument("--sizer", required=False, default="",
                        metavar="kwargs", help="kwargs in key=value format")

    parser.add_argument("--strat", required=False, default="",
                        metavar="kwargs", help="kwargs in key=value format")

    parser.add_argument("--plot", required=False, default="",
                        nargs="?", const="{}",
                        metavar="kwargs", help="kwargs in key=value format")

    return parser.parse_args(pargs)


if __name__ == "__main__":
    runstrat()