2 things I'm having trouble with in this alg and 1 question::
1) Average Volume, is this the right way to do it.
2) I'm getting an error on the boolean indicators, open_long_position and open_short_position. Im trying to avoid taking another position if I have one already.
3) For set_universe, is it possible to filter the stock selection based on prices, i.e., stocks between 1 and 10 dollars for instance, or does that have to be done as in if statement in the handle_data loop?
# Put any initialization logic here. The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
set_universe(universe.DollarVolumeUniverse(98, 100))
# Will be called on every trade event for the securities you specify.
def handle_data(context, data):
#track the volume history for 3 days
volume_history = history(bar_count=50, frequency='1d', field='volume')
# average_volume = sum(volume_history)/50 (getting an error here)
#track the price history for 3 days
price_history = history(bar_count=4, frequency='1d', field='price')
# get close price history
for stock in data:
# Moving Averages - http://www.forexonlinetradingsystems.info/simple-systems/triple-moving-averages-crossover
slow_ma = data[stock].mavg(50)
medium_ma = data[stock].mavg(25)
fast_ma = data[stock].mavg(10)
# volume_1 = volume_history[-1]
if open_long_position is None:
open_long_position = False
if open_short_position is None:
open_short_position = False
# Open Long Position
if fast_ma>medium_ma and fast_ma>slow_ma and context.portfolio.positions[stock]==0:
order_target(stock, 100)
open_long_position = true
log.info("Open Long Position: " + str(stock))
# Close Long Position
if fast_ma<=medium_ma and context.portfolio.positions[stock]>0 and open_long_position==True and open_short_position==False:
order_target(stock, 0)
open_long_position = false
log.info("Close Long Position: " + str(stock))
# Open Short Position
if fast_ma<medium_ma and fast_moving_average<slow_moving_average and context.portfolio.positions[stock]==0:
order_target(stock, -100)
open_short_position = true
log.info("Open Short Position: " + str(stock))
# Cover Short Position
if fast_ma>=medium_ma and context.portfolio.positions[stock]>0 and open_short_position==True and open_long_position==False:
order_target(stock, 0)
open_short_position = false
log.info("Cover Short Position: " + str(stock))
record(SMA=slow_ma,MMA=medium_ma,FMA=fast_ma)