Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Error at adding factors!!!

I was trying to create a factor that would contain stocks with the highest 10 (roa, roe....) and lowest 10 (pe and debt ratio). I tried to do this in the following code:

ranking_factor_1 = roa_factor + roe_factor + EPS_Growth_factor + Current_R_factor + dividentyield_factor
ranking_factor_2 = PE_factor + debt_to_marketcap_long_factor
ranking_factor_I = ranking_factor_1.top(20) + ranking_factor_2.bottom(20)

But adding factors with top and bottom atributes seems to not work. My question is: how to solve the problem while keeping the same logic?

4 responses

The 'top' and 'bottom' methods return a filter and NOT a factor. That's why arithmetic operators don't work.

However, it seems you are really trying to take the top 20 securities as ranked by ranking_factor_1 and the bottom 20 securities as ranked by ranking_factor_2. This will give you 40 potential securities (assuming there is no overlap in the two sets). If this is the intent, then one doesn't want arithmetic addition, but rather a logical OR of the two filters. Use the | operand for this.


my_securities = ranking_factor_1.top(20) | ranking_factor_2.bottom(20)

Does that help?

Firstly thank you for the idea. But then I do an extra calculation :
longs = ranking_factor_I.top(10, mask=n_longs)
shorts = ranking_factor_II.bottom(5, mask=n_shorts)
And I get an error.

I do understand the error, but then I need to mask at least the n_longs and n_shorts, if not select top 10 / bottom 5 . How can I solve the problem?

Maybe you have a typo and really wanted the following?

longs = ranking_factor_1.top(10, mask=n_longs)  
shorts = ranking_factor_2.bottom(5, mask=n_shorts)

Attached is a backtest which works.