backtrader 已經可以從分鐘數據中重新採樣。接受價格變動數據不是問題,只需將 4 個常用欄位(open、 high、 low、 close)設置為價格變動值。
但是傳遞要重新採樣的逐筆報價數據再次生成相同的數據。作為或版本 1.1.11.88,情況已不再如此。現在
-
時間框架 (backtrader.TimeFrame) 已擴展為包含 “Ticks”、“MicroSeconds” 和 “Seconds” 的常量和名稱
-
重新採樣可以管理上述 3 個時間幀並對其進行採樣。
注意
因為逐筆報價數據是最低可能的時間幀,它實際上可以被“壓縮”(n 根柱線到 1 根柱線),但不能從最小的時間幀內進行採樣。
新版本包含一個小tickdata.csv 示例,該示例添加到源數據中,並添加了一個新的示例腳本 resample-tickdata.py 來使用它。
注意
更新了腳本以使用新Cerebro.resampledata 方法,從而避免了手動實例化 backtrader.DataResampler
預設執行不涉及資料:
$ ./resample-tickdata.py
產生此圖表:
將 3 個分時壓縮為 1 個:
$ ./resample-tickdata.py --timeframe ticks --compression 3
產生此圖表:
壓縮后,我們不再有單個「價格變動」 而是「柱線」。
現在壓縮到秒和5條壓縮:
$ ./resample-tickdata.py --timeframe seconds --compression 5
使用新圖表:
最後到幾分鐘。範例資料包含 4 個不同分鐘的逐筆報價資料(檔案中 last 分時是第 4 分鐘 的唯一價格變動):
$ ./resample-tickdata.py --timeframe minutes
有4個柱(在頂部可以看到最終價格是3069)。第 4 根 柱線是此分鐘的單個點,檔中存在單個價格變動。
文稿用法:
$ ./resample-tickdata.py --help
usage: resample-tickdata.py [-h] [--dataname DATANAME]
[--timeframe {ticks,microseconds,seconds,minutes,daily,weekly,monthly}]
[--compression COMPRESSION]
Resampling script down to tick data
optional arguments:
-h, --help show this help message and exit
--dataname DATANAME File Data to Load
--timeframe {ticks,microseconds,seconds,minutes,daily,weekly,monthly}
Timeframe to resample to
--compression COMPRESSION
Compress n bars into 1
還有代碼。
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/ticksample.csv'
data = btfeeds.GenericCSVData(
dataname=datapath,
dtformat='%Y-%m-%dT%H:%M:%S.%f',
timeframe=bt.TimeFrame.Ticks,
)
# Handy dictionary for the argument timeframe conversion
tframes = dict(
ticks=bt.TimeFrame.Ticks,
microseconds=bt.TimeFrame.MicroSeconds,
seconds=bt.TimeFrame.Seconds,
minutes=bt.TimeFrame.Minutes,
daily=bt.TimeFrame.Days,
weekly=bt.TimeFrame.Weeks,
monthly=bt.TimeFrame.Months)
# Resample the data
data = cerebro.resampledata(data,
timeframe=tframes[args.timeframe],
compression=args.compression)
# add a writer
cerebro.addwriter(bt.WriterFile, csv=True)
# Run over everything
cerebro.run()
# Plot the result
cerebro.plot(style='bar')
def parse_args():
parser = argparse.ArgumentParser(
description='Resampling script down to tick data')
parser.add_argument('--dataname', default='', required=False,
help='File Data to Load')
parser.add_argument('--timeframe', default='ticks', required=False,
choices=['ticks', 'microseconds', 'seconds',
'minutes', 'daily', 'weekly', 'monthly'],
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()