Search code examples
rfinancequantmod

R: how to avoid explicit names when using a variable


I have the following code in R:

library(quantmod)

mySymbol = "^STOXX50E"
getSymbols(mySymbol, from="2004-01-01", to=Sys.Date())

chartSeries(Cl(STOXX50E))

which simply download the time series for the inder Eurostoxx and then plots the closing price. It works as expected. Anyway, I was wondering how I can avoid to write explicitely "STOXX50E" everytime I want to reference to this variable. For example, I would like to be able to reference the variable that contains the data with a generic name like "INDEX" so that I don't need to change all the calls when I want to launch the code with another inder.

For example, if i want to download and plot the closing price for the S&P500 I have to do:

library(quantmod)

mySymbol = "^GSPC"
getSymbols(mySymbol, from="2004-01-01", to=Sys.Date())

chartSeries(Cl(GSPC))

so I have to change the variable name not only on the second line but also on the last. I would rather something more generic like:

library(quantmod)

mySymbol = "^GSPC"
getSymbols(mySymbol, from="2004-01-01", to=Sys.Date())

chartSeries(Cl(mySymbol))

So that once I have set the name for mySymbol I don't have to change all the rest of the code. But this doesn't work. How can I accomplish this?


Solution

  • You can do it this way:

    library(quantmod)
    
    mySymbol = "^STOXX50E"
    getSymbols(mySymbol, from="2004-01-01", to=Sys.Date())
    
    chartSeries(Cl(get(substring(mySymbol,2,nchar(mysymbol)))))
    

    If you want to change the title of the plot do:

    chartSeries(Cl(get(substring(mySymbol,2,nchar(mysymbol)))), name=mySymbol)
    

    Essentially when you use getSymbols a variable named STOXX50E is stored on your global environment which contains the data. Using get you can access a variable name by providing a string i.e. "^STOXX50E". I then use substring to avoid the first character of the variable mySymbol which is ^.

    And it works. You essentially change mySymbol and the code runs without having to alter anything else!

    enter image description here

    EDIT:

    This is probably a better way in terms that the code is more readable and you avoid the annoying ^ in the title:

    library(quantmod)
    
    mySymbol = "STOXX50E"
    getSymbols(paste('^',mySymbol,sep=''), from="2004-01-01", to=Sys.Date())
    
    chartSeries(Cl(get(mySymbol)),name=mySymbol)
    

    enter image description here