我正在尝试在 R 中设置一个简单的 for 循环计算,其中数据框填充有计算值。
这是它的要点:
- 我有一个 10 列宽和 30 行长的数据框;列是模拟回报的向量,行是一个月的天数。
- 我有另一个相同大小的数据框,其中第一行是今天的股票价格,所有其他行都是空的。
- 我只想使用给定的起始价格和第一个数据帧中的模拟回报,使用如下基本公式,用计算出的价格迭代填充第二个数据帧的其余部分:
价格(今天)= 价格(昨天)*(1 + 模拟收益(今天))
下面是一个例子:
## This makes a 30x10 dataframe of random simulated returns
ret = replicate(10, rnorm(30, mean = 0.1, sd = 0.25))
## This makes the empty 30x10 dataframe where prices will go
pri = ret
pri[] = NA
## This fills the first row of the second dataframe with given values (today's price)
given = replicate(10, 1234)
pri[1,] = given
在这一点之后,我在设计正确的 for 循环时遇到了问题。我不确定如何构建语法以进行迭代,以便根据第一个数据帧中时间 (t) 的相应返回值,对于第二个数据帧中的每个空行,空单元格被一个一个填充,并且使用我上面描述的基本公式,第二个数据帧中前一个时间段 (t-1) 的价格。
我想要的想法是这样的
pri[2,] = pri[1,] * (1 + ret[2,])
但是对于连续第二个数据帧中的所有剩余行(行 2:30,按列分隔)。任何建议将不胜感激。
sapply
下面解释了使用基于函数的解决方案。逻辑是用模拟回报因子填充价格矩阵,并用今天的价格填充第一行。sapply
将一次取 1 列并根据Price(today) = Price(yesterday) * (1 + Simulated Return(today))
该列的返回值执行计算,
## This makes a 30x10 dataframe of random simulated returns.
## Notice I have changed it to data.frame
ret = data.frame(replicate(10, rnorm(30, mean = 0.1, sd = 0.25))
## This makes the empty 30x10 dataframe where prices will go
pri = ret
## pri[] = NA -- no need. Let the factor be available for dates.
## This fills the first row of the second dataframe with given values (today's price)
given = replicate(10, 1234)
pri[1,] = given
# Function that performs calculation on simulated price based on previous day
poputate_value <- function(x){
for(i in 2:length(x)){
x[i] <- x[i-1] * (1 + x[i])
}
x
}
# Function will be applied on all columns and value will be returned to result
result <- sapply(pri, poputate_value)
## > head(result)
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
[1,] 1234.000 1234.000 1234.0000 1234.000 1234.0000 1234.000 1234.0000 1234.0000 1234.0000 1234.0000
[2,] 1038.855 1580.027 991.9454 1975.709 1447.9575 1733.466 856.0908 928.6600 1119.1489 1011.4543
[3,] 1113.040 1411.237 807.3748 1791.978 1333.1235 1957.516 972.3401 874.6964 1133.1161 1095.7755
[4,] 1242.637 1104.528 906.7417 1443.040 944.8004 2198.782 1242.2810 1314.4354 1722.6803 1478.0986
[5,] 1822.834 1224.279 1245.4425 1381.826 1295.5291 2887.676 1349.2818 1367.2311 908.4315 780.4360
[6,] 1690.193 1218.778 883.5074 2126.224 1340.3102 2994.756 1542.1661 1300.4834 998.1949 702.0578
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句