• Backtrader中文笔记之CSV Data Feed Data


    When data is only available in a single timeframe and the analysis has to be done for a different timeframe, it’s time to do some resampling.

    当数据只在单个时间框架可用,并且必须在不同的时间段内进行分析时,就需要进行一些重采样

    “Resampling” should actually be called “Upsampling” given that one goes from a source timeframe to a larger time frame (for example: days to weeks)

    “重采样”实际上应该称为“上采样”,因为它是从一个源时间框架到一个更大的时间框架(例如:天到周)

    backtrader has built-in support for resampling by passing the original data through a filter object. Although there are several ways to achieve this, a straightforward interface exists to achieve this:

    backtrader内置了对重新采样的支持,通过过滤对象传递原始数据。虽然有几种方法可以实现这一点,但有一个简单的界面可以实现这一点:

    • Instead of using cerebro.adddata(data) to put a data into the system use

    • cerebro.resampledata(data, **kwargs)

    • 使用cerebro.resampledata(data, **kwargs)代替使用cerebro.adddata(data)给系统添加数据

    There are two main options that can be controlled

    有两个主要的控制选项

    • Change the timeframe

    • 改变时间框架
    • Compress bars

    • 压缩bars

    To do so, use the following parameters when calling resampledata:

    为此,在调用resampledata时使用以下参数:

    • timeframe (default: bt.TimeFrame.Days)

      Destination timeframe which to be useful has to be equal or larger than the source

    • 目标时间框架必须等于或大于源时间框架
    • compression (default: 1)

      Compress the selected value “n” to 1 bar

    • 压缩可以是1或者n

    Let’s see an example from Daily to Weekly with a handcrafted script:

    让我们看看一个例子,从每日到每周的手工脚本:

    $ ./resampling-example.py --timeframe weekly --compression 1
    

     输出

    We can compare it to the original daily data

    $ ./resampling-example.py --timeframe daily --compression 1
    

     The output:

    The magic is done by executing the following steps:

    魔术是通过以下步骤完成的

    • Loading the data as usual

    • 像以往一样加载数据
    • Feeding the data into cerebro with resampledata with the desired parameters:

    • 将所需参数的数据用resampledata输入cerebro:
      • timeframe

      • compression

    The code in the sample (the entire script at the bottom).

        # Load the Data
        datapath = args.dataname or '../../datas/2006-day-001.txt'
        data = btfeeds.BacktraderCSVData(dataname=datapath)
    
        # Handy dictionary for the argument timeframe conversion
        tframes = dict(
            daily=bt.TimeFrame.Days,
            weekly=bt.TimeFrame.Weeks,
            monthly=bt.TimeFrame.Months)
    
        # Add the resample data instead of the original
        cerebro.resampledata(data,
                             timeframe=tframes[args.timeframe],
                             compression=args.compression)
    

     A last example in which we first change the time frame from daily to weekly and then apply a 3 to 1 compression:

    最后一个例子,我们首先将时间框架从每天改为每周,然后应用3到1压缩:

    $ ./resampling-example.py --timeframe weekly --compression 3
    

     The output:

    From the original 256 daily bars we end up with 18 3-week bars. The breakdown:

    从最初的256日线bars到18个 3粥bars。分解如下

    • 52 weeks

    • 52 / 3 = 17.33 and therefore 18 bars

    It doesn’t take much more. Of course intraday data can also be resampled.

    不需要更多。当然,日内数据也可以重新采样。

    The resampling filter supports additional parameters, which in most cases should not be touched:

    重采样过滤器支持附加参数,在大多数情况下不应触及:

    • bar2edge (default: True)

      resamples using time boundaries as the target. For example with a “ticks -> 5 seconds” the resulting 5 seconds bars will be aligned to xx:00, xx:05, xx:10 …

    • 使用时间边界作为目标重新采样。例如,对于“ticks-> 5秒”,得到的5秒bars将对齐到xx:00、xx:05、xx:10…
    • adjbartime (default: True)

      Use the time at the boundary to adjust the time of the delivered resampled bar instead of the last seen timestamp. If resampling to “5 seconds” the time of the bar will be adjusted for example to hh:mm:05 even if the last seen timestamp was hh:mm:04.33
      使用边界处的时间来调整交付的重采样条的时间,而不是最后看到的时间戳。如果重新采样到“5秒”,则条的时间将调整为hh:mm:05,即使最后看到的时间戳是hh:mm:04.3

    • Note

      Time will only be adjusted if “bar2edge” is True. It wouldn’t make sense to adjust the time if the bar has not been aligned to a boundary

      只有当“bar2edge”正确时,时间才会调整。如果工具条没有对齐到边界,那么调整时间就没有意义了

    • rightedge (default: True)

      Use the right edge of the time boundaries to set the time.

    • 使用时间边界的右边界来设置时间。

      If False and compressing to 5 seconds the time of a resampled bar for seconds between hh:mm:00 and hh:mm:04 will be hh:mm:00 (the starting boundary

    • 如果为假,压缩到5秒,则重新采样的时间条在hh:mm:00和hh:mm:04之间的秒将为hh:mm:00(起始边界)
    • If True the used boundary for the time will be hh:mm:05 (the ending boundary)

    • 如果为真,使用的时间边界将是hh:mm:05(结束边界)
    • boundoff (default: 0)

      Push the boundary for resampling/replaying by an amount of units.

    • 将重采样/重放的边界按单位数量推进。
    • If for example the resampling is from 1 minute to 15 minutes, the default behavior is to take the 1-minute bars from 00:01:00 until 00:15:00 to produce a 15-minutes replayed/resampled bar.

    • 例如,如果重新采样从1分钟到15分钟,默认行为是将1分钟的条从00:01:00到00:15:00使用,以生成15分钟的重播/重新采样条。
    • If boundoff is set to 1, then the boundary is pushed 1 unit forward. In this case the original unit is a 1-minute bar. Consequently the resampling/replaying will now:

    • 如果boundoff设置为1,则边界向前推1个单位。在这种情况下,最初的单位是1分钟的巧克力棒。因此重采样/重放现在将:
      • Use the bars from 00:00:00 to 00:14:00 for the generation of the 15-minutes bar
      • 使用从00:00:00到00:14:00的条形图来生成15分钟条形图

    The sample code for the resampling test script.

    from __future__ import (absolute_import, division, print_function,
                            unicode_literals)
    
    import argparse
    
    import backtrader as bt
    import backtrader.feeds as btfeeds
    
    
    def runstrat():
        args = parse_args()
    
        # Create a cerebro entity
        cerebro = bt.Cerebro(stdstats=False)
    
        # Add a strategy
        cerebro.addstrategy(bt.Strategy)
    
        # Load the Data
        datapath = args.dataname or '../../datas/2006-day-001.txt'
        data = btfeeds.BacktraderCSVData(dataname=datapath)
    
        # Handy dictionary for the argument timeframe conversion
        tframes = dict(
            daily=bt.TimeFrame.Days,
            weekly=bt.TimeFrame.Weeks,
            monthly=bt.TimeFrame.Months)
    
        # Add the resample data instead of the original
        cerebro.resampledata(data,
                             timeframe=tframes[args.timeframe],
                             compression=args.compression)
    
        # Run over everything
        cerebro.run()
    
        # Plot the result
        cerebro.plot(style='bar')
    
    
    def parse_args():
        parser = argparse.ArgumentParser(
            description='Pandas test script')
    
        parser.add_argument('--dataname', default='', required=False,
                            help='File Data to Load')
    
        parser.add_argument('--timeframe', default='weekly', required=False,
                            choices=['daily', 'weekly', 'monhtly'],
                            help='Timeframe to resample to')
    
        parser.add_argument('--compression', default=1, required=False, type=int,
                            help='Compress n bars into 1')
    
        return parser.parse_args()
    
    
    if __name__ == '__main__':
        runstrat()
    
  • 相关阅读:
    P2009 跑步
    P3916 图的遍历
    P2865 [USACO06NOV]路障Roadblocks
    P2820 局域网
    P2176 [USACO14FEB]路障Roadblock
    讨伐!数论
    网络流入门——EK算法
    最被低估的特质
    我的天哪我有博客了!
    Area POJ
  • 原文地址:https://www.cnblogs.com/sidianok/p/13491277.html
Copyright © 2020-2023  润新知