![](/img/trans.png)
[英]How can I loop through the r tvm "XIRR" function to calculate xirr for different trade strategies?
[英]How to loop the xirr function in r over multiple ID's
我想為表中的每個ID計算IRR(使用包tvm中的xirr函數),其中每個ID具有不同的行數。 我相信我必須使用第一次出現到最后一次出現1,但是在那之后,我不確定該怎么做。 有沒有人有什么建議?
我在下面發布了一個示例數據框,為此,我嘗試在dplyr中將summary函數與xirr函數一起使用,並編寫一個for循環。 沒有成功
exampledf<-data.frame(c(2, 2, 2, 3, 3, 3, 3, 3), c("2017-11-30", "2017-12-31", "2018-01-31", "2017-11-30", "2017-12-31", "2018-01-31", "2018-02-28", "2018-03-31"), c(-65000, 33000, 33000, -40000, 10250, 10250, 10000, 10500))
names(exampledf)<-c("ID","Date","CashFlow")
exampledf %>% group_by(ID) %>% summarise(
IRR = xirr(cf = exampledf$CashFlow, d = exampledf$Date, tau = NULL, comp_freq = 12, interval = c(-1, 10)))
預期結果應類似於:
ID IRR
1 2 0.127
2 3 0.125
當前,在運行summary函數時,它對兩個ID返回相同的IRR,事實並非如此。 我對for循環的嘗試也未成功,這里的任何幫助將不勝感激!
我們需要從summarise
刪除example$
,因為example$
將選擇整個列,而不是每個'ID'中的'CashFlow'。 此外,“日期”列類型應更改為“ Date
library(dplyr)
library(tvm)
exampledf %>%
mutate(Date = as.Date(Date)) %>%
group_by(ID) %>%
summarise(
IRR = xirr(cf =CashFlow, d = Date,
tau = NULL, comp_freq = 12, interval = c(-1, 10)))
# A tibble: 2 x 2
# ID IRR
# <dbl> <dbl>
#1 2 0.121
#2 3 0.119
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.