3

I just got introduced to quantmod, and looked at examples here http://www.r-chart.com/2010/06/stock-analysis-using-r.html I tried the following code,

getSymbols(c("^GSPC","^VIX"))
head(as.xts(merge(GSPC,VIX)))
chartSeries(c(GSPC, VIX), subset='last 3 months')

but the graph was completely out-of-scale, so I hope some of the experts on this forum can show me how to plot this correctly.

user1155299
  • 877
  • 5
  • 20
  • 29
  • 1
    If you want the candlestick and volume plots, it would be more readable to use separate plots, as in a previous question: http://stackoverflow.com/questions/8815697/r-quantmod-multiple-charts-all-using-the-same-y-axis. If you want to compare the price movements, you can divide the adjusted price time series by their first value, so that they start at the same point. – Vincent Zoonekynd Jan 23 '12 at 01:49
  • I only want to compare price movements. I was looking for a way to plot the raw time series on 2 separate axis. Given how many features this package has, I presume there must be something to handle two different axes. – user1155299 Jan 23 '12 at 01:57
  • To have two different y axes, you may want to check: http://stackoverflow.com/questions/6142944/how-can-i-plot-with-2-different-y-axes-in-r – Vincent Zoonekynd Jan 23 '12 at 02:10

2 Answers2

4

Try this:

chart_Series(GSPC)
add_Series(OHLC(VIX)+1000,on=1)

You need to use OHLC to remove the volume from VIX, since it's always zero and seems to hose up the automatic ylim calculation. I also added 1000 to make the levels of the two series to be a bit closer together.

Joshua Ulrich
  • 173,410
  • 32
  • 338
  • 418
2

Here is an example that does not use chartSeries.

ind <- function(x) {
  # Divide each column by the first non-NA value
  # (There may already be a function to do that.)
  coredata(x) <- t(t(coredata(x)) / apply(coredata(x),2,function(u){ c(u[!is.na(u)&u!=0],NA)[1] }))
  x
}
x <- cbind( Ad(GSPC), Ad(VIX) )
x <- x["2011-11::"]

# Using base graphics
matplot( 
  index(x), coredata(ind(x)), 
  xlab="", ylab="", main="",
  type="l", lty=1, lwd=3, axes=FALSE 
)
abline(h=1, lty=3, col="lightgrey")
axis(2, las=1)
axis.Date(1, index(x))
box()
legend( "topleft", gsub("\\..*", "", names(x)), lty=1, lwd=3, col=1:2 )

# If you prefer ggplot2
library(ggplot2)
library(reshape2)
d <- data.frame( date = index(x), coredata(ind(x)) )
names(d) <- gsub("\\..*", "", names(d))
d <- melt(d, id.vars="date")
ggplot(d, aes(date, value, color=variable)) + geom_line(size=2)
Vincent Zoonekynd
  • 31,893
  • 5
  • 69
  • 78