Nonlinear least squares estimate

question

#1

I am trying to calibrate an option pricing model (nonlinear) with 3 parameters to estimate, but not sure how to do it in Julia.


function GKprice(S0, K, r, T, σ, d, Flag = "call") 


    normcdf(x) = cdf(Normal(0, 1), x)
    
    d1=(log(S0/K)+(r-d+σ*σ*0.5)*T)/(σ*sqrt(T))

    d2=d1-σ*sqrt(T)
    
    Price=0.0

    if Flag == "call"
        
        Price=S0*exp(-d*T)*normcdf(d1)-K*exp(-r*T)*normcdf(d2);
        
    else
        
        Price=-S0*exp(-d*T)*normcdf(-d1)+K*exp(-r*T)*normcdf(-d2);
    
    end
    
    return Price;
    
end







    function GCprice(spot, K, r, T, sigma, d, gamma1, gamma2,  FlagIsCall)

        #FlagIsCall equals 1 for call option and 0 for put option 

        D = ( log(spot / K) + (r - d + 0.5 * sigma ^ 2 ) * T ) / ( sigma * sqrt(T) )
        
        dist = Normal(0, 1)

        parity = spot * exp(-d * T) - K * exp(-r * T)


        part1 = spot * exp(-d * T) * pdf(dist, D) * sigma * sqrt(T) 

        part2 = gamma1 * (2 * sigma * sqrt(T) - D ) / ( 6 * sqrt(T))

        part3 = gamma2 * (1 - D^2 + 3 * D * sigma * sqrt(T) - 3 * sigma^2 * T) / (24 * T)  

        adjustment = part1 * (part2 - part3) 
        


        Price = GKprice(spot, K, r, T, sigma, d) + adjustment - (FlagIsCall - 1) * parity

            return Price
        
    end

GCprice is my model and I made up the data sample as an example (no variation in some independent variables). The real data is a exchange rate option data.


df = DataFrame(FlagIsCall = rand(0:1, 100),
    K = collect(1941:0.2:1960.8), spot = 1943.09, d = 0.021589, T = 0.0219178, 
    r = 0.00390208, GC_price = rand(1:30, 100))

GC_price is my dependent variable, my independent variables include K,
spot, d, T and r. It has 3 parameters to estimate, which are sigma, gamma1, and gamm2. I want to do a least squared estimate for them, but have to write my code from scratch and use the Optim package to find the minimum SSE. I want to know if there is easy way to fit a nonlinear model in Julia. Thanks.


#2

LsqFit.jl


#3

I read the doc, but I am not sure if it has multivariate estimate choice.


#4

It does. You just use an array and a closure.


#5

Do you mean I should do it like

x = Array(Float64, (x1, x2, x3…))

x1 = x [1]

x2 = x [2]

x3 = x [3]


#6

Yes. And just throw a function over it so that you send f(p) to send it to the package.