简体   繁体   中英

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?

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))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM