Quantcast
Channel: Active questions tagged r - Stack Overflow
Viewing all articles
Browse latest Browse all 201867

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

$
0
0



I have a matrix with multiple columns (each column represents a company) and multiple rows (consisting of stock prices)

I would like to calculate the Returns without the use of a package!

I try to do it with a double for-Loop, but it doesn't work, I get an error:

"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

Viewing all articles
Browse latest Browse all 201867

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>