From e9d24adbfd21477e918fcc33a0a6028325dbe72b Mon Sep 17 00:00:00 2001 From: bspeice Date: Sat, 5 Mar 2016 18:50:53 -0500 Subject: [PATCH] Handle array inputs to black scholes --- REQUIRE | 2 +- src/blackscholes.jl | 8 +++++--- test/blackscholes.jl | 15 ++++++++++++++- 3 files changed, 20 insertions(+), 5 deletions(-) diff --git a/REQUIRE b/REQUIRE index 7960486..48285cb 100644 --- a/REQUIRE +++ b/REQUIRE @@ -1 +1 @@ -StatsFuns +using Distributions diff --git a/src/blackscholes.jl b/src/blackscholes.jl index e056b86..2c44feb 100644 --- a/src/blackscholes.jl +++ b/src/blackscholes.jl @@ -4,7 +4,9 @@ # Designed to be a reference implementation of the Black-Scholes option # pricing formula, supporting the original formula and greeks calculation ### -using StatsFuns +using Distributions + +Φ = x -> cdf(Normal(0, 1), x) """ Calculate the value of \$d_1\$ in the Black-Scholes Formula @@ -21,12 +23,12 @@ function blackscholes_call(S, K, σ, r, T, t=0) d1_val = d1(S, K, σ, r, T, t) d2_val = d2(d1_val, σ, T, t) - return normcdf(d1_val) .* S - normcdf(d2_val) .* K .* exp(-r .* (T - t)) + return Φ(d1_val) .* S - Φ(d2_val) .* K .* exp(-r .* (T - t)) end function blackscholes_put(S, K, σ, r, T, t=0) d1_val = d1(S, K, σ, r, T, t) d2_val = d2(d1_val, σ, T, t) - return normcdf(-d2_val).*K.*exp(-r.*(T-t)) - normcdf(-d1_val).*S + return Φ(-d2_val).*K.*exp(-r.*(T-t)) - Φ(-d1_val).*S end diff --git a/test/blackscholes.jl b/test/blackscholes.jl index 935fea9..52f4f87 100644 --- a/test/blackscholes.jl +++ b/test/blackscholes.jl @@ -3,7 +3,20 @@ using Base.Test using Quant @test 15.047 < blackscholes_call(100, 95, .25, .05, 2, 1) < 15.0471 -@test blackscholes_call(100, 95, .25, .05, 2, 1) == blackscholes_call(100, 95, .25, .05, 1) +@test blackscholes_call(100, 95, .25, .05, 2, 1) == + blackscholes_call(100, 95, .25, .05, 1) + +precompute_low = [15.047, 15.047] +precompute_high = [15.0471, 15.0471] +S = [100, 100]; K = [95, 95]; σ = [.25, .25]; r = [.05, .05] +T = [2, 2]; t = [1, 1] +@test all(precompute_low .< blackscholes_call(S, K, σ, r, T, t) + .< precompute_high) @test 5.413 < blackscholes_put(100, 95, .25, .05, 2, 1) < 5.414 @test blackscholes_put(100, 95, .25, .05, 2, 1) == blackscholes_put(100, 95, .25, .05, 1) + +precompute_low = [5.413, 5.413] +precompute_high = [5.414, 5.414] +@test all(precompute_low .< blackscholes_put(S, K, σ, r, T, t) + .< precompute_high)