Quantiative programming tutorial VBA Excel, c++ etc.

Discussion in 'Trading Software' started by Batman28, Aug 23, 2006.

  1. I wrote c++ code to do the Black Scholes calculation. It works in a command window. A Borland c++ compiler is available for free download at http://community.borland.com/article/0,1410,20633,00.html

    Here is the code:

    ==========================

    #include <fstream.h>

    #define Pi 3.141592653589793238462643

    char CallPutFlag;
    double S,T,X,r,v;

    double BlackScholes(char, double, double, double, double, double);
    double CND(double);

    /////////////////////////////////////////////////////////////////////////////////

    // The Black and Scholes (1973) Stock option formula
    double BlackScholes(char CallPutFlag, double S, double X, double T, double r, double v)
    {
    double d1, d2;


    d1=(log(S/X)+(r+v*v/2)*T)/(v*sqrt(T));
    d2=d1-v*sqrt(T);

    if(CallPutFlag == 'c')
    return S *CND(d1)-X * exp(-r*T)*CND(d2);
    else if(CallPutFlag == 'p')
    return X * exp(-r * T) * CND(-d2) - S * CND(-d1);

    return 0;
    }

    /////////////////////////////////////////////////////////////////////////////////

    // The cumulative normal distribution function
    double CND( double X )
    {

    double L, K, w ;

    double const a1 = 0.31938153, a2 = -0.356563782, a3 = 1.781477937;
    double const a4 = -1.821255978, a5 = 1.330274429;

    L = fabs(X);
    K = 1.0 / (1.0 + 0.2316419 * L);
    w = 1.0 - 1.0 / sqrt(2 * Pi) * exp(-L *L / 2) * (a1 * K + a2 * K *K + a3 * pow(K,3) + a4 * pow(K,4) + a5 * pow(K,5));

    if (X < 0 )
    w= 1.0 - w;

    return w;
    }

    /////////////////////////////////////////////////////////////////////////////////

    void main(void)
    {

    cout << "\nElite Trader Black Scholes Option Pricer\n\n";

    cout << "Enter c for call option, p for put option ";
    cin >> CallPutFlag;

    if (CallPutFlag != 'c' && CallPutFlag != 'p')
    {
    cout << "Let's try again, enter c for call option, p for put option\n\n";
    exit(0);
    }

    cout << "Enter stock price ";
    cin >> S;
    cout << "Enter strike price ";
    cin >> X;
    cout << "Enter risk free rate ";
    cin >> r;
    cout << "Enter years to maturity ";
    cin >> T;
    cout << "Enter volatility ";
    cin >> v;

    if ( CallPutFlag == 'c' )
    cout << "\nCall price is " << BlackScholes(CallPutFlag, S, X, T, r, v);
    if ( CallPutFlag == 'p' )
    cout << "\nPut price is " << BlackScholes(CallPutFlag, S, X, T, r, v);

    cout << "\n";

    }

    ===============

    The zipped executable is attached.
     
    • bs1.zip
      File size:
      69.7 KB
      Views:
      87
    #11     Aug 26, 2006
  2. #12     Aug 26, 2006
  3. dsss27

    dsss27

    Obviously credit goes to Espen Haug's website. But can anyone help in telling me how to vectorize the function BlackSholes()? I am trying to input an array (range) of stock prices, and output an array (range) of corresponding option prices. Code below.

    TIA,

    dsss27

    -----------------------------------------

    from math import *

    # S=Stock Price
    # X=Strike Price
    # T=Years to Maturity
    # r=Risk Free Rate
    # v=volatility

    # Cumulative normal distribution

    def CND(X):
    (a1,a2,a3,a4,a5) = (0.31938153, -0.356563782, 1.781477937,
    -1.821255978, 1.330274429)
    L = abs(X)
    K = 1.0 / (1.0 + 0.2316419 * L)
    w = 1.0 - 1.0 / sqrt(2*pi)*exp(-L*L/2.) * (a1*K + a2*K*K + a3*pow(K,3) +
    a4*pow(K,4) + a5*pow(K,5))
    if X<0:
    w = 1.0-w
    return w


    # Black Sholes Function
    ########## HOW DO I VECTORIZE THIS CODE BELOW? ##################

    def BlackSholes(CallPutFlag,S,X,T,r,v):
    d1 = (log(S/X)+(r+v*v/2.)*T)/(v*sqrt(T))
    d2 = d1-v*sqrt(T)
    if CallPutFlag=='c':
    return S*CND(d1)-X*exp(-r*T)*CND(d2)
    else:
    return X*exp(-r*T)*CND(-d2)-S*CND(-d1)
     
    #13     Aug 26, 2006
  4. rosy2

    rosy2

    is vectorize the right word? you could just loop over your price array.
     
    #14     Aug 26, 2006
  5. dsss27

    dsss27

    I am currently doing that, but want to speed up the process by using numarray or Numeric libraries.

    Also, (I am not object oriented versed), but I think having the flexibility of a function accepting different data types, scalar versus vector in this case, I think is called overloading or something. Similar with what one can do interactively with Matlab.

    dsss27
     
    #15     Aug 26, 2006
  6. thanks for all those contributing.. but pls if u do contribute, try to explain what you're doing and elaborate a little without just given the code..


    Grant, your code seems to be ok, but you're using lotus!? I'm not sure how it compares, but i think this is my first time hearing someone uses it.. in terms of efficiency, flexibility and scalability, i definately recommnd excel.

    this time, we are going to compare our black&scholes model with the binomial option pricing model.. we will use compare a BS call with a binomial european call.

    the code for the BS is same as before. but for the binomial we creat a new function called BinomialECall:

    -----------------------------------------------------

    Function BinomialECall(S, K, T, rf, sigma, n)
    u = Exp(sigma * ((T / n) ^ 0.5))
    d = Exp(-sigma * ((T / n) ^ 0.5))
    r = Exp(rf * (T / n))
    rn_u = (r - d) / (r * (u - d))
    rn_d = 1 / r - rn_u
    BinomialECall = 0
    For i = 0 To n
    BinomialECall = BinomialECall + Application.Combin(n, i) * rn_u ^ i * rn_d ^ (n - i) * Application.Max(S * u ^ i * d ^ (n - i) - K, 0)
    Next i
    End Function

    -----------------------------------------------------

    if you don't know the binomial model, have a look at http://www.global-derivatives.com/options/european-options.php to see what we are trying to achieve with the above code.

    I hope everyone's familiar with excels referencing now.. so now we're going to make things look a bit nicer.

    right-click on excels tool bar, and tick the "forms" box, so we have the forms tool appear. click on "Toggle Grid" on this tool bar, which is 2nd last.

    now lets add a scroll bar. right-click on the tool bar again, and this time make sure the "Control Toolbox" is ticked. when it appears, click on a "scroll bar" and drop one anywhere on your spreadsheet. now on the same tool bar (control toolbox), click "design mode", which is the first button on the left. this allows us to edit the scroll bar. right click on the scroll bar you made, and then click "properties". on this properties setting, set the "max" to 100. this is the maximum value of the scroll bar. leave the min at 0. now in "Linked Cell", type J7 so it corresponds to the price we have on our spread sheeet. now close it, and click on the design mode button again to get out of it.

    lets also make a bar chart. click chart wizard on excels standard tool bar, select a bar chart type, then click next. now click on series, and click add. for the name of series one, reference it to H14 which referes to the binomial name. for its value, references it to i14. add another series in the same way for BS. u can change the colour if u like.

    and now u can play around changing the price of the security conveniently with the scroll bar and see how the two different call prices change.. that again took us only 10 min.. worked attached..
     
    #16     Aug 27, 2006
  7. Why are you comparing a BS call with a binomial european call? What are you looking to show? Option pricing is new to me and I'm not completely following the logic of it.
     
    #17     Aug 27, 2006
  8. good question. as i mentioned earlier to Windiff, our examples are arbitrary, and we're mainly concerned with how to go on about doing things in programming. we're not too concerned with theory here, or atempting to win the Nobel. but nevertheless, I thought it's just interesting to see how the two price models behave next to each other. there are many option pricing models and some that go beyond the scope of our thread, but most are extensions of these two models. the binomial simply follows the bonomial framework in statistics, and is actually considered to be more accurate than the blackscholes model at times. althought mainly used for european options (as oppose to american ones -which can be excercised at any time), they are also frequently used to price/check american/bermudian options too. it's a matter of theoretical judgement to decide which is more accruate.. most options are priced using these formulas.. and u can compare them to market, looking for price inefficencies.. however if one does have the holy grail formula, perhaps some extensions of the these models, then they be more successful in trading of options than otherwise.

    perhaps i should've said a little on applications of our work. what is the use of having an automated formula? well it simply makes constructing strategy and execution much more efficient. take the simple strategy example given by Lo at MIT for "CDP LP": "shorting out-of-the-money S&P 500 (SPX) put options on each monthly expiration date for maturities less than or equal to three months, and with strikes approximately 7 percent out of the money. The number of contracts to be sold each month is determined by the combination of: (1) Chicago Board Options Exchange margin requirements, (2) an assumption that 66 percent of the margin is required to be posted as collateral, and (3) $10 million of initial risk capital." althought very very risky, it returned over 2500% over 5-6 yrs. now if u have a similar strategy, u can either sit down and use pen and paper, or use a spreadsheet. the choice is obvious.

    for those interested in Lo's strategy: http://www.econbrowser.com/archives/2005/11/hedge_fund_risk.html
     
    #18     Aug 27, 2006
  9. rosy2

    rosy2

    #19     Aug 27, 2006
  10. rosy2

    rosy2

    i found that scipy has a vectorize function but it doesn't take char args as far as i can tell. this works...


    from math import *
    from scipy import vectorize

    #for calls
    def C_BlackSholes(S,X,T,r,v):
    d1 = (log(S/X)+(r+v*v/2.)*T)/(v*sqrt(T))
    d2 = d1-v*sqrt(T)
    return S*CND(d1)-X*exp(-r*T)*CND(d2)


    vec_bs= vectorize(C_BlackSholes)
    vec_bs( [100.0 ,110.0]
    ,[100.0 ,100.0]
    ,[0.2 ,0.2 ]
    ,[0.5 ,0.5 ]
    ,[0.12 ,0.12 ] )
     
    #20     Aug 27, 2006