Search code examples
rfunctionfinancequantmodyahoo-api

Quantmod package passing arguments in R


I want to built a custom stock valuation function in R. My code is:

stock_valuation <- function(company1 = "GOOGL", start = "2018-04-01", end = "2018-06-01"){


stock1 = getSymbols(company1, src = "yahoo", from = start, to = end)  

}


stock_valuation()

I want to have those default values as well. However when I run the function (as shown in the code) I receive no answer - nothing at all. What am I doing wrong? How to properly pass those arguments?

Or maybe there is a better way to scrap stock quotes?

In other words I want it to return data frame to global environment.

Any possible answers?


Solution

  • By using the default argument auto.assign = TRUE in getSymbols, your getSymbols call passes the GOOGL data into the environment inside the function, and assigns the string name "GOOGL" to your variable stock1 (not the data), as expected by getSymbols by default.

    Try this instead:

    library(quantmod)
    stock_valuation <- function(company1 = "GOOGL", start = "2018-04-01", end = "2018-06-01"){
    
    
      stock1 = getSymbols(company1, src = "yahoo", from = start, to = end, auto.assign = FALSE)  
      stock1
    }
    
    
    res <- stock_valuation()
    

    res is an xts object, but you can easily convert this to a data.frame, such as like this:

    df <- data.frame(time = index(res), coredata(res))