[英]How can I loop through the r tvm "XIRR" function to calculate xirr for different trade strategies?
I'm importing a data frame from a csv file that looks like the below, however with hundreds of strategies and thousands of cash flows for each strategy:我正在从 csv 文件中导入一个数据框,该文件如下所示,但是每个策略都有数百个策略和数千个现金流:
TRADE_STRATEGY EVENT_DATE BOOK_VALUE_USD
A 1/1/2021 -1.5
A 2/28/2021 -2
A 3/31/2021 4
B 2/1/2021 -1.75
B 3/31/2021 -1.25
B 4/30/2021 5.75
How can I loop through the XIRR function that would save results in a data frame?如何循环通过 XIRR function 将结果保存在数据框中? Ie IE
TRADE_STRATEGY IRR
A 1.357539928
B 2.48654511
I can suggest using the group_by()
function of the dplyr
library.我可以建议使用dplyr
库的group_by()
function。
With this, you may group your "data.frame" into different trade strategies ( TRADE_STRATEGY
) and them compute the IRR on the cash flow ( BOOK_VALUE_USD
)有了这个,您可以将您的“data.frame”分组为不同的交易策略( TRADE_STRATEGY
),然后他们计算现金流的内部收益率( BOOK_VALUE_USD
)
Note that I did not know which IRR function to use in R so I decided to use the one suggested by @dmi3kno in this post .请注意,我不知道在 R 中使用哪个 IRR function,所以我决定使用@dmi3kno 在这篇文章中建议的那个。
Here is the code:这是代码:
df <- data.frame(list(
TRADE_STRATEGY = c("A", "A", "A", "B", "B", "B"),
EVENT_DATE = c("1/1/2021", "2/28/2021", "3/31/2021", "2/1/2021", "3/31/2021", "4/30/2021"),
BOOK_VALUE_USD = c(-1.5, -2, 4, -1.75, -1.25, 5.75)
))
df %>%
group_by(TRADE_STRATEGY) %>%
summarise(IRR_value = irr(BOOK_VALUE_USD)$IRR) # The irr() function from @dmi3kno
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.