-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.frameここで s を使用する理由はありません。 xtsすごい; それを受け入れます。

編集: に変換する必要がないことに加えてdata.frame、関数に副作用がない方がおそらく安全です (たとえば、最後getSymbols("SDB")に渡したものに応じて異なる値を返します。また、デフォルトでデータを割り当てます。これは私があなたの関数を編集する方法です:mybetagetSymbols.GlobalEnvauto.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 に答える