You are here:  Home » 量化交易与机器学习 » backtrader » 在步骤 – backtrader中文教程一交易日

交易Steps

It一节似乎在世界上某个地方有兴趣,可以是总结如下:

  • Introduce an order using daily bars but using the opening price

这来自于门票#105订单执行逻辑的交谈当天的数据和calculation

backtrader试图保持尽可能逼真#101动态股权及以下前提与工作时适用daily bars

  • 当正在评估每日酒吧,酒吧是已经over

It是有道理的,因为所有的价格(open/high/low/close)组件众所周知。实际上,它似乎不合逻辑允许对open行动价格当close价格已经known.

The明显的方法,这是使用intraday数据并输入时,开盘价是已知的。但似乎intraday数据也不是那么widespread.

This就是增加了filter到数据馈送可以提供帮助。一个过滤器:

  • Converts daily data into intraday-like data

起泡藤壶!感兴趣的读者会立即指出,upsampling例如MinutesDays是合乎逻辑和工作,但downsampling DaysMinutes不能done.

And它是100%正确的。下面介绍的过滤器将不会尝试,但多谦虚和简单的目标:

  • 打破2 parts
    1. A酒吧每天栏只开盘价没有volume
    2. A 2nd酒吧,是每天定时bar

This的副本仍然可以举行一个合乎逻辑的方法:

  • 见状opening价格,交易者可以在一天中的其他时间act
  • The依次匹配(实际上可以是或者可以不是取决于执行类型和价格约束匹配的)

的完整代码如下。让我们来看看样品运行有一个众所周知的数据的255 daily柱:

$ ./daysteps.py --data ../../datas/2006-day-001.txt

输出:

Calls,Len Strat,Len Data,Datetime,Open,High,Low,Close,Volume,OpenInterest
0001,0001,0001,2006-01-02T23:59:59,3578.73,3578.73,3578.73,3578.73,0.00,0.00
- I could issue a buy order during the Opening
0002,0001,0001,2006-01-02T23:59:59,3578.73,3605.95,3578.73,3604.33,0.00,0.00
0003,0002,0002,2006-01-03T23:59:59,3604.08,3604.08,3604.08,3604.08,0.00,0.00
- I could issue a buy order during the Opening
0004,0002,0002,2006-01-03T23:59:59,3604.08,3638.42,3601.84,3614.34,0.00,0.00
0005,0003,0003,2006-01-04T23:59:59,3615.23,3615.23,3615.23,3615.23,0.00,0.00
- I could issue a buy order during the Opening
0006,0003,0003,2006-01-04T23:59:59,3615.23,3652.46,3615.23,3652.46,0.00,0.00
...
...
0505,0253,0253,2006-12-27T23:59:59,4079.70,4079.70,4079.70,4079.70,0.00,0.00
- I could issue a buy order during the Opening
0506,0253,0253,2006-12-27T23:59:59,4079.70,4134.86,4079.70,4134.86,0.00,0.00
0507,0254,0254,2006-12-28T23:59:59,4137.44,4137.44,4137.44,4137.44,0.00,0.00
- I could issue a buy order during the Opening
0508,0254,0254,2006-12-28T23:59:59,4137.44,4142.06,4125.14,4130.66,0.00,0.00
0509,0255,0255,2006-12-29T23:59:59,4130.12,4130.12,4130.12,4130.12,0.00,0.00
- I could issue a buy order during the Opening
0510,0255,0255,2006-12-29T23:59:59,4130.12,4142.01,4119.94,4119.94,0.00,0.00

会出现以下情况:

  • next被称为:510 times255 x 2
  • lenStrategy`和的data达到总的255,这是预期的:的数据仅具有那些许多bars
  • Every时间lendata`的增加,4个价格成分有相同的值,即openprice

    这里一个备注被打印出来,以指示在这一opening相可以采取行动,例如像buying.

Effectively:

  • 的日数据馈送正被replayed用2步的每一天,让该选项来open而且价格components

该过滤器将被添加到backtrader在里面接下来release.

示例代码包括filter.

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

import argparse
from datetime import datetime, time

import backtrader as bt


class DayStepsFilter(object):
    def __init__(self, data):
        self.pendingbar = None

    def __call__(self, data):
        # Make a copy of the new bar and remove it from stream
        newbar = [data.lines[i][0] for i in range(data.size())]
        data.backwards()  # remove the copied bar from stream

        openbar = newbar[:]  # Make an open only bar
        o = newbar[data.Open]
        for field_idx in [data.High, data.Low, data.Close]:
            openbar[field_idx] = o

        # Nullify Volume/OpenInteres at the open
        openbar[data.Volume] = 0.0
        openbar[data.OpenInterest] = 0.0

        # Overwrite the new data bar with our pending data - except start point
        if self.pendingbar is not None:
            data._updatebar(self.pendingbar)

        self.pendingbar = newbar  # update the pending bar to the new bar
        data._add2stack(openbar)  # Add the openbar to the stack for processing

        return False  # the length of the stream was not changed

    def last(self, data):
        """Called when the data is no longer producing bars
        Can be called multiple times. It has the chance to (for example)
        produce extra bars"""
        if self.pendingbar is not None:
            data.backwards()  # remove delivered open bar
            data._add2stack(self.pendingbar)  # add remaining
            self.pendingbar = None  # No further action
            return True  # something delivered

        return False  # nothing delivered here


class St(bt.Strategy):
    params = ()

    def __init__(self):
        pass

    def start(self):
        self.callcounter = 0
        txtfields = list()
        txtfields.append("Calls")
        txtfields.append("Len Strat")
        txtfields.append("Len Data")
        txtfields.append("Datetime")
        txtfields.append("Open")
        txtfields.append("High")
        txtfields.append("Low")
        txtfields.append("Close")
        txtfields.append("Volume")
        txtfields.append("OpenInterest")
        print(",".join(txtfields))

        self.lcontrol = 0

    def next(self):
        self.callcounter += 1

        txtfields = list()
        txtfields.append("%04d" % self.callcounter)
        txtfields.append("%04d" % len(self))
        txtfields.append("%04d" % len(self.data0))
        txtfields.append(self.data.datetime.datetime(0).isoformat())
        txtfields.append("%.2f" % self.data0.open[0])
        txtfields.append("%.2f" % self.data0.high[0])
        txtfields.append("%.2f" % self.data0.low[0])
        txtfields.append("%.2f" % self.data0.close[0])
        txtfields.append("%.2f" % self.data0.volume[0])
        txtfields.append("%.2f" % self.data0.openinterest[0])
        print(",".join(txtfields))

        if len(self.data) > self.lcontrol:
            print("- I could issue a buy order during the Opening")

        self.lcontrol = len(self.data)


def runstrat():
    args = parse_args()

    cerebro = bt.Cerebro()
    data = bt.feeds.BacktraderCSVData(dataname=args.data)

    data.addfilter(DayStepsFilter)
    cerebro.adddata(data)

    cerebro.addstrategy(St)

    cerebro.run(stdstats=False, runonce=False, preload=False)
    if args.plot:
        cerebro.plot(style="bar")


def parse_args():
    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description="Sample for pivot point and cross plotting")

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

    parser.add_argument("--plot", required=False, action="store_true",
                        help=("Plot the result"))

    return parser.parse_args()


if __name__ == "__main__":
    runstrat()

评论被关闭。