在给定条件的情况下更改排名中的值

Changing the value in a rank given a condition

我正在尝试将按 return 排名的 table 股票转换为值矩阵,该值矩阵将作为投资组合中股票的权重输入 PerformanceAnalytics::ReturnPortfolio .

我特别想做的是将33%最好的股票的排名值转换为1,33%表现最差的股票为-1,其余为0。

这是原始代码,我只选取最好的股票并将其排名值更改为 1:

asset_ranking <- db_Momentum %>%
  dplyr::select(-date) %>%
  as.matrix() %>%
  rowRanks(ties.method = "min") %>%
  as.data.frame() %>%
  dplyr::mutate(date = db_Momentum$date) %>%
  dplyr::select(date, everything()) %>%
  purrr::set_names(c("date", tickets)) %>%
  as_tibble()

# Analyzing Sector Selection
asset_selection <- asset_ranking %>%
  mutate_if(is.numeric, ~ + ( . > (length(tickets) - n_assets_buy))) %>%
  dplyr::select(-date)

这是现在的例子:

AAPL IBM KO T TLT SPY
1 2 3 4 6 5
2 1 3 5 4 6
1 4 2 5 3 6
6 4 5 2 1 3

这就是我想要的:

AAPL IBM KO T TLT SPY
1 1 0 0 -1 -1
1 1 0 -1 0 -1
1 0 1 -1 0 -1
-1 0 -1 1 1 0

我们可以遍历 applyMARGIN = 1 的行,得到 quantileprobs 作为 .33.67,在 cut 中将其作为 breaks 传递,转换为 integer 并使用该索引将值替换为 1、0、-1

asset_selection[] <- t(apply(asset_selection, 1, function(x)
   c(1, 0, -1)[as.integer(cut(x, c(-Inf, quantile(x, c(.33, .67)), Inf)))]))

-输出

asset_selection
#  AAPL IBM KO  T TLT SPY
#1    1   1  0  0  -1  -1
#2    1   1  0 -1   0  -1
#3    1   0  1 -1   0  -1
#4   -1   0 -1  1   1   0

数据

asset_selection <- structure(list(AAPL = c(1, 2, 1, 6), 
      IBM = c(2, 1, 4, 4), KO = c(3, 
 3, 2, 5), T = c(4, 5, 5, 2), TLT = c(6, 4, 3, 1), SPY = c(5, 
6, 6, 3)), class = "data.frame", row.names = c(NA, -4L))