Newbie looking for help
I've made myself a indicator and a strategy, and I can see it buying and selling. I want to dig more into it to see how I can improve it by printing out the value of my indicator from inside my strategy, but anytime I try to print anything inside my strategy or indicator I get
<backtrader.linebuffer.LineBuffer object at 0x7feab75cf5f8>or something similar.
How do I properly print out the values so I can see then improve my strategy & indicator?
import backtrader as bt from indicators import efjay_indicator as ei class DevMomentum(bt.SignalStrategy): def __init__(self): ey = ei.EyIndicator(self.data) self.buy_sig = (ey > 0.45) self.sell_sig = (ey < 0.45) def next(self): if not self.position: if self.buy_sig: self.buy(size=1000) else: if self.sell_sig: self.sell(size=1000)
You can do it like this:
This will give you the most recent value. Use
[-1]for the second most recent and so on. (This is a little different to python lists where [-1] will give you the last item. I think there is a note on this in the docs
class TestStrategy(bt.Strategy): def log(self, txt, dt=None): ''' Logging function for this strategy''' dt = dt or self.datas.datetime.date(0) print('%s, %s' % (dt.isoformat(), txt)) def __init__(self): # Keep a reference to the "close" line in the data dataseries self.dataclose = self.datas.close def next(self): # Simply log the closing price of the series from the reference self.log('Close, %.2f' % self.dataclose)
import backtrader as bt import math class eIndicator(bt.Indicator): lines = ('e',) params = (('period', 15),) def __init__(self): self.e_price_avg = bt.indicators.ExponentialMovingAverage( self.data, period=self.params.period ) self.e_price_avg_2 = bt.indicators.ExponentialMovingAverage( self.data, period=self.params.period * 2 ) self.price_rev = (self.e_price_avg_2 - self.e_price_avg) / self.e_price_avg self.lines.e = self.price_rev def next(self): pass
Okay that works inside my strategy to see the line value! Perfect.
How about inside my indicator (shown above), how can I print the e_price_avg and e_price_avg2 for further info. Thanks! I'm just trying to calculate the percent different between two EMAs. Is this even the proper way to do it? I made it by looking at the Indicator development page but I may have misunderstood some things.
@backtrader Ahh. I did try that but I did it inside of the init function, but tried inside the next function this time and it worked. Thanks :)
You then need to read this: Docs - Platform Concepts and see
@backtrader Just what I needed, didn't realize this existed. Thanks again! Will be sure to scour the documentation more before any other questions I may have.