0

我有一个数据框p1,其中包含每月股票收益的时间序列,每个月大约有 500 只股票。我正在尝试计算每个月的投资组合回报、投资组合方差和夏普比率。为此,我想使用该PortfolioAnalytics包,分别应用 Return.portfolio()、var.portfolio() 和 SharpeRatio()。

我想要的输出将是一个新的数据框 ( p1pofo),它由四列 ( "monthyear", "PofoRet", "PofoVar", "PofoSharpe") 组成,每个值都有一行"monthyear"

为了做到这一点,我尝试拆分数据框,然后应用相应的函数,例如 Return.portfolio():

library(PortfolioAnalytics)
library(dplyr)
p1pofo <- p1 %>%
  split(list(p1$monthyear)) %>%
  map_df(~ mutate(., PofoRet=Return.portfolio(p1$MonthlyReturnT1, p1$EWweights)))

但是,我收到以下错误:

Error in try.xts(x, error = "'x' needs to be timeBased or xtsible") : 
  'x' needs to be timeBased or xtsible

任何有关我的代码缺陷或解决我的任务的替代方法的帮助将不胜感激。

可重现的数据样本:

p1 <- structure(list(PERMNO = c(10074, 10085, 10242, 10296, 10304, 
10376, 10074, 10242, 10376, 10446), date = structure(c(9129, 
9129, 9129, 9127, 9129, 9129, 9161, 9161, 9161, 9161), class = "Date"), 
    monthyear = c(199412, 199412, 199412, 199412, 199412, 
    199412, 199501, 199501, 199501, 199501), MonthlyReturnT1 = c(0.0638297872340425, 
    0.00714285714285712, 0.115384615384615, -0.0404040404040404, 
    -0.0379746835443038, 0.0510204081632653, 0.0208333333333333, 
    -0.0333333333333333, -0.00970873786407767, 0.0204081632653061
    ), EWweights = c(0.0040650406504065, 0.0040650406504065, 
    0.0040650406504065, 0.0040650406504065, 0.0040650406504065, 
    0.0040650406504065, 0.00395256916996047, 0.00395256916996047, 
    0.00395256916996047, 0.00395256916996047)), row.names = c(1L, 
2L, 3L, 4L, 5L, 6L, 247L, 248L, 249L, 250L), class = "data.frame")
4

0 回答 0