Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to use history function to obtain historical closing prices for varying frequency?

Every 30 minutes, a scheduling function is called to execute the function "open_positions" which trades based on target percentage.
Inside open_positions, I would like to obtain historical 30 minutes frequency of past, say, 50 data points to analyze and calculate to come up with the list of weights. So essentially, I would like to create a list of list (or vector> equivalent in python) like a matrix, in which rows are securities ID and the columns are in chronologically more recent closing prices of the corresponding securities.

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 import Q1500US 


def initialize(context):  
    context.securities = [sid(24),sid(114)]  
    for i in range(1,300,30):  
        schedule_function(open_positions,date_rules.every_day(),time_rules.market_open(minutes=i)) 

def open_positions(context, data):  
##  
    hist = data.history(context.securities,'close',50,'30m')  
##  
    print hist  
    for i in context.securities:  
        order_target_percent(i,0.2)

So my understanding is that hist will now be a list of list in which columns are securities and rows are closing prices. But it says '30m' frequency is not valid.

1 response

Hope this will help:

def initialize(context):  
    for i in range(1, 390, 30):  
        schedule_function(print_hist_30m ,date_rules.every_day(),time_rules.market_open(minutes = i)) 

def print_hist_30m(context, data):  
    # ------------------------------------------------  
    stocks = symbols('AAPL', 'QQQ')  
    period = 50  
    timeframe = 30  
    timeframe_unit = 'T'  
    bars_1m = period*timeframe  
    timeframe_string = str(timeframe) + timeframe_unit  
    # ------------------------------------------------  
    hist_30m = data.history(stocks, 'price', bars_1m, '1m').resample(timeframe_string).last().ffill().iloc[-1]  
    print hist_30m