Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Please help me. I am new - compile error

Hi guys I cant even compile my code because i have so many errors. Could someone please take a look at it. Thanks so much!!!

import pandas as pd  
import numpy as np  
import datetime  
import math  
import talib  
from datetime import timedelta


#### Variables to change for your own liking #################  
def initialize(context):  
#### Variables to change for your own liking #################  
    #the constant for portfolio turnover rate  
    #number of stocks to pass through the fundamental screener  
    context.num_screener_start = 500  
    context.num_screener_end = 50  
    #number of stocks in portfolio at any time  
    context.num_stock = 20

    #################################################################  
    #month counter for holding period logic.  
    context.holding_months = 12  
    #context.month_count = context.holding_months  
    context.month_count = context.holding_months  
    context.target_leverage = 0.99

    context.hedge_symbol = sid(21519) #IWM  
    context.hedge_ratio = 0.40  

    schedule_function(rebalance, date_rules.month_end(7), time_rules.market_close(hours=2, minutes=30))


def before_trading_start(context,data):  
    """  
      Called before the start of each trading day.  
      It updates our universe with the  
      securities and values found from fetch_fundamentals.  
    """  
    #this code prevents query every day  
    if context.month_count != context.holding_months:  
        return  
    fundamental_df = get_fundamentals(  
        query(  
            # put your query in here by typing "fundamentals."  
            fundamentals.valuation_ratios.ev_to_ebitda,  
            fundamentals.valuation_ratios.pb_ratio,  
            fundamentals.valuation_ratios.ps_ratio,  
            fundamentals.valuation_ratios.pcf_ratio,  
            fundamentals.valuation_ratios.pe_ratio,  
            fundamentals.valuation_ratios.total_yield,  
            fundamentals.valuation_ratios.book_value_yield,  
            fundamentals.earnings_ratios.diluted_cont_eps_growth,  
            fundamentals.earnings_ratios.diluted_eps_growth,  
            fundamentals.earnings_ratios.dps_growth,  
            fundamentals.earnings_report.diluted_eps,  
            fundamentals.operation_ratios.roe,  
            fundamentals.valuation_ratios.payout_ratio,  
            fundamentals.valuation_ratios.sustainable_growth_rate  
        )  
        .filter(fundamentals.valuation.market_cap > 10e6)  
        .filter(fundamentals.income_statement.ebit > 0)  
        .filter(fundamentals.valuation_ratios.ev_to_ebitda > 0)  
        .filter(fundamentals.valuation.shares_outstanding != None)  
        .filter(fundamentals.valuation.market_cap != None)  
        .filter(fundamentals.earnings_report.diluted_eps>0)  
        .order_by(fundamentals.valuation_ratios.ev_to_ebitda.asc())  
        .limit(context.num_screener_end)  
    )  
    for stock in fundamental_df:  
        bookValue = fundamental_df[stock]['book_value_yield']  
        discRate = 0.05  
        eps1 = fundamental_df[stock]['diluted_eps']  
        eps2 = fundamental_df[stock]['diluted_eps']*fundamental_df[stock]['diluted_eps_growth']  
        epsGrowth = fundamental_df[stock]['diluted_cont_eps_growth']  
        divPayout = fundamental_df[stock]['payout_ratio']  
        avgROE = fundamental_df[stock]['roe']  




        bookValueOrig = bookValue # original book value  
       #Year 1  
        roe = float(eps1)/bookValue #find return on equity year 1  
        pbcum = 1 +(roe - discRate) / (1+ discRate) #find the pbcum for year 1  
        cg =1 #cumulated growth  
   #Year 2  
        bookValue = bookValue + (eps1 * (1 - divPayout)) #find book value year 2  
        cg = cg * (1 + (1 - divPayout) * roe)  #find cumulated growth year 2  
        roe = eps2 / bookValue  #find the ROE in year 2  
        pbcum = ((roe - discRate) * cg)/ (1 + discRate)**2 + pbcum#find the pbcum in year 2  
        feps = eps2 #assign  


        for x in range(3, 8): #for loop from year 3 to 8  
          bookValue = (bookValue + feps * (1 - divPayout)) #assign new book value  
          feps = feps * (1 + epsGrowth); #new eps  
          cg = cg * (1 + (1 - divPayout) * roe) #new cumulated growth  
          roe = feps / bookValue; #new return on equity  
          pbcum = (roe - discRate) * cg / (1 + discRate)** x + pbcum #new pbcum  

        ROEY8 = roe #assign new ROE for years 9 onwards  
        for x in range(8, 16): #for loop from year 9 to 16  
          cg = cg * (1 + (1 - divPayout) * roe) #new cumulated growth  
          roe = roe - ((ROEY8 - avgROE) / 8) #new return on equity  
          pbcum = (roe - discRate) * cg / (1 + discRate)**x + pbcum #new pbcum  
#find morningstar value  
        context.aspectmodelnew = bookValueOrig * (pbcum + ((roe - discRate) * cg) /(discRate * ((1 + discRate)**15)))  
        pass  
#Pull current data  
#checks if the stocks data is higher or lower, depending on which it will short or long  


    # Filter out only stocks that fits in criteria  
    context.stocks = [stock for stock in fundamental_df]  
    # Update context.fundamental_df with the securities that we need  
    context.fundamental_df = fundamental_df[context.stocks]

    update_universe(context.fundamental_df.columns.values)  
def ranking(context,data):  
    pricelist = {}  
    for stock in context.fundamental_df:  
        Current = data[stock].price  
#        newPrice = Current - context.aspectmodelnew  
        perc = (context.aspectmodelnew-Current)/Current  
        pricelist.update({stock,perc})  
        #pricelist[stock] = perc  
        sorted(pricelist)  
        print "%.2f" % pricelist  
        print "%.2f" %perc  
        context.upper_percentile = np.percentile(perc, 80)  
        pass  
        #print(perc)  
       #pricelist.update({context.stock,perc})  


        #pricelist.update(map(stock,perc))  
        #sorted(pricelist)  
        #buy = pricelist.itervalues().next()  
        #buy = pricelist.values.itervalues()  
        #print buy  
    for stock,perc in pricelist.items():  
       print(stock)  
       print(perc)  
    pricelist.clear()  
#    newPrice = 0  
def rebalance(context, data):

    # track how many positions we're holding  
    #pricelist = {}  
    if context.month_count >= context.holding_months:  
        context.month_count = 1  
    else:  
        context.month_count += 1  
        return  
    # Exit all positions before starting new ones  
    for stock in context.portfolio.positions:  
        if stock not in context.fundamental_df:  
            order_target_percent(stock, 0)  




    # Create weights for each stock  
    weight = create_weights(context, context.stocks)

    # Rebalance all stocks to target weights


    for stock in context.fundamental_df:  
        if weight != 0 and stock in data:  
            Current = data[stock].price 

            #newlist = sorted(pricelist, key=itemgetter(newPrice))  
            if Current <  context.aspectmodelnew*0.8 :  
                print(context.buy)  
                print "%.2f" %context.pricelist  
                print(stock)  
                order_target_percent(context.upper_percentile,weight) # Long  
            #elif Current > context.aspectmodelnew*1.2:  
           #    order_target_percent(stock, -weight) # Short

            else:  
                order_target_percent(stock, 0)  
            #order_target_percent(stock, weight)  

    record(leverage=context.account.leverage)        

#def calculate(context, data):  


def handle_data (context,data):

    bookValue = fundamental_df[stock]['book_value_yield']  
    discRate = 0.05  
    eps1 = fundamental_df[stock]['diluted_eps']  
    eps2 = fundamental_df[stock]['diluted_eps']*fundamental_df[stock]  ['diluted_eps_growth']  
    epsGrowth = fundamental_df[stock]['diluted_cont_eps_growth']  
    divpayout = fundamental_df[stock]['payout_ratio']  
    avgROE = fundamental_df[stock]['roe']  




    bookValueOrig = bookValue # original book value  
  #Year 1  
    roe = float(eps1)/bookValue #find return on equity year 1  
    pbcum = 1 +(roe - discRate) / (1+ discRate) #find the pbcum for year 1  
    cg =1 #cumulated growth  
  #Year 2  
    bookValue = bookValue + (eps1 * (1 - divPayout)) #find book value year 2  
    cg = cg * (1 + (1 - divPayout) * roe)  #find cumulated growth year 2  
    roe = eps2 / bookValue  #find the ROE in year 2  
    pbcum = ((roe - discRate) * cg)/ (1 + discRate)**2 + pbcum#find the pbcum in year 2  
    feps = eps2 #assign  


    for x in range(3, 8): #for loop from year 3 to 8  
        bookValue = (bookValue + feps * (1 - divPayout)) #assign new book value  
        feps = feps * (1 + epsGrowth); #new eps  
        cg = cg * (1 + (1 - divPayout) * roe) #new cumulated growth  
        roe = feps / bookValue; #new return on equity  
        pbcum = (roe - discRate) * cg / (1 + discRate)** x + pbcum #new pbcum  

    ROEY8 = roe #assign new ROE for years 9 onwards  
    for x in range(8, 16): #for loop from year 9 to 16  
        cg = cg * (1 + (1 - divPayout) * roe) #new cumulated growth  
        roe = roe - ((ROEY8 - avgRoe) / 8) #new return on equity  
        pbcum = (roe - discRate) * cg / (1 + discRate)**x + pbcum #new pbcum  
#find morningstar value  
    aspectModelNew = bookValueOrig * (pbcum + ((roe - discRate) * cg) /(discRate * ((1 + discRate)**15)))  
#Pull current data  
    Current = data[context.stock].price  
#checks if the stocks data is higher or lower, depending on which it will short or long


def create_weights(context, stock):  
    """  
        Takes in a list of securities and weights them all equally  
    """  
    if len(stock) == 0:  
        return 0  
    else:  
        weight = 0.99/len(stock)  
        return weight  
    record(leverage=context.account.leverage)  
1 response

What errors are popping up?