Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Need help trying to understand the optimized API

Hello,
I'm learning about the API for Quantopian and I'm new to its particular manner of code. I'm good at python.
Here i put a simple code i tried to throw together from a sample and my own pair trading strategy. It has two pairs (abt,adbe) and (tmo, biib) that change their position when their spread is too close or too wide and what i try to do is change the weights for each. However it has a runtime error and I'm not sure why.
Im sure once i understand some of the basics of this api, i'll have this all under control, but i'd appreciate if someone could teach my why this isn't working with the quantopian api.
Thanks

"""
This algorithm defines a long-only equal weight portfolio and  
rebalances it at a user-specified frequency.  
"""

# Import the libraries we will use here  
import datetime  
import pandas as pd

#Here, we import the optimize API modules  
import quantopian.algorithm as opt  
from quantopian.optimize import TargetWeights


def initialize(context):  
    # In this example, we're looking at 9 sector ETFs.  
    context.security_list = symbols('abt', 'adbe', 'tmo','biib')

    # This is a dictionary of weights we'll populate and then feed into the optimizer in the rebalance function:  
    context.weights = {}  
    context.abt = sid(62)  
    context.adbe = sid(114)  
    context.tmo = sid(7493)  
    context.biib = sid(3806)

    # Rebalance every day (or the first trading day if it's a holiday).  
    # At 11AM ET, which is 1 hour and 30 minutes after market open.  
    schedule_function(rebalance,  
                      date_rules.week_start(days_offset=0),  
                      time_rules.market_open(hours = 1, minutes = 30))  


def rebalance(context, data):

    # Do the rebalance. Loop through each of the stocks and order to  
    # the target percentage.  If already at the target, this command  
    # doesn't do anything. A future improvement could be to set rebalance  
    # thresholds.  
    for sec in context.security_list:  
        if data.can_trade(sec):  
            context.weights[sec] = 0.99/len(context.security_list)  
    abt_av = np.mean(data.history(context.abt,'price',6,'1d'))  
    adbe_av = np.mean(data.history(context.adbe,'price',6,'1d'))  
    tmo_av = np.mean(data.history(context.tmo,'price',6,'1d'))  
    biib_av = np.mean(data.history(context.biib,'price',6,'1d'))  
    spread_av_12 = adbe_av - abt_av  
    spread_av_34 = biib_av - tmo_av  
    abt_curr = data.current(context.abt, 'price')  
    adbe_curr = data.current(context.adbe, 'price')  
    tmo_curr = data.current(context.tmo, 'price')  
    biib_curr = data.current(context.biib, 'price')  
    spread_curr_12 = adbe_curr - abt_curr  
    spread_curr_34 = biib_curr - tmo_curr  
    if spread_curr_12 > spread_av_12 *1.10:#detect a wide spread  
        print("wide: spread_avg, spread_curr: ",spread_avg,spread_curr)  
        context.weights['biib'] = 0  
        context.weights['tmo'] = .99 / 2  
    elif spread_curr_12 < spread_av_12 *.90:#detect a tight spread  
        print("tight: spread_avg, spread_curr: ",spread_avg,spread_curr)  
        context.weights['biib'] = .99 / 2  
        context.weights['tmo'] = 0  
    else:  
        pass  

    if spread_curr_34 > spread_av_34 *1.10:#detect a wide spread  
        print("wide: spread_avg, spread_curr: ",spread_avg,spread_curr)  
        context.weights['adbe'] = 0  
        context.weights['abt'] = .99 / 2  
    elif spread_curr_34 < spread_av_34 *.90:#detect a tight spread  
        print("tight: spread_avg, spread_curr: ",spread_avg,spread_curr)  
        context.weights['adbe'] = .99 / 2  
        context.weights['abt'] = 0  
    else:  
        pass  

    #Use order optimal portfolio to calculate and then order a portfolio with the TargetWeights objective (and for now, no constraints)  
    opt.order_optimal_portfolio(  
        objective=TargetWeights(context.weights),  
        constraints=[]  
    )

    # Get the current exchange time, in the exchange timezone  
    exchange_time = get_datetime('US/Eastern')  
    log.info("Rebalanced to target portfolio weights at %s" % str(exchange_time))  
1 response

The dict passed to the TargetWeights method needs to have security objects as the keys. You have the ticker symbols as the keys. So, as an example instead of this

        context.weights['abt'] = 0  

do this

        context.weights[context.abt] = 0  

This needs to be changed in several places in the algo. Generally Quantopian uses the security objects as indexes and keys and rarely uses the ticker symbols.

Attached is the algo with these changes. BTW, it's a good idea to attach a backtest to a post rather than simply pasting the text. Makes it easier for others to help debug.

Hope that helps.