Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
ERROR: Computing the 1 period simple return

Hello,

I'm trying to compute the 1 period simple return, but I'm getting the following error:
15 Error Runtime exception: IndexError: index 27796 is out of bounds for axis 0 with size 10

Any ideas on what I'm doing wrong? Thank you in advance.

Here is the code:

import numpy as np

def initialize(context):  
    # http://money.usnews.com/funds/etfs/rankings/small-cap-funds  
    context.stocks = [sid(27796),sid(33412),sid(38902),sid(21508),sid(39458),sid(25899),sid(40143),sid(21519),sid(39143),sid(26449)]  
    context.m = len(context.stocks)  
def handle_data(context, data):  
    loss = np.zeros(context.m)  
    price_history = history(bar_count=2, frequency='1d', field='price')  
    for s in context.stocks:  
        prev_bar = price_history[s][-2]  
        curr_bar = price_history[s][-1]  
        loss[s] = curr_bar/prev_bar - 1  
4 responses

Amir,

I got this to run. I think it computes what you want:

def initialize(context):  
    # http://money.usnews.com/funds/etfs/rankings/small-cap-funds  
    context.stocks = [sid(27796),sid(33412),sid(38902),sid(21508),sid(39458),sid(25899),sid(40143),sid(21519),sid(39143),sid(26449)]  
def handle_data(context, data):  
    price_history = history(bar_count=2, frequency='1d', field='price')  
    loss = {}  
    for s in context.stocks:  
        prev_bar = price_history[s.sid][-2]  
        curr_bar = price_history[s.sid][-1]  
        loss[s] = curr_bar/prev_bar - 1  
    for s in context.stocks:  
        print loss[s]  

If you prefer to store the loss in a numpy ndarray, it is doable too. Just let me know.

Grant

Hi Grant,

No. I don't need numpy at all. It was in the code I was using as a baseline.

Thank you for your reply,

Amir

From the FAQ, it seems that prev_bar will give me the value for the previous day's bar. How can I get the value for the previous minute?

Amir,

Here's one way:

import pandas as pd

window = 2

def initialize(context):  
# http://money.usnews.com/funds/etfs/rankings/small-cap-funds  
    context.stocks = [sid(27796),sid(33412),sid(38902),sid(21508),sid(39458),sid(25899),sid(40143),sid(21519),sid(39143),sid(26449)]  
    context.prices = pd.DataFrame()  
def handle_data(context, data):  
    prices = history(1,'1d','price')  
    context.prices = context.prices.append(prices)  
    context.prices = context.prices.tail(window)  
    if len(context.prices.index) < window:  
        return  
    print get_datetime()  
    print context.prices  

The last row of context.prices is the current bar, and the first row is the previous bar. Note that there is no intra-day restriction, so, for example, the current bar can be the first minute of the current day, with the previous bar the closing minute of the prior day.

Grant