# Trying to compute the average range of the last 10 daily bars?

My assumption is that I can loop through the object 'db' and compute the range for each day and append the range to a list. My code is not working though, what am I missing?

def init(self) : #, **params - if passing in parameters is desired
self.inPositionLong=0
self.inPositionShort=0
self.decvol=list()
self.avgrange=list()
self.earlyrangehigh=list()
self.earlyrangelow=list()
#pass

``````# called at the beginning of each instance
#def on_start(self, md, order, service, account) :
def on_start(self, md, order, service, account) :
db = md.bar.daily(start=-10,include_empty=False) # Get 10 Days of Daily Bars
for x in db :
range = x.high - x.low
self.avgrange = self.avgrange.append(range)
self.tendayavgrange = (sum(self.avgrange)/10)
print(self.tendayavgrange)
``````

• edited June 2018 Answer ✓

JL

What you are missing is what is actually in your object. Remember, the print statement is your friend.
When you ask for 10 bars of historical data you get just that.. open close high low volume timestamps etc etc etc 16 individual lists in total.
You are then looping through those 16 items.
You want to pull out just the high bars and the low bars.

Try the code below...

``````from cloudquant.interfaces import Strategy

class ten_day_range_question(Strategy):

@classmethod
def is_symbol_qualified(cls, symbol, md, service, account):
return symbol=="SPY"

def on_start(self, md, order, service, account) :

# Get 10 Days of Daily Bars
db = md.bar.daily(start=-10,include_empty=False)

# So the length of your db is 16, that is because there are 16 items in every bar. open high low close volume etc
print len(db)
print db # see

# So when you get to the loop, you are looping through the 16 items
for x in db :
print x,"\n"

# You can, however, pull out just the high and low lists
high=db.high
low=db.low
print "Highs :",len(high),high
print "Lows :",len(low),low

# we can then loop through one of these lists (if we have a high we will have a low)
# first we create our empty list
self.avgrange = []
print "\nA better loop:\n"
for x in range(len(high)) :
myrange = high[x] - low[x]
print x,high[x],low[x],myrange
self.avgrange.append(myrange)

print

# I would also use the length of the new list as your denom because it could be less than 10, best not to assume.
self.tendayavgrange = (sum(self.avgrange)/len(self.avgrange))

# but why loop when you could just do this?
altrange=(sum(high)-sum(low))/len(high)
print "My Range :",altrange

# average true range is what most people use.
print "Average True Range :",md.stat.atr

service.terminate()
``````