Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Sorting Returns

Maybe my brain isn't working quite yet, but this does not seem to sort.

    prices = history(2, '1d', 'close_price')  
    prices = prices.pct_change().dropna().sort(axis=1)  

Am I missing something?

4 responses

Try the "column" keyword. For example:

    prices = history(4, '1d', 'close_price')  
    changes = prices.pct_change().dropna()  
    sorted_changes = changes.sort(columns=changes.columns[0])

Instead of selecting the sort column with a positional index, you can also use a column name. Details here: http://pandas.pydata.org/pandas-docs/dev/generated/pandas.DataFrame.sort.html

Thanks, but that did not seem to sort as intended either, see output below:

2015-01-05PRINTSecurity(2 [AA])         -0.057311  
Security(24 [AAPL])      -0.027905  
Security(26892 [HLF])    -0.121938  
Security(39840 [TSLA])   -0.042041  
Name: 2015-01-05 00:00:00+00:00, dtype: float64  
2015-01-06PRINTSecurity(2 [AA])          0.006019  
Security(24 [AAPL])      -0.000188  
Security(26892 [HLF])    -0.078532  
Security(39840 [TSLA])    0.005236  
Name: 2015-01-06 00:00:00+00:00, dtype: float64  

I'm sorry, I misunderstood what you wanted to do. Here's a fix:

def initialize(context):  
    context.secs = [sid(2), sid(24), sid(26892), sid(39840)]

def handle_data(context, data):  
    prices = history(2, '1d', 'close_price')  
    changes = prices.pct_change().dropna().iloc[0]  
    sorted_changes = changes.order()  
    log.info('\n{sc}'.format(sc=sorted_changes))  

Output:

2015-01-05handle_data:8INFO  
Security(26892 [HLF])    -0.121938  
Security(2 [AA])         -0.057311  
Security(39840 [TSLA])   -0.042041  
Security(24 [AAPL])      -0.027905  
Name: 2015-01-05 00:00:00+00:00, dtype: float64  
2015-01-06handle_data:8INFO  
Security(26892 [HLF])    -0.078532  
Security(24 [AAPL])      -0.000188  
Security(39840 [TSLA])    0.005236  
Security(2 [AA])          0.006019  
Name: 2015-01-06 00:00:00+00:00, dtype: float64  

Thank you! I will need to figure out why order() works versus sort() in this instance.

Appreciate the help.