R语言 按组和在滚动时间范围内应用自定义函数

wljmcqd8  于 2023-05-04  发布在  其他
关注(0)|答案(1)|浏览(119)

我有一些股票收益的数据。它包括两个投资者在相同的五个月内的投资组合。两个投资者持有的同一只股票的数量不同。这些投资组合权重在相关月份不会发生变化。

returns_df <- data.frame(
Investor = c("Jane","Jane","Jane","Jane","Jane","Tom","Tom","Tom","Tom","Tom"),
Month = c("January","February","March","April","May","January","February","March","April","May"),
Stock_A = c(0.2,0.3,-0.1,0.2,0.4,0.2,0.3,-0.1,0.2,0.4),
Stock_B = c(0.1,-0.3,0.5,0.6,-0.1,0.1,-0.3,0.5,0.6,-0.1),
Stock_C = c(0.5,0.7,-0.3,-0.3,0.1,0.5,0.7,-0.3,-0.3,0.1),
Weight_Stock_A = c(0.5,0.5,0.5,0.5,0.5,0.2,0.2,0.2,0.2,0.2),
Weight_Stock_B = c(0.2,0.2,0.2,0.2,0.2,0.4,0.4,0.4,0.4,0.4),
Weight_Stock_C = c(0.3,0.3,0.3,0.3,0.3,0.4,0.4,0.4,0.4,0.4))

我有一个自定义的R函数可以计算股票组合的方差-

lvar <- function(x, weights, na.rm = TRUE) {
      if (missing(weights)) {
        weights <- rep(1, ncol(x))
    }
  
    covmat <- var(x = x, na.rm = na.rm)
    utc <- upper.tri(covmat)
    wt.var <- sum(diag(covmat) * weights^2)
    wt.cov <- sum(weights[row(covmat)[utc]] *
                  weights[col(covmat)[utc]] *
                  covmat[utc])
    variance <- wt.var + 2 * wt.cov
    return(variance)
      }

我想计算每个投资者在三个月滚动窗口(1月至3月,2月至4月等)而不是整个五个月内的加权投资组合波动率。
以下计算了数据中整个五个月的投资组合波动率。如何在三个月的滚动窗口中为每个投资者应用它?谢谢大家。

library(dplyr)
returns_df %>% 
  reframe(out = lvar(pick(starts_with("Stock")), 
  weights = pick(starts_with("Weight"))), .by = Investor)
7d7tgy0s

7d7tgy0s1#

试试看

library(dplyr) # version >= 1.1.0
library(slider)
returns_df %>% 
 reframe(out = slide_dbl(row_number(), .after = 2,
   .f = \(i) lvar(pick(starts_with("Stock")) %>% slice(i),
   weights = pick(starts_with("Weight")) %>% slice(i)), .complete = TRUE), 
  .by = Investor) %>% 
 drop_na(out)

相关问题