For loop not working as expected

question

#1

My code is as below:

using FinancialToolbox


    r=0.01*0.303
    q=0.01*0.202
    s=0.20
    T=0.50
    b=r-q
    S=1500 
    K=1000:5:2000
    
    
    for i = 1:length(K)
        res1 = zeros(length(K))
        res1[i] = blsprice(S, K[i], r, T, s, q)
    end

It seems the res1 I got is still zero arrays, and I am not sure what could be the issue.


#2

You are using res1 = zeros(length(K)) at each loop iteration, what do you expect at the nth iteration other than an all-zeros array with only res1[n] having nonzero value?

Move this line res1 = zeros(length(K)) before the for-loop.

⋮
res1 = zeros(length(K))
for i = 1:length(K)
    res1[i] = blsprice(S, K[i], r, T, s, q)
end

Outputs:

julia> res1
	201-element Array{Float64,1}:
	 500.103
	 495.124
	 490.147
	 485.171
	 480.197
	 475.225
	 470.255
	 465.288
	 460.323
	 455.362
	 450.403
	 445.447
	 440.495
	   ⋮
	   3.15828
	   3.0192
	   2.88581
	   2.7579
	   2.63527
	   2.51772
	   2.40506
	   2.29711
	   2.19369
	   2.09462
	   1.99974
	   1.90889

#3

HAHA, thanks so much! By the way, do you know if the blsprice function has a call/put parameter input? I could not find any documentation about the financialtoolbox package.


#4

I didn’t use this package my self, but you can see the implementation of this function at this line in the source of FinancialToolbox.jl.


#5

I use this code

blsprice(10.0,10.0,0.01,2.0,0.2,0.01, FlagIsCall = false)

but got the error message

ERROR: function blsprice does not accept keyword arguments


#6

FlagIsCall = false is keyword argument.
Following the error message, you should use blsprice(10.0,10.0,0.01,2.0,0.2,0.01, false) instead.
For further information on keyword argument, see: https://docs.julialang.org/en/stable/manual/functions/#Keyword-Arguments-1


#7

FlagIsCall is not a keyword argument, it is an optional positional argument!

julia> foo(positional, optional = true) = (positional, optional)
foo (generic function with 2 methods)

julia> foo(false)
(false, true)

julia> foo(false, false)
(false, false)

julia> foo(false, optional = false)
ERROR: function foo does not accept keyword arguments
Stacktrace:
 [1] kwfunc(::Any) at ./boot.jl:237

Keyword arguments are declared after a semicalon ; in the parameter list:

julia> bar(positional, optional = true; keyword = 42) = (positional, optional, keyword)
bar (generic function with 2 methods)

julia> bar(false)
(false, true, 42)

julia> bar(false, false)
(false, false, 42)

julia> bar(false, false, keyword = 7)
(false, false, 7)