【发布时间】:2020-04-22 11:20:15
【问题描述】:
我是 R 新手,目前正在尝试根据特定分数创建等权重的投资组合,但我在部分代码方面遇到了一些问题。我为得分最高和最低的贡献者创建了单独的数据框,并计算了每月回报。数据集现在看起来像这样:
Company Year Score Date Return Market Value
Company x 2008 26.26 2008-01-01 -0.32 601.26
Company x 2008 26.26 2008-02-01 -0.10 410.65
Company x 2008 26.26 2008-03-01 -0.06 369.80
Company x 2008 26.26 2008-04-01 0.01 348.15
Company x 2008 26.26 2008-05-01 0.28 353.10
Company x 2008 26.26 2008-06-01 -0.25 452.43
Company x 2008 26.26 2008-07-01 0.11 338.91
Company x 2008 26.26 2008-08-01 0.15 376.86
Company x 2008 26.26 2008-09-01 -0.12 433.62
Company x 2008 26.26 2008-10-01 -0.27 383.72
Company x 2008 26.26 2008-11-01 -0.25 281.95
Company x 2008 26.26 2008-12-01 -0.17 211.20
我的最终目标是从高投资组合中减去表现不佳的投资组合,看看高投资组合是否会带来异常回报。为此,我想编写一个 if 函数,该函数允许我指定如果 previous 月份的市场价值 > 0,那么我希望我的回报列成倍增加与相应的权重列。我遇到了这个问题,因为我的数据集中的一些公司在这一年中被除名,然后需要在一年中的剩余月份将权重重新分配给剩余的公司。 各种网站都提供了很大的帮助(尤其是这个:https://www.codingfinance.com/post/2018-04-05-portfolio-returns/),但我似乎无法找到解决上述问题的方法。感谢所有帮助,如果代码混乱,我深表歉意,谢谢。
returnhigh <- highport %>%
group_by(Company) %>%
# Trying to add the weight constraint
if(test$`Market Value` > 0) {
# This is the part where I struggle to specify the market value of the previous month
returnhigh$Weight <- 1/length(highport$Company)
}
returnhigh <- returnhigh %>% mutate(wt_return = Weight * Return)
porthigh <- returnhigh %>% group_by(Date) %>% summarise(port_ret = sum(wt_return))
returnlow <- lowport %>%
group_by(Company) %>%
if(test$`Market Value` > 0) {
# Same problem as above
returnlow$Weight <- 1/length(lowport$Company)
}
returnlow <- returnlow %>% mutate(wt_return = Weight * Return)
portlow <- returnlow %>% group_by(Date) %>% summarise(port_ret = sum(wt_return))
result <- porthigh - portlow
return(result)
}
【问题讨论】:
-
欢迎来到 SO。人们很难根据您提供的代码来帮助您。添加一些示例数据集和您想要的输出将会很棒。
-
谢谢弗兰克,我现在添加了更多上下文。如果还有什么我可以提供的,请告诉我。
标签: r if-statement portfolio