Your volume for the last period is the volume for the minute - not the day as you expect. Which will never be greater than the average daily volume.
Try this:
import talib
import numpy
macdShort = 12; macdLong = 26; macdSignal = 9
volMAPeriods = 20
def initialize(context):
set_symbol_lookup_date('2013-01-01')
context.stocks = symbols('DD', 'MRK', 'KO', 'MMM')
context.init_cash = context.portfolio.cash
schedule_function(func=HandleDataScheduled,
date_rule=date_rules.every_day(),
time_rule=time_rules.market_open(hours=0, minutes=1))
def handle_data(context, data):
pass
def HandleDataScheduled(context, data):
# Historical data for the stocks
prices = history(macdLong + macdSignal + 1, '1d', 'close_price')
volumes = history(volMAPeriods + 1, '1d', 'volume').ffill().bfill()
eligibleStocks = []
inEligibleStocks = []
for stock in context.stocks:
closes = numpy.array(prices[stock].values.tolist())
macdIndicator = talib.MACD(closes, macdShort, macdLong, macdSignal)
macd = macdIndicator[0][-1]
signal = macdIndicator[1][-1]
currentPosition = context.portfolio.positions[stock].amount
stockVolumes = volumes[stock].values.tolist()[0:-1]
stockVolume = stockVolumes[-1]
volEMA = talib.EMA(numpy.array(stockVolumes), timeperiod = volMAPeriods)[-1]
### New or continuation signal
if (macd < signal and stockVolume > volEMA):
eligibleStocks.append(stock)
### Exit signal
elif (macd > signal and currentPosition > 0 and stockVolume > volEMA):
inEligibleStocks.append(stock)
### Maintain position
elif (currentPosition > 0):
eligibleStocks.append(stock)
eligibleCount = float(len(eligibleStocks))
for stock in eligibleStocks:
order_target_percent(stock, 1.0 / eligibleCount)
for stock in inEligibleStocks:
order_target(stock, 0)
record(Leverage = context.account.leverage, Cash = context.portfolio.cash)