10.12.2019 Views

Python for Finance

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Options and Futures

Generating our own module p4f

We could combine many small Python progams as one program, such as p4f.py. For

instance, the preceding Python program called bs_call() function is included. Such

a collection of programs offers several benefits. First, when we use the bs_call()

function, we don't have to type those five lines. To save space, we only show a few

functions included in p4f.py. For brevity, we remove all comments included for

each function. Those comments are designed to help future users when issuing the

help() function, such as help(bs_call()):

def bs_call(S,X,T,rf,sigma):

from scipy import log,exp,sqrt,stats

d1=(log(S/X)+(rf+sigma*sigma/2.)*T)/(sigma*sqrt(T))

d2 = d1-sigma*sqrt(T)

return S*stats.norm.cdf(d1)-X*exp(-rf*T)*stats.norm.cdf(d2)

def binomial_grid(n):

import networkx as nx

import matplotlib.pyplot as plt

G=nx.Graph()

for i in range(0,n+1):

for j in range(1,i+2):

if i<n:

G.add_edge((i,j),(i+1,j))

G.add_edge((i,j),(i+1,j+1))

posG={} #dictionary with nodes position

for node in G.nodes():

posG[node]=(node[0],n+2+node[0]-2*node[1])

nx.draw(G,pos=posG)

def delta_call(S,X,T,rf,sigma):

from scipy import log,exp,sqrt,stats

d1=(log(S/X)+(rf+sigma*sigma/2.)*T)/(sigma*sqrt(T))

return(stats.norm.cdf(d1))

def delta_put(S,X,T,rf,sigma):

from scipy import log,exp,sqrt,stats

d1=(log(S/X)+(rf+sigma*sigma/2.)*T)/(sigma*sqrt(T))

return(stats.norm.cdf(d1)-1)

To apply the Black-Scholes-Merton call option model, we simply use the

following codes:

>>>import p4f

>>>c=p4f.bs_call(40,42,0.5,0.015,0.2)

>>>round(c,2)

1.56

[ 348 ]

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!