Back to Community
Help with error on 1st algorithm

Thanks to Grant, Dan and Dennis for helping me get this far.

I have an error on line 38 that I cannot quite figure out.

I want my algorithm to buy if the current price is between open + .10 and open + .20. Then sell if price is below open - .20 or the start of a new day.

def initialize(context):  
    context.nflx =sid(23709)  

    context.initialize = True  
    context.event_day = 0  
    context.first_day = False  
    context.new_day = False  
    context.day_counter = 0  
    context.bought = False  
     # setup list of stocks to trade (or call set_universe)  
    context.stocks = [sid(23709), sid(24791)] #NFLX, CSTR  
    #set_universe(universe.DollarVolumeUniverse(98.0,99.0))  
def handle_data(context, data):  
    event_datetime = data[context.stocks[0]].datetime  
    event_day = data[context.stocks[0]].datetime.day  
    if context.initialize:  
        context.event_day = event_day  
        context.initialize = False  
        context.first_day = True  
    if event_day != context.event_day:  
        context.new_day = True  
        order(context.nflx,-100)  
        context.bought = False  
    else:  
        context.new_day = False  
    if context.first_day or context.new_day:  
        context.day_counter = context.day_counter + 1  
        price = data[context.nflx].price  
     if price + .10 <= data[context.nflx].price <= price + .20:  
        order(context.nflx,100)  
        context.bought = True  
        print event_datetime  
        print 'Order submitted'  
      if context.bought = True  
      if data[context.nflx].price <= price - .20:  
        order(context.nflx,-100)  
        context.bought = False  

    context.first_day = False  
    context.event_day = event_day  
6 responses

Hi Chuck,

I don't have time now to tinker with it, but perhaps you could try commenting out sections of code until you can get it to run. Then you can run a full backtest and post the code here (with the "Add Backtest" button). It'll make it easier to debug, especially any problem with nesting of if statements.

Also, which line is causing an error? Please copy it here, rather than referring to the line number.

Grant

Hi Chuck,

Not entirely sure how your algorithm is supposed to work, but on this section:

    if context.first_day or context.new_day:  
        context.day_counter = context.day_counter + 1  
        price = data[context.nflx].price  
     if price + .10 <= data[context.nflx].price <= price + .20:  
        order(context.nflx,100)  
        context.bought = True  

If "context.first_day or context.new_day" is false, then "price" is never initialized, so the next statement ("if price + .10...") will be checking an uninitialized variable. If the "price = data[context.nflx].price..." assignment happens outside of the if block, then the error seems to go away.

Also, this section:
if context.bought = True if data[context.nflx].price <= price - .20: order(context.nflx,-100)

"if context.bought = True" is kind of floating in the ether - either it needs a colon (and a statement to execute), or you should combine it with the following if statement using "and".

Hope that helps!

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.

Thanks John and Grant,

I noticed both these errors as I was commenting out the errors.

I am going to give it another go from scratch line by line.

How would I test for my openp variable?

Seem to be getting an error on the line where I am comparing that value to price before openp is assigned a value.

Clone Algorithm
13
Loading...
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month

def initialize(context):
    
    context.stocks = [sid(23709)] #NFLX
    
    context.initialize = True
    context.event_day = 0
    context.first_day = False
    context.new_day = False
    context.day_counter = 0
    

    


def handle_data(context, data):
   
    
    event_datetime = data[context.stocks[0]].datetime    
    event_day = data[context.stocks[0]].datetime.day
    
    if context.initialize:
        context.event_day = event_day
        context.initialize = False
        context.first_day = True
    
    if event_day != context.event_day:
        context.new_day = True
    else:
        context.new_day = False
        
    if context.first_day or context.new_day:
        context.day_counter = context.day_counter + 1
        
        
        print event_datetime
       
        openp = data[context.stocks[0]].price
        
        print openp
        log.info("New day, open price:  {p} ".format(p=openp))
    else:
        price = data[context.stocks[0]].price
        
        log.info("Current time {t}, price:  {p} ".format(t=event_datetime, p=price))
        
        if price > openp + .10:
            print "buy"
    context.first_day = False
    context.event_day = event_day
There was a runtime error.

Try this - I moved "openp" from a local variable (which was getting lost on each successive call to handle_data) to stuffing it into the more persistent "context" object. This preserves it for every iteration.

def handle_data(context, data):

    event_datetime = data[context.stocks[0]].datetime  
    event_day = data[context.stocks[0]].datetime.day  
    # Called only on the very first run.  
    if context.initialize:  
        context.event_day = event_day  
        context.initialize = False  
        context.first_day = True  
    # True at the turn of each new trading day.  
    if event_day != context.event_day:  
        context.new_day = True  
    else:  
        context.new_day = False  
    # If this is the very first event of the day,  
    # mark the open price  
    if context.first_day or context.new_day:  
        context.day_counter = context.day_counter + 1  
        print event_datetime  
        context.openp = data[context.stocks[0]].price  
        print context.openp  
        log.info("New day, open price:  {p} ".format(p=context.openp))  
    else:  
        price = data[context.stocks[0]].price  
        log.info("Current time {t}, price:  {p} ".format(t=event_datetime, p=price))  
        if price > context.openp + .10:  
            print "buy"  
    context.first_day = False  
    context.event_day = event_day  

Thanks John.

That put me on the right track! Now to add more conditions to this algorithm!