Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Storing previous 20-day's prices & volumes [Code Question]

Hello! This is my first post here and I am really enjoying this site since joining last week.

My first algorithm I'm trying to develop needs access to the previous 20 close prices of the last 20 days, including volume. I looked up some previous people's questions that were similar and got some help, however I still can't quite figure it out.

I'd like it so that every day when the market opens, get the previous 20 day prices and volumes and store them in a list or array of some sort.

I've figured out that I think I'm going to need to change my Window length but that doesn't seem to fix the problem.
Here is what I have so far, any help would be greatly appreciated! Thanks!

import numpy as np

# globals for get_data batch transform decorator  
R_P = 1  # refresh period in days  
W_L = 2  # window length in days

def initialize(context):  
      context.aapl = [sid(24)]  
def handle_data(context, data):  
    # get data  
    d = get_data(data,context.aapl)  
    if d == None:  
       print 'nothing happened'  
       return  
    price = d[0]  
    #volumes = d[1]  
    print price  
    #log.debug(prices)  
    #log.debug(volumes)  
@batch_transform(refresh_period=R_P, window_length=W_L) # set globals R_P & W_L above  
  def get_data(datapanel,sids):  
      p = datapanel['price'].as_matrix(sids)  
     # v = datapanel['volume'].as_matrix(sids)  
      return [p]  
10 responses

Lincoln,

Here's an example that uses history to obtain the trailing window of trade data.

Grant

Thanks! That is still a bit confusing, it looks like it is trying to pull the previous prices every minute? Also, it is printing the number 24 for some reason.

Is there anyway I can clean it up to only pull the previous twenty prices once a day store them in an array of some sort?

Here is my log output

Hello Lincoln,

The batch transform does not "warm up" as history does, so it will output 'None' until the window is full. The nice thing about history is that the trailing window of data is available at the backtest start.

If you want, just skip all but one time of each trading day by putting in some logic, such as I shared above:

# Trade only once per day  
    loc_dt = get_datetime().astimezone(timezone('US/Eastern'))  
    if loc_dt.hour == 9 and loc_dt.minute == 31:  
        pass  
    else:  
        return  

Grant

Thanks! Getting closer! The code below grabs the 20 previous prices but I still need to store them somewhere. I need to implement logic that says, "If the current price of AAPL breaks out above the highest price in the last 20 days, do something." Is there any way I can store these twenty values in an array/list and access them?

# Trade only once per day  
    loc_dt = get_datetime().astimezone(timezone('US/Eastern'))  
    if loc_dt.hour == 9 and loc_dt.minute == 31:  
        c = history(20,'1d','price')[0:-1] # closing prices  
        print c  
        pass  
    else:  
        return  

Something like this
list_of_prices = [20] for i in range(20): #take each previous day price and put them in list_of_prices[i]

I would like to be able to say

If current price is higher than the highest price in the last twenty days:  
  do things  

Hello Lincoln,

No need to create a separate list, since history returns all of the data in a Pandas DataFrame. You might have at look at:

https://www.quantopian.com/posts/working-with-history-dataframes

Grant

Thanks Grant,

I looked through everything on that page and couldn't quite figure it out. I'm very new to this and I can't quite figure out how to get my previous 20 prices into a dataframe or how that would help. Do you know of any way I can store the previous 20 prices in a way so that I can index them and access them? Much like an Array or list.

Right now I have this line of code pulling the previous 20 prices. I just need to store them in a way where I can access each element. Any help would be great! Once I figure out this slight impass the rest of my algorithm should be easy to implement.

c = history(20,'1d','price')[0:-1] # closing prices  

Lincoln,

I don't have time now to work up an example. I suggest sending a note to Quantopian support, or post to https://www.quantopian.com/posts/working-with-history-dataframes.

Yes, you can index rows/columns/elements of a Pandas DataFrame, so you are on the right track.

Grant

Hi Lincoln,
Here's an example that should do what you want. This gives a numpy array which behaves similarly to a list.

How does this work out for you?

Gus

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.

Thanks Gus!! That's exactly what I needed thanks!

I have another question, how do I get the current price. I plan on implementing logic that says, "if the current price of Apple is above the highest price of Apple in the last 20 days, DO SOMETHING. " Any help?

Lincoln,

Here's an example you can tweak:

# http://www.sectorspdr.com/sectorspdr/

from pytz import timezone

trading_freq = 20 # trading frequency in elapsed full trading days

def initialize(context):  
    context.stocks = [ sid(19662),  # XLY Consumer Discrectionary SPDR Fund  
                       sid(19656),  # XLF Financial SPDR Fund  
                       sid(19658),  # XLK Technology SPDR Fund  
                       sid(19655),  # XLE Energy SPDR Fund  
                       sid(19661),  # XLV Health Care SPRD Fund  
                       sid(19657),  # XLI Industrial SPDR Fund  
                       sid(19659),  # XLP Consumer Staples SPDR Fund  
                       sid(19654),  # XLB Materials SPDR Fund  
                       sid(19660)]  # XLU Utilities SPRD Fund  
    context.day_count = -1  
def handle_data(context, data):  
    # trading control  
    #################################  
    # Trade only once per day (skip days for which market closes early)  
    loc_dt = get_datetime().astimezone(timezone('US/Eastern'))  
    if loc_dt.hour == 10 and loc_dt.minute == 0:  
        context.day_count += 1  
        pass  
    else:  
        return  
    # Limit trading frequency  
    if context.day_count % trading_freq != 0.0:  
        return  
    #################################

    # get bar data  
    prices = history(21,'1d','price').iloc[0:-1,:] # prices in a Pandas DataFrame  
    # find percent change  
    pricesPctChange = prices.pct_change(periods=19).iloc[-1,:]  
    # determine allocation  
    #################################  
    allocation = {}  
    for stock in context.stocks:  
        if pricesPctChange[stock] > 0:  
            allocation[stock] = 1.0  
        else:  
            allocation[stock] = 0.0  
    # normalize  
    denom = sum(allocation.values())  
    if denom == 0.0:  
        denom = 1  
    #################################  
    # apply allocation  
    for stock in context.stocks:  
        order_target_percent(stock,allocation[stock]/denom)  

Also, you might have a look at http://pandas.pydata.org/pandas-docs/dev/computation.html.

Grant