Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
What is the error in this program, after backtest, it returns "key error 1"

""" This is a template algorithm on Quantopian for you to adapt and fill in.
""" from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline import Pipeline
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import AverageDollarVolume
from quantopian.pipeline.filters.morningstar import Q500US
attach_pipeline

def handle_data(context, data):

context.aapl = sid(24)  
context.spy = sid(8554)  
context.googl = sid(46631)  
context.agn = sid(205)  
context.infn = sid(33979)  
stocks= [sid(24), sid(8554), sid(46631), sid(205), sid(33979)]  
context.stocks=stocks  
histofstocks= data.history(stocks, 'price', 30, '1d')  
currentpriceofstocks= data.history(stocks, 'price', 1, '1m')  
#log.info ('30d max  ' + str(histofaapl.max()) +'\r\n')  
#log.info ('curprice ' + str(aaplprice[-1]) + '\r\n')  
if histofstocks.min() > currentpriceofstocks[-1] and data.can_trade(stocks):  
    order_target_percent(stocks, .05)

record(leverage=context.account.leverage)  

def make_pipeline():
"""
A function to create our dynamic stock selector (pipeline). Documentation on
pipeline can be found here: https://www.quantopian.com/help#pipeline-title
"""

# Base universe set to the Q500US  
base_universe = Q500US()

# Factor of yesterday's close price.  
yesterday_close = USEquityPricing.close.latest  

pipe = Pipeline(  
    screen = base_universe,  
    columns = {  
        'close': yesterday_close,  
    }  
)  
return pipe  

def before_trading_start(context, data):
results = pipeline_output('my_pipeline')
print results.head(5)
"""
Called every day before market open.
"""
#I MAY NEED THIS context.output = pipeline_output('my_pipeline')

# These are the securities that we are interested in trading each day.  
#COULD NEED THIS context.security_list = context.output.index  

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

def my_rebalance(context,data):
"""
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 initialize(context):
attach_pipeline(make_pipeline(), 'my_pipeline')
pipe= Pipeline()

context.aapl = sid(24)  
context.spy = sid(8554)  
context.googl = sid(46631)  
context.agn = sid(205)  
context.infn = sid(33979)  
stocks= ['aapl, goog, agn, infn']

"""  
Called once at the start of the algorithm.  
"""  
# Rebalance every day, 1 hour after market open.  
schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(hours=1))  

# 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] )

11 responses

Please help with this

One problem is with the code

if histofstocks.min() > currentpriceofstocks[-1] and data.can_trade(stocks):  
    order_target_percent(stocks, .05)

Your 'histofstocks' and 'currentpriceofstocks' are pandas dataframes. The rows are the dates and the columns are the equity objects. The values are the prices. You will need to narrow the 'histofstocks' and 'currentpriceofstocks' to a specific equity. Maybe some code like below?

for stock in stocks:  
    if histofstocks.ix[0:-1, stock].min() > currentpriceofstocks.ix[-1, stock] and data.can_trade(stock):  
        order_target_percent(stock, .05)

Also notice 'histofstocks.ix[0:-1, stock]'. You'll need to exclude the most recent data point (hence the index of [0:-1]). Otherwise that inequality will never be true. (It actually returns a value every once in awhile but I believe only because it's comparing two floating point numbers which don't exactly match).

Charles,
You may try this:

def initialize(context):  
    schedule_function(my_rebalance, date_rules.every_day(), time_rules.market_open(hours=1)) 

def my_rebalance(context,data):  
    stocks = symbols('AAPL','SPY','AAPL','GOOG','AGN','INFN',)  

    for stock in stocks:  
        if get_open_orders(stock): return  
        hist= data.history(stock, 'price', 30, '1d')  
        if  hist[-1] < hist[0:-2].min() and data.can_trade(stock):  
            order_target_percent(stock, 0.2 )  
        elif hist[-1] >= hist[0:-2].max()  and data.can_trade(stock):  
            order_target(stock, 0)

    record(leverage=context.account.leverage)  

Thank you both very much, sorry, i just found out how to access my posts. Yeah, Vladimir, that worked very well thank you very much.

how do i make it not go above x leverage, (how much leverage for competitions is allowed

how do i sell, order negative shares? or is that short selling?

also could i substitute the stock array for like, say the q500 thing

Vladimir, did you put a sell function in their? because on the backtest leverage goes to zero sometimes

elif hist[-1] >= hist[0:-2].max()  and data.can_trade(stock):  
            order_target(stock, 0)  

is order to sell.

aha! thanks for that

how do i maintain a legal leverage?