I want to implement a ranking of stocks based on talib.OBV "On Balance Volume"
I have implemented it using some long above a level and short below a level
however I want it to be done based on ranking.
Thanks in advance
I want to implement a ranking of stocks based on talib.OBV "On Balance Volume"
I have implemented it using some long above a level and short below a level
however I want it to be done based on ranking.
Thanks in advance
Try this:
def handle_data(context, data):
#set_nodata_policy(NoDataPolicy.LOG_ONLY)
days = 90
prices = history(bar_count=days, frequency='1d', field='price').dropna(axis=1)
volumes = history(bar_count=days, frequency='1d', field='volume').dropna(axis=1)
# Store each stock's OBV value in a dict
# obv = {'sid1': val1, 'sid2': val2, ...}
obv = {}
for stock in volumes:
obv[stock] = talib.OBV(prices[stock], volumes[stock])[-1]
# Rank obv values in ascending order (in a list of tuples)
# obv = [(sid1, val1), (sid2, val2), ...]
obv = sorted(obv.items(), key=lambda x: x[1])
# Go $10,000 long the top 10 stocks
for i in range(-10, 0):
amount = int(10000/data[obv[i][0]].price)
order(obv[i][0], amount)
log.info('entry %s %s' % (obv[i][0], amount))
# Go $10,000 short the bottom 10 stocks
for i in range(10):
amount = -int(10000/data[obv[i][0]].price)
order(obv[i][0], amount)
log.info('entry %s %s' % (obv[i][0], amount))