For reference if anyone has a similar issue and comes here through google, here is the cleaned up working version
from __future__ import (absolute_import, division, print_function,
unicode_literals)
import argparse
import datetime
import backtrader as bt
import backtrader.feeds as btfeeds
import backtrader.indicators as btind
class SMAStrategy(bt.Strategy):
params = (
('period', 10),
('onlydaily', False),
)
def __init__(self):
self.sma_small_tf = btind.SMA(self.data, period=self.p.period)
if not self.p.onlydaily:
self.sma_large_tf = btind.SMA(self.data1, period=self.p.period)
def nextstart(self):
print('--------------------------------------------------')
print('nextstart called with len', len(self))
print('--------------------------------------------------')
super(SMAStrategy, self).nextstart()
def runstrat():
args = parse_args()
# Create a cerebro entity
cerebro = bt.Cerebro(stdstats=False)
# Add a strategy
if not args.indicators:
cerebro.addstrategy(bt.Strategy)
else:
cerebro.addstrategy(
SMAStrategy,
# args for the strategy
period=args.period,
onlydaily=args.onlydaily,
)
tframes = dict(minutes=bt.TimeFrame.Minutes,daily=bt.TimeFrame.Days, weekly=bt.TimeFrame.Weeks,
monthly=bt.TimeFrame.Months)
# Get the dates from the args
fromdate = datetime.datetime.strptime(args.fromdate, '%Y-%m-%d')
todate = datetime.datetime.strptime(args.todate, '%Y-%m-%d')
# Load the Data
datapath = args.dataname or '../../datas/2006-day-001.txt'
data = bt.feeds.GenericCSVData(
dataname=datapath,
nullvalue=0.0,
dtformat=('%m/%d/%Y'),
tmformat=('%H:%M:%S'),
timeframe = tframes[args.ltf_resample],
compression = args.ltf_comp,
fromdate=fromdate,
todate=todate,
datetime=0,
time=1,
high=3,
low=4,
open=2,
close=5,
volume=6,
openinterest=-1 #-1 means not used
)
cerebro.resampledata(data, timeframe=tframes[args.ltf_resample],
compression=args.ltf_comp)
# Handy dictionary for the argument timeframe conversion
# Resample the data
data2 = bt.feeds.GenericCSVData(
dataname=datapath,
nullvalue=0.0,
timeframe = tframes[args.htf_resample],
compression = args.htf_comp,
dtformat=('%m/%d/%Y'),
tmformat=('%H:%M:%S'),
fromdate=fromdate,
todate=todate,
datetime=0,
time=1,
high=3,
low=4,
open=2,
close=5,
volume=6,
openinterest=-1 #-1 means not used
)
cerebro.resampledata(data2, timeframe=tframes[args.htf_resample],
compression=args.htf_comp)
# Run over everything
cerebro.run()
# Plot the result
cerebro.plot(style='bar')
def parse_args():
parser = argparse.ArgumentParser(
description='Multitimeframe test')
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('--indicators', action='store_true',
help='Wether to apply Strategy with indicators')
parser.add_argument('--ltf_comp', default=1, type=int,
help='Compression setting for lower time frame resampling')
parser.add_argument('--ltf_resample', required=True,
help='resample data for LTF. Valid\
intervals:\n monthly\n weekly\n daily\n minutes')
parser.add_argument('--htf_comp', default=1, type=int,
help='Compression setting for higher time frame resampling')
parser.add_argument('--htf_resample', required=True,
help='resample data for HTF. Valid\
intervals:\n monthly\n weekly\n daily\n minutes')
parser.add_argument('--period', default=10, required=False, type=int,
help='Period to apply to indicator')
parser.add_argument('--fromdate', '-f',
required=True,
help='Starting date in YYYY-MM-DD format')
parser.add_argument('--todate', '-t',
required=True,
help='Ending date in YYYY-MM-DD format')
return parser.parse_args()
if __name__ == '__main__':
runstrat()