Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R: Converting output from getSymbols() to data frame in one command without calling the object name explicitly

I would like to to convert output from the getSymbols in quantmod package to a data frame. Presently I achieve that with the following code.

Data <- new.env()
getSymbols(Symbols = "EUR/USD", src = "oanda", from = "2005-01-01", 
    to = "2006-01-01", env = Data)
test <- as.data.frame(Data$EURUSD)
head(test)

Ideally, I would like to shorten this code to something on the lines:

test <- as.data.frame(getSymbols(Symbols = "EUR/USD", 
   src = "oanda", from = "2005-01-01", to = "2006-01-01"))

But this doesn't work as it should:

> head(test)
  getSymbols(Symbols = "EUR/USD", src = "oanda", from = "2005-01-01", to = "2006-01-01")
1                                                                                 EURUSD

Ideally, I would like to avoid referring to the pair EUR/USD when working with the data as in future I will be working to make this component dynamic so having to type test <- as.data.frame(Data$EURUSD) spoils the fun. My ideal code, would work like that:

test <- as.data.frame(getSymbols(Symbols = *user input*, 
   src = "oanda", from = "2005-01-01", to = "2006-01-01"))

At the moment I'm not necessairly interested in the user input but in coercing quantmod output to data frame without the need to call the quantmod object name.

like image 721
Konrad Avatar asked Jan 30 '15 14:01

Konrad


2 Answers

You can try something like this:

userInput="EUR/USD"
test<-as.data.frame(getSymbols(Symbols = userInput, 
    src = "oanda", from = "2005-01-01",to = "2006-01-01", env = NULL))

Setting the env to NULL results in no creating the data in the environment and returning it.

like image 77
NicE Avatar answered Nov 13 '22 23:11

NicE


The tidyquant package is ideal for this scenario. You can try this:

tq_get("EUR/USD", get = "exchange.rates")

If you want more currency pairs in the same data frame, try this:

c("EUR/USD", "EUR/JPY", "EUR/GBP") %>% 
     tq_get(get = "exchange.rates")

You can then use all of the functionality of the "tidyverse" such as grouping with group_by, mutating with mutate, etc. In addition, the tidyquant package has other functions for working specifically with time series data.

like image 37
Matt Dancho Avatar answered Nov 14 '22 01:11

Matt Dancho