title: Building portfolios in R:
body: <p>I tried to ask a similar question earlier, but I see now that it lacked information needed to answer it, so I've tried to make a replicable example now.</p>
  
  <p>I want to test the momentum theory on a stock market, and therefore has to make some momentum portfolios. I have the returns of the stocks and their returns' ranked every day.</p>
  
  <pre><code>require(quantmod)
  options(scipen=999)
  getSymbols(c("YHOO","GOOG","MSFT","AAPL")) 
  data = merge(AAPL[,4], GOOG[,4], MSFT[,4], YHOO[,4])
  
  return = ROC(data)
  
  RankFUN &lt;- function(x){
    r &lt;- as.xts(t(apply(-x, 1, rank, na.last = "keep", ties.method="first"))) #med ties.method = first velger R
    return(r)                                                                 #å gi lavest verdi den først kolonnen
  }     
  
  Rank = RankFUN(return)
  </code></pre>
  
  <p>So, the return and rank is organized as following:</p>
  
  <pre><code>    AAPL.Close    GOOG.Close   MSFT.Close    YHOO.Close
  2016-02-22  0.008708287  0.0078871623  0.015890101  0.0369262336
  2016-02-23 -0.022864649 -0.0151325292 -0.028317446 -0.0161711157
  2016-02-24  0.014780876  0.0053174777  0.003510848  0.0090880533
  2016-02-25  0.006844411  0.0088095040  0.014305232  0.0131601959
  2016-02-26  0.001549048 -0.0009639685 -0.015474178  0.0003188267
  2016-02-29 -0.002272749 -0.0104075344 -0.008220794  0.0132997523
  
             AAPL.Close GOOG.Close MSFT.Close YHOO.Close
  2016-02-22          3          4          2          1
  2016-02-23          3          1          4          2
  2016-02-24          1          3          4          2
  2016-02-25          4          3          1          2
  2016-02-26          1          3          4          2
  2016-02-29          2          4          3          1
  </code></pre>
  
  <p>Its here I meet problems. I need to be able to code something that makes R buy the %top quantile and sell %bottom based on performance in time t-1, and keep them untill t+1 and then rebalance. Is there any packs or anything that can do something similar to this? I have looked on a few portfolio packs, but most of them were oriented against optimization of portfolios.</p>
  
  <p>EX: Say for a strategy were you buy stocks based on the t-1 month performance and rebalance again every month. Then I need to code something that states:
  For every t, give me the output that is top quantile - bottom quantile based on lag[1] or something like this, making an output like:</p>
  
  <pre><code>           1-month mom 3-month mom
  2016-02-22  0.008708287  0.0078871623
  2016-02-23 -0.022864649 -0.0151325292
  2016-02-24  0.014780876  0.0053174777
  2016-02-25  0.006844411  0.0088095040
  2016-02-26  0.001549048 -0.0009639685
  2016-02-29 -0.002272749 -0.0104075344
  </code></pre>