ryahoo-financeyahoo-apitidyquant

Handling xts objects that contain special characters


I'd like to retrieve financial data from Yahoo using the tidyquant package (or any other package).

For retrieving Microsoft's (index: MSFT) closing prices, the following code works fine:

#load packages
library(tidyquant)

#acquire monthly average stock prices
getSymbols("MSFT", from = "2000-08-01", to = "2021-07-31", src = 'yahoo', periodicity = 'daily')
output <- aggregate(MSFT$MSFT.Close, list(format(index(MSFT), "%Y-%m")), mean)
colnames(output) <- c('ClosingPrice')

#create time series for closing stock prices
price = ts(output$ClosingPrice, frequency=12, start=c(2000,08))
summary(price)

However, for retrieving the prices of crude oil (index: CL=F), it doesn't work as the index contains a special character. More specifically, I get an error message here:

#acquire monthly average stock prices
getSymbols("CL=F", from = "2000-08-01", to = "2021-07-31", src = 'yahoo', periodicity = 'daily')
output <- aggregate(CL=F$CL=F.Close, list(format(index(MSFT), "%Y-%m")), mean)

Does anyone have an idea of how to could get around this issue? Thanks a lot!


Solution

  • The object names with special characters can be backquoted. Also, if there are NA values, specify the na.rm = TRUE along with na.action = NULL as aggregate can remove the whole row if there is NA in any of the columns

    out <- aggregate(`CL=F`$`CL=F.Close`, list(format(index(`CL=F`), "%Y-%m")), 
           mean, na.rm = TRUE, na.action = NULL)
    

    -output

    > head(out)
                    
    2000-08 32.54571
    2000-09 33.87100
    2000-10 32.97318
    2000-11 34.26450
    2000-12 28.35500
    2001-01 29.26667
    > tail(out)
                    
    2021-02 59.06105
    2021-03 62.35739
    2021-04 61.70381
    2021-05 65.15700
    2021-06 71.35273
    2021-07 72.43048