Backtrader 文档学习-Order Management and Execution

这篇具有很好参考价值的文章主要介绍了Backtrader 文档学习-Order Management and Execution。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Backtrader 文档学习-Order Management and Execution

本章提供了关于order的详细功能测试用例,很好很重要。

最后的示例部分,详细分析总结了不同参数的效果和输出。

如果不能模拟订单交易回测就不会完整。为此,平台中提供了以下功能, 对于订单管理3个基本要素:

  • buy
  • sell
  • cancel
    对order执行逻辑,有以下类型:
  • Market
  • Close
  • Limit
  • Stop
  • StopLimit

1.Order Management

# buy the main data, with sizer default stake, Market order
# 使用默认data ,默认购买数量,市价订单
order = self.buy()

# Market order - valid will be "IGNORED"
# 有效截止日期到当前时间3天后
order = self.buy(valid=datetime.datetime.now() + datetime.timedelta(days=3))

# Market order - price will be IGNORED
# 成交价格用收盘价的+2%
order = self.buy(price=self.data.close[0] * 1.02)

# Market order - manual stake
# 市价单,25股
order = self.buy(size=25)

# Limit order - want to set the price and can set a validity
# 执行类型,限价执行,+2%的收盘价,当前三天内有效
order = self.buy(exectype=Order.Limit,
                 price=self.data.close[0] * 1.02,
                 valid=datetime.datetime.now() + datetime.timedelta(days=3)))

# StopLimit order - want to set the price, price limit
# 限价单模式,+2%成交价收盘价,+7%成交价收盘价,止损(盈)
order = self.buy(exectype=Order.StopLimit,
                 price=self.data.close[0] * 1.02,
                 plimit=self.data.close[0] * 1.07)

# Canceling an existing order
# 取消未执行的订单
self.broker.cancel(order)

所有订单类型都可以通过创建订单实例(或其子类之一)来创建,然后通过以下方式传递给代理:

order = self.broker.submit(order)

2.Order Execution Logic

当前数据已经发生,不能用于执行订单。 如果策略中的逻辑是:

 if self.data.close > self.sma:  # where sma is a Simple Moving Average
     self.buy()

策略中用收盘价检查是否触发buy,不能期望订单用策略中正在检查的收盘价执行,因为收盘价已经发生了。
策略条件设置,订单可以在下一组开盘/高/低/收盘价格点(以及订单在此规定的条件)的范围内触发执行 。修改为,用前一天的收盘价做策略,则可以触发buy 。

 if self.data.close[-1] > self.sma:  # where sma is a Simple Moving Average
     self.buy()
  • 成交量不起作用
    在实际交易中,如果交易者买入非流动性资产,或者恰好触及价格的极限(高/低),就会出现这种情况。(不明白 ??)

但触及高点/低点的情况很少发生(如果你做了……你就不需要BT),所选资产将有足够的流动性来吸收任何常规交易的订单 。(还是不明白 ??)

3.Market

执行:
下一组开盘/高/低/收盘价的开盘价(通常称为bar)
逻辑:
如果逻辑已经在时间点X执行并发布了市价单,将发生的下一个价格点就是即下一个bar的开盘价 。
说明:
该订单始终执行,不考虑用于创建该订单的price和valid 参数

4.Close

执行:
在下一bar平仓时 ,使用下一bar实际收盘价执行。

逻辑:
大多数回测加载数据包含已经收盘bar,订单将立即以下一bar收盘价执行。每日数据加载是最常见的示例。

但是系统可以加载“tick”价格,并且实际bar(时间/日期方面)会随着新tick成交点不断更新,不会实际移动到下一个bar(因为时间和/或日期没有改变,同一天内)。
意思是支持加载类似5分钟线,15分钟线,以tick可以触发买点。

只有当时间或日期改变时,bar才能实际上平仓,订单才会执行 。

5.Limit

  • 执行:
    如果数据触及订单创建时设置的价格,则下一个价格bar开始执行订单。
    如果设置了valid条件,达到有效时间点,订单将被取消

  • 价格匹配:
    BT尝试为限价单提供最现实的执行价格Limit。
    使用4个价格点(开盘/高/低/收盘)可以部分推断出请求的价格是否可以提高。

  • 对于买订单:

    • 场景1:
      如果bar开盘价低于限价订单将立即以开盘价执行。订单将在会话的开始阶段清除。

    • 场景 2:
      如果开盘价没有跌破限价,但最低价低于限价,则在交易期间达到限价,订单可以执行 。

卖单的逻辑显然是颠倒的。

6.Stop

  • 执行:
    数据触及订单时设置的触发价格,从下一个bar的价格开始。
    如果设置了valid并且达到了时间点,订单将被取消
  • 价格匹配:
    BT尝试为止损单提供最现实的触发价格。
    使用4个价格点(开盘/高/低/收盘)可以部分推断出请求的价格是否可以提高。

For Stop orders which Buy

场景 1:
如果bar开盘价高于止损价,订单将立即以开盘价执行。
目的是在价格相对于现有空头头寸向上移动时止损。做空止损

场景 2:
如果开盘价未突破止损价,但最高价高于止损价,则在交易过程中触发止损,订单执行 。
止损订单的逻辑与Sell相反。

7.StopLimit

  • 执行:
    触发价格从下一个bar价格开始设置订单。

  • 价格匹配:
    触发:使用- 止损匹配逻辑(但仅触发并将订单转换为限价订单)

  • Limit: 使用限价匹配逻辑 。

8.示例

信号出现:使用CrossOver 交叉指标的交叉。
对生成的buy订单调用被保留,在系统中最多只允许一个订单执行。

(1)Execution Type: Market
            if self.p.exectype == 'Market':
                self.buy(exectype=bt.Order.Market)  # default if not given 是默认值

                self.log('BUY CREATE, exectype Market, price %.2f' %
                         self.data.close[0])
<1>图示

Backtrader 文档学习-Order Management and Execution,BackTrader,数据分析,量化,BackTrader

<2>输出
python ./order-execution-samples.py --exectype Market
2006-01-26T23:59:59.999989, BUY CREATE, exectype Market, price 3641.42
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-01-27T23:59:59.999989, BUY EXECUTED, Price: 3643.35, Cost: 3643.35, Comm 0.00
2006-03-02T23:59:59.999989, SELL CREATE, 3763.73
2006-03-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-03T23:59:59.999989, SELL EXECUTED, Price: 3763.95, Cost: 3643.35, Comm 0.00
<3>说明
  • notify_order() 检查状态:ORDER ACCEPTED/SUBMITTED ,BUY EXPIRED ,BUY EXECUTED ,SELL EXECUTED ,打印输出
  • next() 执行买卖操作
  • 2006-01-26T23:59:59.999989, BUY CREATE, exectype Market, price 3641.42 ,next触发
  • 2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED ,notify_order触发,是两个状态,第一次是提交,第二次是接收,所以有两条记录。
  • 2006-01-27T23:59:59.999989, BUY EXECUTED, Price: 3643.35, Cost: 3643.35, Comm 0.00 ,next触发,以27日的open价格成交买入。
  • 卖出的效果一下
(2)Execution Type: Close
            elif self.p.exectype == 'Close':
                self.buy(exectype=bt.Order.Close)

                self.log('BUY CREATE, exectype Close, price %.2f' %
                         self.data.close[0])
<1> 图示

Backtrader 文档学习-Order Management and Execution,BackTrader,数据分析,量化,BackTrader

<2> 输出
python ./order-execution-samples.py --exectype Close
2006-01-26T23:59:59.999989, BUY CREATE, exectype Close, price 3641.42
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-01-27T23:59:59.999989, BUY EXECUTED, Price: 3685.48, Cost: 3685.48, Comm 0.00
2006-03-02T23:59:59.999989, SELL CREATE, 3763.73
2006-03-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-03T23:59:59.999989, SELL EXECUTED, Price: 3763.95, Cost: 3685.48, Comm 0.00
<3>说明
  • 2006-01-27T23:59:59.999989, BUY EXECUTED, Price: 3685.48, Cost: 3685.48, Comm 0.00 ,执行类型是close ,买入的时候以收盘价买入,1月27日的收盘价。
  • 2006-03-03T23:59:59.999989, SELL EXECUTED, Price: 3763.95, Cost: 3685.48, Comm 0.00 ,卖出的时候,没有指定类型,sell()都没指定参数,默认是Market ,所以还是以3月3日的开票价卖出。
  • bt.Order.Close 执行模式,是要求以收盘价成交!!
  • 如果做复杂统一点,可以把sell()也加上相应的参数,与buy一直。
(3)Execution Type: Limit

有效性参数传递设置

            if self.p.valid:
                valid = self.data.datetime.date(0) + \
                        datetime.timedelta(days=self.p.valid)
            else:
                valid = None

设置低于信号生成价格1%的限价(bar的收盘价)。请注意这是如何阻止上面的许多订单被执行的。

            elif self.p.exectype == 'Limit':
                price = self.data.close * (1.0 - self.p.perc1 / 100.0)

                self.buy(exectype=bt.Order.Limit, price=price, valid=valid)

                if self.p.valid:
                    txt = 'BUY CREATE, exectype Limit, price %.2f, valid: %s'
                    self.log(txt % (price, valid.strftime('%Y-%m-%d')))
                else:
                    txt = 'BUY CREATE, exectype Limit, price %.2f'
                    self.log(txt % price)
<1> 图示

Backtrader 文档学习-Order Management and Execution,BackTrader,数据分析,量化,BackTrader

<2> 输出
python ./order-execution-samples.py --exectype Limit --perc1 1
2006-01-26T23:59:59.999989, BUY CREATE, exectype Limit, price 3605.01
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-05-18T23:59:59.999989, BUY EXECUTED, Price: 3605.01, Cost: 3605.01, Comm 0.00
2006-06-05T23:59:59.999989, SELL CREATE, 3604.33
2006-06-05T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-05T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-06T23:59:59.999989, SELL EXECUTED, Price: 3598.58, Cost: 3605.01, Comm 0.00
2006-06-21T23:59:59.999989, BUY CREATE, exectype Limit, price 3491.57
2006-06-21T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-21T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-28T23:59:59.999989, BUY EXECUTED, Price: 3491.57, Cost: 3491.57, Comm 0.00
2006-07-13T23:59:59.999989, SELL CREATE, 3562.56
2006-07-13T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-07-13T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-07-14T23:59:59.999989, SELL EXECUTED, Price: 3545.92, Cost: 3491.57, Comm 0.00
2006-07-24T23:59:59.999989, BUY CREATE, exectype Limit, price 3596.60
2006-07-24T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-07-24T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
<3>说明
  • 2006-01-26T23:59:59.999989, BUY CREATE, exectype Limit, price 3605.01,next创建了买单,因为是限价单,用1月26日的收盘价,3641.42 * (100 - 1)/100 = 3605.0058 = 3605.01 。即挂单是低于触发时的收盘价-1% 作为限价
  • 因为没有valid ,所以一直挂单到5月18日
  • 2006-05-18T23:59:59.999989, BUY EXECUTED, Price: 3605.01, Cost: 3605.01, Comm 0.00 ,5月18日的价格区间包括3605.01 ,所以能够成交买单,不用OLHC的价格,使用限价价格成交。

2006-5-18 3607.41 3649.54 3558.27 3606.33

  • 2006-06-06T23:59:59.999989, SELL EXECUTED, Price: 3598.58, Cost: 3605.01, Comm 0.00 ,卖单触发后,因为没有限价参数,所以都是以开盘价成交。
(4)Execution Type: Limit with validity

为了不永远等待限价单(限价单可能仅在价格与buy订单相反执行),该订单的有效期仅为4天(日历)。

<1>图示

Backtrader 文档学习-Order Management and Execution,BackTrader,数据分析,量化,BackTrader

<2>输出
python ./order-execution-samples.py --exectype Limit --perc1 1 --valid 4
2006-01-26T23:59:59.999989, BUY CREATE, exectype Limit, price 3605.01, valid: 2006-01-30
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-01-30T23:59:59.999989, BUY EXPIRED
2006-03-10T23:59:59.999989, BUY CREATE, exectype Limit, price 3760.48, valid: 2006-03-14
2006-03-10T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-10T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-14T23:59:59.999989, BUY EXPIRED
2006-03-30T23:59:59.999989, BUY CREATE, exectype Limit, price 3835.86, valid: 2006-04-03
2006-03-30T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-30T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-04-03T23:59:59.999989, BUY EXPIRED
2006-04-20T23:59:59.999989, BUY CREATE, exectype Limit, price 3821.40, valid: 2006-04-24
2006-04-20T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-04-20T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-04-24T23:59:59.999989, BUY EXPIRED
2006-05-04T23:59:59.999989, BUY CREATE, exectype Limit, price 3804.65, valid: 2006-05-08
2006-05-04T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-05-04T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-05-08T23:59:59.999989, BUY EXPIRED
2006-06-01T23:59:59.999989, BUY CREATE, exectype Limit, price 3611.85, valid: 2006-06-05
2006-06-01T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-01T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-05T23:59:59.999989, BUY EXPIRED
2006-06-21T23:59:59.999989, BUY CREATE, exectype Limit, price 3491.57, valid: 2006-06-25
2006-06-21T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-21T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-26T23:59:59.999989, BUY EXPIRED
2006-07-24T23:59:59.999989, BUY CREATE, exectype Limit, price 3596.60, valid: 2006-07-28
2006-07-24T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-07-24T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-07-28T23:59:59.999989, BUY EXPIRED
2006-09-12T23:59:59.999989, BUY CREATE, exectype Limit, price 3751.07, valid: 2006-09-16
2006-09-12T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-09-12T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-09-18T23:59:59.999989, BUY EXPIRED
2006-09-20T23:59:59.999989, BUY CREATE, exectype Limit, price 3802.90, valid: 2006-09-24
2006-09-20T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-09-20T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-09-22T23:59:59.999989, BUY EXECUTED, Price: 3802.90, Cost: 3802.90, Comm 0.00
2006-11-02T23:59:59.999989, SELL CREATE, 3974.62
2006-11-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-03T23:59:59.999989, SELL EXECUTED, Price: 3979.73, Cost: 3802.90, Comm 0.00
2006-11-06T23:59:59.999989, BUY CREATE, exectype Limit, price 4004.77, valid: 2006-11-10
2006-11-06T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-06T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-10T23:59:59.999989, BUY EXPIRED
2006-12-11T23:59:59.999989, BUY CREATE, exectype Limit, price 4012.36, valid: 2006-12-15
2006-12-11T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-12-11T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-12-15T23:59:59.999989, BUY EXPIRED
<3>说明
  • 2006-01-26, BUY CREATE, exectype Limit, price 3605.01, valid: 2006-01-30 ,触发买单,注意有valid ,限制在4天内有效,当前是26日,有效期到30日
  • 2006-01-30T23:59:59.999989, BUY EXPIRED ,30日,没有能够到达限价内,并且时间限制到达,所以买单过期
  • 2006-09-20T23:59:59.999989, BUY CREATE, exectype Limit, price 3802.90, valid: 2006-09-24 ,收盘价:3841.31,限价:3841.31 * 0.99 = 3802.8969 =3802.90 ,9月24日超期。
  • 2006-09-22T23:59:59.999989, BUY EXECUTED, Price: 3802.90, Cost: 3802.90, Comm 0.00 ,在9月22日的价格区间内,并且没有超过4天,买单成交。

2006-9-22 3839.51 3839.65 3800.65 3812.73

(5)Execution Type: Stop

设置高于信号价格1%的止损价格。该策略只在信号产生且价格继续攀升时买入,可解读为强势信号。

            elif self.p.exectype == 'Stop':
                price = self.data.close * (1.0 + self.p.perc1 / 100.0)

                self.buy(exectype=bt.Order.Stop, price=price, valid=valid)

                if self.p.valid:
                    txt = 'BUY CREATE, exectype Stop, price %.2f, valid: %s'
                    self.log(txt % (price, valid.strftime('%Y-%m-%d')))
                else:
                    txt = 'BUY CREATE, exectype Stop, price %.2f'
                    self.log(txt % price)
<1>图示

Backtrader 文档学习-Order Management and Execution,BackTrader,数据分析,量化,BackTrader

<2>输出
python ./order-execution-samples.py --exectype Stop --perc1 1
2006-01-26T23:59:59.999989, BUY CREATE, exectype Stop, price 3677.83
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-01-27T23:59:59.999989, BUY EXECUTED, Price: 3677.83, Cost: 3677.83, Comm 0.00
2006-03-02T23:59:59.999989, SELL CREATE, 3763.73
2006-03-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-03T23:59:59.999989, SELL EXECUTED, Price: 3763.95, Cost: 3677.83, Comm 0.00
2006-03-10T23:59:59.999989, BUY CREATE, exectype Stop, price 3836.44
2006-03-10T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-10T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-15T23:59:59.999989, BUY EXECUTED, Price: 3836.44, Cost: 3836.44, Comm 0.00
2006-03-28T23:59:59.999989, SELL CREATE, 3811.45
2006-03-28T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-28T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-29T23:59:59.999989, SELL EXECUTED, Price: 3811.85, Cost: 3836.44, Comm 0.00
2006-03-30T23:59:59.999989, BUY CREATE, exectype Stop, price 3913.36
2006-03-30T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-30T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-09-29T23:59:59.999989, BUY EXECUTED, Price: 3913.36, Cost: 3913.36, Comm 0.00
2006-11-02T23:59:59.999989, SELL CREATE, 3974.62
2006-11-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-03T23:59:59.999989, SELL EXECUTED, Price: 3979.73, Cost: 3913.36, Comm 0.00
2006-11-06T23:59:59.999989, BUY CREATE, exectype Stop, price 4085.67
2006-11-06T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-06T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-13T23:59:59.999989, BUY EXECUTED, Price: 4085.67, Cost: 4085.67, Comm 0.00
2006-11-24T23:59:59.999989, SELL CREATE, 4048.16
2006-11-24T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-24T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-27T23:59:59.999989, SELL EXECUTED, Price: 4045.05, Cost: 4085.67, Comm 0.00
2006-12-11T23:59:59.999989, BUY CREATE, exectype Stop, price 4093.42
2006-12-11T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-12-11T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-12-13T23:59:59.999989, BUY EXECUTED, Price: 4093.42, Cost: 4093.42, Comm 0.00
<3>说明
  • 2006-01-26T23:59:59.999989, BUY CREATE, exectype Stop, price 3677.83 ,收盘价:3641.42 , 限价:3641.42 *1.01 = 3677.8342 = 3677.83

2006-1-26 3578.92 3641.42 3577.98 3641.42

  • 2006-01-27T23:59:59.999989, BUY EXECUTED, Price: 3677.83, Cost: 3677.83, Comm 0.00 ,限价包括在27日的价格中,成交。

2006-1-27 3643.35 3685.48 3643.35 3685.48

  • 从Limit 和 Stop 对比,区别在于设置限价,Limit是降低1个百分点,stop 是升高1个百分点。把Stop的增加1个百分点,修改为降低1个百分点,也可以执行。对比理解:
    Limit降低1个百分点的结果:
python ./order-execution-samples.py --exectype Limit --perc1 1
2006-01-26, BUY CREATE, exectype Limit, price 3605.01
2006-01-26, ORDER ACCEPTED/SUBMITTED
2006-01-26, ORDER ACCEPTED/SUBMITTED
2006-05-18, BUY EXECUTED, Price: 3605.01, Cost: 3605.01, Comm 0.00

Stop降低1个百分点的结果:

python ./order-execution-samples.py --exectype Stop --perc1 1
2006-01-26, BUY CREATE, exectype Stop, price 3605.01
2006-01-26, ORDER ACCEPTED/SUBMITTED
2006-01-26, ORDER ACCEPTED/SUBMITTED
2006-01-27, BUY EXECUTED, Price: 3643.35, Cost: 3643.35, Comm 0.00

Limit 和Stop 的区别:

  • Limit 执行的价格,要市价达到 3605.01 价格,才能成交,以限价价格成交。
  • Stop 执行的价格,只要市价大于 3605.01 价格,就可以成交,以市价的开盘价成交。所以有止损的功能!
(6)Execution Type: StopLimit

设置高于信号价格1%的止损价格。但是限价设置在信号(收盘)价以上0.5%,解释为等待力量出现,但不要购买峰值,等待下落。
有效期上限为20天(日历)。

            elif self.p.exectype == 'StopLimit':
                price = self.data.close * (1.0 + self.p.perc1 / 100.0)

                plimit = self.data.close * (1.0 + self.p.perc2 / 100.0)

                self.buy(exectype=bt.Order.StopLimit, price=price, valid=valid,
                         plimit=plimit)

                if self.p.valid:
                    txt = ('BUY CREATE, exectype StopLimit, price %.2f,'
                           ' valid: %s, pricelimit: %.2f')
                    self.log(txt % (price, valid.strftime('%Y-%m-%d'), plimit))
                else:
                    txt = ('BUY CREATE, exectype StopLimit, price %.2f,'
                           ' pricelimit: %.2f')
                    self.log(txt % (price, plimit))
<1>图示

Backtrader 文档学习-Order Management and Execution,BackTrader,数据分析,量化,BackTrader

<2>输出
python ./order-execution-samples.py --exectype StopLimit --perc1 1 --perc2 0.5 --valid 20
2006-01-26T23:59:59.999989, BUY CREATE, exectype StopLimit, price 3677.83, valid: 2006-02-15, pricelimit: 3659.63
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-01-26T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-02-03T23:59:59.999989, BUY EXECUTED, Price: 3659.63, Cost: 3659.63, Comm 0.00
2006-03-02T23:59:59.999989, SELL CREATE, 3763.73
2006-03-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-03T23:59:59.999989, SELL EXECUTED, Price: 3763.95, Cost: 3659.63, Comm 0.00
2006-03-10T23:59:59.999989, BUY CREATE, exectype StopLimit, price 3836.44, valid: 2006-03-30, pricelimit: 3817.45
2006-03-10T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-10T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-21T23:59:59.999989, BUY EXECUTED, Price: 3817.45, Cost: 3817.45, Comm 0.00
2006-03-28T23:59:59.999989, SELL CREATE, 3811.45
2006-03-28T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-28T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-29T23:59:59.999989, SELL EXECUTED, Price: 3811.85, Cost: 3817.45, Comm 0.00
2006-03-30T23:59:59.999989, BUY CREATE, exectype StopLimit, price 3913.36, valid: 2006-04-19, pricelimit: 3893.98
2006-03-30T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-03-30T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-04-19T23:59:59.999989, BUY EXPIRED
2006-04-20T23:59:59.999989, BUY CREATE, exectype StopLimit, price 3898.60, valid: 2006-05-10, pricelimit: 3879.30
2006-04-20T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-04-20T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-05-10T23:59:59.999989, BUY EXPIRED
2006-06-01T23:59:59.999989, BUY CREATE, exectype StopLimit, price 3684.81, valid: 2006-06-21, pricelimit: 3666.57
2006-06-01T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-01T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-02T23:59:59.999989, BUY EXECUTED, Price: 3666.57, Cost: 3666.57, Comm 0.00
2006-06-05T23:59:59.999989, SELL CREATE, 3604.33
2006-06-05T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-05T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-06T23:59:59.999989, SELL EXECUTED, Price: 3598.58, Cost: 3666.57, Comm 0.00
2006-06-21T23:59:59.999989, BUY CREATE, exectype StopLimit, price 3562.11, valid: 2006-07-11, pricelimit: 3544.47
2006-06-21T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-21T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-06-23T23:59:59.999989, BUY EXECUTED, Price: 3544.47, Cost: 3544.47, Comm 0.00
2006-07-13T23:59:59.999989, SELL CREATE, 3562.56
2006-07-13T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-07-13T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-07-14T23:59:59.999989, SELL EXECUTED, Price: 3545.92, Cost: 3544.47, Comm 0.00
2006-07-24T23:59:59.999989, BUY CREATE, exectype StopLimit, price 3669.26, valid: 2006-08-13, pricelimit: 3651.09
2006-07-24T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-07-24T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-08-01T23:59:59.999989, BUY EXECUTED, Price: 3651.09, Cost: 3651.09, Comm 0.00
2006-09-06T23:59:59.999989, SELL CREATE, 3772.21
2006-09-06T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-09-06T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-09-07T23:59:59.999989, SELL EXECUTED, Price: 3766.80, Cost: 3651.09, Comm 0.00
2006-09-12T23:59:59.999989, BUY CREATE, exectype StopLimit, price 3826.85, valid: 2006-10-02, pricelimit: 3807.90
2006-09-12T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-09-12T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-09-22T23:59:59.999989, BUY EXECUTED, Price: 3807.90, Cost: 3807.90, Comm 0.00
2006-11-02T23:59:59.999989, SELL CREATE, 3974.62
2006-11-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-02T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-03T23:59:59.999989, SELL EXECUTED, Price: 3979.73, Cost: 3807.90, Comm 0.00
2006-11-06T23:59:59.999989, BUY CREATE, exectype StopLimit, price 4085.67, valid: 2006-11-26, pricelimit: 4065.45
2006-11-06T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-06T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-20T23:59:59.999989, BUY EXECUTED, Price: 4065.45, Cost: 4065.45, Comm 0.00
2006-11-24T23:59:59.999989, SELL CREATE, 4048.16
2006-11-24T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-24T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-11-27T23:59:59.999989, SELL EXECUTED, Price: 4045.05, Cost: 4065.45, Comm 0.00
2006-12-11T23:59:59.999989, BUY CREATE, exectype StopLimit, price 4093.42, valid: 2006-12-31, pricelimit: 4073.15
2006-12-11T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-12-11T23:59:59.999989, ORDER ACCEPTED/SUBMITTED
2006-12-22T23:59:59.999989, BUY EXECUTED, Price: 4073.15, Cost: 4073.15, Comm 0.00
<3>说明
  • 2006-01-26T23:59:59.999989, BUY CREATE, exectype StopLimit, price 3677.83, valid: 2006-02-15, pricelimit: 3659.63

2006-1-26 3578.92 3641.42 3577.98 3641.42
用收盘价计算:
3641.42 * 1.01 = 3677.8342 = 3677.83
3641.42 * 1.005 = 3659.6271 = 3659.63

数据一致:
price: 3677.83
pricelimit: 3659.63

  • 2006-02-03T23:59:59.999989, BUY EXECUTED, Price: 3659.63, Cost: 3659.63, Comm 0.00

2006-2-3 3677.05 3696 3652.76 3678.48
不是以限价3677.83成交,而是以止损限价3659.63成交。

再理解一下:
设置高于信号价格1%的止损价格。但是限价设置在信号(收盘)价以上0.5%,解释为等待力量出现,但不要购买峰值,等待下落。

(7)Test Script Execution Help
python ./order-execution-samples.py --help
usage: order-execution-samples.py [-h] [--infile INFILE]
                                  [--csvformat {bt,visualchart,sierrachart,yahoo,yahoo_unreversed}]
                                  [--fromdate FROMDATE] [--todate TODATE]
                                  [--plot] [--plotstyle {bar,line,candle}]
                                  [--numfigs NUMFIGS] [--smaperiod SMAPERIOD]
                                  [--exectype EXECTYPE] [--valid VALID]
                                  [--perc1 PERC1] [--perc2 PERC2]

Showcase for Order Execution Types

optional arguments:
  -h, --help            show this help message and exit
  --infile INFILE, -i INFILE
                        File to be read in
  --csvformat {bt,visualchart,sierrachart,yahoo,yahoo_unreversed}, -c {bt,visualchart,sierrachart,yahoo,yahoo_unreversed}
                        CSV Format
  --fromdate FROMDATE, -f FROMDATE
                        Starting date in YYYY-MM-DD format
  --todate TODATE, -t TODATE
                        Ending date in YYYY-MM-DD format
  --plot, -p            Plot the read data
  --plotstyle {bar,line,candle}, -ps {bar,line,candle}
                        Plot the read data
  --numfigs NUMFIGS, -n NUMFIGS
                        Plot using n figures
  --smaperiod SMAPERIOD, -s SMAPERIOD
                        Simple Moving Average Period
  --exectype EXECTYPE, -e EXECTYPE
                        Execution Type: Market (default), Close, Limit, Stop,
                        StopLimit
  --valid VALID, -v VALID
                        Validity for Limit sample: default 0 days
  --perc1 PERC1, -p1 PERC1
                        % distance from close price at order creation time for
                        the limit/trigger price in Limit/Stop orders
  --perc2 PERC2, -p2 PERC2
                        % distance from close price at order creation time for
                        the limit price in StopLimit orders
(8)源码
from __future__ import (absolute_import, division, print_function,
                        unicode_literals)

import argparse
import datetime
import os.path
import time
import sys


import backtrader as bt
import backtrader.feeds as btfeeds
import backtrader.indicators as btind


class OrderExecutionStrategy(bt.Strategy):
    params = (
        ('smaperiod', 15),
        ('exectype', 'Market'),
        ('perc1', 3),
        ('perc2', 1),
        ('valid', 4),
    )

    def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        dt = dt or self.data.datetime[0]
        if isinstance(dt, float):
            dt = bt.num2date(dt)
        print('%s, %s' % (dt.isoformat(), txt))

    def notify_order(self, order):
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            self.log('ORDER ACCEPTED/SUBMITTED', dt=order.created.dt)
            self.order = order
            return

        if order.status in [order.Expired]:
            self.log('BUY EXPIRED')

        elif order.status in [order.Completed]:
            if order.isbuy():
                self.log(
                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))

            else:  # Sell
                self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                         (order.executed.price,
                          order.executed.value,
                          order.executed.comm))

        # Sentinel to None: new orders allowed
        self.order = None

    def __init__(self):
        # SimpleMovingAverage on main data
        # Equivalent to -> sma = btind.SMA(self.data, period=self.p.smaperiod)
        sma = btind.SMA(period=self.p.smaperiod)

        # CrossOver (1: up, -1: down) close / sma
        self.buysell = btind.CrossOver(self.data.close, sma, plot=True)

        # Sentinel to None: new ordersa allowed
        self.order = None

    def next(self):
        if self.order:
            # An order is pending ... nothing can be done
            return

        # Check if we are in the market
        if self.position:
            # In the maerket - check if it's the time to sell
            if self.buysell < 0:
                self.log('SELL CREATE, %.2f' % self.data.close[0])
                self.sell()

        elif self.buysell > 0:
            if self.p.valid:
                valid = self.data.datetime.date(0) + \
                        datetime.timedelta(days=self.p.valid)
            else:
                valid = None

            # Not in the market and signal to buy
            if self.p.exectype == 'Market':
                self.buy(exectype=bt.Order.Market)  # default if not given

                self.log('BUY CREATE, exectype Market, price %.2f' %
                         self.data.close[0])

            elif self.p.exectype == 'Close':
                self.buy(exectype=bt.Order.Close)

                self.log('BUY CREATE, exectype Close, price %.2f' %
                         self.data.close[0])

            elif self.p.exectype == 'Limit':
                price = self.data.close * (1.0 - self.p.perc1 / 100.0)

                self.buy(exectype=bt.Order.Limit, price=price, valid=valid)

                if self.p.valid:
                    txt = 'BUY CREATE, exectype Limit, price %.2f, valid: %s'
                    self.log(txt % (price, valid.strftime('%Y-%m-%d')))
                else:
                    txt = 'BUY CREATE, exectype Limit, price %.2f'
                    self.log(txt % price)

            elif self.p.exectype == 'Stop':
                price = self.data.close * (1.0 + self.p.perc1 / 100.0)

                self.buy(exectype=bt.Order.Stop, price=price, valid=valid)

                if self.p.valid:
                    txt = 'BUY CREATE, exectype Stop, price %.2f, valid: %s'
                    self.log(txt % (price, valid.strftime('%Y-%m-%d')))
                else:
                    txt = 'BUY CREATE, exectype Stop, price %.2f'
                    self.log(txt % price)

            elif self.p.exectype == 'StopLimit':
                price = self.data.close * (1.0 + self.p.perc1 / 100.0)

                plimit = self.data.close * (1.0 + self.p.perc2 / 100.0)

                self.buy(exectype=bt.Order.StopLimit, price=price, valid=valid,
                         plimit=plimit)

                if self.p.valid:
                    txt = ('BUY CREATE, exectype StopLimit, price %.2f,'
                           ' valid: %s, pricelimit: %.2f')
                    self.log(txt % (price, valid.strftime('%Y-%m-%d'), plimit))
                else:
                    txt = ('BUY CREATE, exectype StopLimit, price %.2f,'
                           ' pricelimit: %.2f')
                    self.log(txt % (price, plimit))


def runstrat():
    args = parse_args()

    cerebro = bt.Cerebro()

    data = getdata(args)
    cerebro.adddata(data)

    cerebro.addstrategy(
        OrderExecutionStrategy,
        exectype=args.exectype,
        perc1=args.perc1,
        perc2=args.perc2,
        valid=args.valid,
        smaperiod=args.smaperiod
    )
    cerebro.run()

    if args.plot:
        cerebro.plot(numfigs=args.numfigs, style=args.plotstyle)


def getdata(args):

    dataformat = dict(
        bt=btfeeds.BacktraderCSVData,
        visualchart=btfeeds.VChartCSVData,
        sierrachart=btfeeds.SierraChartCSVData,
        yahoo=btfeeds.YahooFinanceCSVData,
        yahoo_unreversed=btfeeds.YahooFinanceCSVData
    )

    dfkwargs = dict()
    if args.csvformat == 'yahoo_unreversed':
        dfkwargs['reverse'] = True

    if args.fromdate:
        fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
        dfkwargs['fromdate'] = fromdate

    if args.todate:
        fromdate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')
        dfkwargs['todate'] = todate

    dfkwargs['dataname'] = args.infile

    dfcls = dataformat[args.csvformat]

    return dfcls(**dfkwargs)


def parse_args():
    parser = argparse.ArgumentParser(
        description='Showcase for Order Execution Types')

    parser.add_argument('--infile', '-i', required=False,
                        default='./datas/2006-day-001.txt',
                        help='File to be read in')

    parser.add_argument('--csvformat', '-c', required=False, default='bt',
                        choices=['bt', 'visualchart', 'sierrachart',
                                 'yahoo', 'yahoo_unreversed'],
                        help='CSV Format')

    parser.add_argument('--fromdate', '-f', required=False, default=None,
                        help='Starting date in YYYY-MM-DD format')

    parser.add_argument('--todate', '-t', required=False, default=None,
                        help='Ending date in YYYY-MM-DD format')

    parser.add_argument('--plot', '-p', action='store_false', required=False,
                        help='Plot the read data')

    parser.add_argument('--plotstyle', '-ps', required=False, default='bar',
                        choices=['bar', 'line', 'candle'],
                        help='Plot the read data')

    parser.add_argument('--numfigs', '-n', required=False, default=1,
                        help='Plot using n figures')

    parser.add_argument('--smaperiod', '-s', required=False, default=15,
                        help='Simple Moving Average Period')

    parser.add_argument('--exectype', '-e', required=False, default='Market',
                        help=('Execution Type: Market (default), Close, Limit,'
                              ' Stop, StopLimit'))

    parser.add_argument('--valid', '-v', required=False, default=0, type=int,
                        help='Validity for Limit sample: default 0 days')

    parser.add_argument('--perc1', '-p1', required=False, default=0.0,
                        type=float,
                        help=('%% distance from close price at order creation'
                              ' time for the limit/trigger price in Limit/Stop'
                              ' orders'))

    parser.add_argument('--perc2', '-p2', required=False, default=0.0,
                        type=float,
                        help=('%% distance from close price at order creation'
                              ' time for the limit price in StopLimit orders'))

    return parser.parse_args()


if __name__ == '__main__':
    runstrat()
(9)修改为ipython版本

把所有输入参数都内置到程序中,通过调整参数,实现命令行方式的参数测试。文章来源地址https://www.toymoban.com/news/detail-820776.html

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

#import argparse
import datetime
import os.path
import time
import sys


import backtrader as bt
import backtrader.feeds as btfeeds
import backtrader.indicators as btind

%matplotlib inline

class OrderExecutionStrategy(bt.Strategy):
    params = (
        ('smaperiod', 15),
        ('exectype', 'Market'),
        ('perc1', 3),
        ('perc2', 1),
        ('valid', 4),
    )

    def log(self, txt, dt=None):
        ''' Logging function fot this strategy'''
        dt = dt or self.data.datetime[0]
        if isinstance(dt, float):
            dt = bt.num2date(dt)
        print('%s, %s' % (dt.isoformat()[:10], txt)) # 字符串,仅显示日期,不显示时分秒

    def notify_order(self, order):
        
        # 订单提交、接收状态处理
        if order.status in [order.Submitted, order.Accepted]:
            # Buy/Sell order submitted/accepted to/by broker - Nothing to do
            self.log('ORDER ACCEPTED/SUBMITTED', dt=order.created.dt)
            self.order = order
            return

        #订单过期处理
        if order.status in [order.Expired]:
            self.log('BUY EXPIRED')

        #订单完成处理
        elif order.status in [order.Completed]:
            #买单操作
            if order.isbuy():
                self.log(
                    'BUY EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                    (order.executed.price,
                     order.executed.value,
                     order.executed.comm))

            #卖单操作
            else:  # Sell
                self.log('SELL EXECUTED, Price: %.2f, Cost: %.2f, Comm %.2f' %
                         (order.executed.price,
                          order.executed.value,
                          order.executed.comm))

        # Sentinel to None: new orders allowed
        self.order = None

    def __init__(self):
        # SimpleMovingAverage on main data
        # Equivalent to -> sma = btind.SMA(self.data, period=self.p.smaperiod)
        # SMA赋值,用params参数中的周期 15 天
        sma = btind.SMA(period=self.p.smaperiod)

        # CrossOver (1: up, -1: down) close / sma
        # 买卖标志,收盘上穿SMA 1 ,收盘下穿SMA -1 
        self.buysell = btind.CrossOver(self.data.close, sma, plot=True)

        # Sentinel to None: new orders allowed
        self.order = None

    def next(self):
        
        # 如有订单,无操作,返回
        if self.order:
            # An order is pending ... nothing can be done
            return

        # Check if we are in the market
        # 如无订单,检查仓位
        if self.position:
            # In the maerket - check if it's the time to sell
            # 小于0 ,卖出
            if self.buysell < 0:
                self.log('SELL CREATE, %.2f' % self.data.close[0])
                self.sell()

        # 大于0 ,买入
        elif self.buysell > 0:
            # 买入时,(1)先检查param的参数valid ,使用valid参数,设置订单有效期限
            if self.p.valid:
                valid = self.data.datetime.date(0) + \
                        datetime.timedelta(days=self.p.valid)
            else:
                valid = None

            # Not in the market and signal to buy
            # 买入时,(2)检查执行类型 ,默认是 Market 
            if self.p.exectype == 'Market':
                self.buy(exectype=bt.Order.Market)  # default if not given

                self.log('BUY CREATE, exectype Market, price %.2f' %
                         self.data.close[0])

            # 买入时,执行类型,Close
            elif self.p.exectype == 'Close':
                self.buy(exectype=bt.Order.Close)

                self.log('BUY CREATE, exectype Close, price %.2f' %
                         self.data.close[0])

            # 买入时,执行类型,限价Limit
            elif self.p.exectype == 'Limit':
                price = self.data.close * (1.0 - self.p.perc1 / 100.0)

                # 执行买入操作,限价,执行参数: price valid
                self.buy(exectype=bt.Order.Limit, price=price, valid=valid)

                # valid ??
                if self.p.valid:
                    txt = 'BUY CREATE, exectype Limit, price %.2f, valid: %s'
                    self.log(txt % (price, valid.strftime('%Y-%m-%d')))
                else:
                    txt = 'BUY CREATE, exectype Limit, price %.2f'
                    self.log(txt % price)

            # 买入时,执行类型,止损止盈 Stop
            elif self.p.exectype == 'Stop':
                # 执行价格:收盘价的 +3% 
                price = self.data.close * (1.0 + self.p.perc1 / 100.0)

                # 执行买入操作, Stop操作
                self.buy(exectype=bt.Order.Stop, price=price, valid=valid)

                if self.p.valid:
                    txt = 'BUY CREATE, exectype Stop, price %.2f, valid: %s'
                    self.log(txt % (price, valid.strftime('%Y-%m-%d')))
                else:
                    txt = 'BUY CREATE, exectype Stop, price %.2f'
                    self.log(txt % price)

            # 设置高于信号价格3%的止损止盈价格,限价设置在信号(收盘)价以上1%
            elif self.p.exectype == 'StopLimit':
                price = self.data.close * (1.0 + self.p.perc1 / 100.0)

                plimit = self.data.close * (1.0 + self.p.perc2 / 100.0)

                self.buy(exectype=bt.Order.StopLimit, price=price, valid=valid,
                         plimit=plimit)

                if self.p.valid:
                    txt = ('BUY CREATE, exectype StopLimit, price %.2f,'
                           ' valid: %s, pricelimit: %.2f')
                    self.log(txt % (price, valid.strftime('%Y-%m-%d'), plimit))
                
                else:
                    txt = ('BUY CREATE, exectype StopLimit, price %.2f,'
                           ' pricelimit: %.2f')
                    self.log(txt % (price, plimit))

'''
--exectype Market
--exectype Close
--exectype Limit --perc1 1
--exectype Limit --perc1 1 --valid 4
--exectype Stop --perc1 1
--exectype StopLimit --perc1 1 --perc2 0.5 --valid 20
'''

def runstrat():
    param_exectype = ['Market', 'Close', 'Limit','Stop', 'StopLimit']
    param_plotstyle=['bar', 'line', 'candle']
    param_numfigs = 1 # no use 
    param_perc1 = 0
    param_perc2 = 0
    param_valid = 0
    param_smaperiod = 15
    param_plot = False

    cerebro = bt.Cerebro()

    data = getdata()
    #print(data)
    
    cerebro.adddata(data)
    #print('add data finished!')

    cerebro.addstrategy(
        OrderExecutionStrategy,
        exectype=param_exectype[3],
        perc1=param_perc1,
        perc2=param_perc2,
        valid=param_valid,
        smaperiod=param_smaperiod
    )
    #print('add strategy finished!')
    
    cerebro.run()

    if param_plot:
        cerebro.plot(iplot=False, style=param_plotstyle[0])


def getdata():

    dataformat = dict(
        bt=btfeeds.BacktraderCSVData,
        visualchart=btfeeds.VChartCSVData,
        sierrachart=btfeeds.SierraChartCSVData,
        yahoo=btfeeds.YahooFinanceCSVData,
        yahoo_unreversed=btfeeds.YahooFinanceCSVData
    )
    choices=['bt', 'visualchart', 'sierrachart','yahoo', 'yahoo_unreversed']

    param_infile = './datas/2006-day-001.txt'
    param_csvformat = choices[0] # default : bt
    
    param_fromdate = None
    param_todate = None
    
    dfkwargs = dict()
    if param_csvformat == 'yahoo_unreversed':
        dfkwargs['reverse'] = True

    if param_fromdate:
        fromdate = datetime.datetime.strptime(param_fromdate, '%Y-%m-%d')
        dfkwargs['fromdate'] = fromdate

    if param_todate:
        tomdate = datetime.datetime.strptime(param_todate, '%Y-%m-%d')
        dfkwargs['todate'] = todate

    dfkwargs['dataname'] = param_infile

    dfcls = dataformat[param_csvformat]
    #print (dfkwargs)
    
    return dfcls(**dfkwargs)


if __name__ == '__main__':
    runstrat()

到了这里,关于Backtrader 文档学习-Order Management and Execution的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • openssl密钥证书管理(Key and Certificate Management)

            前两日应别人要求提供一份CSR文件过去,方便他们生成相关证书,对于这一块本来也不熟,于是找到openssl官网,想找找相关的教程看看,一番小找,果有收获,是个宝藏,源文档在这(OpenSSL Cookbook烹饪宝典),有意者可前往一观(最好是能仔细看看官方提供的原

    2024年04月13日
    浏览(34)
  • 【阅读笔记】Blockchain management and ML adaptation for IoT environment in 5G and beyond ...

    本文是一篇CCF C类文章,作者来自印度旁遮普邦帕蒂拉塔帕工程技术学院计算机科学与工程系 🙋‍♂️张同学 📧zhangruiyuan@zju.edu.cn 有问题请联系我~ 5G 和 B5G有什么区别? 答:5G主要解决了我们熟悉的高清视频、传输速率等问题;而B5G(Beyond-5G)将解决一些应用场景与技术的完

    2023年04月09日
    浏览(50)
  • web server apache tomcat11-21-monitor and management 监控与管理

    整理这个官方翻译的系列,原因是网上大部分的 tomcat 版本比较旧,此版本为 v11 最新的版本。 从零手写实现 tomcat minicat 别称【嗅虎】心有猛虎,轻嗅蔷薇。 web server apache tomcat11-01-官方文档入门介绍 web server apache tomcat11-02-setup 启动 web server apache tomcat11-03-deploy 如何部署 web

    2024年04月25日
    浏览(55)
  • Blockchain for Internet of Energy management: Review, solutions, and challenges

    本文是《Blockchain for Internet of Energy management: Review, solutions, and challenges》的中文翻译。 继智能电网之后,通过整合不同形式的能源,能源互联网(IoE)已成为能源领域的一项流行技术。IoE利用互联网收集、组织、优化和管理来自不同边缘设备的网络能源信息,以开发分布式智

    2024年02月02日
    浏览(43)
  • RuntimeError: CUDA out of memory See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF

    报错: If reserved memory is allocated memory try setting max_split_size_mb to avoid fragmentation. See documentation for Memory Management and PYTORCH_CUDA_ALLOC_CONF 当reserved memory is allocated memory,进行如下设置,可解决此bug: 代码如下:

    2024年02月11日
    浏览(51)
  • 【mysql学习篇】Order by与Group by优化以及排序算法详解

    Case1: 分析: 利用 最左前缀 法则:中间字段不能断,因此查询用到了name索引,从key_len=74也能看出,age索引列用在排序过程中,因为Extra字段里没有using filesort 注意: order by age 虽然用到了索引,但是不会在key_len列体现 Case 2: 分析: 从explain的执行结果来看:key_len=74,查询

    2024年02月15日
    浏览(56)
  • Linux_红帽8学习笔记分享_8(文件系统管理FS Management)

    它的全称是Basic Input/Output System即基本输入/输出系统,是比较老的传统的操作系统启动方式,如果笔记本电脑是win7之前的,红帽企业6之前的,那么它采用的启动方式都是BIOS启动方式。它在开机时需要进行自检,启动过程较复杂,时间较长。它无法识别GPT分区表,只能识别MBR分区

    2024年02月02日
    浏览(45)
  • 【搜索引擎】Document indexing and retrieval: 文档索引与检索

    作者:禅与计算机程序设计艺术 搜索引擎作为互联网信息获取的一种重要手段之一,无论是在PC、移动端还是电脑上使用,都可以快速找到想要的信息。而对于文档信息的搜索引擎索引构建,则是一个更加复杂的问题。 文档索引与检索(Document Indexing and Retrieval, DIR)的目标是建

    2024年02月08日
    浏览(40)
  • SQLite学习(六)SQLite的GLOB、LIMIT、ORDER、GROUP UP子句语法和应用

    在上一篇《SQLite学习(五)SQLite的WHERE、AND、OR、LIKE子句语法和应用》 中,讲解了 SQLite中 WHERE、AND、OR、LIKE 子句的语法,在本篇博客中,将继续讲解 SQLite 子句的基本语法。 同学们将学习到: SQLite GLOB 子句语法 SQLite LIMIT 子句语法 SQLite ORDER 子句语法 SQLite GROUP UP 子句语法

    2024年02月06日
    浏览(66)
  • Neo4j文档阅读笔记-Installation and Launch Guide

    ①找到下载好的Neo4j Desktop文件,然后双击进行安装; ②安装Neo4j Desktop根据下一步进行安装。 ①激活 打开Neo4j Desktop应用程序后,将激活码输入到“Activation Key”窗口中。 ②创建数据库 激活后,点击“New Graph”按钮,选择“Create a local graph”。然后输入“Database name”和“pa

    2024年02月14日
    浏览(39)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包