matlab - 在 Matlab 中具有矢量输入的 Black Scholes 函数
问题描述
我正在尝试在 Matlab 中编写一个函数,该函数使用带有矢量输入的 Black Scholes 公式计算调用价格。我到目前为止:
function [C] = BlackScholesCall(S,K,t,r,sigma)
%This function calculates the call price per Black-Scholes equation
%INPUT S ... stock price at time 0
% K ... strike price
% r ... interest rate
% sigma ... volatility of the stock price measured as annual standard deviation
% t ... duration in years
%OUTPUT C ... call price
%USAGE BlackScholesCall(S,K,t,r,sigma)
for l = 1:length(K)
for z = 1:length(t)
d1 = (log(S/K(l)) + (r + 0.5*sigma^2)*t(z))/(sigma*sqrt(t(z)));
d2 = d1 - sigma*sqrt(t(z));
N1 = 0.5*(1+erf(d1/sqrt(2)));
N2 = 0.5*(1+erf(d2/sqrt(2)));
C(l) = S*N1-K(l)*exp(-r*t(z))*N2;
end
end
end
Fe调用我的函数的代码是
S = 20
K = 16:21
t = 1:1:5
r = 0.02
sigma = 0.25
C = BlackScholesCall(S, K, t, r, sigma)
但是当我将此与 Matlab 中 blsprice 函数的结果进行比较时,我得到了不同的结果。我怀疑我做循环的方式可能有问题?
解决方案
R 版本可能如下。
BlackScholesCall <- function(S, K, tt, r, sigma){
f <- function(.K, .tt){
d1 <- (log(S/.K) + (r + 0.5*sigma^2)*.tt)/(sigma*sqrt(.tt))
d2 <- d1 - sigma*sqrt(.tt)
S*pnorm(d1) - .K*exp(-r*.tt)*pnorm(d2)
}
m <- length(K)
n <- length(tt)
o <- outer(K, tt, f)
last <- if(m > n) o[n:m, n] else o[m, m:n]
c(diag(o), last)
}
BlackScholesCall(S, K, tt, r, sigma)
#[1] 4.703480 4.783563 4.914990 5.059922 5.210161 5.210161 4.809748
推荐阅读
- python-3.x - 使用 os 模块返回位于 Python 中当前工作目录正上方的目录名称
- python - 属性实例的 Django ListView
- ios - iOS:以编程方式捕获大于屏幕的视图屏幕截图
- html - 如何使背景颜色占据屏幕/页面的整个高度?
- flask - 如何在Flask中请求最后一段url
- javascript - 如何解析跳过三个主要节点的 JSON 数据?
- mysql - MySQL InnoDB FULLTEXT 索引随机忽略记录
- php - 如何在这里使用 esc_attr?
- sql - 如何使用带有连接表的 postgres 计算会计余额
- puppeteer - puppeteer 在信用卡输入字段中输入的问题