Python学习:numpy库(二)

本文通过重温控制流讲座中的债券定价公式,展示了如何使用numpy计算不同期限的债券价格,并介绍了矩阵乘法在投资组合现金流计算中的应用,以及一系列矩阵操作函数如创建矩阵、数字框架、对角矩阵和列交换等。
摘要由CSDN通过智能技术生成

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=1N(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:

  1. Define a numpy array N that contains all maturities between 1 and 10 (hint look at the np.arange function).
  2. 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
  • 24
    点赞
  • 41
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值