Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to identify number of the days since: the highest close, second highest close, and third highest close

I've been away from Quantopian for a few months, so my limited Python skills are rusty. I am trying to identify the number of days since each of these events occurred:

Highest close
Second highest close
Third highest close

Any ideas on how to accomplish this? I asked a similar question and James provided a function that returned the days since a higher high.

Could this be done by making a dictionary of [close_price, days ago] and then sorting by [price]? If so, how to code that?

Thanks for your assistance!

2 responses

Probably simpler and faster to sort the data frame by prices descending, slice for the top three, then map/apply over the index to calculate today - x.

At first glance, it seems like numpy.argsort would work. For example, as shown on http://docs.scipy.org/doc/numpy-1.10.0/reference/generated/numpy.argsort.html:

>> x = np.array([[0, 3], [2, 2]])  
>> np.argsort(x, axis=0)  
array([[0, 1],  
       [1, 0]])  

So, it is a matter of putting your closing prices in an ndarray, with each column corresponding to a security. Then, if you do an np.argsort with axis = 0, you can just read off the indices of the first three rows (or last three rows, depending on the order of the sort).