Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Not able to get 52 week high of SPY

Hi,

I am fairly new to the community. I am trying to get the 52 week high of the SPY and print the value on a daily basis.
Looking around at some code I found, I decided to go with the following code which seems to work at first:

high_history = history(252,'1d','high')  
high = max(high_history[context.spy])  
print(high)

This code is part of the before_trading_start() function, therefore it prints the 52 week high every day at 8:45. So far so good...
When i run the code, on 2018-01-29 08:45 PRINT 286.58, this makes sense since on 2018-01-26 (the trading day before) SPY reach a new 52 week high to 286.58 (actually it should be 286.63 according to Yahoo, is there a reason why I can't get the actual high?).

What make less sense however in that on 2018-03-16 08:45 PRINT 285.437035591 this value remains for a couple of days until 2018-06-15 08:45 PRINT 284.161427485 which also remains a couple of days...

However until this day the SPY 52 week high is 286.58, can someone help me with fixing my little code?

2 responses

The issue is that the 'data.history' method returns split and dividend adjusted prices. Check out the docs for more info https://www.quantopian.com/help#ide-history .

This becomes apparent when one prints not only the high value but also the high date. Something like this.

    highs = data.history(SPY, 'high', 252, '1d')  
    max_high = highs.max()  
    max_date = highs.argmax()  
    print('max was {} on {}'.format(max_high, max_date))

When one does this, and runs the code from 1-29-2018 thru 7-2-2018, it prints the high date as always being 1-26-2018. However, as the original post noted, the high value changes from 286.58 down to 284.161. This is because SPY generates dividends and these dividends are subtracted from the price to get 'adjusted' values. The 'actual' unadjusted high on 1-26-2018 was 286.58 but the dividends posted on 3-16-2018 and 6-15-2018 adjusted this value (and changed the adjusted prices).

A few things with the original code. Use the 'data.history' to get price data. 'history' is deprecated. Also, it's better not to use the basic python max function but rather the pandas 'max' method which take into account NaNs and generally is more forgiving. And finally, if one is simply getting daily data then it's more efficient to do this within a pipeline framework than by using 'data.history'.

See attached backtest and check the logs.

Excellent! Thank you very much for the explanation!