title: Calculating average daily returns with For-Loop
body: <p>I am trying to put my script into a For-Loop in order to calculate the mean daily return for multiple stocks.</p>
  
  <p>But when I setup the For-Loop I get the following error:</p>
  
  <blockquote>
    <p>Error in getSymbols(Symbols = stock, src = "yahoo", from = "2005-01-01",  : 
      must use auto.assign=TRUE for multiple Symbols requests</p>
  </blockquote>
  
  <p>So I removed <code>env = NULL</code> and replaced it with <code>auto.assign=TRUE</code> but when I run the script I get <code>NaN</code> as a result. </p>
  
  <p>Any advice would be much appreciated. Thanks.</p>
  
  <pre><code>install.packages('quantmod')
  library(quantmod)
  
  stock &lt;- c("AAPL") 
  {
  stock.xts &lt;- getSymbols(Symbols = stock, src = "yahoo", 
                         from = "2005-01-01",
                         to = "2019-09-10", 
                         env = NULL)
  
  stock.xts &lt;- as.data.frame(stock.xts)
  
  N &lt;- nrow(stock.xts)
  todays.price &lt;- stock.xts[2 : N,4]
  yesterdays.price &lt;- stock.xts[1 : N-1,4]
  stock_dailyreturn &lt;- (todays.price - yesterdays.price)/yesterdays.price
  stock.xts$daily.return &lt;- c(NA,(todays.price - yesterdays.price)/yesterdays.price)
  print(mean(stock_dailyreturn)) 
  }
  </code></pre>
  
  <p>With the For-Loop:</p>
  
  <pre><code>stock &lt;- c("AAPL", "MSFT", "CRM", "ORCL", "NFLX", "GOOG")
  
  for(i in 1:length(stock)){
    stock.xts &lt;- getSymbols(Symbols = stock, src = "yahoo", 
                            from = "2005-01-01",
                            to = "2019-09-10",
                            auto.assign = TRUE)
    stock.xts &lt;- as.data.frame(stock.xts)
  
    N &lt;- nrow(stock.xts)
    todays.price &lt;- as.numeric(stock.xts[2 : N,4])
    yesterdays.price &lt;- as.numeric(stock.xts[1 : N-1,4])
    stock_dailyreturn &lt;- (todays.price - yesterdays.price)/yesterdays.price
    stock.xts$daily.return &lt;- c(NA,(todays.price - yesterdays.price)/yesterdays.price)
    print(mean(stock.xts$daily.return))
  }
  </code></pre>