Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Variable weights instead of fixed ones

Hi,
I have been recently be working on this algo for a college seminar. I currently pick 25 stocks for my long positions and 25 for my short positions with equal weights; How can I make this weights more variable?
Let's say one of my indicators in my market_close_trades function gives me a huge positive signal to go long. How can I modify my code so that the algo invests more in that opportunity?
Thanks so much in advance,
Mattia

3 responses

Some code I copy/pasted from my algorithms, so you might want to double check that

# this is the factor  
overnight_returns = returns.iloc[-1]

# compute weights, helper function  
def to_weights(factor):  
    demeaned_vals = factor - factor.mean()  
    return demeaned_vals / demeaned_vals.abs().sum()

# factor to weights  
weights = to_weights(overnight_returns)  
longs  = weights[ weights > 0 ]  
shorts = weights[ weights < 0 ].abs()

# limit number of securities  
if context.max_long_sec:  
    longs  = longs.order(ascending=False).head(context.max_long_sec)  
if context.max_short_sec:  
    shorts = shorts.order(ascending=False).head(context.max_short_sec)

# normalize weights to 1.  
longs  /= longs.sum()  
shorts /= shorts.sum()  
longs  /= 2  
shorts /= 2

Hi Luca,
First of all thanks so much, thanks to your help I have definitively improved my long run result, from this:

To this one:

My only concern is:
if on the one hand in the "market_close_trades" function I found no issues in implementing the strategy; on the other hand, when I tried to do the exact same process for the "market_open_trades" it doesn't seem to work properly. Do I have do build a helper function for every single function individually? Or do you have any suggestions?