简体   繁体   中英

How to correctly log trades using backtrader in python?

Using data from csv file in 60 minute format. Trying to log all buy/sell decisions using backtrader backtester.

Issue: The time logger doesn't seem to work properly as all hours are outputted as "23:59:59.999989" when this is not the case.

See sample code:

def log(self, txt, dt=None):
    dt = dt or self.data.datetime.datetime(0)
    print('%s, %s' % (dt, txt)) 


def next(self):
    if self.data.close > self.sma1:
        self.buy()
        self.log('BUY CREATE, exectype Market, price %.2f' % self.data.close[0])

#Get Data
data = btfeeds.GenericCSVData(dataname='AAPL.csv',fromdate=datetime.datetime(2018, 1, 2),todate=datetime.datetime(2020, 4, 28),nullvalue=0.0,dtformat=('%Y-%m-%d %H:%M:%S'),datetime=0,open=1,low=2,high=3,close=4,volume=5,openinterest=6)

Sample Output:

2019-07-12 23:59:59.999989, BUY CREATE, exectype Market, price 203.52
2019-07-12 23:59:59.999989, BUY CREATE, exectype Market, price 203.30
2019-07-12 23:59:59.999989, BUY CREATE, exectype Market, price 203.24
2019-07-12 23:59:59.999989, BUY CREATE, exectype Market, price 203.24
2019-07-15 23:59:59.999989, BUY CREATE, exectype Market, price 204.11

Data & Format from Csv file:

2018-01-02  9:30:00 AM

This problem also took me few hours. And I find the solution from another web. enter link description here

For minute data tell cerebro that you are using minute data (timeframe) and how many minutes per bar (compression).

#Get Data
data = btfeeds.GenericCSVData(
dataname='AAPL.csv',
fromdate=datetime.datetime(2018, 1, 2),
todate=datetime.datetime(2020, 4, 28),
nullvalue=0.0,

dtformat=('%Y-%m-%d %H:%M:%S'),
**timeframe=bt.TimeFrame.Minutes,**

datetime=0,
open=1,
low=2,
high=3,
close=4,
volume=5,
openinterest=6)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM