# Improving my code of Margrabe Formula in Python

I am new to Python and I want to see how can I improve my code to make it faster and cleaner. Below you can see the code of Margrabe's Formula for pricing Exchange Options.

I think the part where I check if the argument is None and if not take predetermined values, can be improved but i don't know how to do it. Is using scipy.stats.norm for calculating the pdf and cdf of the normal distribution faster than manually coding it myself?

    from __future__ import division
from math import log, sqrt, pi
from scipy.stats import norm

s1 = 10
s2 = 20
sigma1 = 1.25
sigma2 = 1.45
t = 0.5
rho = 0.85

def sigma(sigma1, sigma2, rho):
return sqrt(sigma1**2 + sigma2**2 - 2*rho*sigma1*sigma2)

def d1(s1, s2, t, sigma1, sigma2, rho):
return (log(s1/s2)+ 1/2 * sigma(sigma1, sigma2, rho)**2 * t)/(sigma(sigma1, sigma2, rho) * sqrt(t))

def d2(s1, s2, t, sigma1, sigma2, rho):
return d1(s1,s2,t, sigma1, sigma2, rho) - sigma(sigma1, sigma2, rho) * sqrt(t)

def Margrabe(stock1=None, stock2=None, sig1=None, sig2=None, time=None, corr=None):

if stock1 == None:
stock1 = s1
if stock2 == None:
stock2 = s2
if time == None:
time = t
if sig1 == None:
sig1 = sigma1
if sig2 == None:
sig2 = sigma2
if corr==None:
corr = rho

dd1 = d1(stock1, stock2, time, sig1, sig2, corr)
dd2 = d2(stock1, stock2, time, sig1, sig2, corr)
return stock1*norm.cdf(dd1) - stock2*norm.cdf(dd2)

print "Margrabe = " + str(Margrabe())


First of all, when you compare to None, you are better off using if stock1 is None: - an object can define equality, so potentially using == could return True even when stock1 is not None. Using is checks identity, so it will only return True in the case it really is None.

As to simplifying your code, you can simply place the default values directly into the function definition:

def margrabe(stock1=s1, stock2=s2, sig1=t, sig2=sigma1, time=sigma2, corr=rho):
dd1 = d1(stock1, stock2, time, sig1, sig2, corr)
dd2 = d2(stock1, stock2, time, sig1, sig2, corr)
return stock1*norm.cdf(dd1) - stock2*norm.cdf(dd2)


It is also worth a note that CapWords is reserved for classes in Python - for functions, use lowercase_with_underscores - this is defined in PEP-8 (which is a great read for making your Python more readable), and helps code highlighters work better, and your code more readable.