BackTrader 中文文档(二十五)(2)

简介: BackTrader 中文文档(二十五)

BackTrader 中文文档(二十五)(1)https://developer.aliyun.com/article/1505456

填充缺失数据

对输出的深入检查显示如下:

...
61,2006-01-02-volume-min-001,61,2006-01-02 10:30:00,3613.0,3614.0,3613.0,3614.0,112.0,0.0,Strategy,61
62,2006-01-02-volume-min-001,62,2006-01-02 10:31:00,3614.0,3614.0,3614.0,3614.0,183.0,0.0,Strategy,62
63,2006-01-02-volume-min-001,63,2006-01-02 10:34:00,3614.0,3614.0,3614.0,3614.0,841.0,0.0,Strategy,63
64,2006-01-02-volume-min-001,64,2006-01-02 10:35:00,3614.0,3614.0,3614.0,3614.0,17.0,0.0,Strategy,64
...

缺少分钟 10:32 和 10:33 的数据。作为一年中的第 1 个交易日,可能根本没有进行交易。或者数据源可能未能捕获到这些数据。

为了解决票号 #23 的问题,并能够将给定分钟的成交量与前一天的同一分钟进行比较,我们将填补缺失的数据。

backtrader中已经存在一个SessionFiller,按预期填补了缺失的数据。代码很长,比过滤器的复杂性更多(请参阅末尾的完整实现),但让我们看看类/参数定义:

class SessionFiller(with_metaclass(metabase.MetaParams, object)):
    '''
    Bar Filler for a Data Source inside the declared session start/end times.
    The fill bars are constructed using the declared Data Source ``timeframe``
    and ``compression`` (used to calculate the intervening missing times)
    Params:
      - fill_price (def: None):
        If None is passed, the closing price of the previous bar will be
        used. To end up with a bar which for example takes time but it is not
        displayed in a plot ... use float('Nan')
      - fill_vol (def: float('NaN')):
        Value to use to fill the missing volume
      - fill_oi (def: float('NaN')):
        Value to use to fill the missing Open Interest
      - skip_first_fill (def: True):
        Upon seeing the 1st valid bar do not fill from the sessionstart up to
        that bar
    '''
    params = (('fill_price', None),
              ('fill_vol', float('NaN')),
              ('fill_oi', float('NaN')),
              ('skip_first_fill', True))

示例脚本现在可以过滤和填充数据了:

./data-filler.py --writer --wrcsv --tstart 09:30 --tend 17:30 --filter --filler
...
62,2006-01-02-volume-min-001,62,2006-01-02 10:31:00,3614.0,3614.0,3614.0,3614.0,183.0,0.0,Strategy,62
63,2006-01-02-volume-min-001,63,2006-01-02 10:32:00,3614.0,3614.0,3614.0,3614.0,0.0,,Strategy,63
64,2006-01-02-volume-min-001,64,2006-01-02 10:33:00,3614.0,3614.0,3614.0,3614.0,0.0,,Strategy,64
65,2006-01-02-volume-min-001,65,2006-01-02 10:34:00,3614.0,3614.0,3614.0,3614.0,841.0,0.0,Strategy,65
...

分钟 10:32 和 10:33 已存在。脚本使用最后已知的“收盘”价格填充价格值,并将成交量和持仓量字段设置为 0。脚本接受一个--fvol参数,将成交量设置为任何值(包括’NaN’)

完成票号 #23

使用SessionFilter和SessionFiller完成了以下工作:

  • 未提供盘前/盘后市数据
  • 不存在数据(在给定时间范围内)丢失

现在,在实施RelativeVolume指标的 Ticket 23 中讨论的“同步”不再需要,因为所有日期的条形图数量完全相同(在示例中从 09:30 到 17:30 的所有分钟都包括在内)

请记住,默认情况下将缺失的成交量设置为0,可以开发一个简单的RelativeVolume指标:

class RelativeVolume(bt.Indicator):
    csv = True  # show up in csv output (default for indicators is False)
    lines = ('relvol',)
    params = (
        ('period', 20),
        ('volisnan', True),
    )
    def __init__(self):
        if self.p.volisnan:
            # if missing volume will be NaN, do a simple division
            # the end result for missing volumes will also be NaN
            relvol = self.data.volume(-self.p.period) / self.data.volume
        else:
            # Else do a controlled Div with a built-in function
            relvol = bt.DivByZero(
                self.data.volume(-self.p.period),
                self.data.volume,
                zero=0.0)
        self.lines.relvol = relvol

使用backtrader中的内置辅助功能,足够聪明,可以避免除零错误。

在下次脚本调用中将所有部分组合起来:

./data-filler.py --writer --wrcsv --tstart 09:30 --tend 17:30 --filter --filler --relvol
===============================================================================
Id,2006-01-02-volume-min-001,len,datetime,open,high,low,close,volume,openinterest,Strategy,len,RelativeVolume,len,relvol
1,2006-01-02-volume-min-001,1,2006-01-02 09:30:00,3604.0,3605.0,3603.0,3604.0,546.0,0.0,Strategy,1,RelativeVolume,1,
2,2006-01-02-volume-min-001,2,2006-01-02 09:31:00,3604.0,3606.0,3604.0,3606.0,438.0,0.0,Strategy,2,RelativeVolume,2,
...

RelativeVolume指标在第 1 个条形图期间产生了预期外的输出。周期在脚本中计算为:(17:30 - 09:30 * 60) + 1。让我们直接看看相对成交量在第二天的 10:32 和 10:33 是如何看待的,考虑到第 1 天,成交量值被填充为0:

...
543,2006-01-02-volume-min-001,543,2006-01-03 10:31:00,3648.0,3648.0,3647.0,3648.0,56.0,0.0,Strategy,543,RelativeVolume,543,3.26785714286
544,2006-01-02-volume-min-001,544,2006-01-03 10:32:00,3647.0,3648.0,3647.0,3647.0,313.0,0.0,Strategy,544,RelativeVolume,544,0.0
545,2006-01-02-volume-min-001,545,2006-01-03 10:33:00,3647.0,3647.0,3647.0,3647.0,135.0,0.0,Strategy,545,RelativeVolume,545,0.0
546,2006-01-02-volume-min-001,546,2006-01-03 10:34:00,3648.0,3648.0,3647.0,3648.0,171.0,0.0,Strategy,546,RelativeVolume,546,4.91812865497
...

如预期那样,它被设置为0。

结论

数据源中的filter机制打开了完全操纵数据流的可能性。请谨慎使用。

脚本代码和用法

在backtrader的源码中提供了示例:

usage: data-filler.py [-h] [--data DATA] [--filter] [--filler] [--fvol FVOL]
                      [--tstart TSTART] [--tend TEND] [--relvol]
                      [--fromdate FROMDATE] [--todate TODATE] [--writer]
                      [--wrcsv] [--plot] [--numfigs NUMFIGS]
DataFilter/DataFiller Sample
optional arguments:
  -h, --help            show this help message and exit
  --data DATA, -d DATA  data to add to the system
  --filter, -ft         Filter using session start/end times
  --filler, -fl         Fill missing bars inside start/end times
  --fvol FVOL           Use as fill volume for missing bar (def: 0.0)
  --tstart TSTART, -ts TSTART
                        Start time for the Session Filter (HH:MM)
  --tend TEND, -te TEND
                        End time for the Session Filter (HH:MM)
  --relvol, -rv         Add relative volume indicator
  --fromdate FROMDATE, -f FROMDATE
                        Starting date in YYYY-MM-DD format
  --todate TODATE, -t TODATE
                        Starting date in YYYY-MM-DD format
  --writer, -w          Add a writer to cerebro
  --wrcsv, -wc          Enable CSV Output in the writer
  --plot, -p            Plot the read data
  --numfigs NUMFIGS, -n NUMFIGS
                        Plot using numfigs figures

代码:

from __future__ import (absolute_import, division, print_function,
                        unicode_literals)
import argparse
import datetime
import math
# The above could be sent to an independent module
import backtrader as bt
import backtrader.feeds as btfeeds
import backtrader.utils.flushfile
import backtrader.filters as btfilters
from relativevolume import RelativeVolume
def runstrategy():
    args = parse_args()
    # Create a cerebro
    cerebro = bt.Cerebro()
    # Get the dates from the args
    fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
    todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')
    # Get the session times to pass them to the indicator
    # datetime.time has no strptime ...
    dtstart = datetime.datetime.strptime(args.tstart, '%H:%M')
    dtend = datetime.datetime.strptime(args.tend, '%H:%M')
    # Create the 1st data
    data = btfeeds.BacktraderCSVData(
        dataname=args.data,
        fromdate=fromdate,
        todate=todate,
        timeframe=bt.TimeFrame.Minutes,
        compression=1,
        sessionstart=dtstart,  # internally just the "time" part will be used
        sessionend=dtend,  # internally just the "time" part will be used
    )
    if args.filter:
        data.addfilter(btfilters.SessionFilter)
    if args.filler:
        data.addfilter(btfilters.SessionFiller, fill_vol=args.fvol)
    # Add the data to cerebro
    cerebro.adddata(data)
    if args.relvol:
        # Calculate backward period - tend tstart are in same day
        # + 1 to include last moment of the interval dstart <-> dtend
        td = ((dtend - dtstart).seconds // 60) + 1
        cerebro.addindicator(RelativeVolume,
                             period=td,
                             volisnan=math.isnan(args.fvol))
    # Add an empty strategy
    cerebro.addstrategy(bt.Strategy)
    # Add a writer with CSV
    if args.writer:
        cerebro.addwriter(bt.WriterFile, csv=args.wrcsv)
    # And run it - no trading - disable stdstats
    cerebro.run(stdstats=False)
    # Plot if requested
    if args.plot:
        cerebro.plot(numfigs=args.numfigs, volume=True)
def parse_args():
    parser = argparse.ArgumentParser(
        description='DataFilter/DataFiller Sample')
    parser.add_argument('--data', '-d',
                        default='../../datas/2006-01-02-volume-min-001.txt',
                        help='data to add to the system')
    parser.add_argument('--filter', '-ft', action='store_true',
                        help='Filter using session start/end times')
    parser.add_argument('--filler', '-fl', action='store_true',
                        help='Fill missing bars inside start/end times')
    parser.add_argument('--fvol', required=False, default=0.0,
                        type=float,
                        help='Use as fill volume for missing bar (def: 0.0)')
    parser.add_argument('--tstart', '-ts',
                        # default='09:14:59',
                        # help='Start time for the Session Filter (%H:%M:%S)')
                        default='09:15',
                        help='Start time for the Session Filter (HH:MM)')
    parser.add_argument('--tend', '-te',
                        # default='17:15:59',
                        # help='End time for the Session Filter (%H:%M:%S)')
                        default='17:15',
                        help='End time for the Session Filter (HH:MM)')
    parser.add_argument('--relvol', '-rv', action='store_true',
                        help='Add relative volume indicator')
    parser.add_argument('--fromdate', '-f',
                        default='2006-01-01',
                        help='Starting date in YYYY-MM-DD format')
    parser.add_argument('--todate', '-t',
                        default='2006-12-31',
                        help='Starting date in YYYY-MM-DD format')
    parser.add_argument('--writer', '-w', action='store_true',
                        help='Add a writer to cerebro')
    parser.add_argument('--wrcsv', '-wc', action='store_true',
                        help='Enable CSV Output in the writer')
    parser.add_argument('--plot', '-p', action='store_true',
                        help='Plot the read data')
    parser.add_argument('--numfigs', '-n', default=1,
                        help='Plot using numfigs figures')
    return parser.parse_args()
if __name__ == '__main__':
    runstrategy()

SessionFiller

来自backtrader源码:

class SessionFiller(with_metaclass(metabase.MetaParams, object)):
    '''
    Bar Filler for a Data Source inside the declared session start/end times.
    The fill bars are constructed using the declared Data Source ``timeframe``
    and ``compression`` (used to calculate the intervening missing times)
    Params:
      - fill_price (def: None):
        If None is passed, the closing price of the previous bar will be
        used. To end up with a bar which for example takes time but it is not
        displayed in a plot ... use float('Nan')
      - fill_vol (def: float('NaN')):
        Value to use to fill the missing volume
      - fill_oi (def: float('NaN')):
        Value to use to fill the missing Open Interest
      - skip_first_fill (def: True):
        Upon seeing the 1st valid bar do not fill from the sessionstart up to
        that bar
    '''
    params = (('fill_price', None),
              ('fill_vol', float('NaN')),
              ('fill_oi', float('NaN')),
              ('skip_first_fill', True))
    # Minimum delta unit in between bars
    _tdeltas = {
        TimeFrame.Minutes: datetime.timedelta(seconds=60),
        TimeFrame.Seconds: datetime.timedelta(seconds=1),
        TimeFrame.MicroSeconds: datetime.timedelta(microseconds=1),
    }
    def __init__(self, data):
        # Calculate and save timedelta for timeframe
        self._tdunit = self._tdeltas[data._timeframe] * data._compression
        self.seenbar = False  # control if at least one bar has been seen
        self.sessend = MAXDATE  # maxdate is the control for bar in session
    def __call__(self, data):
        '''
        Params:
          - data: the data source to filter/process
        Returns:
          - False (always) because this filter does not remove bars from the
        stream
        The logic (starting with a session end control flag of MAXDATE)
          - If new bar is over session end (never true for 1st bar)
            Fill up to session end. Reset sessionend to MAXDATE & fall through
          - If session end is flagged as MAXDATE
            Recalculate session limits and check whether the bar is within them
            if so, fill up and record the last seen tim
          - Else ... the incoming bar is in the session, fill up to it
        '''
        # Get time of current (from data source) bar
        dtime_cur = data.datetime.datetime()
        if dtime_cur > self.sessend:
            # bar over session end - fill up and invalidate
            self._fillbars(data, self.dtime_prev, self.sessend + self._tdunit)
            self.sessend = MAXDATE
        # Fall through from previous check ... the bar which is over the
        # session could already be in a new session and within the limits
        if self.sessend == MAXDATE:
            # No bar seen yet or one went over previous session limit
            sessstart = data.datetime.tm2datetime(data.sessionstart)
            self.sessend = sessend = data.datetime.tm2datetime(data.sessionend)
            if sessstart <= dtime_cur <= sessend:
                # 1st bar from session in the session - fill from session start
                if self.seenbar or not self.p.skip_first_fill:
                    self._fillbars(data, sessstart - self._tdunit, dtime_cur)
            self.seenbar = True
            self.dtime_prev = dtime_cur
        else:
            # Seen a previous bar and this is in the session - fill up to it
            self._fillbars(data, self.dtime_prev, dtime_cur)
            self.dtime_prev = dtime_cur
        return False
    def _fillbars(self, data, time_start, time_end, forcedirty=False):
        '''
        Fills one by one bars as needed from time_start to time_end
        Invalidates the control dtime_prev if requested
        '''
        # Control flag - bars added to the stack
        dirty = False
        time_start += self._tdunit
        while time_start < time_end:
            dirty = self._fillbar(data, time_start)
            time_start += self._tdunit
        if dirty or forcedirty:
            data._save2stack(erase=True)
    def _fillbar(self, data, dtime):
        # Prepare an array of the needed size
        bar = [float('Nan')] * data.size()
        # Fill datetime
        bar[data.DateTime] = date2num(dtime)
        # Fill the prices
        price = self.p.fill_price or data.close[-1]
        for pricetype in [data.Open, data.High, data.Low, data.Close]:
            bar[pricetype] = price
        # Fill volume and open interest
        bar[data.Volume] = self.p.fill_vol
        bar[data.OpenInterest] = self.p.fill_oi
        # Fill extra lines the data feed may have defined beyond DateTime
        for i in range(data.DateTime + 1, data.size()):
            bar[i] = data.lines[i][0]
        # Add tot he stack of bars to save
        data._add2stack(bar)
        return True


BackTrader 中文文档(二十五)(3)https://developer.aliyun.com/article/1505459

相关文章
|
9月前
|
存储 C语言 内存技术
C语言深度解析:大小端字节序——多字节数据的底层存储规则
大小端指CPU对多字节数据在内存中的存放顺序:大端高字节存低地址,小端反之。x86/ARM默认小端,网络字节序统一为大端。跨平台、网络通信、二进制协议开发中必须显式处理字节序转换,否则数据解析必错。
1508 138
|
索引
bisect_left,bisect_right,bisect的用法,区别以及源码分析
bisect_left,bisect_right,bisect的用法,区别和源码分析
1460 0
bisect_left,bisect_right,bisect的用法,区别以及源码分析
|
人工智能 自然语言处理 前端开发
Director:构建视频智能体的 AI 框架,用自然语言执行搜索、编辑、合成和生成等复杂视频任务
Director 是一个构建视频智能体的 AI 框架,用户可以通过自然语言命令执行复杂的视频任务,如搜索、编辑、合成和生成视频内容。该框架基于 VideoDB 的“视频即数据”基础设施,集成了多个预构建的视频代理和 AI API,支持高度定制化,适用于开发者和创作者。
1621 9
Director:构建视频智能体的 AI 框架,用自然语言执行搜索、编辑、合成和生成等复杂视频任务
|
算法 测试技术 AI芯片
CPU反超NPU,llama.cpp生成速度翻5倍!LLM端侧部署新范式T-MAC开源
【9月更文挑战第7天】微软研究院提出了一种名为T-MAC的创新方法,旨在解决大型语言模型在资源受限的边缘设备上高效部署的问题。T-MAC通过查表法在CPU上实现低比特LLM的高效推理,支持混合精度矩阵乘法,无需解量化。其通过位级查表实现统一且可扩展的解决方案,优化数据布局和重用率,显著提升了单线程和多线程下的mpGEMV及mpGEMM性能,并在端到端推理吞吐量和能效方面表现出色。然而,表量化和快速聚合技术可能引入近似和数值误差,影响模型准确性。论文详见:[链接](https://www.arxiv.org/pdf/2407.00088)。
1365 10
|
前端开发 Linux 调度
ftrace、perf、bcc、bpftrace、ply的使用
ftrace、perf、bcc、bpftrace、ply的使用
1253 2
|
Linux 虚拟化
top中的st含义—虚拟化底层从你的vm里偷了多少资源
linux在top中打印中有st显示项,这一显示项单位为百分比,它的值表明你的系统花了百分之多少等待得到真正的cpu资源。 在正常情况下在云平台下st最好为0,这表明你的vm得到了所有必要的cpu资源。
5788 0
|
存储 编解码 API
BackTrader 中文文档(四)(1)
BackTrader 中文文档(四)
469 1
|
安全 程序员 编译器
【C++ 异常 】深入了解C++ 异常机制中的 terminate()处理 避免不必要的错误(一)
【C++ 异常 】深入了解C++ 异常机制中的 terminate()处理 避免不必要的错误
1464 1
|
数据库 索引 Python
BackTrader 中文文档(十六)(2)
BackTrader 中文文档(十六)
370 0
|
Python
BackTrader 中文文档(十)(3)
BackTrader 中文文档(十)
708 0

热门文章

最新文章