rowwise iteration in r on a data table

时间:2016-10-20 12:50:25

标签: r data.table

library(quantmod)
library(PerformanceAnalytics)
getSymbols("YHOO",src="google")
stock_dat=data.table(PerformanceAnalytics::
CalculateReturns(Cl(YHOO)[1:10],'discrete'))
stock_dat[,Price:=0]
stock_dat[1,2]=Cl(YHOO)[1]
stock_dat[,D:=(1+YHOO.Close)*shift(Price,1)] 

The above code generates the below result:

 stock_dat
      YHOO.Close Price     D
 1:           NA 25.61    NA
 2:  0.048418586  0.00 26.85
 3:  0.033147114  0.00  0.00
 4:  0.006488825  0.00  0.00
 5: -0.012177650  0.00  0.00
 6:  0.040609137  0.00  0.00
 7:  0.017421603  0.00  0.00
 8:  0.008561644  0.00  0.00
 9: -0.005432937  0.00  0.00
10: -0.008193923  0.00  0.00

The YHOO.Close is assumed to be a simulated returns and i need to back out the prices from that. And i am using the first price as the base. The above code needs to ideally use the price in D from row 3.

nrowsDF <- nrow(stock_dat)

for(i in 2:nrowsDF){
  stock_dat[i,2]=(1+stock_dat[i,1,with=FALSE])*stock_dat[i-1,2,with=FALSE]
}

The above code solves the problem. But am looking for a more efficent way to do this, as i have to repeat this for over 5000 simulated return series

The below is the answer i actually need

stock_dat
      YHOO.Close Price
 1:           NA 25.61
 2:  0.048418586 26.85
 3:  0.033147114 27.74
 4:  0.006488825 27.92
 5: -0.012177650 27.58
 6:  0.040609137 28.70
 7:  0.017421603 29.20
 8:  0.008561644 29.45
 9: -0.005432937 29.29
10: -0.008193923 29.05

1 个答案:

答案 0 :(得分:4)

您可以使用这样的累积产品:

DT <- fread("      YHOO.Close Price     D
                     NA 25.61    NA
            0.048418586  0.00 26.85
            0.033147114  0.00  0.00
            0.006488825  0.00  0.00
           -0.012177650  0.00  0.00
            0.040609137  0.00  0.00
            0.017421603  0.00  0.00
            0.008561644  0.00  0.00
           -0.005432937  0.00  0.00
           -0.008193923  0.00  0.00")

DT[, res := Price[1] * c(1, cumprod(1 + YHOO.Close[-1]))]
#      YHOO.Close Price     D   res
# 1:           NA 25.61    NA 25.61
# 2:  0.048418586  0.00 26.85 26.85
# 3:  0.033147114  0.00  0.00 27.74
# 4:  0.006488825  0.00  0.00 27.92
# 5: -0.012177650  0.00  0.00 27.58
# 6:  0.040609137  0.00  0.00 28.70
# 7:  0.017421603  0.00  0.00 29.20
# 8:  0.008561644  0.00  0.00 29.45
# 9: -0.005432937  0.00  0.00 29.29
#10: -0.008193923  0.00  0.00 29.05