You are here:  Home » 量化交易与机器学习 » backtrader » 战略选择 – backtrader中文教程

战略Selection

Houston我们有一个问题:

  • cerebro并不意味着要运行好几次。这不是1st时间而非以为用户做错了,现在看来,这是一个使用case.

This有趣的使用情况下想出了通过票务177.在这种情况下cerebro被多次使用,以评估其正在differet策略从外部数据source.

backtrader牵强仍然可以支持这种使用情况下,而不是在它具有直接的方式被attempted.

Optimizing的selection

The BUIL,在优化backtrader已经做了必要的事情:

  • 实例化几个战略实例和收集results

Being唯一的instances都属于同一个class。这个正是Python的帮助通过配股我们控制的object.

First的创建,使用Signal技术内置backtrader

class St0(bt.SignalStrategy):
    def __init__(self):
        sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
        crossover = bt.ind.CrossOver(sma1, sma2)
        self.signal_add(bt.SIGNAL_LONG, crossover)


class St1(bt.SignalStrategy):
    def __init__(self):
        sma1 = bt.ind.SMA(period=10)
        crossover = bt.ind.CrossOver(self.data.close, sma1)
        self.signal_add(bt.SIGNAL_LONG, crossover)

It不能得到easier.

And现在让我们做瞧提供这两个strategies.

class StFetcher(object):
    _STRATS = [St0, St1]

    def __new__(cls, *args, **kwargs):
        idx = kwargs.pop("idx")

        obj = cls._STRATS[idx](*args, **kwargs)
        return obj

Et的魔力!当类StFetcher被实例化,方法__new__需要创建实例的控制。在这种情况下:

  • 获取idx这是传递给it
  • Uses这个参数去从_STRATS名单一本战略PARAM,使我们的前面的例子战略已经stored

    Note

    Nothing将阻止使用这种idx值获取从服务器和/或database.

  • Instantiate和战略返回fecthedstrategy

Running的show

    cerebro.addanalyzer(bt.analyzers.Returns)
    cerebro.optstrategy(StFetcher, idx=[0, 1])
    results = cerebro.run(maxcpus=args.maxcpus, optreturn=args.optreturn)

Indeed!Optimiization它!而不是addstrategy我们用optstrategy和传递值的数组,idx。这些值将被遍历优化engine.

Becausecerebro可以在每趟优化托管多个策略中,结果将包含了list of lists。每个子表是每个的结果优化pass.

在我们的情况,并与每道只有1个策略,我们可以快速展平结果和提取分析器的值,我们有added.

    strats = [x[0] for x in results]  # flatten the result
    for i, strat in enumerate(strats):
        rets = strat.analyzers.returns.get_analysis()
        print("Strat {} Name {}:\n  - analyzer: {}\n".format(
            i, strat.__class__.__name__, rets))

A样品run

./strategy-selection.py

Strat 0 Name St0:
  - analyzer: OrderedDict([(u"rtot", 0.04847392369449283), (u"ravg", 9.467563221580632e-05), (u"rnorm", 0.02414514457151587), (u"rnorm100", 2.414514457151587)])

Strat 1 Name St1:
  - analyzer: OrderedDict([(u"rtot", 0.05124714332260593), (u"ravg", 0.00010009207680196471), (u"rnorm", 0.025543999840699633), (u"rnorm100", 2.5543999840699634)])

Our 2个策略已经运行,并提供(如预期)不同results.

Note

样品是最小的,但已与所有可用运行的CPU。与执行它--maxpcpus=1会更快。欲了解更多使用所有的CPU复杂的场景将是useful.

Conclusion

TheStrategy Selection的使用情况是可能的,并不需要规避任何在内置设施要么backtraderPythonitself.

Sample Usage

$ ./strategy-selection.py --help
usage: strategy-selection.py [-h] [--data DATA] [--maxcpus MAXCPUS]
                             [--optreturn]

Sample for strategy selection

optional arguments:
  -h, --help         show this help message and exit
  --data DATA        Data to be read in (default:
                     ../../datas/2005-2006-day-001.txt)
  --maxcpus MAXCPUS  Limit the numer of CPUs to use (default: None)
  --optreturn        Return reduced/mocked strategy object (default: False)

The code

Which已被列入在backtrader

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

import argparse

import backtrader as bt


class St0(bt.SignalStrategy):
    def __init__(self):
        sma1, sma2 = bt.ind.SMA(period=10), bt.ind.SMA(period=30)
        crossover = bt.ind.CrossOver(sma1, sma2)
        self.signal_add(bt.SIGNAL_LONG, crossover)


class St1(bt.SignalStrategy):
    def __init__(self):
        sma1 = bt.ind.SMA(period=10)
        crossover = bt.ind.CrossOver(self.data.close, sma1)
        self.signal_add(bt.SIGNAL_LONG, crossover)


class StFetcher(object):
    _STRATS = [St0, St1]

    def __new__(cls, *args, **kwargs):
        idx = kwargs.pop("idx")

        obj = cls._STRATS[idx](*args, **kwargs)
        return obj


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

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

    cerebro.addanalyzer(bt.analyzers.Returns)
    cerebro.optstrategy(StFetcher, idx=[0, 1])
    results = cerebro.run(maxcpus=args.maxcpus, optreturn=args.optreturn)

    strats = [x[0] for x in results]  # flatten the result
    for i, strat in enumerate(strats):
        rets = strat.analyzers.returns.get_analysis()
        print("Strat {} Name {}:\n  - analyzer: {}\n".format(
            i, strat.__class__.__name__, rets))


def parse_args(pargs=None):

    parser = argparse.ArgumentParser(
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        description="Sample for strategy selection")

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

    parser.add_argument("--maxcpus", required=False, action="store",
                        default=None, type=int,
                        help="Limit the numer of CPUs to use")

    parser.add_argument("--optreturn", required=False, action="store_true",
                        help="Return reduced/mocked strategy object")

    return parser.parse_args(pargs)


if __name__ == "__main__":
    runstrat()

评论被关闭。