Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Using history(), how do I take a specific number from that?

I have something like:

price_history = history(bar_count=120, frequency="1d", field = "price")
# log.debug(price_history)

# These variables will keep track of our total gains and losses so far within the loop  

gains = 0  
losses = 0  

# This loop will traverse the array from current day to 120 days back, 1 day at a time  
for x in range(0,-120,-1):  
    # If current price is positive, assign it to current_gain and add it to our gains variable  
    # If its negative, do the latter  
    if price_history.iloc[[x]]>0:  
        current_gain = price_history.iloc[[x]]  
        gains += price_history.iloc[[x]]  
    if price_history.iloc[[x]]<0:  
        current_loss = price_history.iloc[[x]]  
        losses += price_history.iloc[[x]]

I ONLY want to get the price part of this. I don't fully understand Pandas data series and things like that yet. How do I take just the price int out of price_history?

3 responses

You want the return in the 120 days?

You could do something like?

    price_history = history(bar_count=days, frequency="1d", field='price')  
    p_price = p_price / p_price[0] - 1  
    p_price = np.sum(p_price)  

There is also a magic function

 price_history = history(bar_count=days, frequency="1d", field='price')  
 price_history.pct_change()  

http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.pct_change.html

If you look below, I just need ONE thing from the numpy.ndarray object (what I get from history()). How do I pull just that one number out?

A very simple algorithm that buys and sells based on a calculated RSI value for a given stock (Relative Strength Index)

RSI = 100-100/(1+RS*) where RS* = avg(total gains)/avg(total losses)

import pandas as pd

def initialize(context):
context.security = symbol('AAPL')

def handle_data(context, data):

# Get the prices from the past 6 months (about 120 trading days)  

price_history = history(bar_count=120, frequency="1d", field = "price")  
# log.debug(price_history)  

# These variables will keep track of our total gains and losses so far within the loop  

gains = 0  
losses = 0  

# This loop will traverse the array from current day to 120 days back, 1 day at a time  
for x in range(-1,-120,-1):  
    # If current price is positive, assign it to current_gain and add it to our gains variable  
    # If its negative, do the latter  
    current_price = list(price_history.iloc[[x]])  

    print current_price  

    #price_change = current_price - price_history.iloc[[x+1]]  
    price_change=2 # temp  
    current_gain=5 #temp  
    current_loss=4 #temp  

    #print "price change: " + price_change  
    if current_price > 0:  

        #current_gain = price_change  
        gains += price_change  

    if current_price < 0:  

        #current_loss = price_change  
        losses += price_change  

    # Calculate average gain and loss thus far by dividing total gains or total losses by number of days passed  
    current_avg_gain = ((gains)/x)  
    current_avg_loss = ((losses)/x)  

    # Average overall gain/loss overall is calculated by ((prev gain or loss)*(x-1)+current gain or loss)/x  
    avg_gain_overall = ((current_avg_gain)*(x-1)+current_gain)/x  
    avg_loss_overall = ((current_avg_loss)*(x-1)+current_loss)/x  

    # We can calculate our RSI value b using the equation 100-100/(1+RS) where RS is average of x days' up closes divided  
    # by avg of x days' down closes  

    RS = avg_gain_overall/avg_loss_overall  

    RSI = 100-100/(1+RS)  

    if RSI <= 30:  
        curr_price = data[context.security].price  
        cash = context.portfolio.cash  

        num_shares = int(cash/curr_price)  
        order(context.security, +num_shares)  
        #log.info("Buying %s" % (context.security.symbol))  

    if RSI >= 70:  
        curr_price = data[context.security].price  
        cash = context.portfolio.cash  

        num_shares = int(cash/curr_price)  
        order(context.security, 0)  
        #log.info("Sold all shares of %s" % (context.security.symbol))  

record(portfolio_value=context.portfolio.portfolio_value)  

Hi John,

Which "one thing" do you need from the history call? Is it price from the last minute bar for a specific stock? If so you can do this:

price_history = history(bar_count=120, frequency="1d", field = "price")  
aapl_price = price_history[context.security][-1]  
log.info(aapl_price)  

If you need help building your algo, check out the example RSI algorithm and the pandas mini-tutorial. Hope that helps!

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.