rowwise iteration in r on a data table

后端 未结 1 1516
闹比i
闹比i 2021-01-21 06:36
library(quantmod)
library(PerformanceAnalytics)
getSymbols(\"YHOO\",src=\"google\")
stock_dat=data.table(PerformanceAnalytics::
CalculateReturns(Cl(YHOO)[1:10],\'discret         


        
1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 07:17

    You can use the cumulative product like this:

    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
    

    0 讨论(0)
提交回复
热议问题