对每一行应用GBSVolatility(Apply GBSVolatility to each row)

编程入门 行业动态 更新时间:2024-10-10 14:23:38
对每一行应用GBSVolatility(Apply GBSVolatility to each row)

我有一个相当简单的问题,但遗憾的是无法得到结果:我想将GBSVolatility函数应用于我的data.frame的每一行。

我做了以下事情:

> vol <- function(x) GBSVolatility(x$Price, "c", S = 1000, x$Strike, Time = 1/4, r = 0.01, b = 0.02, maxiter = 500) > foo$iv <- apply(foo, 1, vol)

但这不起作用。 有人可以告诉我为什么吗?

非常感谢

达尼

更新:感谢您的建议。 我的数据框叫做foo,看起来像这样

Date Price Strike Name 1.1 100 1200 X 1.1 120 1500 P etc.

我想创建一个隐含波动率的新列。 我试着申请,

vol <- function(x) GBSVolatility(x["Price"], "c", S = 1000, x["Strike"], Time = 1/4, r = 0.01, b = 0.02, maxiter = 500) foo$iv <- apply(foo, 1, vol)

但它没有奏效。

你有什么其他的建议? 谢谢

I have a rather simple question but unfortunately just cannot get to a result: I would like to apply the GBSVolatility function to each row of my data.frame.

I did the following:

> vol <- function(x) GBSVolatility(x$Price, "c", S = 1000, x$Strike, Time = 1/4, r = 0.01, b = 0.02, maxiter = 500) > foo$iv <- apply(foo, 1, vol)

But this does not work. Can someone tell me why?

Thanks alot

Dani

Update: Thank you for your suggestion. My data frame is called foo and looks like this

Date Price Strike Name 1.1 100 1200 X 1.1 120 1500 P etc.

I would like to make a new column with the implied volatility. I tried to apply,

vol <- function(x) GBSVolatility(x["Price"], "c", S = 1000, x["Strike"], Time = 1/4, r = 0.01, b = 0.02, maxiter = 500) foo$iv <- apply(foo, 1, vol)

but it didn't work as well.

Do you have any other suggestions? Thanks

最满意答案

如果数据框的一列或多列是字符,则在行上申请数据框会将数字转换为字符。 如此简单的解决方法是再次转换为vol:

vol <- function(x) GBSVolatility(as.numeric(x["Price"]), "c", S = 1000, as.numeric(x["Strike"]), Time = 1/4, r = 0.01, b = 0.02, maxiter = 500) apply(foo, 1, vol)

这不优雅。 我现在不记得更优雅的方式,可能使用d * ply或者其他东西......

可能这更优雅:

library(plyr) vol <- function(x) GBSVolatility(x$Price, "c", S = 1000, x$Strike, Time = 1/4, r = 0.01, b = 0.02, maxiter = 500) foo$iv <- adply(foo, 1, vol)$V1

applying for data frame on row converts numeric to character if one or more column of the data frame is character. So easy workaround is to convert again in vol:

vol <- function(x) GBSVolatility(as.numeric(x["Price"]), "c", S = 1000, as.numeric(x["Strike"]), Time = 1/4, r = 0.01, b = 0.02, maxiter = 500) apply(foo, 1, vol)

This is not elegant. I can not recall just now the more elegant way, probably using d*ply or something...

Probably this is more elegant:

library(plyr) vol <- function(x) GBSVolatility(x$Price, "c", S = 1000, x$Strike, Time = 1/4, r = 0.01, b = 0.02, maxiter = 500) foo$iv <- adply(foo, 1, vol)$V1

更多推荐

本文发布于:2023-07-31 08:32:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1342028.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:GBSVolatility   Apply   row

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!