使用双 for 循环(不使用包)从多家公司的股票价格计算股票 returns

Computing stock returns from stock prices of multiple companies using a double for-Loop (without using a package)



我有一个包含多列(每列代表一家公司)和多行(由股票价格组成)的矩阵

我想计算Returns不用使用一个包!

我尝试用双 for 循环来完成它,但它不起作用,我得到一个错误:

"Error in Portf_Returns[i, j] <- Portf_ClosingPrices[i + 1, j]/Portf_ClosingPrices[i, : incorrect number of subscripts on matrix"

# 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

您需要将矩阵初始化为 return 值:

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

您可以使用此 nested sapply,它在第一阶段计算每一行的 return,然后移动到另一列。您不需要指定输出矩阵的维度。

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

将 3 替换为 ncol(Portf_ClosingPrices),将 10 替换为 nrow(Portf_ClosingPrices),您将获得完全动态的效果。

另一种选择是:

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