I have the following code:
library("quantmod")
stockValuation <- function(company1, company2,
a=GOOGL,
b=AAPL,
start_i = "2018-01-01", end_i = "2018-05-20") {
#start <- as.Date(start_i)
#end <- as.Date(end_i)
tckr <- c(company1, company2)
getSymbols(tckr, src = "yahoo", from = start_i, to = end_i)
chrtlist <- c(a,b)
chartSeries(a, multi.col=TRUE, theme='white', TA="addMACD()")
dev.copy(pdf, paste(company1,".pdf",sep=""))
dev.off()
chartSeries(b, multi.col=TRUE, theme='white', TA="addMACD()")
dev.copy(pdf, paste(company2, ".pdf",sep=""))
dev.off()
}
Idea is to have a function that produces two diagrams and then export it to .pdf however chartSeries function does not want to use arguments in quotation marks i.e. instead of "GOOGL" you need to have GOOGL on the contrary getSymbols uses quotation marks thus you need to have "GOOGL".
Now i have created a version with two arguments one with quotation marks the other one without it how to force it to work with just one argument? i.e. as arguments i want to have either "GOOGL" or GOOGL but not both at the same time
Make the company tickers arguments to your function. Then use auto.assign = FALSE
in the getSymbols()
calls, so you can assign the data for each ticker to a specific object. Then you can call chartSeries()
on those two objects.
Here's an updated version of your function that does what I suggest:
stockValuation <-
function(ticker1, ticker2, from = "2018-01-01", to = "2018-05-20")
{
a <- getSymbols(ticker1, from = from, to = to,
src = "yahoo", auto.assign = FALSE)
b <- getSymbols(ticker2, from = from, to = to,
src = "yahoo", auto.assign = FALSE)
chartSeries(a, multi.col = TRUE, theme = "white", TA = "addMACD()")
dev.copy(pdf, paste0(ticker1, ".pdf"))
dev.off()
chartSeries(b, multi.col = TRUE, theme = "white", TA = "addMACD()")
dev.copy(pdf, paste0(ticker2, ".pdf"))
dev.off()
}