我有一个矩阵,其中有多列(每列代表一家公司)和多行(由股票价格组成)
我想在不使用包的情况下计算退货!
我尝试使用双重for-Loop来执行此操作,但是它不起作用,但出现错误:
“ Portf_Returns [i,j]中的错误<-Portf_ClosingPrices [i + 1,j] / Portf_ClosingPrices [i,: 矩阵上的下标数目不正确”
# Trying to compute Returns in a matrix of stock Prices with double for-loop
ClosingPrices <- sample(10,30,10) # I generate some random stock prices
Portf_ClosingPrices <- matrix(ClosingPrices,nrow = 10, ncol = 3) # 3 companies (3 colums) and 10 stock prices for each company
Portf_Returns <- NULL
i <- 1
j <- 1
for (j in 1:3) {
for (i in 1:9) {
Portf_Returns[i,j] <- Portf_ClosingPrices[i+1,j] / Portf_ClosingPrices[i,j] - 1
}
}
Portf_Returns
答案 0 :(得分:0)
您需要初始化矩阵以返回值:
ClosingPrices <- sample(10,30,10) # I generate some random stock prices
Portf_ClosingPrices <- matrix(ClosingPrices,nrow = 10, ncol = 3) # 3 companies (3 colums) and 10 stock prices for each company
Portf_Returns <- matrix(NA,10,3)
for (j in 1:3) {
for (i in 1:9) {
Portf_Returns[i,j] <- Portf_ClosingPrices[i+1,j] / Portf_ClosingPrices[i,j] - 1
}
}
Portf_Returns
[,1] [,2] [,3]
[1,] -0.7500000 7.0000000 -0.8333333
[2,] 2.0000000 -0.6250000 2.0000000
[3,] -0.5000000 2.0000000 2.0000000
[4,] 1.0000000 0.0000000 0.0000000
[5,] 0.6666667 -0.7777778 -0.2222222
[6,] -0.6000000 2.0000000 0.2857143
[7,] -0.7500000 0.5000000 -0.8888889
[8,] 2.0000000 -0.5555556 7.0000000
[9,] 2.0000000 0.2500000 -0.1250000
[10,] NA NA NA
答案 1 :(得分:0)
您可以使用此nested sapply
在第一阶段计算每一行的收益,然后移至另一列。您无需指定输出矩阵的尺寸。
sapply(1:3, function(j) sapply(2:10, function(i) Portf_ClosingPrices[,j][i] / Portf_ClosingPrices[,j][i-1] - 1)) -> Portf_Returns
[,1] [,2] [,3]
[1,] -0.8000000 3.0000000 0.0000000
[2,] 0.0000000 0.0000000 -0.3333333
[3,] 3.5000000 0.1250000 -0.6666667
[4,] -0.1111111 -0.4444444 2.5000000
[5,] 0.2500000 0.0000000 0.4285714
[6,] -0.5000000 0.8000000 -0.1000000
[7,] 0.8000000 -0.5555556 0.0000000
[8,] -0.1111111 -0.2500000 -0.5555556
[9,] 0.2500000 2.3333333 1.0000000
用ncol(Portf_ClosingPrices)
替换3,并用nrow(Portf_ClosingPrices)
替换10,这完全是动态的。
答案 2 :(得分:0)
另一个选择是:
exp(diff(log(Portf_ClosingPrices))) - 1
输出:
[,1] [,2] [,3]
[1,] 1.0000000 -0.6000000 -0.3000000
[2,] 1.0000000 2.5000000 -0.4285714
[3,] -0.5000000 0.0000000 0.0000000
[4,] 1.0000000 -0.7142857 0.2500000
[5,] -0.7500000 1.0000000 0.2000000
[6,] 9.0000000 0.2500000 -0.1666667
[7,] -0.3000000 -0.8000000 0.0000000
[8,] -0.1428571 5.0000000 -0.4000000
[9,] 0.1666667 -0.3333333 2.0000000