[R] Trying to Generalize a Function in R

rsherry8 r@herry8 @ending from comc@@t@net
Thu Aug 9 19:12:45 CEST 2018


I wrote the following function:

# This method gets historical stock data for the stock Avalon Bay whose 
symbol is AVB.
getReturns <- function(norm = FALSE)
{
     library(quantmod)

     getSymbols("AVB", src = "yahoo", from = start, to = end)
     length = length(  AVB$AVB.Close )
     close = as.numeric( AVB$AVB.Close )
     cat( "length = ", length(close ), "\n" )
     for( i in 1:length-1 )
         diff[i] = ((close[i+1] - close[i]) ) / close[i]
     u = mean(diff)
     stdDev = sd(diff)
     cat( "stdDev = ", stdDev, "\n" )

     if ( norm == TRUE ) {
         diff = (diff - u)
         diff = diff / stdDev
     }
     return (diff)
}

I would like to generalize it to work for any stock by passing in the 
stock symbol. So the header for the
function would be:

getReturns <- function(symbol, norm = FALSE)

Now how do I update this line:
     length = length(  AVB$AVB.Close )
This statement will not work:
     length = length(  symbol$AVB.Close )
because the name that holds the closing price is a function of the stock 
symbol.

Thanks,
Bob



More information about the R-help mailing list