5

I am trying to plot two charts on one chartSeries in quantmod in R. I am having some difficulty doing this.

library(quantmod)    
tickers <- c('GLD', 'GDX')
data <- new.env()
getSymbols(tickers, src = 'yahoo', from = '1980-01-01', env = data)
chartSeries(Cl(data$GLD), TA="addTA(Cl(data$GDX), on=1)")
addRSI()
FXQuantTrader
  • 6,821
  • 3
  • 36
  • 67
Defcon
  • 807
  • 3
  • 15
  • 36

1 Answers1

10

You could use chart_Series instead of chartSeries.

chart_Series(Cl(data$GLD))
add_TA(Cl(data$GDX), on = 1)

And then if you want RSI below in a sub panel, just add add_RSI().

Another approach is to use version >= 0.10.0 of xts (i.e. don't use quantmod at all), which you can get from https://github.com/joshuaulrich/xts (0.10.0 is not yet on CRAN). The new plot function in xts is very friendly with plotting multiple columns of an xts object all at once. Check out ?plot.xts for examples of new functionality.

Edit #2:

To see relative changes more easily, you can normalise your price series in many ways. This is a typical approach (using a 0 origin is what Google charts does):

normalise_series <- function(xdat) xdat / coredata(xdat)[1]
getSymbols("USO")
window <- "2013/"

# Define colour of default chart line to chart_Series in mytheme object
# which is passed to chart_Series:
mytheme <- chart_theme()
mytheme$col$line.col <- "darkgreen"
chart_Series(normalise_series(Cl(data$GLD)[window]) - 1, theme = mytheme)
add_TA(normalise_series(Cl(data$GDX)[window]) - 1, on = 1, col = "red", lty = 3)
add_TA(normalise_series(Cl(USO)[window]) - 1, on = 1, col = "blue", lty =2)

add_TA(RSI(Cl(data$GLD)), on = NA, col = "darkgreen")
add_TA(RSI(Cl(data$GDX)), on = 2, col = "red", lty = 3)
# Or add RSIs on different subpanels to improve readability of charts:
add_TA(RSI(Cl(USO)), on = NA, col = "blue", lty = 2)

enter image description here

FXQuantTrader
  • 6,821
  • 3
  • 36
  • 67
  • is there a way to normalize the graph? So it is not on absolute price data but scaled to compare the charts – Defcon Jul 01 '16 at 03:13
  • Scaled in what sense? On the main chart? You could divide the security prices by the initial price level so they both start at 1 (say) before plotting? – FXQuantTrader Jul 01 '16 at 06:12
  • Scaled by percentage gained similar to Google chart that can overlay different stocks. I wanted to add rsi paths too so I can see the trends. – Defcon Jul 01 '16 at 14:26
  • See second edit above. This is exactly what my first comment suggests, and seems to be what google does too. This answers your question + adds a few extra features (Formating) you might find useful in using chart_Series functionality. – FXQuantTrader Jul 02 '16 at 01:13