-6

这是我计算中国股市贝塔的函数:

mybeta <- function(company) {
  require(quantmod)
  setSymbolLookup(CSI300=list(name="000300.ss",src="yahoo"))
  getSymbols("CSI300",from="2010-01-01",to="2011-01-01")
  setSymbolLookup(SDB=list(name=company,src="yahoo"))
  getSymbols("SDB",from="2010-01-01",to="2011-01-01")
  csi=as.data.frame(weeklyReturn(CSI300))
  sdb=as.data.frame(weeklyReturn(SDB))
  cbeta=merge(csi, sdb, by="row.names")
  cov(cbeta[2],cbeta[3])/var(cbeta[2])
}

当我输入:

mybeta("600005.ss")
                  weekly.returns.y
weekly.returns.x          1.105631

我只想要1.105631输出,而不是“weekly.returns.y”和“weekly.returns.x”。我怎样才能做到这一点?

4

2 回答 2

3

It's clear English isn't your first language, so I will be patient.

You have revealed what you are actually trying to do, so your first two questions (one, two) could have been avoided because they are not useful for solving your actual problem.

Here is a modified version of your function that accomplishes the same goal, with a lot less unnecessary work.

mybeta <- function(company) {
  if(!require(quantmod))
    stop("quantmod must be installed; try install.packages('quantmod')")
  setSymbolLookup(CSI300=list(name="000300.ss",src="yahoo"), 
                  SDB=list(name=company,src="yahoo"))
  getSymbols(c("CSI300","SDB"),from="2010-01-01",to="2011-01-01")
  ret <- merge(weeklyReturn(CSI300),weeklyReturn(SDB))
  cbeta <- cov(ret, use="pairwise.complete.obs")
  cbeta[1,2]/cbeta[1,1]
}
于 2012-07-11T22:57:10.327 回答
2

利用as.numeric

制作函数的最后一行

as.numeric(cov(cbeta[2],cbeta[3])/var(cbeta[2]))

顺便说一句,这里没有理由使用data.frames。 xts太棒了; 接受它。

编辑:除了不需要转换为 之外data.frame,您的函数没有副作用可能更安全(例如,getSymbols("SDB")根据您mybeta最后传递的内容返回不同的值;此外,默认情况下getSymbols分配数据。您.GlobalEnv可能会考虑使用auto.assign=FALSE. 这就是我将如何编辑您的功能:

mybeta <- function(company) {
  require("quantmod")
  CSI300 <- getSymbols("000300.ss", src='yahoo', from="2010-01-01", 
                       to="2011-01-01", auto.assign=FALSE)
  SDB <- getSymbols(company, src='yahoo', from="2010-01-01", to="2011-01-01", 
                    auto.assign=FALSE)
  csi <- weeklyReturn(CSI300)
  sdb <- weeklyReturn(SDB)
  cbeta=merge(csi, sdb)
  as.numeric(cov(cbeta[, 1], cbeta[, 2])/var(cbeta[, 1]))
}
于 2012-07-11T22:29:42.330 回答