使用双循环(不使用包)从多家公司的股票价格计算股票收益 [英] Computing stock returns from stock prices of multiple companies using a double for-Loop (without using a package)
本文介绍了使用双循环(不使用包)从多家公司的股票价格计算股票收益的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个多列(每列代表一家公司)和多行(由股票价格组成)的矩阵
I have a matrix with multiple columns (each column represents a company) and multiple rows (consisting of stock prices)
我想计算退货不使用包!
我尝试使用双 for 循环来实现,但不起作用,出现错误:
I try to do it with a double for-Loop, but it doesn't work, I get an error:
"错误在 Portf_Returns[i, j] <- Portf_ClosingPrices[i + 1, j]/Portf_ClosingPrices[i, :矩阵上的下标数量不正确"
"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
推荐答案
您需要初始化矩阵以返回值:
You need to initialize the matrix to return the values:
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
这篇关于使用双循环(不使用包)从多家公司的股票价格计算股票收益的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文