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. - Second Edition

You're reading from  Python for Finance. - Second Edition

Product type Book
Published in Jun 2017
Publisher
ISBN-13 9781787125698
Pages 586 pages
Edition 2nd Edition
Languages

Table of Contents (23) Chapters

Python for Finance Second Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface
Python Basics Introduction to Python Modules Time Value of Money Sources of Data Bond and Stock Valuation Capital Asset Pricing Model Multifactor Models and Performance Measures Time-Series Analysis Portfolio Theory Options and Futures Value at Risk Monte Carlo Simulation Credit Risk Analysis Exotic Options Volatility, Implied Volatility, ARCH, and GARCH Index

Chapter 10. Options and Futures

In modern finance, the option theory (including futures and forwards) and its applications play an important role. Many trading strategies, corporate incentive plans, and hedging strategies include various types of options. For example, many executive incentive plans are based on stock options. Assume that an importer located in the US has just ordered a piece of machinery from England with a payment of £10 million in three months. The importer has a currency risk (or exchange rate risk). If the pound depreciates against the US dollar, the importer would be better off since he/she pays less US dollars to buy £10 million. On the contrary, if the pound appreciates against the US dollar, then the importer would suffer a loss. There are several ways that the importer could avoid or reduce such a risk: buy pounds right now, enter a futures market to buy pounds with a fixed exchange rate determined today, or long a call option with a fixed exercise price. In this...

Introducing futures


Before discussing the basic concepts and formulas related to futures, let's review the concept of continuously compounded interest rates. In Chapter 3, Time Value of Money, we learned that the following formula could be applied to estimate the future value of a given present value:

Here, FV is the future value, PV is the present value, R is the effective period rate and n is the number of periods. For example, assume that the Annual Percentage Rate (APR) is 8%, compounded semiannually. If we deposit $100 today, what is its future value in two years? The following code shows the result:

import scipy as ps
pv=100
APR=0.08
rate=APR/2.0
n=2
nper=n*2
fv=ps.fv(rate,nper,0,pv)
print(fv)

The output is shown here:

-116.985856

The future value is $116.99. In the preceding program, the effective semiannual rate is 4% since the APR is 8% compounded semiannually. In options theory, risk-free rates and dividend yields are defined as continuously compounded. It is easy to derive the relationship...

Payoff and profit/loss functions for call and put options


An option gives its buyer the right to buy (call option) or sell (put option) something in the future to the option seller at a predetermined price (exercise price). For example, if we buy a European call option to acquire a stock for X dollars, such as $30, at the end of three months our payoff on maturity day will be the one calculated using the following formula:

Here, is the stock price at the maturity date (T), the exercise price is X (X=30 in this case). Assume that three months later the stock price is $25. We would not exercise our call option to pay $30 in exchange for the stock since we could buy the same stock with $25 in the open market. On the other hand, if the stock price is $40, we will exercise our right to reap a payoff of $10, that is, buy the stock at $30 and sell it at $40. The following program presents the payoff function for a call:

>>>def payoff_call(sT,x):
        return (sT-x+abs(sT-x))/2

Applying...

European versus American options


A European option can be exercised only on maturity day, while an American option can be exercised any time before or on its maturity day. Since an American option could be held until it matures, its price (option premium) should be higher than or equal to its European counterpart:

An import difference is that for a European option, we have a close form solution, that is, the Black-Scholes-Merton option model. However, we don't have a close-form solution for an American option. Fortunately, we have several ways to price an American option. Later in the chapter, we show how to use the Binomial-tree method, also called the CRR method, to price an American option.

Understanding cash flows, types of options, rights and obligations

We know that for each business contract, we have two sides: buyer versus seller. This is true for an option contract as well. A call buyer will pay upfront (cash output) to acquire a right. Since this is a zero-sum game, a call option...

Black-Scholes-Merton option model on non-dividend paying stocks


The Black-Scholes-Merton option model is a closed-form solution to price a European option on a stock which does not pay any dividends before its maturity date. If we use or the price today, X for the exercise price, r for the continuously compounded risk-free rate, T for the maturity in years, for the volatility of the stock, the closed-form formulae for a European call (c) and put (p) are:

Here, N() is the cumulative standard normal distribution. The following Python codes represent the preceding equations to evaluate a European call:

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)

In the preceding program, the stats.norm.cdf() is the cumulative normal distribution, that is, N() in the Black-Scholes-Merton option model. The current stock price is $40, the strike price is...

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:             
            ...

European options with known dividends


Assume that we have a known dividend d1 distributed at time T1, T1<T, where T is our maturity date. We can modify the original Black-Scholes-Merton option model by replacing S0 with S, where :

In the preceding example, if we have a known dividend of $1.5 delivered in one month, what is the price of the call?

>>>import p4f
>>>s0=40
>>>d1=1.5
>>>r=0.015
>>>T=6/12
>>>s=s0-exp(-r*T*d1)
>>>x=42
>>>sigma=0.2 
>>>round(p4f.bs_call(s,x,T,r,sigma),2)
1.18

The first line of the program imports the module called p4f which contains the call option model. The result shows that the price of the call is $1.18, which is lower than the previous value ($1.56). It is understandable since the price of the underlying stock would drop roughly by $1.5 in one month. Because of this, the chance that we could exercise our call option will be smaller, that is, less likely to go beyond $42. The preceding...

Various trading strategies


In the following table, we summarize several commonly used trading strategies involving various types of options:

Put-call parity and its graphic presentation


Let's look at a call with an exercise price of $20, a maturity of three months and a risk-free rate of 5%. The present value of this future $20 is given here:

>>>x=20*exp(-0.05*3/12)   
>>>round(x,2)
19.75
>>>

In three months, what will be the wealth of our portfolio which consists of a call on the same stock plus $19.75 cash today? If the stock price is below $20, we don't exercise the call and keep the cash. If the stock price is above $20, we use our cash of $20 to exercise our call option to own the stock. Thus, our portfolio value will be the maximum of those two values: stock price in three months or $20, that is, max(s,20).

On the other hand, how about a portfolio with a stock plus a put option with an exercise price of $20? If the stock price falls by $20, we exercise the put option and get $20. If the stock price is above $20, we simply keep the stock. Thus, our portfolio value will be the maximum of those two...

Binomial tree and its graphic presentation


The binomial tree method was proposed by Cox, Ross, and Robinstein in 1979. Because of this, it is also called the CRR method. Based on the CRR method, we have the following two-step approach. First, we draw a tree, such as the following one-step tree. Assume that our current stock value is S. Then, there are two outcomes of Su and Sd, where u>1 and d<1, see the following code:

import matplotlib.pyplot as plt 
plt.xlim(0,1) 
plt.figtext(0.18,0.5,'S')
plt.figtext(0.6,0.5+0.25,'Su')
plt.figtext(0.6,0.5-0.25,'Sd')

plt.annotate('',xy=(0.6,0.5+0.25), xytext=(0.1,0.5), arrowprops=dict(facecolor='b',shrink=0.01))
plt.annotate('',xy=(0.6,0.5-0.25), xytext=(0.1,0.5), arrowprops=dict(facecolor='b',shrink=0.01))
plt.axis('off')
plt.show()

The graph is shown here:

Obviously, the simplest tree is a one-step tree. Assume that today's price is $10, the exercise price is $11, and a call option will mature in six months. In addition, assume that we know that...

Hedging strategies


After selling a European call, we could hold shares of the same stock to hedge our position. This is named a delta hedge. Since the delta is a function of the underlying stock (S), to maintain an effective hedge we have to rebalance our holding constantly. This is called dynamic hedging. The delta of a portfolio is the weighted deltas of individual securities in the portfolio. Note that when we short a security, its weight will be negative:

Assume that a US importer will pay £10 million in three months. He or she is concerned with a potential depreciation of the US dollar against the pound. There are several ways to hedge such a risk: buy pounds now, enter a futures contract to buy £10 million in three months with a fixed exchange rate, or buy call options with a fixed exchange rate as its exercise price. The first choice is costly since the importer does not need pounds today. Entering a future contract is risky as well since an appreciation of the US dollar would cost...

Implied volatility


From the previous sections, 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:

def bs_call(S,X,T,r,sigma):
    from scipy import log,exp,sqrt,stats
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, if we are given a set values...

Binary-search


To estimate the implied volatility, the logic underlying the earlier methods is to run the Black-Scholes-Merton option model 100 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 linear search is the n...

Retrieving option data from Yahoo! Finance


There are many sources of option data that we can 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.

  3. Click on Options in the navigation bar.

The related page is http://finance.yahoo.com/quote/IBM/options?p=IBM. A screenshot of this web page is as follows:

Volatility smile and skewness


Obviously, each stock should possess one value for its volatility. However, when estimating implied volatility, different strike prices might offer us different implied volatilities. More specifically, the implied volatility based on out-of-the-money options, at-the-money options, and in-the-money options might be quite different. Volatility smile is the shape going down then up with the exercise prices, while the volatility skewness is downward or upward sloping. The key is that investors' sentiments and the supply and demand relationship have a fundamental impact on the volatility skewness. Thus, such a smile or skewness provides information on whether investors, such as fund managers, prefer to write calls or puts, as shown in the following code:

import datetime
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.finance import quotes_historical_yahoo_ochl as getData

# Step 1: input area
infile="c:/temp/callsFeb2014.pkl"
ticker='IBM'
r=0.0003...

References


Please refer to the following articles:

Appendix A – data case 6: portfolio insurance

Portfolio insurance is a method of hedging a portfolio of stocks against market risk by short selling stock index futures. This hedging technique is frequently used by institutional investors when the market direction is uncertain or volatile. Assume that you manage one of the industry portfolios with a current value of $50 million. If you expect the whole market to be quite volatile in next three months--in other words, the market might go down significantly--what might be our choices at the...

Exercises


  1. If the APR is 5% compounded quarterly, what is its equivalent continuously compounded rate?

  2. The value of a portfolio is $4.77 million today with a beta of 0.88. If the portfolio manager explains the market will surge in the next three months and s/he intends to increase her/ his portfolio beta from 0.88 to 1.20 in just three months by using S&P500 futures, how many contracts should s/he long or short? If the S&P500 index increases by 70 points what will be her/his gain or loss? How about if the S&P500 falls by 50 points instead?

  3. Write a Python program to price a call option.

  4. Explain the empty shell method when writing a complex Python program.

  5. Explain the logic behind the so-called comment-all-out method when writing a complex Python program.

  6. Explain the usage of the return value when we debug a program.

  7. When we write the CND (cumulative standard normal distribution), we could define a1, a2, a3, a4, and a5 separately. What are the differences between the following two approaches...

Summary


In this chapter, first we have explained many basic concepts related to portfolio theory, such as covariance,correlation, the formulas on how to calculate variance of a 2-stock portfolio and variance of an n-stock portfolio. After that, we have discussed various risk measures for individual stocks or portfolios, such as Sharpe ratio, Treynor ratio, Sortino ratio, how to minimize portfolio risk based on those measures (ratios), how to setup an objective function, how to choose an efficient portfolio for a given set of stocks, and how to construct an efficient frontier.

In the next chapter, we will discuss one of the most important theory in modern finance: options and futures. We will start from the basic concepts such as payoff functions for a call and for a put. Then we explain the related applications such as various trading strategies, corporate incentive plans, and hedging strategies including different types of options and futures.

lock icon The rest of the chapter is locked
You have been reading a chapter from
Python for Finance. - Second Edition
Published in: Jun 2017 Publisher: ISBN-13: 9781787125698
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}

Names

Description

Direction of initial cash-flow

Expectation of future price movement

Bull spread with calls

Buy a call (x1) sell a call (x2) [ x1< x2 ]

Outflow

Rise

Bull spread with puts

Buy a put (x1), sell a put (x2) [ x1< x2 ]

Inflow

Rise

Bear spread with puts

Buy a put (x2), sell a put (x1) [ x1 < x2 ]

Outflow

Fall

Bear spread with calls

Buy a call (x2), sell a call (x1) [x1 < x2 ]

Inflow

Fall

Straddle

Buy a call & sell a put with the same x

Outflow

Rise or fall

Strip

Buy two puts and a call (with the same x)

Outflow

Prob (fall) > prob (rise)

Strap

Buy two calls and one put (with the same x)

Outflow

Prob (rise)> prob(fall)

Strangle

Buy a call (x2) and buy a put (x1) [x1 < x2 ]

Outflow

Rise or fall

Butterfly with calls

Buy two calls (x1,x3) and sell two calls (x2) [x2=(x1+x3)/2]

Outflow...