Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
[Help!] How can I give weight to every stock according to the rank?

Hi everyone!Here is my assignment from my seminar. I am supposed to calculate the weight of the stock according to the rank. The formula should be:1/(the rank of a stock)/sum(1/the rank of a stock); for example: there are three stocks, the rank of every stock should be 2,5,7,so the weight of the first stock will be 1/2/(1/2+1/5+1/7)=0.59322034.

As a beginner in python and quantopian, I spend a lot of time in finding the code .

Can somebody help me out?

Thank you in advance!:)

2 responses

A lot of ways to do this. Assuming you want to use the 'combo_rank' as the rank, maybe just make another series of the inverse ranks and then use the 'sum' method.

def open_short(context,data):  
    inverse_combo_rank_long = 1.0 / context.long_list.combo_rank  
    long_weight = inverse_combo_rank_long / inverse_combo_rank_long.sum()  
    inverse_combo_rank_short = 1.0 / context.short_list.combo_rank  
    short_weight = inverse_combo_rank_short / inverse_combo_rank_short.sum()

    for stock in context.long_list.index:  
            order_target_percent(stock, long_weight.at[stock])  
    for stock in context.short_list.index:  
            order_target_percent(stock, short_weight.at[stock])  

As one way, my example for you does that and then feeds the weights to optimize in your code at https://www.quantopian.com/posts/overnight-return-based-on-four-factor-overnight-return-has-been-improved#5a6ffad699e3a90017f559c6

context.output['combo_raw']  = context.output['combo_raw'].rank()  
context.output['combo_raw'] -= abs(context.output['combo_raw'].mean())   # shift downward so some are negative

order_optimal_portfolio(  
    objective   = opt.MaximizeAlpha(-context.output['combo_raw']),  # minus, flip long & short, better result