You are here:  Home » 量化交易与机器学习 » backtrader » 从OHLC需要土地backtrader中文逃生教程

逃生从OHLC Land

One的概念和发展过程中应用的关键概念backtrader是flexibility。该metaprogrammingintrospectionPython的能力(现在依然是)让很多事情的基础灵活的同时仍然能够deliver.

An旧后显示分机concept.

  • Extending一个datafeed

The基础知识:

from backtrader.feeds import GenericCSVData

class GenericCSV_PE(GenericCSVData):
    lines = ("pe",)  # Add "pe" to already defined lines

完成。backtrader的背景限定最常用的线:OHLC.

If我们挖入GenericCSV_PE,继承和的最后一个方面加新定义的线会产生下列行:

("close", "open", "high", "low", "volume", "openinterest", "datetime", "pe",)

这可以是检查在任何时间与方法getlinealiases(适用于DataFeeds, Indicators, StrategiesObservers

机制是灵活的,戳了一下到你可以在内部实际上得到任何东西,但它已被证明不被enough.

Ticket#60问起支持High Frequency Data,即:买入/卖出的数据。这意味着,预定义的lines的层次结构中的形式OHLC是不足够的。该BidAsk价格,数量和交易数量可制成以适应现有的OHLC领域,但也不会感觉自然。而如果一个人只关注该BidAsk价格,就不会有太多的领域留下untouched.

This呼吁已实现与版本1.2.1.88的解决方案。该理念可以概括为:

  • 现在,不仅有可能extend现有层次结构,也replace有了新one

Only一个约束的层次结构:

  • 必须有一个datetime领域存在(这将有望遏制有意义的datetime信息)

    这是因为backtrader需要的东西同步(多DATAS,多重时间周期,重采样,回放)就像阿基米德需要lever.

Here它是如何工作的:

from backtrader.feeds import GenericCSVData

class GenericCSV_BidAsk(GenericCSVData):
    linesoverride = True
    lines = ("bid", "ask", "datetime")  # Replace hierarchy with this one

Done.

Ok,不完全。但是,仅仅是因为我们正在装载从线csv源。层次结构实际上已经replacedbid, ask datetime定义多亏了linesoverride=Truesetting.

The原来GenericCSVData类解析了csv文件并且需要一个提示,其中fields对应于lines是位于。原来的定义是:

class GenericCSVData(feed.CSVDataBase):
    params = (
        ("nullvalue", float("NaN")),
        ("dtformat", "%Y-%m-%d %H:%M:%S"),
        ("tmformat", "%H:%M:%S"),

        ("datetime", 0),
        ("time", -1),  # -1 means not present
        ("open", 1),
        ("high", 2),
        ("low", 3),
        ("close", 4),
        ("volume", 5),
        ("openinterest", 6),
    )

层次结构重新定义,class可以用轻触摸来完成:

from backtrader.feeds import GenericCSVData

class GenericCSV_BidAsk(GenericCSVData):
    linesoverride = True
    lines = ("bid", "ask", "datetime")  # Replace hierarchy with this one

    params = (("bid", 1), ("ask", 2))

这表明Bid价格是CSV流场中的#1和Ask价格是现场#2。我们已经离开了datetime#0的定义从基本不变class.

Crafting的场合一个小的数据文件帮助:

TIMESTAMP,BID,ASK
02/03/2010 16:53:50,0.5346,0.5347
02/03/2010 16:53:51,0.5343,0.5347
02/03/2010 16:53:52,0.5543,0.5545
02/03/2010 16:53:53,0.5342,0.5344
02/03/2010 16:53:54,0.5245,0.5464
02/03/2010 16:53:54,0.5460,0.5470
02/03/2010 16:53:56,0.5824,0.5826
02/03/2010 16:53:57,0.5371,0.5374
02/03/2010 16:53:58,0.5793,0.5794
02/03/2010 16:53:59,0.5684,0.5688

添加一个小的测试脚本,方程(为那些更多内容谁直接前往来源中的样品)(见末完整的代码):

$ ./bidask.py

和输出讲了一切:

 1: 2010-02-03T16:53:50 - Bid 0.5346 - 0.5347 Ask
 2: 2010-02-03T16:53:51 - Bid 0.5343 - 0.5347 Ask
 3: 2010-02-03T16:53:52 - Bid 0.5543 - 0.5545 Ask
 4: 2010-02-03T16:53:53 - Bid 0.5342 - 0.5344 Ask
 5: 2010-02-03T16:53:54 - Bid 0.5245 - 0.5464 Ask
 6: 2010-02-03T16:53:54 - Bid 0.5460 - 0.5470 Ask
 7: 2010-02-03T16:53:56 - Bid 0.5824 - 0.5826 Ask
 8: 2010-02-03T16:53:57 - Bid 0.5371 - 0.5374 Ask
 9: 2010-02-03T16:53:58 - Bid 0.5793 - 0.5794 Ask
10: 2010-02-03T16:53:59 - Bid 0.5684 - 0.5688 Ask

的Et瞧!该Bid /Ask价格已经正确读取,解析和解释和战略已经能够访问.bid.ask在数据线馈通self.data.

重新定义lines层次打开一个宽泛的问题,虽然那是已经预定义Indicators.

  • Example的用法:将Stochastic是依赖于close, high的指示器和low如果我们的价格来计算其output

    Even虽然关于Bid作为close(因为是第一个)有只有一个其它price元件(Ask),而不是两个。和概念Ask无关与highlow

    很可能有人用这些领域的工作和操作(或研究)在高频Trading域不关心Stochastic作为choice

  • Other指标像移动average是完全没有。他们认为没有什么领域意味着或暗示,并会乐意接受任何东西。这样一个可以这样做:
    mysma = backtrader.indicators.SMA(self.data.bid, period=5)
    

    和的移动平均值在过去的5bid价格将delivered

The测试脚本已经支持添加了SMA。让我们来执行:

$ ./bidask.py --sma --period=3

输出:

 3: 2010-02-03T16:53:52 - Bid 0.5543 - 0.5545 Ask - SMA: 0.5411
 4: 2010-02-03T16:53:53 - Bid 0.5342 - 0.5344 Ask - SMA: 0.5409
 5: 2010-02-03T16:53:54 - Bid 0.5245 - 0.5464 Ask - SMA: 0.5377
 6: 2010-02-03T16:53:54 - Bid 0.5460 - 0.5470 Ask - SMA: 0.5349
 7: 2010-02-03T16:53:56 - Bid 0.5824 - 0.5826 Ask - SMA: 0.5510
 8: 2010-02-03T16:53:57 - Bid 0.5371 - 0.5374 Ask - SMA: 0.5552
 9: 2010-02-03T16:53:58 - Bid 0.5793 - 0.5794 Ask - SMA: 0.5663
10: 2010-02-03T16:53:59 - Bid 0.5684 - 0.5688 Ask - SMA: 0.5616

Note

Plotting仍然依赖于open, high, low, closevolume存在于datafeed.

Some例可直接覆盖通过简单地用绘制Line on Close并采取只在对象中的1st定义线。但是,一个声音模型,以开发。对于即将到来的版本backtrader

测试脚本使用:

$ ./bidask.py --help
usage: bidask.py [-h] [--data DATA] [--dtformat DTFORMAT] [--sma]
                 [--period PERIOD]

Bid/Ask Line Hierarchy

optional arguments:
  -h, --help            show this help message and exit
  --data DATA, -d DATA  data to add to the system (default:
                        ../../datas/bidask.csv)
  --dtformat DTFORMAT, -dt DTFORMAT
                        Format of datetime in input (default: %m/%d/%Y
                        %H:%M:%S)
  --sma, -s             Add an SMA to the mix (default: False)
  --period PERIOD, -p PERIOD
                        Period for the sma (default: 5)

而且测试脚本本身(包含在backtrader源)

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

import argparse

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


class BidAskCSV(btfeeds.GenericCSVData):
    linesoverride = True  # discard usual OHLC structure
    # datetime must be present and last
    lines = ("bid", "ask", "datetime")
    # datetime (always 1st) and then the desired order for
    params = (
        # (datetime, 0), # inherited from parent class
        ("bid", 1),  # default field pos 1
        ("ask", 2),  # default field pos 2
    )


class St(bt.Strategy):
    params = (("sma", False), ("period", 3))

    def __init__(self):
        if self.p.sma:
            self.sma = btind.SMA(self.data, period=self.p.period)

    def next(self):
        dtstr = self.data.datetime.datetime().isoformat()
        txt = "%4d: %s - Bid %.4f - %.4f Ask" % (
            (len(self), dtstr, self.data.bid[0], self.data.ask[0]))

        if self.p.sma:
            txt += " - SMA: %.4f" % self.sma[0]
        print(txt)


def parse_args():
    parser = argparse.ArgumentParser(
        description="Bid/Ask Line Hierarchy",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
    )

    parser.add_argument("--data", "-d", action="store",
                        required=False, default="../../datas/bidask.csv",
                        help="data to add to the system")

    parser.add_argument("--dtformat", "-dt",
                        required=False, default="%m/%d/%Y %H:%M:%S",
                        help="Format of datetime in input")

    parser.add_argument("--sma", "-s", action="store_true",
                        required=False,
                        help="Add an SMA to the mix")

    parser.add_argument("--period", "-p", action="store",
                        required=False, default=5, type=int,
                        help="Period for the sma")

    return parser.parse_args()


def runstrategy():
    args = parse_args()

    cerebro = bt.Cerebro()  # Create a cerebro

    data = BidAskCSV(dataname=args.data, dtformat=args.dtformat)
    cerebro.adddata(data)  # Add the 1st data to cerebro
    # Add the strategy to cerebro
    cerebro.addstrategy(St, sma=args.sma, period=args.period)
    cerebro.run()


if __name__ == "__main__":
    runstrategy()

评论被关闭。