Lab Dates: Wednesday-Thursday, 13 & 21 February 2013
Today's lab will focus on the python mathematics library.
An option in financial markets is a contract that allows you to buy (but does not require you to buy) at a set price on a set date in the future. For example, if you have an option to buy Apple stock at $700 per share on December 1, then if Apple stock is at $720, then you can use the option and make $20 per share. If the Apple stock is $680, then since the contract only gives you the option of buying the shares, you can ignore it.
Companies work hard to price options to maximize their profits. The program for today is
to write a program that calculates some of what's needed to price options.
A common way to price options is to use the
Black Scholes model (we won't go into how the model works, but if you are interested there
are many sites that explain more about options and pricing models such as
this wiki page
and beginner's guide)
The relevant formulas (from beginner's guide)
are:
where C is the cost of the option that we are calculating. S, T, and K are inputs that represent
the current cost of the stock, the time until maturity, and the strike (the fixed price in the future)
of the stock, respectively. N() is the cumulative distribution function of the standard normal
distribution, r is the risk free rate, and σ (sigma) is volatility of the underlying asset.
That's a lot of math! Python has a built-in library that contains many commonly used math functions already defined for you. We will use them to define d1 and d2. (the cost C can also be calculated using only the math library but requires some understanding of statistics, so, we won't do it here).
To use the math library, you need to include a line in your python file:
import mathwhich tells the python intepreter to include all the functions in the math library. (You can also use from math import * .)
Looking at the equations for d1 and d2, we will need to calculate logarithm and square roots. For example to find the logarithm of S/K, we would write:
math.log(S/K)and to find the square root of T, we would write:
math.sqrt(T)Let's put this altogether in a program to compute d_1:
# Lab 3: calculating option pricing # Your name here def optionPricing(): S,T,K,r,sigma = eval(input("Enter values for the stock price, maturity time, strike price, risk free rate, and volatility (separated by commas):")) d1 = (math.log(S/K) + (r + sigma*sigma/2 )*T ) / (sigma*math.sqrt(T)) print("d1 is", d1) # Run your program: optionPricing()Remember when writing mathematics in python to use * for multiplication and to use parenthesis to group terms together. Test your program with a stock price of 100, maturity time of 1, strike price of 200, risk free rate of 2.5, and volatility of .1 (10%) (your program should display 18.1185281944).
Now, extend your program to calculate and display d2. For the test case above, you should print out 18.0185281944 for d2.
Included with the textbook is a simple graphics library. To use it, place the file graphics.py to the directory where you saved your python files. There is a useful cheat sheet of the graphics functions.
Here is the first program (inspired from motionscript.com):
#Idea from: http://www.motionscript.com/mastering-expressions/simulation-basics-1.html from math import * from graphics import * from time import * def goodSine(): veloc = .5 #horizontal velocity (pixels per second) amp = 50 #sine wave amplitude (pixels) freq = .01 #oscillations per second #Set up a graphics window: win = GraphWin("Good Sine Waves",400,200) win.setCoords(0.0, -100.0, 200.0, 100.0) #Draw a line for the x-axis: p1 = Point(0,0) p2 = Point(200,0) xAxis = Line(p1,p2) xAxis.draw(win) #Draw a ball that follows a sine wave for time in range(1000): x = time*veloc y = amp*sin(freq*time*2*pi) ball = Circle(Point(x,y),2) ball.draw(win) sleep(0.1) #Needed so that animation runs slowly enough to be seen win.getMouse() win.close() goodSine()Save this file to your USB or MyDocuments folder (along with graphics.py) and run the program. Lets go through what each part does:
from math import * from graphics import * from time import *The import statement asks python to include the functions from a given module, or collection of functions. These three import statements ask for the functions from the math, graphics, and time modules. The math and time modules are built-in to python; the graphics module was written by Zelle, the textbook's author.
veloc = .5 #horizontal velocity (pixels per second) amp = 50 #sine wave amplitude (pixels) freq = .01 #oscillations per secondThese three variables control the speed, height, and bounce of the ball. Try changing them and see what happens to the animation. Your goal is to have the ball touch the ceiling every time.
#Set up a graphics window: win = GraphWin("Good Sine Waves",400,200) win.setCoords(0.0, -100.0, 200.0, 100.0)These lines set up the graphics window. This window will have the title, "Good Sine Waves" and width 400 pixels and height 200 pixel. A pixel is just one tiny light bulb in your computer's screen. So, 400 pixels is 400 tiny lights in the screen. You can assume that computers have screens that are at least 800 by 600 pixels. In the graphics module, there is a function for changing the coordinates of a graphics window. We did so here to make the math calculating the height of the bouncing ball easier.
#Draw a line for the x-axis: p1 = Point(0,0) p2 = Point(200,0) xAxis = Line(p1,p2) xAxis.draw(win)The graphics module has several standard shapes (see list of graphics objects). We created two points, called p1 and p2, that will be the endpoints of a line called xAxis. For our line to be seen, we need to draw it to our window (which we called win). Since it is possible to have multiple windows in a given program, we need to include the name of our window as the input to the draw function.
#Draw a ball that follows a sine wave for time in range(1000): x = time*veloc y = amp*sin(freq*time*2*pi) ball = Circle(Point(x,y),2) ball.draw(win) sleep(0.1) #Needed so that animation runs slowly enough to be seenThis loop repeats the indented statements 1000 times. First time through the variable time is 0; the next time through it is 1; and it keeps going until time is 999. Each repetition of the loop sets the variable x to a multiple of time and sets the variable y to the sine of a multiple of time. It then makes a circle centered at (x,y) and draws that circle (called ball) to the window. Lastly, we have a call to the sleep function so that the animation runs slowly enough so we can see it.
win.getMouse() win.close()We add these lines at the end of our graphics programs to keep the window open. The first command is waiting for a mouse click. After the mouse is clicked in the window, the next statement is executed, win.close() which closes the window.
goodSine()This is a call (or invocation) of the function goodSine() that we just wrote. It is not necessary to have in your file, but if you do, you do not have to type goodSine() in the Python shell to run your function. Instead, it will be called when you use the F5 key.
To make the ball appear to bounce, we need for it to stay above the line representing the x-axis. Another way of saying that is its y-coordinate should always be positive. A simple way to do that is to take the absolute value of the expression for the y variable:
y = abs(amp*sin(freq*time*2*pi))Try running your program to see the bouncing ball!
After completing your program, go to Labs in Blackboard and click on the link: Lab 3. Take the 5 question test about the lab. Remember to click the Submit button before closing the lab exercise. You may take the test as many times as you want until you get a perfect score.