首页 > 解决方案 > 在 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 函数的结果进行比较时,我得到了不同的结果。我怀疑我做循环的方式可能有问题?

标签: matlaboptions

解决方案


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

推荐阅读