Python for Finance Chapter 7

Python for Finance Chapter 7

Chapter7 介绍了matplotlib包的使用,内容较多,所有单独记作一篇博客。不过因为这本书是第一版,内容很老了,所以很多代码没办法运行了,很多图画不出来了。

一个简单的示例

1
2
3
4
5
6
7
8
9
from matplotlib.pyplot import *
rcParams['savefig.dpi'] = 600
rcParams['figure.dpi'] = 600
plot([1,2,3,10])
xlabel('x-axis')
ylabel('y-axis')
title('My figure')
savefig('20180623a1.png')
show()

数学函数

1
2
3
4
5
6
7
8
from pylab import *
rcParams['savefig.dpi'] = 800
rcParams['figure.dpi'] = 800
x = np.linspace(-np.pi, np.pi, 256, endpoint = True)
C, S = np.cos(x), np.sin(x)
plot(x, C), plot(x, S)
savefig("20180623a2.png")
show()

散点图

1
2
3
4
5
6
7
8
9
import numpy as np
rcParams['savefig.dpi'] = 600
rcParams['figure.dpi'] = 600
n = 1024
X = np.random.normal(0, 1, size = n)
Y = np.random.normal(0, 1, size = n)
scatter(X, Y)
savefig('20180623a3.png')
show()

单利与复利

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from matplotlib.font_manager import *
from pylab import *
# 定义自定义字体,文件名从查看系统中文字体中来
myfont = FontProperties(fname='/Library/Fonts/Songti.ttc')
# 解决负号'-'显示为方块的问题
matplotlib.rcParams['axes.unicode_minus'] = False
rcParams['savefig.dpi'] = 600 # 图片像素
rcParams['figure.dpi'] = 600 # 分辨率
pv, n, r = (1000, 10, 0.08)
t = np.linspace(0, n, n)
y1 = np.ones(len(t))*pv # 一条水平参考线
y2 = pv*(1+r*t)
y3 = pv*(1+r)**t
title(u"单利vs复利", fontproperties = myfont)
xlabel(u"期数", fontproperties = myfont)
ylabel(u"值", fontproperties = myfont)
xlim(0, 11)
ylim(800, 2200)
plot(t, y1, 'b-')
plot(t, y2, 'g--')
plot(t, y3, 'r-')
savefig('20180623a4.png')
show()

杜邦恒等式

$$
ROE = \frac{Net \ income}{Sales} \times \frac{Sales}{Total \ Assets}\times \frac{Total \ Assets}{Book value of Equity}
$$

IBM、DELL和WMT三家公司的相关数据如下表:

Ticker Fiscal Year Ending Date ROE Gross Profit Margin Assets Turnover Equity Multiplier
IBM 2012-12-31 0.8804 0.1589 0.8766 6.3209
DELL 2013-02-01 0.2221 0.0417 1.1977 4.4513
WMT 2013-01-31 0.2227 0.0362 2.3099 2.6604

Python代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.font_manager import *
ind = np.arange(3) # ind = array([0, 1, 2])
myfont = FontProperties(fname = '/Library/Fonts/Songti.ttc')
rcParams['savefig.dpi'] = 1200
rcParams['figure.dpi'] = 1200
matplotlib.rcParams['axes.unicode_minus'] = False
plt.title(u'杜邦恒等式', fontproperties = myfont)
plt.xlabel(u'公司', fontproperties = myfont)
ROE = [0.88, 0.22, 0.22]
a = [0.16, 0.04, 0.036]
b = [0.88, 1.12, 2.31]
c = [6.32, 4.45, 2.66]
width = 0.45
p1 = plt.bar(ind, a, width, color = 'b')
p2 = plt.bar(ind, b, width, color = 'r', bottom = a)
p3 = plt.bar(ind, c, width, color = 'y', bottom = b)
plt.xticks(ind, ['IBM', 'DELL', 'WMT'])
plt.figtext(0.2, 0.85, 'ROE = 0.88')
plt.figtext(0.5, 0.7, 'ROE = 0.22')
plt.figtext(0.8, 0.6, 'ROE = 0.22')
plt.figtext(0.2, 0.75, 'Ptofit Marigin = 0.16')
plt.figtext(0.5, 0.5, "0.41")
plt.figtext(0.8, 0.4, "0.036")
plt.ylim(0, 8)
savefig('20180623c2.png')
plt.show()


需要注意的是,不同于Stata中文本位置的指定,这里的文本位置是用百分比的。

NPV&IRR

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
from scipy import *
from matplotlib.pyplot import *
from matplotlib.font_manager import *
matplotlib.rcParams['axes.unicode_minus'] = False
myfont = FontProperties(fname = '/Library/Fonts/Songti.ttc')
rcParams['savefig.dpi'] = 1000
rcParams['figure.dpi'] = 1000
cashFlows = [-100, 50, 60, 70]
rate = []
mynpv = []
x = (0, 0.7)
y = (0, 0)
for i in range(1, 70):
rate.append(0.01*i)
mynpv.append(npv(0.01*i, cashFlows[0:]))
plot(rate, mynpv), plot(x, y)
xlabel(u'贴现率', fontproperties = myfont)
ylabel('NPV')
title(u'NPV与折现率', fontproperties = myfont)
savefig('20180623c3.png')
show()

含两个的IRR的现金流

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import scipy as sp
import matplotlib.pyplot as plt
cashFlows = [504, -432, -432, -432, 822]
rate = []
mynpv = []
x = [0, 0.3]
y = [0, 0]
for i in range(1, 30):
rate.append(0.01*i)
mynpv.append(sp.npv(0.01*i, cashFlows[0:]))
plt.plot(x, y), plt.plot(rate, mynpv)
plt.title('Two IRR')
plt.xlabel('Discount rate')
plt.ylabel('NPV')
rcParams['figure.dpi'] = 1000
rcParams['savefig.dpi'] = 1000
savefig('20180623c4.png')
plt.show()

颜色选择

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import matplotlib.pyplot as plt
A_EPS = (5.02, 4.54, 4.18, 3.73)
B_EPS = (1.35, 1.88, 1.35, 0.73)
ind = np.arange(len(A_EPS)) # x的位置
width = 0.4
fig, ax = plt.subplots()
A_std = B_std = (2, 2, 2, 2)
rects1 = ax.bar(ind, A_EPS, width, color = 'r', yerr = A_std)
rects2 = ax.bar(ind, B_EPS, width, color = 'y', yerr = B_std)
ax.set_xlabel('Year')
ax.set_ylabel('EPS')
ax.set_title('Diluted EPS Excluding Extraordinary Iterms')
ax.set_xticks(ind+width)
ax.set_xticklabels(('2012', '2013', '2014', '2015'))
ax.legend((rects1[0], rects2[0]), ('WMT', 'DELL'))
def autolabel(rects):
for rect in rects:
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2.,
1.05 * height, '%d' % int(height),
ha = 'center', va = 'center')
autolabel(rects1)
autolabel(rects2)
plt.show()


一些颜色代码:

Letters Color Chinese name Letters Color Chinese name
‘b’ Blue 蓝色 ‘m’ Magenta 品红
‘g’ Green 绿色 ‘y’ Yellow 黄色
‘r’ Red 红色 ‘k’ Black 黑色
‘c’ Cyan 青色 ‘w’ White 白色

一些形状代码:

Character Chinese name Character Chinese name
‘-‘ 实线 ‘3’ 向左的三角形
‘–’ 虚线 ‘4’ 向右的三角形
‘-.’ 虚线-点 ‘s’ 正方形
‘:’ 点线 ‘p’ ⭐️(pentagon)
‘.’ ‘*’ *
‘,’ 像素点 ‘h’ 六边形(hexagon)
‘o’ ⭕️ ‘H’ 六边形(hexagon)
‘v’ 向下的三角形 ‘+’ +
‘^’ 向上的三角形 ‘x’ x
‘<’ 向左的三角形 ‘D’ 💎
‘>’ 向右的三角形 ‘d’ Thin 💎
‘1’ 向下的三角形 竖线 竖线
‘2’ 向上的三角形 ‘_’ _

投资组合的分散效应

比较均值方差

1
2
3
4
5
6
7
8
import numpy as np
ret_A = [0.102, -0.02, 0.213, 0.12, 0.13]
ret_B = [0.1062, 0.23, 0.045, 0.234, 0.113]
p = (np.array(ret_A) + np.array(ret_B))/2
round(np.mean(ret_A), 3), round(np.mean(ret_B), 3), round(p.mean(), 3)
Out[16]: (0.109, 0.146, 0.127)
round(np.std(ret_A), 3), round(np.std(ret_B), 3), round(p.std(), 3)
Out[17]: (0.075, 0.074, 0.027)

图示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rcParams
year = [2009, 2010, 2011, 2012, 2013]
ret_A = [0.102, -0.02, 0.213, 0.12, 0.13]
ret_B = [0.1062, 0.23, 0.045, 0.234, 0.113]
p = (np.array(ret_A) + np.array(ret_B))/2
plt.figtext(0.2, 0.65, "Stock A")
plt.figtext(0.15, 0.4, "Stock B")
plt.xlabel('Year')
plt.ylabel('Returns')
plt.plot(year, ret_A, lw = 2)
plt.plot(year, ret_B, lw = 2)
plt.plot(year, p, lw = 2)
plt.title('Individual stocks vs. an equal-weighted 2-stock portfolio')
plt.annotate('Equal-weighted Portfolio',
xy = (2010, 0.1),
xytext = (2011, 0),
arrowprops = dict(facecolor = 'black', shrink = 0.05))
plt.ylim(-0.1, 0.3)
rcParams['savefig.dpi'] = 1000
plt.savefig('20180623c6.png')
plt.show()

计算相关系数

1
2
3
4
5
import scipy as sp
sp.corrcoef(ret_A, ret_B)
Out[19]:
array([[ 1. , -0.74583429],
[-0.74583429, 1. ]])

投资组合的分散程度与风险

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from matplotlib.pyplot import *
n=[1,2,4,6,8,10,12,14,16,18,20,25,30,35,40,45,50,75,100,200,300,400,500,600,700,800,900,1000]
port_sigma=[0.49236,0.37358,0.29687,0.26643,0.24983,0.23932,0.23204,0.22670,
0.22261,0.21939,0.21677,0.21196,0.20870,0.20634,0.20456,0.20316,0.20203,0.19860,
0.19686,0.19432,0.19336,0.19292,0.19265,0.19347,0.19233,0.19224,0.19217,0.19211,0.19158]
xlim(0, 50)
ylim(0.1, 0.4)
hlines(0.19217, 0, 50, color = 'r', linestyles = '--')
annotate('', xy = (5, 0.19),
xycoords = 'data',
xytext = (5, 0.28),
textcoords = 'data', arrowprops = {'arrowstyle':'<->'})
annotate('', xy = (30, 0.19),
xycoords = 'data',
xytext = (30, 0.1),
textcoords = 'data', arrowprops = {'arrowstyle':'<->'})
annotate('Total portfolio risk',
xy = (5, 0.3),
xytext = (25, 0.35),
arrowprops = dict(facecolor = 'black', shrink = 0.02))
figtext(0.15, 0.4, "Diversiable risk")
figtext(0.65, 0.25, "Nondiversiable risk")
plot(n[0:17], port_sigma[0:17])
title('Relationship between n and portfolio risk')
xlabel("Number of stocks in a portfolio")
ylabel("Ratio of Portfolio std to std one stock")
rcParams['figure.dpi'] = 1000
rcParams['savefig.dpi'] = 1000
savefig('20180623c7.png')
show()

理解货币的时间价值

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from matplotlib.pyplot import *
from matplotlib import rcParams
fig1 = figure(facecolor='white')
ax1 = axes(frameon = False)
ax1.set_frame_on(False)
ax1.get_xaxis().tick_bottom()
ax1.axes.get_yaxis().set_visible(False)
x = range(0, 11, 2)
x1 = range(len(x), 0, -1)
y = [0]*len(x)
annotate("Today's value of $100 received today",
xy = (0, 0),
xytext = (2, 0.1),
arrowprops = dict(facecolor = 'black', shrink = 0.02))
annotate("Today's value of $100 received in 2 years",
xy = (2, 0.00005),
xytext = (3.7, 0.08),
arrowprops = dict(facecolor = 'black', shrink = 0.02))
annotate("received in 4 years",
xy = (4, 0.00005),
xytext = (5.3, 0.06),
arrowprops = dict(facecolor = 'black', shrink = 0.02))
annotate("received in 10 years",
xy = (10, -0.00005),
xytext = (6, -0.06),
arrowprops = dict(facecolor = 'black', shrink = 0.02))
s = [50*2.5**n for n in x1];
title("Time value of money")
xlim(-2, 11)
xlabel("Time (number of years)")
scatter(x, y, s = s)
rcParams['savefig.dpi'] = 800
savefig('20180623c8.png')
show()

插入图片

1
2
3
4
5
6
7
import matplotlib.pyplot as plt
import matplotlib.cbook as cbook
image_file = cbook.get_sample_data('/Users/mr.cheng/Desktop/Python_for_Finance/20180623c5.png')
image = plt.imread(image_file)
plt.imshow(image)
plt.savefig('20180623c9.png')
plt.show()

# Python

评论

程振兴

程振兴 @czxa.top
截止今天,我已经在本博客上写了658.8k个字了!

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×