使用行值作为 R 函数中的变量在数据框中创建新列 [英] Creating a new column in dataframe using row values as variables in a function in R
问题描述
我有一个数据框:
df <- structure(list(LAST = c(3.4, 2.52, 1.82, 1.16, 0.69, 0.36, 4,
3.21, 2.54, 1.93), CURRENTPRICE = c(464.16, 464.16, 464.16, 464.16,
464.16, 464.16, 464.16, 464.16, 464.16, 464.16), STRIKEPRICE = c(461,
462, 463, 464, 465, 466, 461, 462, 463, 464), YEARSTOEXPIRATION = c(0.00273972602739726,
0.00273972602739726, 0.00273972602739726, 0.00273972602739726,
0.00273972602739726, 0.00273972602739726, 0.010958904109589,
0.010958904109589, 0.010958904109589, 0.010958904109589)), row.names = c(NA,
-10L), class = c("data.table", "data.frame"))
我正在尝试使用来自每一行的数据并使用 RQuantLib 包中的 AmericanOptionImpliedVolatility 函数创建一个新列,计算每一行的隐含波动率:
I am trying to create a new column calculating implied volatility for each row using data from each row and using the AmericanOptionImpliedVolatility function from the RQuantLib package:
df$IMPLIEDVOLATILITY <- AmericanOptionImpliedVolatility(type="call", value=df$LAST, underlying=df$CURRENTPRICE, strike=df$STRIKEPRICE, dividendYield=0.00, riskFreeRate=.03, maturity=df$YEARSTOEXPIRATION, volatility=0.2)
我知道代码是错误的,因此我收到一条错误消息:
I know that the code is wrong and I accordingly get an error message:
在 americanOptionImpliedVolatilityEngine 中出错(类型,值,底层,:期望一个值:[extent=10]."
"Error in americanOptionImpliedVolatilityEngine(type, value, underlying, : Expecting a single value: [extent=10]."
我如何正确使用AmericanOptionImpliedVolatility"?以行值作为变量的函数,以创建具有该结果值的新列?
How do I correctly use the "AmericanOptionImpliedVolatility" function with the row values as variables to create a new column with that resulting value?
推荐答案
df %>%
rowwise() %>%
mutate(IMPLIEDVOLATILITY =
RQuantLib::AmericanOptionImpliedVolatility(type="call",
value = LAST,
underlying = CURRENTPRICE,
strike = STRIKEPRICE,
dividendYield = 0.00,
riskFreeRate =.03,
maturity = YEARSTOEXPIRATION,
volatility=0.2))
LAST CURRENTPRICE STRIKEPRICE YEARSTOEXPIRATI~ IMPLIEDVOLATILI~
<dbl> <dbl> <dbl> <dbl> <AmrcnOIV>
1 3.4 464. 461 0.00274 0.12058321
2 2.52 464. 462 0.00274 0.11218994
3 1.82 464. 463 0.00274 0.11577334
4 1.16 464. 464 0.00274 0.10918985
5 0.69 464. 465 0.00274 0.10744424
6 0.36 464. 466 0.00274 0.10472401
7 4 464. 461 0.0110 0.09853768
8 3.21 464. 462 0.0110 0.09443249
9 2.54 464. 463 0.0110 0.09343687
10 1.93 464. 464 0.0110 0.09130677
使用基础 R,您可以:
With base R, you could do:
transform(df, IMPLIEDVOLATILITY =
Vectorize(RQuantLib::AmericanOptionImpliedVolatility)(type="call",
value = LAST,
underlying = CURRENTPRICE,
strike = STRIKEPRICE,
dividendYield = 0.00,
riskFreeRate =.03,
maturity = YEARSTOEXPIRATION,
volatility=0.2))
这篇关于使用行值作为 R 函数中的变量在数据框中创建新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!