Hi,
New guy here. I'm having a hard time figuring out how to buy a basket of stocks based on an ETF's price. As an example, say I want to buy AAPL, CRM and VOD when the current price of QQQ crosses the 50 day MAVG of QQQ. And then sell all shares when it goes below the MAVG. This is what I have so far, and it isn't working. Thanks in advance...
#############################################
def initialize(context):
context.qqq = symbol('QQQ')
context.aapl = symbol('AAPL')
context.crm = symbol('CRM')
context.vod = symbol('VOD')
set_benchmark(sid(19920)) # QQQ
def handle_data(context, data):
average_price = data[context.qqq].mavg(50)
current_price = data[context.qqq].price
cash = context.portfolio.cash
if current_price > 1.003*average_price and cash > current_price:
# Need to know how many shares we can buy
number_of_shares = int(cash/current_price)
# Place the buy order (positive means buy, negative means sell)
order_percent(symbol('AAPL'), .333)(symbol('CRM'), .333)(symbol('VOD'), .334)
elif current_price < 0.997*average_price:
# Sell all of our shares by setting the target position to zero
order_target(symbol('AAPL'), 0)(symbol('CRM'), 0)(symbol('VOD'), 0)