Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Trading Help

I am trying to just make a simple trading decision......whoever has the biggest DIFFERENCE from the CustomFactor output I want to buy 20 shares of that stock (its either AAPL or IBM) and If I own one i want to sell the other and I want to make this decision every day. Where am I going wrong??

class Last_Close_30(CustomFactor):

    # output (yesterdays price, average projection of tomorrows price, difference of yesterdays and average, standard deviation)  
    out.yesterday[:] = close[-1]  
    out.projection[:] = average  
    out.difference[:] = difference  
    out.standard[:] = std_mc  

def initialize(context):

# Rebalance every day  
schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open())  

# Record tracking variables at the end of each day.  
schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())  


# Create our dynamic stock selector.  
attach_pipeline(make_pipeline(), 'my_pipeline')  

def make_pipeline():

pipe = Pipeline()  

#base_universe = Q500US()  

# make mask to have desired stocks we want  
aapl = StaticAssets(symbols('AAPL','IBM'))  

#call Last_Close_30 Class  
projection_price = Last_Close_30(window_length = 30, mask = aapl)  

# top 10 stocks with highest positive difference and low std  
# highest = projection_price.difference.top(10)  

# Add the desired values to our pipe.  
#pipe.add(highest, 'highest 10')  


pipe.add(projection_price, 'projection')  

pipe.set_screen(aapl)  
#pipe.set_screen(base_universe)  

return pipe  

def before_trading_start(context, data):

# Called every day before market open.  

context.output = pipeline_output('my_pipeline')  

print context.output  

def my_assign_weights(context, data):
"""
Assign weights to securities that we want to order.
"""
pass

def my_rebalance(context,data):
context.aapl = sid(24)
context.ibm = sid(37)

# if ibm better then apple hold one share vice  
if aapl.difference > ibm.difference  
    order_target(context.aapl, 20)  
    order_target(context.ibm, 0)  
else  
    order_target(context.aapl, 0)  
    order_target(context.ibm, 20)  

"""  
Execute orders according to our schedule_function() timing.  
"""  
pass  
3 responses

If this is the complete code, it looks like you need to put the contents of your CustomFactor in the compute function (see the tutorial lesson on CustomFactors). If not, it would be helpful if you could attach a backtest, which includes the code.

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.

Yea sorry I didn't put all the code! Here it is! The rebalance part isnt working

class Last_Close_30(CustomFactor):
"""
Gets the latest prices for each asset
"""
inputs = [USEquityPricing.close]
window_length = 30

outputs = ['yesterday','projection','difference','standard']  
def compute(self, today, assets, out, close):  

    a = -1  
    b = -2  
    look_back = 0  
    sample = []  

    # gets log return from last 30 close prices and puts in array  
    for look_back in range(0,29):  
        #print str(close[a])+" "+str(close[b])  
        #print close[a]/close[b]  
        logs = (np.log(close[a]/close[b]))  
        sample.append(logs)  
        a = a-1  
        b = b-1  
    #print sample  

    # project 10 time steps ahead and make projected price 10 days out  
    # that process done 1000 times (monte carlo)  

    monte_carlo = []  

    for num in range(0,1000):  
        tomorrow_projection = close[-1]  
        for count in range(0, 10):  
            random_number = random.choice(sample)  
            tomorrow_projection = tomorrow_projection * np.exp(random_number)  
        monte_carlo.append(tomorrow_projection)  

    # average close prices for each stock  
    average = (sum(monte_carlo))/1000  

    # difference from average  
    difference = average - close[-1]  

    std_mc = np.std(monte_carlo,axis = 0)  
    #print std_mc  

    # output (yesterdays price, average projection of tomorrows price, difference of yesterdays and average, standard deviation)  
    out.yesterday[:] = close[-1]  
    out.projection[:] = average  
    out.difference[:] = difference  
    out.standard[:] = std_mc  

def initialize(context):

# Rebalance every day  
schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open())  

# Record tracking variables at the end of each day.  
schedule_function(my_record_vars, date_rules.every_day(), time_rules.market_close())  


# Create our dynamic stock selector.  
attach_pipeline(make_pipeline(), 'my_pipeline')  

def make_pipeline():

pipe = Pipeline()  

#base_universe = Q500US()  

# make mask to have desired stocks we want  
stocks = StaticAssets(symbols('AAPL','IBM'))  

#call Last_Close_30 Class  
projection_price = Last_Close_30(window_length = 30, mask = stocks)  

# top 10 stocks with highest positive difference and low std  
# highest = projection_price.difference.top(10)  

# Add the desired values to our pipe.  
#pipe.add(highest, 'highest 10')  


pipe.add(projection_price, 'projection')  

pipe.set_screen(stocks)  
#pipe.set_screen(base_universe)  

return pipe  

def before_trading_start(context, data):

# Called every day before market open.  

context.output = pipeline_output('my_pipeline')  

print context.output  

def my_assign_weights(context, data):
"""
Assign weights to securities that we want to order.
"""
pass

def my_rebalance(context,data):

context.aapl = sid(24)  
context.ibm = sid(37)  

projection_price_aapl = Last_Close_30(window_length = 30, mask = context.aapl)  

projection_price_ibm = Last_Close_30(window_length = 30, mask = context.ibm)  

difference_aapl = projection_price_aapl.difference  
difference_ibm = projection_price_ibm.difference  

# if ibm better then apple hold one share vice  
if (difference_aapl > difference_ibm):  
    order_target(context.aapl, 20)  
    order_target(context.ibm, 0)  
elif (difference_ibm > difference_aapl):  
    order_target(context.aapl, 0)  
    order_target(context.ibm, 20)  

"""  
Execute orders according to our schedule_function() timing.  
"""  
pass  

def my_record_vars(context, data):
"""
Plot variables at the end of each day.
"""
pass

def handle_data(context,data):
pass

Could you run a full backtest and attach it to this post? As well, could you give a description of the problem? For example, if you're getting an error, copying the error message would be helpful. If it's a logic error, it would be helpful if you could explain the output you expect and what you're observing.

A general tip on custom factors is that you want to perform computations in a vectorized fashion instead of in a for loop. I also noticed that you're using random number generation without a seed, which isn't supported in live or paper trading.