Back to Community
Passing through different methods

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  
3 responses
#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

If you are just doing your rebalance weekly, then handle_data() can just be a "pass" and you can have all of your logic in your rebalance() function. You don't need to pass any data back and forth. In pseudocode it might look like this:


def initialize(context):  
    context.secs =   [ sid list ]  
    schedule_function(rebalance,date_rules.week_start(),time_rules.market_close())  
    context.buy=[]  
def rebalance(context,data):  
   if good:  
        buy  
  if bad:  
        sell  

def handle_data(context,data):  
    pass  

If you do have things you need to do in handle_data(), the context object is how you pass it back and forth.

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Can I upload all of the same talib imports like I did in the handle_data method? I wanted to see if I could code something that used more than initialize and handle data. When is a better time to use other functions?