使用R中的quantmod绘制SPX与VIX的关系图

时间:2012-01-23 01:17:50

标签: r quantmod

我刚刚介绍了quantmod,并在这里查看了示例 http://www.r-chart.com/2010/06/stock-analysis-using-r.html 我尝试了以下代码,

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

但图表完全超出了规模,所以我希望这个论坛上的一些专家可以告诉我如何正确地绘制这个图。

2 个答案:

答案 0 :(得分:3)

试试这个:

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

您需要使用OHLC从VIX中移除音量,因为它始终为零并且似乎会自动计算ylim。我还添加了1000,以使两个系列的级别更加接近。

答案 1 :(得分:2)

以下是一个不使用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)