Hey guys!! I am trying to develop an algorithm that buys on technical data, and rebalances weekly. I cannot figure out how to get my stocks from the handle data method into the rebalance method.
#I am buying etfs weekly depending on last week's growth, and if they are above their moving averages.
def initialize(context):
context.secs = [ sid(19662), # XLY Consumer Discrectionary SPDR Fund
sid(19656), # XLF Financial SPDR Fund
sid(19658), # XLK Technology SPDR Fund
sid(19655), # XLE Energy SPDR Fund
sid(19661), # XLV Health Care SPRD Fund
sid(19657), # XLI Industrial SPDR Fund
sid(19659), # XLP Consumer Staples SPDR Fund
sid(19654), # XLB Materials SPDR Fund
sid(19660) ] # XLU Utilities SPRD Fund
context.spy = sid(8554)
schedule_function(rebalance,date_rules.week_start(),time_rules.market_close())
context.buy=[]
def rebalance(context,data):
if stock in context.portfolio.positions:
order_target_percent(context.secs,0)
count=len(buy) #count how many stocks it will order
if count==0:
return
else:
purchase=.90/count
for stock in context.buy:
order_target_percent(context.secs,purchase)
def handle_data(context,data):
context.buy=[]
for stock in context.secs:
price_history=history(7,'1d','price')
pct_change=((price_history.iloc[-7]-price_history.iloc[-1])/ price_history.iloc[-1])*100
pct_change = pct_change.dropna()
if pct_change<0: #If last week lost value, we wil not buy this etf.
return
etf_price=data[context.secs].close_price
etf_ma40=data[context.secs].mavg(40)
spy_price=data[context.spy].close_price
spy_ma40=data[context.spy].mavg(40)
if etf_price>etf_ma40 and spy_price>spy_ma40: #If both the SPY and ETF are greater than there average then we will buy the stock.
context.buy.append(context.secs)
rebalance(context,data) #trying to get my stocks from buy into the rebalance