Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Calculating Range for the last few days.

I have little experience with Python, so please bear with me.

I am trying to find the range (High-Low) for the last several days, and then calculate the average of those values. This was easy in a spreadsheet, but I am struggling to work with the arrays in Python.

I am starting with

    H_History = history(context.days, "1d", "high")  
    L_History = history(context.days, "1d", "low")  

I can't use the average of H_History & L_History separately. I need the average of the combination (H_History - L_History) from each day. I found
[Calculate the past 5 days' returns for each security.] returns = (prices.iloc[-1] - prices.iloc[0]) / prices.iloc[0] in the sample "Mean Reversion Algorithm", so it seems that something like
Range_History = H_History.iloc[0] - L_History.iloc[0] should work, but I can't seem to get it to go. Ultimately I just want a number that I can pass to other calculations.

6 responses

Hey Timothy!

After you get a little experience with Python I guarantee that you'll fall in love with how simple it is and end up preferring it over spreadsheets. If you want to subtract "(H_History - L_History)" like you wrote above, just write that in Python high_low_range = H_History - L_History and if you want the mean or average of those values well why not just write that in Python too mean_range = high_low_range.mean()In fact you could boil that down to a one-liner mean_range = (H_History - L_History).mean()

Overall...

H_History = history(context.days, "1d", "high")  
L_History = history(context.days, "1d", "low") 

mean_range = (H_History - L_History).mean()  

Print that result and it should be a collection of the average range for each security.

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. That helps a lot. But there is a new challenge. I am wanting the PREVIOUS days' data, not including today's data. Frankly I am a bit surprised there that 'history' cannot start 'x' bars back and go for 'y' bars back from there. Or at a minimum, the ability to exclude the current bar and use the true "history" (ie data from the past but not the present).

I tried simply subtracting history(1, "1d", "high") but that doesn't work. I tried moving the history(context.days*+1**, "1d", "high")* to the 'before_trading_start(context)' section, but that returned empty values for the highs. I need to simply remove the last line from history(context.days*+1**, "1d", "high")* . Or find the mean of the first 5 lines of data, but ignore the 6th.

:-/

Hmmmm .... I jsut found this in the help page:

def handle_data(context, data):  
    price_history = history(bar_count=2, frequency='1d', field='price')  
    for s in data:  
        prev_bar = price_history[s][-2]  
        curr_bar = price_history[s][-1]  
        if curr_bar > prev_bar:  
            order(s, 20)  

I think I can steal and modify that to fit my needs.

So yes ignoring the latest bar of data is a very common occurrence when doing time series analysis, but even more so it is a common occurrence in programming in general so Python has this super powerful operation called slicing. Here is a good Stack Overflow explanation of slicing. The object that history() returns allows slicing as well so if you want everything except the last value you can just say [:-1]

price_history = history(10, "1d", "price")  
history_except_today = price_history[:-1]  

Check out my response in this thread for some good places to start when learning to use Quantopian or learning Python. It really is worth struggling through things like this as the struggle will make you a better programmer which will in turn make you a better algorithm writer.

J

Is there also an efficient way to identify any securities that have had a sudden drop of, say, 50% of the range between max and min?

@garyha

That's kind of an arbitrary question, a drop in relation to what price? The max and min over what time span? These kind of questions are similar to how you bound the definition for max drawdown.

Any. Easiest would be fine. Dev choice.