[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Convert C to VB.NET - Black Scholes Implied Volatility - Stock Market Options Formula

Posted on 2004-11-07
6
Medium Priority
?
2,083 Views
Last Modified: 2008-01-09
Hi all.

I want to build a class that calculates the Black Scholes Implied Volatility on Share Market Options data.

I have the Data in a DataSet and have built the interface to work with, but need the formula to achieve the result.

I know how to build the class, know how to pass the data to the class, don't know how to compute the result.

This has been done before as seen below (I think this is C code, you tell me);

// file black_scholes_imp_vol_bisect.cc
// author: Bernt A Oedegaard
// calculate implied volatility of Black Scholes formula

#include "fin_algoritms.h"
#include <cmath>

double option_price_implied_volatility_call_black_scholes_bisections(
   double S, double X, double r, double time, double option_price)
{ // check for arbitrage violations:
    // if price at almost zero volatility greater than price, return 0

    double sigma_low=0.0001;
    double price = option_price_call_black_scholes(S,X,r,sigma_low,time);
    if (price>option_price) return 0.0;
 
    // simple binomial search for the implied volatility.
    // relies on the value of the option increasing in volatility
    const double ACCURACY = 1.0e-5; // make this smaller for higher accuracy
    const int MAX_ITERATIONS = 100;
    const double HIGH_VALUE = 1e10;
    const double ERROR = -1e40;
 
    // want to bracket sigma. first find a maximum sigma by finding a sigma
    // with a estimated price higher than the actual price.
    double sigma_high=0.3;
    price = option_price_call_black_scholes(S,X,r,sigma_high,time);
    while (price < option_price) {  
      sigma_high = 2.0 * sigma_high; // keep doubling.
      price = option_price_call_black_scholes(S,X,r,sigma_high,time);
      if (sigma_high>HIGH_VALUE) return ERROR; // panic, something wrong.
    };
    for (int i=0;i<MAX_ITERATIONS;i++){
      double sigma = (sigma_low+sigma_high)*0.5;
      price = option_price_call_black_scholes(S,X,r,sigma,time);
      double test =  (price-option_price);
      if (fabs(test)<ACCURACY) { return sigma; };
      if (test < 0.0) { sigma_low = sigma; }
      else { sigma_high = sigma; }
    };
    return ERROR;
};


This code came from the following site;

http://finance.bi.no/~bernt/gcc_prog/algoritms_v1/algoritms/node8.html#SECTION00423000000000000000

My Question:  Can someone convert this code into VB.NET for me?
Any comments or resources you have come across for this type of project would also be of interest.

Regards,

Grant.
0
Comment
Question by:Grant_Aust
  • 3
  • 3
6 Comments
 
LVL 5

Accepted Solution

by:
Ignacio Soler Garcia earned 750 total points
ID: 12521403
It's very easy, but you still need two functions defined elsewhere called option_price_call_black_scholes and fabs. The rest of the code is like this:

    Public Function option_price_implied_volatility_call_black_scholes_bisections(ByVal S As Double, ByVal X As Double, ByVal r As Double, ByVal time As Double, ByVal option_price As Double) As Double
        Const ACCURACY As Double = 0.00001 ' make this smaller for higher accuracy
        Const MAX_ITERATIONS As Integer = 100
        Const HIGH_VALUE As Double = 10000000000.0
        Const ERRORVALUE As Double = -1.0E+40

        ' check for arbitrage violations:
        ' if price at almost zero volatility greater than price, return 0
        Dim sigma_low As Double = 0.0001
        Dim price As Double = option_price_call_black_scholes(S, X, r, sigma_low, time)
        Dim i As Integer

        If (price > option_price) Then Return 0.0
        ' simple binomial search for the implied volatility.
        ' relies on the value of the option increasing in volatility

        ' want to bracket sigma. first find a maximum sigma by finding a sigma
        ' with a estimated price higher than the actual price.
        Dim sigma_high As Double = 0.3
        price = option_price_call_black_scholes(S, X, r, sigma_high, time)

        While (price < option_price)
            sigma_high = 2.0 * sigma_high ' keep doubling.
            price = option_price_call_black_scholes(S, X, r, sigma_high, time)
            If (sigma_high > HIGH_VALUE) Then Return ERRORVALUE ' panic, something wrong.
        End While

        For i = 0 To MAX_ITERATIONS
            Dim sigma As Double = (sigma_low + sigma_high) * 0.5
            price = option_price_call_black_scholes(S, X, r, sigma, time)
            Dim test As Double = (price - option_price)
            If (fabs(test) < ACCURACY) Then Return sigma
            If (test < 0.0) Then
                sigma_low = sigma
            Else
                sigma_high = sigma
            End If
        Next
        Return ERRORVALUE
    End Function

It's obvious that the stile of the code is terrible but that's how was the original ...

Ask me for more if you need it.

SoMoS

0
 

Author Comment

by:Grant_Aust
ID: 12522752
Hey, looks good SoMoS.

I found the extra function option_price_call_black_scholes, it's on that website, below;

// file: black_scholes_call
// author: Bernt A Oedegaard
//    Calculation of the Black Scholes option price formula.

#include <cmath>              // mathematical library
#include "normdist.h"          // this defines the normal distribution
 
double option_price_call_black_scholes( double S, // spot price
                              double X, // Strike (exercise) price,
                              double r,  // interest rate
                              double sigma,
                              double time)
{  
    double time_sqrt = sqrt(time);
    double d1 = (log(S/X)+r*time)/(sigma*time_sqrt) + 0.5*sigma*time_sqrt;
    double d2 = d1-(sigma*time_sqrt);
    double c = S * N(d1) - X * exp(-r*time) * N(d2);
    return c;
};




So to convert this it would look like......

'Note: S = Spot Price, X = Strike (exercise) price, r = interest rate...
    Public Function option_price_call_black_scholes _
    (ByVal S As Double, ByVal X As Double, ByVal r As Double, ByVal sigma As Double, ByVal Time As Double)

        Dim time_sqrt As Double
        Dim d1 As Double
        Dim d2 As Double
        Dim c As Double

        time_sqrt = Math.Sqrt(Time)
        d1 = (Math.Log(S / X) + r * Time) / (sigma * time_sqrt) + 0.5 * sigma * time_sqrt
        d2 = d1 - (sigma * time_sqrt)
        c = S * N(d1) - X * Math.Exp(-r * Time) * N(d2)

        Return c
    End Function

I think I converted it correctly except for the N(d1) and N(d2)...   I can't find N() on the web for C programming...
Do you know what N() is?   It's probably a standart Math function, but I don't want to make a mistake.
Let me know if the conversion is ok apart from that.

My brother in law thinks the N() is cumulative normal distribution because of the #includes normdist.h
See this link for normdist.h
http://www.mahoroba.ne.jp/~felix/Notes/Energy/FNR/src/normdist.html

I dont know what this is in vb.net.   MSDN help doesn't um, you know, help.

Also the fabs(test) is an absolute function in C....   The absolute value of -15 is 15. The absolute value of +15 is 15.
Not that I remember any of this from school, don't you love google.
In vb.net it would look like;

If (Math.Abs(test) < ACCURACY) Then Return sigma

Any ideas on the N()?

Grant.





0
 

Author Comment

by:Grant_Aust
ID: 12532156
Hope you dont mind all these questions but I still don't have a formula that is functional.
Nearly there.

I have worked out N() to the following code;

Public Function Cumulative_Normal_Distribution(ByVal z As Double) As Double
        'The following if statments guard against overflow...
        If z > 6.0 Then
            Return 1.0
            Exit Function
        End If

        If z < -6.0 Then
            Return 0.0
            Exit Function
        End If

        Dim b1 As Double = 0.31938153
        Dim b2 As Double = -0.356563782
        Dim b3 As Double = 1.781477937
        Dim b4 As Double = -1.821255978
        Dim b5 As Double = 1.330274429
        Dim p As Double = 0.2316419
        Dim c2 As Double = 0.3989423

        Dim a As Double = Math.Abs(z)
        Dim t As Double = 1.0 / (1.0 + a * p)
        Dim b As Double = c2 * Math.Exp((-z) * (z / 2.0))
        Dim n As Double = ((((b5 * t + b4) * t + b3) * t + b2) * t + b1) * t

        n = 1.0 - (b * n)

       ??????  If z < 0.0 Then n = 1.0 - n  ??????

        Return n
    End Function

I am not sure of the following C++ code though, how does it convert to VB.NET?

if ( z < 0.0 ) n = 1.0 &#8722; n;

You can see my guess about between the ??????

Thanks again.

Grant.


0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 5

Expert Comment

by:Ignacio Soler Garcia
ID: 12532287
Sorry for the delay ...

From where did you get the line

if ( z < 0.0 ) n = 1.0 &#8722; n;

It's sintax is not correct I think, but I would love to see it in its own context, can you tellme where can I read the whole function? I googleled without success...

See you!
0
 
LVL 5

Expert Comment

by:Ignacio Soler Garcia
ID: 12532296
Oh! And there is a mistake on the declaration of the function, it miss the return type:

Public Function option_price_call_black_scholes _
    (ByVal S As Double, ByVal X As Double, ByVal r As Double, ByVal sigma As Double, ByVal Time As Double)-->As Double<--


SoMoS
0
 

Author Comment

by:Grant_Aust
ID: 12532347
Belay that last question.   I found an answer at;
http://www-numi.fnal.gov/offline_software/srt_public_context/WebDocs/Companion/cxx_crib/if_arglist.html

I think I can manage from now on.

For future reference: Code came from the following stie;

http://finance.bi.no/

Thanks should go to the author: Bernt A Oedegaard

Thanks for the kick off SoMoS.   I probably could have done it myself, but lacked a starting point.   You helped heaps.

If I have any more questions, I will open a new question.

Regards,

Grant.
0

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Well, all of us have seen the multiple EXCEL.EXE's in task manager that won't die even if you call the .close, .dispose methods. Try this method to kill any excels in memory. You can copy the kill function to create a check function and replace the …
1.0 - Introduction Converting Visual Basic 6.0 (VB6) to Visual Basic 2008+ (VB.NET). If ever there was a subject full of murkiness and bad decisions, it is this one!   The first problem seems to be that people considering this task of converting…
Integration Management Part 2
As many of you are aware about Scanpst.exe utility which is owned by Microsoft itself to repair inaccessible or damaged PST files, but the question is do you really think Scanpst.exe is capable to repair all sorts of PST related corruption issues?
Suggested Courses
Course of the Month17 days, 18 hours left to enroll

829 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question