當數據僅在一個時間範圍內可用並且必須在不同的時間範圍內進行分析時,是時候進行一些重新採樣了。
“重新採樣”實際上應該稱為“上採樣”,因為從源時間範圍到更大的時間範圍(例如:幾天到幾週)
“下採樣”尚不可能。
backtrader通過將原始數據傳遞給智能命名為DataResampler的過濾器對象,內置了對重採樣的支持。
該類有兩個功能:
更改時間範圍
壓縮桿
為此, DataResampler在構建期間使用標準feed.DataBase參數:
timeframe(默認:bt.TimeFrame.Days)有用的目標時間範圍必須等於或大於源
compression(默認值:1)將所選值“n”壓縮為 1 bar
讓我們看一個使用手工腳本從每日到每週的示例:
$ ./data-resampling.py --timeframe weekly --compression 1
輸出:
我們可以將其與原始的每日數據進行比較:
$ ./data-resampling.py --timeframe daily --compression 1
輸出:
魔術是通過執行以下步驟來完成的:
像往常一樣加載數據
將數據送入具有所需數據的
DataResampler大體時間
壓縮
示例中的代碼(底部的整個腳本)。
# Load the Data
datapath = args.dataname or '../datas/sample/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)
# Resample the data
data_resampled = bt.DataResampler(
dataname=data,
timeframe=tframes[args.timeframe],
compression=args.compression)
# Add the resample data instead of the original
cerebro.adddata(data_resampled)
最後一個示例,我們首先將時間範圍從每天更改為每週,然後應用 3 比 1 的壓縮:
$ ./data-resampling.py --timeframe weekly --compression 3
輸出:
從最初的 256 個每日柱,我們最終得到 18 個 3 周柱。細分:
52 週
52 / 3 = 17.33 因此 18 個柱
不需要更多。當然,日內數據也可以重新採樣。
重採樣測試腳本的示例代碼。
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/sample/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)
# Resample the data
data_resampled = bt.DataResampler(
dataname=data,
timeframe=tframes[args.timeframe],
compression=args.compression)
# Add the resample data instead of the original
cerebro.adddata(data_resampled)
# 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()