Search code examples
rxtsquantmod

xts variables with "-"


Any help appreciated on this problem and I realise this is probably a really dumb question.

I have a variable that contains a symbol that is causing issues.

I am trying to create a function that calculates various metrics from financial data, in this case sma from a column within an xts variable downloaded with the QUANTMOD package in R. The problem is that the variable is downloaded with an "-" symbol (XLM-USD) in its name and I do not know how to work with this since it produces an error, nor can I find an easy was to rename this variable.

Please see the code and error, below.

Any help would be appreciated.

Thanks :)

library(quantmod)

# download portfolio
getSymbols("XLM-USD", from="2021-03-01")

#create SMA function
mySMA <- function (price,n){
    sma <- c()
    sma[1:(n-1)] <- NA
    for (i in n:length(price)){
        sma[i]<-mean(price[(i-n+1):i])
    }
    sma <- reclass(sma,price)
    return(sma)
}

SMA <- mySMA(Cl(XLM-USD),n=20)

Produces

 Error in has.Cl(x) : object 'XLM' not found 

Solution

  • From ?make.names :

    A syntactically valid name consists of letters, numbers and the dot or underline characters and starts with a letter or the dot not followed by a number.

    Variable names which do not follow these rules need to be surrounded with backticks:

    SMA <- mySMA(Cl(`XLM-USD`),n=20)