1/28/22, 9:49 AM 2022_GR5260_Class2_PythonBasics – Jupyter Notebook
128.41391359210502
Logging info…
128.41391359210502
Copyright By PowCoder代写 加微信 powcoder
Topics: Functions, exception handling, packages & modules, basic data structures, numpy
# consider fixed rate bond that pays coupons annually
# r = coupon rate, y = bond yield, n = number of coupon periods def bond_price(r, y, n, log=False):
for i in range(1,n+1):
price += r*100/(1+y)**i price += 100/(1+y)**n
if log == True:
print(‘Logging info…’) return price
# tab for auto-completion, shift+tab for function definition
bond_price(0.04, 0.01, 10)
# optional inputs
bond_price(r=0.04, y=0.01, n=10, log=True)
# built-in errors: drawback: once error occurs, the execution stops and # the remaining function and program is not executed
bond_price(0.04, 1, -10)
# docstring: optional
def bond_price_test(r, y, n, log=False): ”’
returns bond price given yield
Parameters:
coupon rate
for i in range(1,n+1):
price += r*100/(1+y)**i price += 100/(1+y)**n
if log == True:
print(‘Logging info…’) return price
Error handling
Handling an exception with a try statement is called catching an exception. Python starts by executing the try clause. If all goes well, it skips the except clause and proceeds. If an exception occurs, it jumps out of the try clause and executes the except clause
Built-in exceptions: ValueError, TypeError
localhost:8888/notebooks/Documents/GR5260_2022/0 2022 class notes/2022_GR5260_Class2_PythonBasics.ipynb 1/6
1/28/22, 9:49 AM 2022_GR5260_Class2_PythonBasics – Jupyter Notebook
def bond_price2(r, y, n, log=False): price = 0
# not discuss
#if isinstance(r, np.ndarray) == True:
if type(n) != int: # cannot input an array because range(1,n) won’t work
print(‘r is np.ndarray’)
if r.dtype.type != np.float64 and r.dtype.type != np.float32:
raise TypeError(‘Input array r must be floats’)
raise TypeError(‘Input n must be an integer’) if n < 0:
raise ValueError('Input n must be non-negative')
# let's not discuss checks on r
#if r > 10: #if (r > 10).any() == True:
# raise ValueError(‘Input rate must be smaller than…’) for i in range(1,n+1):
price += r*100/(1+y)**i price += 100/(1+y)**n
except TypeError as e: print(‘Type error:’, e)
except ValueError as e: print(‘Value error:’, e)
print(‘We are still here’) if log == True:
print(‘Logging info…’) return price
Out[43]: 0
bond_price2(0.04, 0.01, -10)
Value error: Input n must be non-negative
We are still here
Packages and modules
# module: souce code files (.py)
# package: a directory of modules, can also be a mix of packages and modules
# Jupyter notebook -> save as a module
# Packages are namespaces
# Use of namespace: ensure all the names in your program are unique and can be used w
# to call a function from a module
import random as rd
#
rd.uniform(0,1)
Out[45]: 0.05109636814726792 In [46]:
# Exercise:
# – create a package (ie. folder) called ‘valuation’
# – create a module (.py file) called ‘bond’ to include a function price_from_yield
localhost:8888/notebooks/Documents/GR5260_2022/0 2022 class notes/2022_GR5260_Class2_PythonBasics.ipynb 2/6
1/28/22, 9:49 AM 2022_GR5260_Class2_PythonBasics – Jupyter Notebook
import valuation.bond as bd r = 0.04
n = 10 bd.price_from_yield(r, y, n)
We are still here
128.41391359210502
We are still here
128.41391359210502
Basic data structures: lists, tuples, dictionary
[‘hello’, ‘changed’, 2.0, ‘data’]
[1, 4, 9, 16]
Numpy: basic functions, vectorization, slice operator, broadcasting
(array([2, 4, 6, 8]), array([ 2, 4, 8, 16]))
(array([ 2.71828183, 7.3890561 , 20.08553692, 54.59815003]),
array([False, False, True, True]))
import valuation as va va.bond.price_from_yield(r, y, n)
# list: sequence of elements, mutable
a = [‘hello’, 1.0, 2.0]
a[1] = ‘changed’
a.append(“data”) # remove(‘hello’), insert(pos,’w’), sort() a
# list comprehension
b = [i**2 for i in range(1,5)] b
# tuple: sequence of elements, immutable, only a few methods available c = (2, 3) # store information
# dictionary: List of key-value pairs, each key is mapped to a value, mutable
data_info = {‘shape’: (100,3), ‘size’: 100}
import numpy as np
x = np.array([i for i in range(1,5)])
x*2, 2**x # vectorization: apply math operations elementwise
# show various math methods in dropdown
np.exp(x), x>2
localhost:8888/notebooks/Documents/GR5260_2022/0 2022 class notes/2022_GR5260_Class2_PythonBasics.ipynb 3/6
1/28/22, 9:49 AM 2022_GR5260_Class2_PythonBasics – Jupyter Notebook
yy = np.linspace(0.01,0.02,3) rr = np.linspace(0.04,0.05,3) bond_price2(rr, yy, n), rr, yy
We are still here
(array([128.41391359, 127.66655366, 126.94775502]),
array([0.04 , 0.045, 0.05 ]),
array([0.01 , 0.015, 0.02 ]))
array([0., 0., 0., 0., 0.])
array([[0, 0, 0],
[0, 0, 0]])
array([[ 0, 1, 2],
[ 3, 4, 5],
[ 6, 7, 8],
[ 9, 10, 11]])
(array([3, 4]),
array([ 3, 4, 5, 6, 7, 8, 9, 10, 11]),
array([ 3, 4, 5, 6, 7, 8, 9, 10]),
array([0, 1, 2]),
array([0, 3, 6, 9]))
array([[ 0.1, 1.2, 2.3],
[ 3.1, 4.2, 5.3],
[ 6.1, 7.2, 8.3],
[ 9.1, 10.2, 11.3]])
np.zeros(5) # float by default
np.zeros(shape=(2,3), dtype=int)
w = np.arange(0,12) w2 = w.reshape((4,3)) w2
# slice operator
w[3:5], w[-1], w[3:], w[3:-1], w2[0,:], w2[:,0]
# broadcasting
# https://docs.scipy.org/doc/numpy/user/basics.broadcasting.html
# Operations on arrays are extended to cover arrays of different dimensions. # Suppose: Want to add .1 to first column, .2 to 2nd column, .3 to 3rd column w3 = np.array([0.1, 0.2, 0.3])
localhost:8888/notebooks/Documents/GR5260_2022/0 2022 class notes/2022_GR5260_Class2_PythonBasics.ipynb 4/6
1/28/22, 9:49 AM 2022_GR5260_Class2_PythonBasics – Jupyter Notebook
# exercise: how about adding different values to different rows?
w4 = np.array([0.1, 0.2, 0.3, 0.4]).reshape((4,1))
w2 + w4, w4
# Not discuss: rule: Two dimensions are compatible when they are equal or one of them
(array([[ 0.1, 1.1, 2.1],
[ 3.2, 4.2, 5.2],
[ 6.3, 7.3, 8.3],
[ 9.4, 10.4, 11.4]]),
array([[0.1],
array([(b’John’, 20, 1.6), (b’Sam’, 19, 1.7)],
dtype=[(‘a1’, ‘S10’), (‘a2’, ‘u1’), (‘a3’, ‘