title: Pandas how to select stocks to invest in based on past performance (momentum, trend following)
body: <p>I have a dataframe of 20-day performances of a universe of 5 stocks that looks like this. Index is Dates, columns are stocks, elements are returns. </p>
  
  <pre><code>           ELET3        ELET6       EMBR3      ENBR3        EQTL3 (...)
  Dates
  2/8/2018    0.277450    0.307260    0.064575    -0.025936   0.051672
  3/12/2018   0.149723    0.100899    0.017105    0.056956    0.044669
  4/10/2018   -0.235531   -0.180462   0.020565    0.026310    -0.006893
  5/9/2018    -0.019453   -0.057651   0.033495    -0.055192   -0.042110
  </code></pre>
  
  <p>From which I have built a dataframe of the ranking of each stock's performance over that period (same as above but with the ranks instead of the returns): </p>
  
  <pre><code>           ELET3    ELET6   EMBR3   ENBR3   EQTL3   (...)
  Dates
  2/8/2018    2.0     1.0     3.0     5.0     4.0
  3/12/2018   1.0     2.0     5.0     3.0     4.0
  4/10/2018   5.0     4.0     2.0     1.0     3.0
  5/9/2018    2.0     5.0     1.0     4.0     3.0
  (...)
  </code></pre>
  
  <p>For each period(i), I want to calculate the average return for period(i) of the 2 stocks from the universe of 50 that had the best performance over the previous period (period(i-1)).</p>
  
  <p>Below is the out put I am looking for.
  There are no returns for 2/8/2018 as it is the first period. For this first period ELET3 and ELET6 are the two best performing stocks so the strategy invests in them for the next period. Their return over the 2/8/2018 - 3/12/2018 period is 0.149723 and 0.100899 so the code should return the average of that (0.12531). They are also the 2 best performing stocks for that 2/8/2018 - 3/12/2018 period. So the strategy stays invested in them over the 3/12/2018 - 4/10/2018 period. For that period they return -0.20800. over that period the 2 best stocks were EMBR3 and ENBR3, so the strategy invests in them over the 4/10/2018 - 5/9/2018 and they return an average return of -0.01085.</p>
  
  <pre><code>           Strategy Return
  Dates
  2/8/2018    
  3/12/2018   0.12531     
  4/10/2018   -0.20800        
  5/9/2018    -0.01085        
  </code></pre>