2014-01-21 31 views
0

我有每月的重量觀察和每日回報,並且我試圖計算一個月內每天的幾何回報。它可能會更容易看到這個模式:從每月觀察得到的每日幾何收益

desired output, from Excel

如何重現「所需的輸出」列?無論是來自R中基本功能的解決方案還是任何軟件包建議,都將受到讚賞!

  • 編輯1: 謝謝。

下面是一些樣本數據和我一直在努力解決方案:

set.seed(33) 

z <- c(.35,NA,NA,NA,.2,NA,NA) 
z1 <- c(.35,.35,.35,.35,.2,.2,.2) 
z2 <- rnorm(7) 
zCbind <- data.frame(cbind(z,z1,z2)) 
colnames(zCbind) <- c("months","na.locf(months)","values") 

solution1 <- ifelse(zCbind[,1] == zCbind[,2], 
       zCbind[,1],         # if TRUE 
       zCbind[,2]*apply(zCbind[,3],2,cumprod))  # if FALSE 

我知道我的問題是在假條件。我已經嘗試解決方案是:

  1. 與刺功能
  2. 改變zCbind的格式替換cumprod [1,3]通過結合或將其轉換矩陣/ DF
  3. 這看上去有希望的,但我不能找不到任何更多的文獻對「cumprod.column」包裝的cumprod功能:http://braverock.com/brian/R/PerformanceAnalytics/html/cum.utils.html
+0

你應該提供一些數據,你已經嘗試了什麼。請閱讀[this](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example)。 – agstudy

+0

所以你想根據上個月的固定權重的最後一天加上每日增量的彙總來計算每日加權? – Troy

回答

0

這個怎麼樣用plyr::ddply()

我重新創建你的數據使它更像原來的格式

sheet<-data.frame(date=as.Date(1:100,origin="2012-01-01"), 
        weight=rep(NA,100), 
        increment=rnorm(100,0,0.5)/100 
      ) 

#get the latest date in each month to replace the NAs 
last_days<-ddply(sheet,.(month=format(date,"%Y-%b")),summarise,last_day=max(date)) 
sheet[sheet$date %in% last_days$last_day,]$weight<-runif(nrow(last_days))/2 

#now we have a table which matches your data 

#set the NA's to 0 
sheet$weight[is.na(sheet$weight)]<-0 

# OK so here you add your seed value for the first month (0.4 in this example) 
# and shift forward into the last month 
sheet$shift<-c(0.4,sheet$weight[1:nrow(sheet)-1]) 

sheet.out<- 
ddply(sheet, 
     .(month=format(date,"%Y-%b")), 
     summarise, 
     date=date, 
     inc=increment,  
     output=cumprod(ifelse(shift==0,1+increment,max(shift)*(1+increment))) #cum product of seed val and day rets 
    ) 

# and lastly update the last days to be the original weight 
sheet.out$output<-ifelse(sheet$weight!=0,sheet$weight,sheet.out$output) 

head(sheet.out) 

#  month  date   inc output 
#1 2012-Apr 2012-04-01 0.0018504578 0.3234371 
#2 2012-Apr 2012-04-02 0.0017762242 0.3240116 
#3 2012-Apr 2012-04-03 0.0091980829 0.3269919 
#4 2012-Apr 2012-04-04 -0.0023334368 0.3262289 
#5 2012-Apr 2012-04-05 0.0042003969 0.3275992 
#6 2012-Apr 2012-04-06 0.0005409113 0.3277764 
+0

特洛伊這似乎是一個解決方案!我應該在我的原始文章中澄清,但我期望對具有自身重量和增量值的多個代幣進行此分析。我可以縮放你的方法來輸出一個矩陣嗎? – jonnie