将S& P 500曲线添加到Brock值

时间:2016-05-07 17:54:18

标签: r quantmod

我有以下代码用于绘制Brock值

require(quantmod)

# Pull S&P500 from Yahoo
getSymbols("^GSPC", src="yahoo", from="1947-01-01")
# Convert to monthly, since GDP/AAA are quarterly/monthly, respectively
SPX <- to.monthly(GSPC, name="SPX")

# Pull GDP and AAA bond yield from FRED
getSymbols("AAA;GDP", src="FRED")
# Convert xts index to yearmon, so series will merge cleanly
index(AAA) <- as.yearmon(index(AAA))
index(GDP) <- as.yearmon(index(GDP))

# Merge, fill w/NA, and omit all obs where we don't have data for all 3 series
x <- na.omit(merge(SPX, GDP, AAA, fill=na.locf))
indexTZ(x) <- "UTC"  # avoid potential timezone issues with non-datetime index

# Calculate Brock Value
x$BV <- x$GDP/(2*x$AAA)
# plot
plot(log(x[,c("SPX.Close","BV")]), main="Brock Value")

以上代码生成以下图:

enter image description here

我想要实现的是在图上叠加一条S&amp; P 500曲线,如下图所示:

enter image description here

这怎么可能?

2 个答案:

答案 0 :(得分:3)

# Your Plot
plot(index(x), log(x[,"SPX.Close"]), 
     main= "Log Brock Value and Log S&P Close", col = "black",
     ylab = "Log Value", xlab = "Years", type = "l")
lines(index(x), log(x[,c("BV")]), col = "red")
legend('bottomright', c("SPX.Close","Brock"), 
       lty=1, col=c('black', 'red'), bty='n', cex=1.2)

enter image description here

答案 1 :(得分:1)

这是一个ggplot2解决方案:

library(ggplot2)

g1 <- ggplot(data=x, aes(x=Index, y=log(BV), color='Brock')) + geom_line() + 
      geom_line(aes(x=Index, y=log(SPX.Close), color='SPX')) + scale_x_yearmon() +
      labs(x='Date', y='Log10(Value)') + ggtitle('Brock Value') + 
      scale_colour_manual(name="Value", values=c(Brock="black", SPX="indianred"))
g1

enter image description here