我想根据一种工具的价格来计算日记收入。
instrument=c(1,2,3,4,5,1,2,3,4,5,1,2,3,4,5)
price=c(12,13,29,20,87,24,14,78,46,98,23,67,25,88,27)
date=c("2019-04-01","2019-04-01","2019-04-01","2019-04-01","2019-04-01","2019-04-02","2019-04-02","2019-04-02","2019-04-02","2019-04-02","2019-04-03","2019-04-03","2019-04-03","2019-04-03","2019-04-03")
tabla1=data.frame(instrument,price,date)
我想知道如何计算在日期2019-04-01至2019-04-02之间从工具1赚取的钱
答案 0 :(得分:0)
如果您希望每日收益为p(t) / p(t-1) - 1
,则:
library(data.table)
dt <- as.data.table(tabla1)
dt[, return := price / shift(price) - 1, by = .(instrument)]