Search code examples
rloopsquantmod

character variable as parameter of function


part of my code for downloading financial data:

library(quantmod)

tickers <- c("XOM", "DIS")
stock1 <- getSymbols(tickers[1], from="2010-03-01", to="2011-02-28", auto.assign=F)
stock2 <- getSymbols(tickers[2], from="2010-03-01", to="2011-02-28", auto.assign=F)

pair <- merge(Ad(stock1), Ad(stock2), all=F)             # 'xts' object, merge adjusted close
pair.DF <- data.frame(pair)                              #  data frame

But I want to call function like this:

tickers <- function(x, y) {
stock1 <- getSymbols(x, from="2010-03-01", to="2011-02-28", auto.assign=F)
stock2 <- getSymbols(y, from="2010-03-01", to="2011-02-28", auto.assign=F)

pair <- merge(Ad(stock1), Ad(stock2), all=F)            
pair.DF <- data.frame(pair)       
}

And then:

tickers("XOM", "DIS")

Or something similar. But what I get is bad result. In this case "x" and "y" aren´t numeric, but character. It seems to be easy, but.. Thanks for any suggestions.


Solution

  • tickers <- function(x, y) {
    stock1 <- getSymbols(x, from="2010-03-01", to="2011-02-28", auto.assign=F)
    stock2 <- getSymbols(y, from="2010-03-01", to="2011-02-28", auto.assign=F)
    
    pair <- merge(Ad(stock1), Ad(stock2), all=F)            
    pair.DF <- data.frame(pair)       
    return(pair.DF)
    }
    

    Works for me as long as you return the pair.DF at the end. Is that your problem?

    I don't think the character class is the problem:

    class(tickers[1])==class("XOM")
    TRUE