仅使用平均收益向量和协方差矩阵进行 R 中的投资组合优化

2024-01-12

我看到的每个包似乎都需要我的资产的时间序列回报。

例如,我喜欢 PortfolioAnalytics 包,并且我需要提供的许多约束(框约束、组约束等)。然而,据我所知,它需要某种时间序列的回报,即使我指定了我自己的时刻(我可能是错的)。

我所拥有的只是 14 项资产中每项资产的预期回报和协方差矩阵。

我如何以此为出发点进行各种形式的优化?最终,我希望建立一个完全有效的边界,并且能够在给定的风险水平(标准差)给定的限制下最大化回报。如果我有一个时间序列,这不会是一个问题......但可惜我没有。

谢谢。我觉得这应该很容易,但我一直在兜圈子。

最坏的情况是我可以构建一个适合 E(R) 和协方差矩阵参数的假时间序列..如果您认为这是我的解决方案,您能为我提供一种简单的方法来做到这一点...但这就是原因我在这里 :)


这个怎么样?

library(stockPortfolio)
library(quadprog)
library(ggplot2)
stocks <- c("SPY",  "EFA",  "IWM",  "VWO",  "LQD",  "HYG")

returns <- getReturns(stocks, freq = "week")

eff.frontier <-  function (returns,
                           short = "no",
                           max.allocation = NULL,
                           risk.premium.up = .5,
                           risk.increment = .005) {
  covariance <- cov(returns)
  print(covariance)
  n <- ncol(covariance)

  # Create initial Amat and bvec assuming only equality constraint (short-selling is allowed, no allocation constraints)
  Amat <- matrix (1, nrow = n)
  bvec <- 1
  meq <- 1

  # Then modify the Amat and bvec if short-selling is prohibited
  if (short == "no") {
    Amat <- cbind(1, diag(n))
    bvec <- c(bvec, rep(0, n))
  }

  # And modify Amat and bvec if a max allocation (concentration) is specified
  if (!is.null(max.allocation)) {
    if (max.allocation > 1 | max.allocation < 0) {
      stop("max.allocation must be greater than 0 and less than 1")
    }
    if (max.allocation * n < 1) {
      stop("Need to set max.allocation higher; not enough assets to add to 1")
    }
    Amat <- cbind(Amat, -diag(n))
    bvec <- c(bvec, rep(-max.allocation, n))
  }

  # Calculate the number of loops based on how high to vary the risk premium and by what increment
  loops <- risk.premium.up / risk.increment + 1
  loop <- 1

  # Initialize a matrix to contain allocation and statistics
  # This is not necessary, but speeds up processing and uses less memory
  eff <- matrix(nrow = loops, ncol = n + 3)
  # Now I need to give the matrix column names
  colnames(eff) <-
    c(colnames(returns), "Std.Dev", "Exp.Return", "sharpe")

  # Loop through the quadratic program solver
  for (i in seq(from = 0, to = risk.premium.up, by = risk.increment)) {
    dvec <-
      colMeans(returns) * i # This moves the solution up along the efficient frontier
    sol <-
      solve.QP(
        covariance,
        dvec = dvec,
        Amat = Amat,
        bvec = bvec,
        meq = meq
      )
    eff[loop, "Std.Dev"] <-
      sqrt(sum(sol$solution * colSums((
        covariance * sol$solution
      ))))
    eff[loop, "Exp.Return"] <-
      as.numeric(sol$solution %*% colMeans(returns))
    eff[loop, "sharpe"] <-
      eff[loop, "Exp.Return"] / eff[loop, "Std.Dev"]
    eff[loop, 1:n] <- sol$solution
    loop <- loop + 1
  }

  return(as.data.frame(eff))
}

eff <-
  eff.frontier(
    returns = returns$R,
    short = "yes",
    max.allocation = .45,
    risk.premium.up = .5,
    risk.increment = .001
  )


eff.optimal.point <- eff[eff$sharpe == max(eff$sharpe),]

ealred  <- "#7D110C"
ealtan  <- "#CDC4B6"
eallighttan <- "#F7F6F0"
ealdark  <- "#423C30"
ggplot(eff, aes(x = Std.Dev, y = Exp.Return)) + geom_point(alpha = .1, color =
                                                             ealdark) +
  geom_point(
    data = eff.optimal.point,
    aes(x = Std.Dev, y = Exp.Return, label = sharpe),
    color = ealred,
    size = 5
  ) +
  annotate(
    geom = "text",
    x = eff.optimal.point$Std.Dev,
    y = eff.optimal.point$Exp.Return,
    label = paste(
      "Risk: ",
      round(eff.optimal.point$Std.Dev * 100, digits = 3),
      "\nReturn: ",
      round(eff.optimal.point$Exp.Return * 100, digits =
              4),
      "%\nSharpe: ",
      round(eff.optimal.point$sharpe * 100, digits = 2),
      "%",
      sep = ""
    ),
    hjust = 0,
    vjust = 1.2
  ) +
  ggtitle("Efficient Frontier\nand Optimal Portfolio") + labs(x = "Risk (standard deviation of portfolio variance)", y =
                                                                "Return") +
  theme(
    panel.background = element_rect(fill = eallighttan),
    text = element_text(color = ealdark),
    plot.title = element_text(size = 24, color = ealred)
  )

这也应该有帮助。

https://www.r-bloggers.com/a-gentle-introduction-to-finance-using-r-efficient-frontier-and-capm-part-1/ https://www.r-bloggers.com/a-gentle-introduction-to-finance-using-r-efficient-frontier-and-capm-part-1/

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

仅使用平均收益向量和协方差矩阵进行 R 中的投资组合优化 的相关文章

  • 按组复制数据框

    我有以下数据框 df structure list Group c 1 1 1 1 2 2 2 2 2 2 3 3 3 index c 1 2 3 4 1 2 3 4 5 6 1 2 3 row names c NA 13L class c
  • 使用 R SOAP (SSOAP) 检索数据/抓取

    在 B cycle 页面 www bcycle com whowantsitmore aspx 上 我试图抓取投票的位置和值 The URL http mapservices bcycle com bcycleservice asmx ht
  • Shiny :针对所有错误显示一条消息

    我在 R 的 Shiny 中有一个应用程序 我想处理消息 以便用户看不到发生了什么错误 我知道通过 tags style type text css shiny output error visibility hidden shiny ou
  • 在zooreg时间序列中查找非唯一索引条目时遇到问题

    我有几年的数据正在尝试将其转化为动物园对象 Dropbox 上的 csv https www dropbox com sh vg8w8pt16e0v3xs AABKtWqDkPu9JVKpwBXO36VOa dl 0 一旦数据被强制转换为动
  • R 无法回忆起内存中的对象

    我正在构建一个包含多个步骤的函数 其中每个步骤都会创建一个对象 某个步骤失败 temp3 并且无法找到前面的步骤对象 错误 未找到对象 temp2 我不知道为什么 我有类似的函数 遵循完全相同的结构 每个步骤都遵循先前创建的对象 在函数内
  • 基本 dyplr 函数给出错误:“check_dots_used”

    试图找出为什么我会收到此错误 以前从未见过 谷歌没有帮助 check dots used action warn 中的错误 未使用参数 action warn 我在下面的非常基本的试验中收到错误 而且在 group by count 中也收
  • 如何将 Shiny 中生成的反应图传递到 Rmarkdown 以生成动态报告

    简而言之 我希望能够通过单击按钮从我的闪亮应用程序生成动态 Rmarkdown 报告文件 pdf 或 html 为此 我想我将使用 Shiny 的参数化报告 但不知何故 我无法将单个谜题转移到所需的目标 使用此代码 我们可以在 R Shin
  • ggplot2 + 使用比例 X 的日期结构

    我真的需要帮助 因为我已经迷路了 我正在尝试创建一个折线图 显示几个团队一年来的表现 我将一年分为几个季度 2012 年 1 月 1 日 2012 年 4 月 1 日 2012 年 8 月 1 日 12 1 12 并将 csv 数据帧加载到
  • NumericVector 和 vector 之间有性能差异吗?

    假设有人使用NumericVector和其他用途vector
  • R 中舍入到下一个数量级的算法

    如果标题不清楚 我很抱歉 但我无法简洁地解释它 给定一个浓度向量 我想将最大值四舍五入到下一个数量级 即 345 到 1000 另外 我想将最小值四舍五入到较低的数量级 即 3 2 到 1 这些浓度也可能低于 1 因此例如 0 034 需要
  • data.table 查找值并翻译

    像许多人一样 我是 R 新手 我有一个大数据集 500M 行 我已将其读取到 data table 中logStats其中有如下数据 head logStats 15 time pid mean 1 2014 03 10 00 00 00
  • dplyr::group_by_ 带有多个变量名的字符串输入

    我正在编写一个函数 要求用户在函数调用中定义一个或多个分组变量 然后使用 dplyr 对数据进行分组 如果只有一个分组变量 它会按预期工作 但我还没有弄清楚如何使用多个分组变量来做到这一点 Example x lt c cyl y lt c
  • R xts 对象中从每日时间序列到每周时间序列

    我正在使用 Zoo 和 xts 包来分析财务数据 ts 包不太合适 因为金融系列有周末 没有可用数据 我读到了 xts 包中可用的 apply 函数 apply daily x FUN apply weekly x FUN apply mo
  • Rcpp 包不包含 Rcpp_precious_remove

    我一直在尝试创建数据库并安装 DBI 包 但仍然遇到此错误 我重新安装了 DBI 和 RSQLite 软件包 但它们似乎不起作用 library DBI con lt dbConnect RSQLite SQLite dbname memo
  • 是否可以创建根据输入对象名称自行命名的列表?

    能够创建 R 列表对象而无需指定每个元素的名称对我来说非常有帮助 例如 a1 lt 1 a2 lt 20 a3 lt 1 20 b lt list a1 a2 a3 inherit name TRUE gt b a1 1 1 a2 1 20
  • “x[] <- as.integer(x)”是什么意思

    当我阅读 R 手册时 我遇到了如下代码行 从 R 手册中的 colSums 复制 x lt cbind x1 3 x2 c 4 1 2 5 dimnames x 1 lt letters 1 8 x lt as integer x 有人能告
  • 有什么方法可以禁用 PDF/Postscript 输出中的“减号破解”吗?

    在 R 中 将绘图保存到 PDF 或 Postscript 文件时 轴标签中的连字符会变成减号 显然 这是设计使然 根据 postscript 设备的文档 正常编码规则 有一个例外 字符 45 始终设置为负号 其在 Adob e ISOLa
  • R中的for循环和if函数

    我正在用 R 中的 if 函数编写一个循环 表格如下 ID category 1 a 1 b 1 c 2 a 2 b 3 a 3 b 4 a 5 a 我想使用 for 循环和 if 函数添加另一列来计算每个分组的 ID 如下所示的计数列 I
  • Pyspark - 一次聚合数据帧的所有列[重复]

    这个问题在这里已经有答案了 我想将数据框分组到单个列上 然后对所有列应用聚合函数 例如 我有一个包含 10 列的 df 我希望对第一列 1 进行分组 然后对所有剩余列 均为数字 应用聚合函数 sum 与此等效的 R 是 summarise
  • 使用 numpy 加速 for 循环

    下一个 for 循环如何使用 numpy 获得加速 我想这里可以使用一些奇特的索引技巧 但我不知道是哪一个 这里可以使用 einsum 吗 a 0 for i in range len b a numpy mean C d e f b i

随机推荐