循环计算价格回报

时间:2017-03-24 09:37:40

标签: r return-value

我有以下代码来计算并生成一个data.frame,其中包含我的收盘价表的日志重新调整。出于某种原因,我只得到0值。不确定问题是否在n值或i值上。

 number <- c(1:505)
    n <- nrow(data_all)
    for (i in number)
    {returns <- log(data_all[2:n, i]) - log(data_all[1:(n-1), i])
    if (i == number[1]) returns_all <- returns else
      returns_all <- merge(returns_all, returns)
rm(returns)    
}

感谢帮助。

2 个答案:

答案 0 :(得分:0)

我根据你的问题做了一个演示。 代码是

data_all <- as.data.frame(matrix(data = runif(10000,1,50),ncol = 505))
number <- c(1:505)
n <- nrow(data_all)
for (i in number)
{
  returns <- log(data_all[2:n, i]) - log(data_all[1:(n-1), i])
  if (i == number[1]) 
    returns_all <- returns 
  else
    returns_all <- merge(returns_all, returns)
}

我建议您可以按照以下步骤进行操作,

data_all <- as.data.frame(matrix(data = runif(10000,1,50),ncol = 505))
number <- c(1:505)
n <- nrow(data_all)
returns_all <- NULL #I add
for (i in number)
{
  returns <- log(data_all[2:n, i]) - log(data_all[1:(n-1), i])
  returns_all <- cbind(returns_all,returns) #I add
}

我希望我能帮助你。

答案 1 :(得分:0)

log(a) - log(b) = log(a/b)起,您可以使用difflog函数进行计算 价格系列的回报如下:

对于多个系列,我建议将系列转换为xts系列

library("xts")

#if closePx is price series with first column as date with format = 2002-02-12
#specify the corresponding date format , %Y-%m-%d, 
#2002/02/12 => %Y/%m/%d
#closePx_xts = xts(closePx[,-1],order.by = as.Date(closePx[,1],format="%Y-%m-%d")

library("quantmod")

#create environment to store price data
stockNames = c("IBM","MSFT")
dataEnv = new.env()
getSymbols(stockNames, env = dataEnv, from = "2002-01-01", to = "2010-01-01")

#check prices

ls(dataEnv)

head(dataEnv$IBM)
head(dataEnv$MSFT)



#combine closing prices, using Cl function on each list member get closing price 
#for each stock and use merge.xts to combine prices
#if you have missing prices checkout `zoo::na.locf` function
#i.e. na.locf function from zoo package

closePx = do.call(merge.xts,lapply(dataEnv,Cl))

#closePx = Cl(IBM)

#log returns
logRet = diff(log(closePx))


head(logRet)
#              IBM.Close   MSFT.Close
#2002-01-02           NA           NA
#2002-01-03  0.017621634  0.032144867
#2002-01-04  0.015566342 -0.004778131
#2002-01-07 -0.012417504 -0.004946962
#2002-01-08  0.005226094  0.011889353
#2002-01-09 -0.001685453 -0.009703864

使用滞后函数,您可以按如下方式计算离散/算术返回值

#discrete returns
discRet = closePx/lag(closePx) - 1


head(discRet)
#              IBM.Close   MSFT.Close
#2002-01-02           NA           NA
#2002-01-03  0.017777811  0.032667094
#2002-01-04  0.015688128 -0.004766734
#2002-01-07 -0.012340725 -0.004934746
#2002-01-08  0.005239774  0.011960312
#2002-01-09 -0.001684034 -0.009656933

另外PerformanceAnalytics包用于更多实用程序功能