Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Averaging Historical Stock Prices

I was wondering if there was a way to compute an average between two prices of the same security within a very short amount of time. Preferably, I would like to find the average of prices between the most recent two trading prices. I was wondering if there was something along the lines of using

data[context.jblu].price  

and then referencing the price that came right before that; but I am not sure how to do this, and I am having trouble finding anything related to this.

6 responses

Matthew,

One approach would be to average open and close prices for a minute bar (i.e. add them and divide by two).

Grant

I had tried averaging the opening and closing prices but those were prices for the day. I am not sure how to use a minute bar in this average though but that sounds like something that might work.

You have to run the backtest in minutely mode. --Grant

Thanks so much! I am still not sure: will an average of open_price and close_price in minute mode use prices in that minute or will they use the price for when the market opened and closed that day still?

Hello Matthew,

When running in minute mode, the bars are minutely, so 'open' refers to the opening price of the bar (near the start of the minute), and 'close' is near the end (I'm reluctant to say exactly at the start and end points in time, since I don't know precisely how the bars are computed by Quantopian). Here's something to tinker with:

def initialize(context):  
    context.stocks = [sid(8554),sid(33652)]  
    context.averages = {}  
    for stock in context.stocks:  
        context.averages[stock] = []  
def handle_data(context, data):

    for stock in context.stocks:  
        o = data[stock].open_price  
        c = data[stock].close_price  
        context.averages[stock].append((o+c)/2)  
        print context.averages[stock]  

Not the best example of coding (likely inefficient, and may eventually hit a memory limit), but it hopefully illustrates the point.

Grant

Great, thank you so much!