我有一个实现(股票)波动率的xts对象,我想对每个股票/柱子施加最小波动率。这是一个我无法正常工作的样本。它奇怪地循环通过最小的vol矢量。谢谢。
require(xts)
set.seed(3)
A <- matrix(runif(18, max=0.30), ncol=3)
A.xts <- xts(A, Sys.Date()-6:1)
Min_Vols <- c(.10, .20, .30)
B <- pmax(as.matrix(A.xts), Min_Vols)
A.xts; B
以上生成
[,1] [,2] [,3]
2015-08-28 0.05041246 0.03739003 0.16021061
2015-08-29 0.24225492 0.08838028 0.16717483
2015-08-30 0.11548271 0.17328298 0.26037585
2015-08-31 0.09832030 0.18929378 0.24891261
2015-09-01 0.18063020 0.15360477 0.03343475
2015-09-02 0.18131822 0.15150717 0.21110651
[,1] [,2] [,3]
2015-08-28 0.1000000 0.1000000 0.1602106
2015-08-29 0.2422549 0.2000000 0.2000000
2015-08-30 0.3000000 0.3000000 0.3000000
2015-08-31 0.1000000 0.1892938 0.2489126
2015-09-01 0.2000000 0.2000000 0.2000000
2015-09-02 0.3000000 0.3000000 0.3000000
我希望B成为:
[,1] [,2] [,3]
2015-08-28 0.10000000 0.20000000 0.30000000
2015-08-29 0.24225492 0.20000000 0.30000000
2015-08-30 0.11548271 0.20000000 0.30000000
2015-08-31 0.10000000 0.20000000 0.30000000
2015-09-01 0.18063020 0.20000000 0.30000000
2015-09-02 0.18131822 0.20000000 0.30000000
答案 0 :(得分:2)
您可以使用sapply
在各列中强加约束
B<-sapply(1:ncol(A),function(i) pmax(A[,i],Min_Vols[i]))
xts(B,index(A.xts))
#> [,1] [,2] [,3]
#> 2015-08-28 0.1000000 0.2 0.3
#> 2015-08-29 0.2422549 0.2 0.3
#> 2015-08-30 0.1154827 0.2 0.3
#> 2015-08-31 0.1000000 0.2 0.3
#> 2015-09-01 0.1806302 0.2 0.3
#> 2015-09-02 0.1813182 0.2 0.3
答案 1 :(得分:1)
你有几个选择。您可以创建一个矩阵以传递给pmax
:
MinVolMatrix <- matrix(Min_Vols, nrow(A), ncol(A), byrow=TRUE)
B <- as.xts(pmax(as.matrix(A.xts), MinVolMatrix))
您可以使用apply
(请注意,由于apply
构造其输出的方式,您必须转置结果):
B <- as.xts(t(apply(A.xts, 1, pmax, Min_Vols)))