BackTrader 中文文档(十三)(3)

简介: BackTrader 中文文档(十三)

BackTrader 中文文档(十三)(2)https://developer.aliyun.com/article/1505344

不使用策略

这是一种言过其实的说法。将应用一种策略,但您可以忽略任何类型的策略,并添加默认的 backtrader.Strategy。

分析器、观察者和指标将自动注入策略中。

一个例子:

btrun --csvformat btcsv \
      --data ../../datas/2006-day-001.txt \
      --cash 20000 \
      --commission 2.0 \
      --mult 10 \
      --margin 2000 \
      --nostdstats \
      --observer :Broker

这将没有太大作用,但达到了预期目的:

  • 默认添加了一个 backtrader.Strategy
  • Cerebro 不会实例化常规的 stdstats 观察者(经纪人、买卖、交易)
  • 手动添加一个 Broker 观察者

如上所述,nostdstats 是一个遗留参数。较新版本的 btrun 可以直接将参数传递给 Cerebro。等效的调用将是:

btrun --csvformat btcsv \
      --data ../../datas/2006-day-001.txt \
      --cash 20000 \
      --commission 2.0 \
      --mult 10 \
      --margin 2000 \
      --cerebro stdstats=False \
      --observer :Broker

添加分析器

btrun 还支持使用与选择策略相同的语法添加 Analyzers

对于 2005-2006 年的 SharpeRatio 分析的示例:

btrun --csvformat btcsv \
      --data ../../datas/2005-2006-day-001.txt \
      --strategy :SMA_CrossOver \
      --analyzer :SharpeRatio

控制台输出为 nothing

如果希望打印 Analyzer 结果,则必须指定:

  • --pranalyzer 默认调用下一个(除非分析器已经覆盖了正确的方法)
  • --ppranalyzer 使用 pprint 模块打印结果

注意

writers 成为 backtrader 的一部分之前,两个打印选项已经实现。添加一个没有 csv 输出的 writer 将达到相同的效果(输出已经得到改进)

扩展上面的示例:

btrun --csvformat btcsv \
      --data ../../datas/2005-2006-day-001.txt \
      --strategy :SMA_CrossOver \
      --analyzer :SharpeRatio \
      --plot \
      --pranalyzer
====================
== Analyzers
====================
##########
sharperatio
##########
{'sharperatio': 11.647332609673256}

好战略!!!(事实上,这只是一个例子,也没有佣金)

图表(仅显示分析器不在图中,因为分析器不能绘制,它们不是线对象)

相同的例子,但使用了 writer 参数:

btrun --csvformat btcsv \
      --data ../../datas/2005-2006-day-001.txt \
      --strategy :SMA_CrossOver \
      --analyzer :SharpeRatio \
      --plot \
      --writer
===============================================================================
Cerebro:
  -----------------------------------------------------------------------------
  - Datas:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    - Data0:
      - Name: 2005-2006-day-001
      - Timeframe: Days
      - Compression: 1
  -----------------------------------------------------------------------------
  - Strategies:
    +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    - SMA_CrossOver:
      *************************************************************************
      - Params:
        - fast: 10
        - slow: 30
        - _movav: SMA
      *************************************************************************
      - Indicators:
        .......................................................................
        - SMA:
          - Lines: sma
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          - Params:
            - period: 30
        .......................................................................
        - CrossOver:
          - Lines: crossover
          - Params: None
      *************************************************************************
      - Observers:
        .......................................................................
        - Broker:
          - Lines: cash, value
          - Params: None
        .......................................................................
        - BuySell:
          - Lines: buy, sell
          - Params: None
        .......................................................................
        - Trades:
          - Lines: pnlplus, pnlminus
          - Params: None
      *************************************************************************
      - Analyzers:
        .......................................................................
        - Value:
          - Begin: 10000.0
          - End: 10496.68
        .......................................................................
        - SharpeRatio:
          - Params: None
          ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          - Analysis:
            - sharperatio: 11.6473326097

添加指标和观察者

StrategiesAnalyzers 一样,btrun 也可以添加:

  • 指标

  • 观察者

当添加 Broker 观察者时,语法与上面看到的完全相同。

让我们重复一下例子,但添加一个 StochasticBroker 并查看图表(我们将更改一些参数):

btrun --csvformat btcsv \
      --data ../../datas/2006-day-001.txt \
      --nostdstats \
      --observer :Broker \
      --indicator :Stochastic:period_dslow=5 \
      --plot

图表

绘图控制

上面大部分的例子都使用了以下选项:

  • --plot 激活了默认图表的创建

通过向 --plot 选项添加 kwargs 可以实现更多控制

  • 例如,使用 --plot style="candle" 来绘制蜡烛图,而不是使用 LineOnClose 样式(这是默认的绘图样式)

调用:

btrun --csvformat btcsv \
      --data ../../datas/2006-day-001.txt \
      --nostdstats \
      --observer :Broker \
      --indicator :Stochastic:period_dslow=5 \
      --plot style=\"candle\"

注意

因为示例在 bash shell 中运行,该 shell 在传递参数给脚本之前会删除反斜杠,所以围绕 candle 的引号被反斜杠 \\ 引用。

在这种情况下需要使用反斜杠引用,以确保“bar”传递到脚本并可以作为字符串进行评估

图表

脚本的用法

直接从脚本中:

$ btrun --help
usage: btrun-script.py [-h] --data DATA [--cerebro [kwargs]] [--nostdstats]
                       [--format {yahoocsv_unreversed,vchart,vchartcsv,yahoo,mt4csv,ibdata,sierracsv,yahoocsv,btcsv,vcdata}]
                       [--fromdate FROMDATE] [--todate TODATE]
                       [--timeframe {microseconds,seconds,weeks,months,minutes,days,years}]
                       [--compression COMPRESSION]
                       [--resample RESAMPLE | --replay REPLAY]
                       [--strategy module:name:kwargs]
                       [--signal module:signaltype:name:kwargs]
                       [--observer module:name:kwargs]
                       [--analyzer module:name:kwargs]
                       [--pranalyzer | --ppranalyzer]
                       [--indicator module:name:kwargs] [--writer [kwargs]]
                       [--cash CASH] [--commission COMMISSION]
                       [--margin MARGIN] [--mult MULT] [--interest INTEREST]
                       [--interest_long] [--slip_perc SLIP_PERC]
                       [--slip_fixed SLIP_FIXED] [--slip_open]
                       [--no-slip_match] [--slip_out] [--flush]
                       [--plot [kwargs]]
Backtrader Run Script
optional arguments:
  -h, --help            show this help message and exit
  --resample RESAMPLE, -rs RESAMPLE
                        resample with timeframe:compression values
  --replay REPLAY, -rp REPLAY
                        replay with timeframe:compression values
  --pranalyzer, -pralyzer
                        Automatically print analyzers
  --ppranalyzer, -ppralyzer
                        Automatically PRETTY print analyzers
  --plot [kwargs], -p [kwargs]
                        Plot the read data applying any kwargs passed
                        For example:
                          --plot style="candle" (to plot candlesticks)
Data options:
  --data DATA, -d DATA  Data files to be added to the system
Cerebro options:
  --cerebro [kwargs], -cer [kwargs]
                        The argument can be specified with the following form:
                          - kwargs
                            Example: "preload=True" which set its to True
                        The passed kwargs will be passed directly to the cerebro
                        instance created for the execution
                        The available kwargs to cerebro are:
                          - preload (default: True)
                          - runonce (default: True)
                          - maxcpus (default: None)
                          - stdstats (default: True)
                          - live (default: False)
                          - exactbars (default: False)
                          - preload (default: True)
                          - writer (default False)
                          - oldbuysell (default False)
                          - tradehistory (default False)
  --nostdstats          Disable the standard statistics observers
  --format {yahoocsv_unreversed,vchart,vchartcsv,yahoo,mt4csv,ibdata,sierracsv,yahoocsv,btcsv,vcdata}, --csvformat {yahoocsv_unreversed,vchart,vchartcsv,yahoo,mt4csv,ibdata,sierracsv,yahoocsv,btcsv,vcdata}, -c {yahoocsv_unreversed,vchart,vchartcsv,yahoo,mt4csv,ibdata,sierracsv,yahoocsv,btcsv,vcdata}
                        CSV Format
  --fromdate FROMDATE, -f FROMDATE
                        Starting date in YYYY-MM-DD[THH:MM:SS] format
  --todate TODATE, -t TODATE
                        Ending date in YYYY-MM-DD[THH:MM:SS] format
  --timeframe {microseconds,seconds,weeks,months,minutes,days,years}, -tf {microseconds,seconds,weeks,months,minutes,days,years}
                        Ending date in YYYY-MM-DD[THH:MM:SS] format
  --compression COMPRESSION, -cp COMPRESSION
                        Ending date in YYYY-MM-DD[THH:MM:SS] format
Strategy options:
  --strategy module:name:kwargs, -st module:name:kwargs
                        This option can be specified multiple times.
                        The argument can be specified with the following form:
                          - module:classname:kwargs
                            Example: mymod:myclass:a=1,b=2
                        kwargs is optional
                        If module is omitted then class name will be sought in
                        the built-in strategies module. Such as in:
                          - :name:kwargs or :name
                        If name is omitted, then the 1st strategy found in the mod
                        will be used. Such as in:
                          - module or module::kwargs
Signals:
  --signal module:signaltype:name:kwargs, -sig module:signaltype:name:kwargs
                        This option can be specified multiple times.
                        The argument can be specified with the following form:
                          - signaltype:module:signaltype:classname:kwargs
                            Example: longshort+mymod:myclass:a=1,b=2
                        signaltype may be ommited: longshort will be used
                            Example: mymod:myclass:a=1,b=2
                        kwargs is optional
                        signaltype will be uppercased to match the defintions
                        fromt the backtrader.signal module
                        If module is omitted then class name will be sought in
                        the built-in signals module. Such as in:
                          - LONGSHORT::name:kwargs or :name
                        If name is omitted, then the 1st signal found in the mod
                        will be used. Such as in:
                          - module or module:::kwargs
Observers and statistics:
  --observer module:name:kwargs, -ob module:name:kwargs
                        This option can be specified multiple times.
                        The argument can be specified with the following form:
                          - module:classname:kwargs
                            Example: mymod:myclass:a=1,b=2
                        kwargs is optional
                        If module is omitted then class name will be sought in
                        the built-in observers module. Such as in:
                          - :name:kwargs or :name
                        If name is omitted, then the 1st observer found in the
                        will be used. Such as in:
                          - module or module::kwargs
Analyzers:
  --analyzer module:name:kwargs, -an module:name:kwargs
                        This option can be specified multiple times.
                        The argument can be specified with the following form:
                          - module:classname:kwargs
                            Example: mymod:myclass:a=1,b=2
                        kwargs is optional
                        If module is omitted then class name will be sought in
                        the built-in analyzers module. Such as in:
                          - :name:kwargs or :name
                        If name is omitted, then the 1st analyzer found in the
                        will be used. Such as in:
                          - module or module::kwargs
Indicators:
  --indicator module:name:kwargs, -ind module:name:kwargs
                        This option can be specified multiple times.
                        The argument can be specified with the following form:
                          - module:classname:kwargs
                            Example: mymod:myclass:a=1,b=2
                        kwargs is optional
                        If module is omitted then class name will be sought in
                        the built-in analyzers module. Such as in:
                          - :name:kwargs or :name
                        If name is omitted, then the 1st analyzer found in the
                        will be used. Such as in:
                          - module or module::kwargs
Writers:
  --writer [kwargs], -wr [kwargs]
                        This option can be specified multiple times.
                        The argument can be specified with the following form:
                          - kwargs
                            Example: a=1,b=2
                        kwargs is optional
                        It creates a system wide writer which outputs run data
                        Please see the documentation for the available kwargs
Cash and Commission Scheme Args:
  --cash CASH, -cash CASH
                        Cash to set to the broker
  --commission COMMISSION, -comm COMMISSION
                        Commission value to set
  --margin MARGIN, -marg MARGIN
                        Margin type to set
  --mult MULT, -mul MULT
                        Multiplier to use
  --interest INTEREST   Credit Interest rate to apply (0.0x)
  --interest_long       Apply credit interest to long positions
  --slip_perc SLIP_PERC
                        Enable slippage with a percentage value
  --slip_fixed SLIP_FIXED
                        Enable slippage with a fixed point value
  --slip_open           enable slippage for when matching opening prices
  --no-slip_match       Disable slip_match, ie: matching capped at
                        high-low if slippage goes over those limits
  --slip_out            with slip_match enabled, match outside high-low
  --flush               flush the output - useful under win32 systems

文章

介绍

原文:www.backtrader.com/blog/

此部分承载了有关backtrader发布的文章。

享受它们!!!

关于回测性能和核心内存执行

原文:www.backtrader.com/blog/2019-10-25-on-backtesting-performance-and-out-of-memory/on-backtesting-performance-and-out-of-memory/

最近有两个redit.com/r/algotrading帖子启发了本文。

我们当然将使用backtrader来解决这些概念

2M 根蜡烛

为了做到这一点,首先要生成那么多根蜡烛。考虑到第一个帖子提到了 77 支股票和 1.6M 根蜡烛,这将导致每支股票有 20,779 根蜡烛,因此我们将采取以下措施以获得良好的数字

  • 为 100 支股票生成蜡烛
  • 每支股票生成 20,000 根蜡烛

即:共计 2M 根蜡烛的 100 个文件。

脚本

import numpy as np
import pandas as pd
COLUMNS = ['open', 'high', 'low', 'close', 'volume', 'openinterest']
CANDLES = 20000
STOCKS
dateindex = pd.date_range(start='2010-01-01', periods=CANDLES, freq='15min')
for i in range(STOCKS):
    data = np.random.randint(10, 20, size=(CANDLES, len(COLUMNS)))
    df = pd.DataFrame(data * 1.01, dateindex, columns=COLUMNS)
    df = df.rename_axis('datetime')
    df.to_csv('candles{:02d}.csv'.format(i))

这将生成 100 个文件,从candles00.csv开始一直到candles99.csv。实际值并不重要。重要的是具有标准的datetimeOHLCV组件(和OpenInterest)。

测试系统

  • 硬件/操作系统:将使用一台配备 Intel i7 和 32 G 字节内存的 Windows 10 15.6 英寸笔记本电脑。
  • Python:CPython 3.6.1pypy3 6.0.0
  • 其他:一个持续运行并占用大约 20% CPU 的应用程序。常见的嫌疑人如 Chrome(102 个进程)、Edge、Word、Powerpoint、Excel 和一些次要应用程序正在运行

backtrader 默认配置

让我们回想一下backtrader的默认运行时配置是什么:

  • 如有可能,预加载所有数据源
  • 如果所有数据源都可以预加载,请在批处理模式(命名为runonce)中运行
  • 首先预先计算所有指标
  • 逐步通过策略逻辑和经纪人


BackTrader 中文文档(十三)(4)https://developer.aliyun.com/article/1505347

相关文章
|
9月前
|
机器学习/深度学习 人工智能 测试技术
BackTrader 中文文档(十四)(3)
BackTrader 中文文档(十四)
86 0
BackTrader 中文文档(十四)(3)
|
9月前
|
存储
BackTrader 中文文档(十四)(4)
BackTrader 中文文档(十四)
93 0
BackTrader 中文文档(十四)(4)
|
9月前
|
算法 数据可视化 程序员
BackTrader 中文文档(十四)(1)
BackTrader 中文文档(十四)
96 0
BackTrader 中文文档(十四)(1)
|
9月前
BackTrader 中文文档(十三)(1)
BackTrader 中文文档(十三)
64 0
|
9月前
|
存储 算法 Python
BackTrader 中文文档(十三)(2)
BackTrader 中文文档(十三)
51 0
|
9月前
|
程序员 Python
BackTrader 中文文档(十三)(4)
BackTrader 中文文档(十三)
68 0
|
9月前
|
Python
BackTrader 中文文档(十四)(2)
BackTrader 中文文档(十四)
77 0
|
9月前
BackTrader 中文文档(十五)(3)
BackTrader 中文文档(十五)
56 0
|
9月前
|
编解码 算法 开发者
BackTrader 中文文档(十五)(1)
BackTrader 中文文档(十五)
72 0
|
9月前
|
调度
BackTrader 中文文档(十五)(2)
BackTrader 中文文档(十五)
94 0