1.Let’s revisit a bond pricing example we saw in the summer lecture on control flow.
Recall that the equation for pricing a bond with coupon payment $ C $,
face value $ M $, yield to maturity $ i $, and periods to maturity
$ N $ is
P = ( ∑ n = 1 N C ( i + 1 ) n ) + M ( 1 + i ) N = C ( 1 − ( 1 + i ) − N i ) + M ( 1 + i ) − N \begin{align*} P &= \left(\sum_{n=1}^N \frac{C}{(i+1)^n}\right) + \frac{M}{(1+i)^N} \\ &= C \left(\frac{1 - (1+i)^{-N}}{i} \right) + M(1+i)^{-N} \end{align*} P=(n=1∑N(i+1)nC)+(1+i)NM=C(i1−(1+i)−N)+M(1+i)−N
In the code cell below, we have defined variables for i
, M
and C
.
You have two tasks:
- Define a numpy array
N
that contains all maturities between 1 and 10 (hint look at thenp.arange
function). - Using the equation above, determine the bond prices of all maturity levels in your array.
i = 0.03
M = 100
C = 5
# Define array here
N = np.arange(1, 11)
# price bonds here
P = C*(1 - (1 + i)**(-N))/i + M*(1 + i)**(-N)
print(np.concatenate((N,P),axis = 0))
2. X@Y :矩阵乘法
可用于portfoflio现金流的计算
y = np.array([3.0, 5.0, 1.1]) # payoffs
x1 = np.array([4.0, 2.5, 8.0]) # portfolio 1
x2 = np.array([2.0, 1.5, 0.0]) # portfolio 2
X = np.array((x1, x2))
X*y
3. 构建矩阵
Write a Python function to take three positive integers m, n, a as parameters, and return an 𝑚×𝑛 matrix with elements starting from a, a+1, a+2, … in numpy array.
def createMatrix(m,n,a):
return np.arange(a,a+m*n).reshape(m,n)
4. Digital frame
Write a Python function to take a positive integer n and return an n*n matrix, in which the elements on the borders will be equal to 1, and inside 0.
def digitalFrame(n):
a = np.ones((n,n))
a[1:-1,1:-1] = 0
return a
5. 创建对角阵
def diagMatrix(n):
a = np.zeros((n,n), dtype = int)
for i in range(n):
a[i,i] = i+1
return a
6. Sum of multiples of 3 or 5
Write a Python function to take a 1-d numpay array and return the sum of the elements which are multiples of 3 or 5.
def sum3_5(n):
return sum(n[(n%5==0)|(n%3==0)])
7. Replace outliers
Write a Python function replaceOutliers(a, ex, value) to replace the outliers (in numpy array a), which values are great than ex, to the value of value.
def replaceOutliers(a, ex, value):
a[a>ex] = value
return a
8. Swap columns
Write a Python function swapColumns(a, m, n) to swap the 𝑛𝑡ℎ column and the 𝑚𝑡ℎ column of the matrix a. (m, n are 0 based)
def swapColumns(a, m,n):
a[:,m], a[:,n] = a[:,n], a[:,m]
return a