Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
Python for Finance

You're reading from  Python for Finance

Product type Book
Published in Apr 2014
Publisher
ISBN-13 9781783284375
Pages 408 pages
Edition 1st Edition
Languages
Author (1):
Yuxing Yan Yuxing Yan
Profile icon Yuxing Yan

Table of Contents (20) Chapters

Python for Finance
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Introduction and Installation of Python Using Python as an Ordinary Calculator Using Python as a Financial Calculator 13 Lines of Python to Price a Call Option Introduction to Modules Introduction to NumPy and SciPy Visual Finance via Matplotlib Statistical Analysis of Time Series The Black-Scholes-Merton Option Model Python Loops and Implied Volatility Monte Carlo Simulation and Options Volatility Measures and GARCH Index

Chapter 10. Python Loops and Implied Volatility

In this chapter, we will study two topics: loops and implied volatility based on the European options (Black-Scholes-Merton option model) and American options. For the first topic, we have the for loop and while loop, the two most used loops. After presenting the definition of the implied volatility and explaining the logic behind it, we discuss three ways for its estimation: based on a for loop, on a while loop, and on a binary search. A binary search is the most efficient way to find a solution in such cases. However, the precondition to apply a binary search is that the objective function is monotone increasing or decreasing function of our target estimate. Fortunately, this is true since the value of an option price is an increasing function of the volatility.

In particular, we will cover the following topics:

  • What is an implied volatility?

  • Logic behind the estimation of an implied volatility

  • Understanding the for loop, while loop, and their...

Definition of an implied volatility


From the previous chapter, we know that for a set of input variables—S (the present stock price), X (the exercise price), T (the maturity date in years), r (the continuously compounded risk-free rate), and sigma (the volatility of the stock, that is, the annualized standard deviation of its returns)—we could estimate the price of a call option based on the Black-Scholes-Merton option model. Recall that to price a European call option, we have the following Python code of five lines:

from scipy import log,exp,sqrt,stats
def bs_call(S,X,T,r,sigma):
    d1=(log(S/X)+(r+sigma*sigma/2.)*T)/(sigma*sqrt(T))
    d2 = d1-sigma*sqrt(T)
    return S*stats.norm.cdf(d1)-X*exp(-r*T)*stats.norm.cdf(d2)

After entering a set of five values, we can estimate the call price as follows:

>>>bs_call(40,40,0.5,0.05,0.25)
3.3040017284767735

On the other hand, if we know S, X, T, r, and c, how can we estimate sigma? Here, sigma is our implied volatility. In other words...

Understanding a for loop


A for loop is one of the most used loops in many computer languages. The following flow diagram demonstrates how a loop works. Usually, we start with an initial value. Then, we test a condition. If the condition is false, the program stops. Otherwise, we execute a set of commands:

The simplest example is given as follows:

>>>for i in range(1,5):
      print i

Running these two lines will print 1, 2, 3, and 4. We have to be careful with the range() function since the last number, 5, will not be printed in Python. Thus, if we intend to print from 1 to n, we have to use the following code:

>>>n=10
>>>for i in range(1,n+1):
      print i

In the previous two examples, the default incremental value is 1. If we intend to use an incremental value other than 1, we have to specify it as follows:

>>>for i in xrange(1,10,3):
      print i

The output values will be 1, 4, and 7. Along the same lines, if we want to print 5 to 1, that is, in descending...

Estimation of IRR via a for loop


In the first two chapters, we learned that we could apply the Internal Rate of Return (IRR) rule to evaluate our project with a set of forecasted current and future cash flows. Based on a for loop, we could calculate the IRR of our project. The two related functions, NPV() and IRR_f(), are shown as follows:

def npv_f(rate, cashflows):
    total = 0.0
    for i, cashflow in enumerate(cashflows):
        total += cashflow / (1 + rate)**i
    return total

Here, the key is finding out what kinds of values the intermediate variables i and cashflow would take. From the previous section, we know that i will take values from 0 to the number of cash flows and that cashflow would take all values from the variable called cashflows. The total+=x statement is equivalent to total=total+x. One issue is that if we enter -1 as our rate, the function would not work. We could add an if command to prevent this from happening (refer to the succeeding solution for the IRR() function...

Understanding a while loop


In the following program, the first line assigns an initial value to i. The second line defines a condition for? when the while loop should stop. The last one increases the value of i by 1. The i+=1 statement is equivalent to i=i+1. Similarly, t**=2 should be interpreted as t=t**2:

i=1
while(i<=4):
    print(i)
    i+=1

The key for a while loop is that an exit condition should be satisfied at least once. Otherwise, we would enter an infinitive loop. For example, if we run the following scripts, we would enter an infinitive loop. When this happens, we can use Ctrl + C to stop it:

i=1
while(i!=2.1):
    print(i)
    i+=1

In the previous program, we compare two real numbers for equality. It is not a good idea to use the equals sign for two real/float/double numbers. The next example is related to the famous Fibonacci series: the summation of the previous two numbers is the current one:

The Python code for computing the Fibonacci series is given as follows:

def fib...

Using keyboard commands to stop an infinitive loop


Sometimes, because of carelessness or other reasons, we might end up with an infinitive loop (refer to the following program). Our original intention is to print just four numbers ranging from one to four. However, since we forgot to add 1 to the variable i after each printing, the exit condition will never be satisfied, that is, it leads to an infinitive loop. For such cases, we could use Ctrl + C or Ctrl + Enter to stop such an infinitive loop:

i=1
While i<5:
    Print i
>>>

If these commands do not work, then use Ctrl + Alt + Del to launch the Task Manager, choose Python, and then click on End Task.

Estimating implied volatility by using a while loop

This time, we use the Black-Scholes-Merton put option model and a while loop to estimate the implied volatility. First, we present the put option model as follows:

def bs_put(S,X,T,rf,sigma):
    from scipy import log,exp,sqrt,stats
    d1=(log(S/X)+(rf+sigma*sigma/2.)*T)/(sigma...

Estimating implied volatility by using an American call


Since almost all exchange listed stock options are American options, we show the following program to estimate an implied volatility based on an American call option:

from math import exp,sqrt
def binomialCallAmerican(s,x,T,r,sigma,n=100):
    deltaT = T /n
    u = exp(sigma * sqrt(deltaT))
    d = 1.0 / u
    a = exp(r * deltaT)
    p = (a - d) / (u - d)
    v = [[0.0 for j in xrange(i + 1)] for i in xrange(n + 1)]
    for j in xrange(i+1):
        v[n][j] = max(s * u**j * d**(n - j) - x, 0.0)
    for i in xrange(n-1, -1, -1):
        for j in xrange(i + 1):
            v1=exp(-r*deltaT)*(p*v[i+1][j+1]+(1.0-p)*v[i+1][j])
            v2=max(s-x,0)
            v[i][j]=max(v1,v2)
    return v[0][0]

The previous Python program is used to estimate an American call option based on the binomial-tree method, or CRR method. Based on the input values, we first calculate u, d, and p, where u represents the up movement, d represents the down movement...

Measuring efficiency by time spent in finishing a program


The following program measures how much time, in seconds, is required to finish a program. The function used is time.clock():

import time
start = time.clock()
n=10000000
for i in range(1,n):
    k=i+i+2
diff= (time.clock() - start)
print round(diff,2)

The total time we need to finish the previous meaningless loop is about 1.59 seconds.

The mechanism of a binary search


To estimate the implied volatility, the logic underlying the earlier methods is to run the Black-Scholes-Merton option model a hundred times and choose the sigma value that achieves the smallest difference between the estimated option price and the observed price. Although the logic is easy to understand, such an approach is not efficient since we need to call the Black-Scholes-Merton option model a few hundred times. To estimate a few implied volatilities, such an approach would not pose any problems. However, under two scenarios, such an approach is problematic. First, if we need higher precision, such as sigma=0.25333, or we have to estimate several million implied volatilities, we need to optimize our approach. Let's look at a simple example.

Assume that we randomly pick up a value between one and 5,000. How many steps do we need to match this value if we sequentially run a loop from one to 5,000? A binomial search is the log(n) worst-case scenario when...

Sequential versus random access


If we have daily stock data, we could have them saved in different patterns. One way is to save them as stock ID, date, high, low, opening price, closing price, and trading volume. We could sort our stock ID and save them one after another. We have two ways to write a Python program to access IBM data: sequential access and random access. For sequential access, we read one line and check its stock ID to see if it matches our ticker. If not, we go to the next line, until we find our data. Such a sequential search is not efficient, especially when our dataset is huge, such as several gigabits. It is a good idea to generate an index file, such as IBM, 1,000, 2,000. Based on this information, we know that IBM's data is located from line 1,000 to line 2000. Thus, to retrieve IBM's data, we could jump to line 1,000 immediately without having to go through the first 999 lines. This is called random access.

Looping through an array/DataFrame


The following program shows how to print all values in an array:

import numpy as np
x = np.arange(10).reshape(2,5)
for y in np.nditer(x):
    print y

For another example of going through all tickers, we download a dataset called yanMonthly.pickle from http://canisius.edu/~yany/yanMonthly.pickle. Assume again that the downloaded dataset is saved under C:\temp\. We could use the following program to retrieve the dataset and run a loop to print a dozen tickets:

x=load('c:/temp/yanMonthly.pickle')
stocks=x.index.unique()
for item in stocks[:10]:
  print item
  # add your codes here

The output of the previous code is shown as follows:

000001.SS
A
AA
AAPL
BC
BCF
C
CNC
COH
CPI

The previous program has no real meaning since we could simply type the following codes to see those tickers. However, we could add our own related codes as follows:

>>>stocks[0:10]
array(['000001.SS', 'A', 'AA', 'AAPL', 'BC', 'BCF', 'C', 'CNC', 'COH',
       'CPI'], dtype=object...

Retrieving option data from CBOE


The Chicago Board Options Exchange ( CBOE) trades options and futures. There is a lot of free data available on the CBOE web pages. For example, we could enter a ticker to download its related option data. To download IBM's option data, we perform the following two steps:

  1. Go to http://www.cboe.com/DelayedQuote/QuoteTableDownload.aspx.

  2. Enter IBM, then click on Download.

The first few lines are shown in the following table. According to the original design, the put data is arranged side by side with the call data. In order to have a clearer presentation, we move the put option data under the call:

Retrieving option data from Yahoo! Finance


There are many sources of option data that we could use for our investments, research, or teaching. One of them is Yahoo! Finance. To retrieve option data for IBM, we have the following procedure:

  1. Go to http://finance.yahoo.com.

  2. Type IBM in the search box (top left-hand side).

  3. Click on Options on the left-hand side.

The web page address of Yahoo! Finance is http://finance.yahoo.com/q/op?s=IBM+Options. The screenshot of this web page is shown as follows:

The following program will download option data from Yahoo! Finance:

>>>from pandas.io.data import Options
>>>ticker='IBM'
>>>x = Options(ticker)
>>>calls, puts = x.get_options_data()

We can use the head() and tail() functions to view the first and last several lines of the retrieved data:

>>>calls.head()
   Strike              Symbol   Last  Chg    Bid    Ask  Vol  Open Int
0     100  IBM140118C00100000  78.25    0  83.65  87.10    2        12
1     125  IBM140118C00125000...

The put-call ratio


The put-call ratio represents the perception of investors jointly towards the future. If there is no obvious trend, that is, we expect a normal future, then the put-call ratio should be close to one. On the other hand, if we expect a much brighter future, the ratio should be lower than one. The following code shows a ratio of this type over the years. First, we have to download the data from CBOE. Perform the following steps:

  1. Go to http://www.cboe.com/.

  2. Click on Quotes & Data on the menu bar.

  3. Click on CBOE Volume & Put/Call Ratios.

  4. Click on CBOE Total Exchange Volume and Put/Call Ratios (11-01-2006 to present) under Current.

Assume that the file named totalpc.csv is saved under C:\temp\. The code is given as follows:

import pandas as pd
from matplotlib.pyplot import *
data=pd.read_csv('c:/temp/totalpc.csv',skiprows=2,index_col=0,parse_dates=True)
data.columns=('Calls','Puts','Total','Ratio')
x=data.index
y=data.Ratio
y2=ones(len(y))
title('Put-call ratio')
xlabel('Date...

Summary


In this chapter, we introduced different types of loops. Then, we demonstrated how to estimate the implied volatility based on a European option (Black-Scholes-Merton option model) and on an American option. We discussed the for loop and the while loop, and their applications. For a given set of input values, such as current stock price, the exercise price, the time to maturity, the continuously compounded risk-free rate, and a call price (or put price), we showed how to estimate a stock's implied volatility. In terms of efficiency, we explained the binary search method and compared it with other approaches when estimating an implied volatility. In addition, we demonstrated how to download option data, such as put-call ratio, from Yahoo! Finance and the CBOE web page.

In the next chapter, we will focus on applications of Monte Carlo simulations on option pricing. Using random numbers drawn from a normal distribution, we could mimic the movements of a stock for a given set of mean...

Exercises


1. How many types of loops are present in Python? What are the differences between them?

2. What are the advantages of using a for loop versus a while loop? What are the disadvantages?

3. Based on a for loop, write a Python program to estimate the implied volatility. For a given set of values S=35, X=36, rf=0.024, T=1, sigma=0.13, and c=2.24, what is the implied volatility?

4. Write a Python program based on the Black-Scholes-Merton option model put option model to estimate the implied volatility.

5. Should we get different volatilities based on the Black-Scholes-Merton option model's call and put?

6. For a stock with multiple calls, we could estimate its implied volatility based on its call or put. Based on the Black-Scholes-Merton option model, could we get different values?

7. When estimating a huge number of implied volatilities, such as 5,000 stocks, how can we make our process more efficient?

8. We could apply the binary search method to estimate an implied volatility based on the...

lock icon The rest of the chapter is locked
You have been reading a chapter from
Python for Finance
Published in: Apr 2014 Publisher: ISBN-13: 9781783284375
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime}

IBM (International Business Machines)

172.8

-0.57

      

December 15, 2013 @ 10:30 ET

Bid

172.51

Ask

172.8

Size

2x6

Vol

4184836

Calls

Last Sale

Net

Bid

Ask

Vol

Open Int

  

13 December 125.00 (IBM1313L125)

0

0

46.75

50

0

0

  

13 December 125.00 (IBM1313L125-4)

0

0

46.45

50.45

0

0

  

13 Dec 125.00 (IBM1313L125-8)

0

0

46.2

50.3

0

0

  
...