《三天搞定Python基礎(chǔ)概念之第二天》中文版

Day2,即第二篇主要是講一些偏計算的Library的使用,也就是numpy,scipy,sympy和matplotlib。

前言:
首先,非常感謝Jiang老師將其分享出來!本課件非常經(jīng)典!
經(jīng)過筆者親測,竟然確實(shí)只要三天,便可管中窺豹洞見Python及主要庫的應(yīng)用。實(shí)屬難得誠意之作!
其次,只是鑒于Jiang老師提供的原始課件用英文寫成,而我作為Python的愛好者計算機(jī)英文又不太熟練,講義看起來比較慢,為了提高自學(xué)課件的效率,故我花了點(diǎn)時間將其翻譯成中文,以便將來自己快速復(fù)習(xí)用。
該版僅用于個人學(xué)習(xí)之用。
再次,譯者因工作中需要用到數(shù)據(jù)分析、風(fēng)險可視化與管理,因此學(xué)習(xí)python,翻譯水平有限,請諒解。
在征得原作者Yupeng Jiang老師的同意后,現(xiàn)在我將中文版本分享給大家。

作者:Dr.Yupeng Jiang

翻譯:Murphy Wan

大綱( Outline)

  • 第1天:Python和科學(xué)編程介紹。 Python中的基礎(chǔ)知識:

    • 數(shù)據(jù)類型
    • 控制結(jié)構(gòu)
    • 功能
    • I/O文件
  • 第2天:用Numpy,Scipy,Matplotlib和其他模塊進(jìn)行計算。 用Python解決一些數(shù)學(xué)問題。

  • 第3天:時間序列:用Pandas進(jìn)行統(tǒng)計和實(shí)際數(shù)據(jù)分析。 隨機(jī)和蒙特卡羅。

------------------------------以下為英文原文-------------------------------------

  • Day 1: Introduction to Python and scientific programming. Basics in Python: data type, contro structures, fu nctions, l/O file.
  • Day 2: Computation with Numpy, Scipy, Matplotlib and other modules. Solving some maths problems with Python.
  • Day 3: Time series: statistics and real data analysis with Pandas. Stochastics and Monte Carlo.

第二天的內(nèi)容

Import modules

Numpy

Scipy

Matplotlib

Sympy

導(dǎo)入模塊 (Import modules)

  • 可以通過輸入import關(guān)鍵字來導(dǎo)入模塊
import numpy
  • 或者使用簡稱,即將模塊通過as關(guān)鍵字來命名一個簡稱
import numpy as np
  • 有時您不必導(dǎo)入整個模塊,就像下面一樣:
from scipy.stats import norm

------------------------------以下為英文原文-------------------------------------

  • One can import a module by typing
import numpy
  • or for short by
2import numpy as np
  • Sometimes you do not have to import the whole module, like
from scipy.stats import norm

練習(xí) (Exercise)

  • 嘗試導(dǎo)入模塊時間,并使用它來獲取計算機(jī)運(yùn)行特定代碼所需的時間。
import timeit
def funl (x, y):      
     return x**2 + y**3

t_start  =  timeit.default_timer()
z =  funl(109.2, 367.1)
t_end  =   timeit.default_timer()

cost  =  t_end -t_start
print ( 'Time cost of funl is  %f' %cost)

------------------------------以下為英文原文-------------------------------------

  • Try to import the module timeit and use it to obtain how long you computer takes to run a specific code.
import timeit
def  funl (x, y):      
return x**2 + y**3
t_start  =  timeit.default_timer()
z =  funl(109.2, 367.1)
t_end  =   timeit.default_timer()
cost  =  t_end -t_start
print ( 'Time cost of funl is  %f' %cost)

我們會遇到的模塊

  • NumPy:多維數(shù)組的有效操作。 高效的數(shù)學(xué)函數(shù)。

  • Matplotlib:可視化:2D和(最近)3D圖

  • SciPy:大型庫實(shí)現(xiàn)各種數(shù)值算法,例如:

    • 線性和非線性方程的解
    • 優(yōu)化
    • 數(shù)值整合
  • Sympy:符號計算(解析的 Analytical)

  • Pandas:統(tǒng)計與數(shù)據(jù)分析(明天)

------------------------------以下為英文原文-------------------------------------

Modules we will encounter

  • NumPy: Efficient manipulation of multidimensional arrays. Efficient mathematical functions.
  • Matplotlib: Visualisations: 2D and (recently) 3D plots
  • SciPy: Large library implementing various numerical algorithms, e.g.:
    • solution of linear and nonlinear equations
    • optimisation
    • numerical integration
  • Sympy: Symbolic computation (Analytical).
  • Pandas: Statistical and data analysis(tomorrow)

Numpy

ndarray類型

  • NumPy提供了一種新的數(shù)據(jù)類型:ndarray(n維數(shù)組)。
    • 與元組和列表不同,數(shù)組只能存儲相同類型的對象(例如只有floats或只有ints)
    • 這使得數(shù)組上的操作比列表快得多; 此外,數(shù)組占用的內(nèi)存少于列表。
    • 數(shù)組為列表索引機(jī)制提供強(qiáng)大的擴(kuò)展。

------------------------------以下為英文原文-------------------------------------

The ndarray type

  • NumPy provides a new data type: ndarray (n-dimensional array).

    • Unlike tuples and lists, arrays can only store objects of the same type (e.g. only floats or only ints)
    • This makes operations on arrays much faster than on lists; in addition, arrays take less memory than lists.
    • Arrays provide powerful extensions to the list indexing mechanism.

創(chuàng)建ndarray

  • 我們導(dǎo)入Numpy(在腳本的開頭或終端):
import numpy as np
  • 然后我們創(chuàng)建numpy數(shù)組:
In [1] : np.array([2, 3, 6, 7])   
Out[l] : array([2, 3, 6, 7])   
In [2] : np.array([2, 3, 6, 7.])   
Out [2] :  array([ 2.,  3.,  6., 7.])  <- Hamogenaous   
In  [3] :  np.array( [2,  3,  6,  7+1j])   
Out [3] :  array([ 2.+0.j,  3.+0.j,  6.+0.j,  7.+1.j])

------------------------------以下為英文原文-------------------------------------

Create the ndarray

  • We import Numpy (at the beginning of the script or in the terminal):
import numpy as np
  • Then we create numpy arrays:
In [1] : np.array([2, 3, 6, 7])   
Out[l] : array([2, 3, 6, 7])   
In [2] : np.array([2, 3, 6, 7.])   
Out [2] :  array([ 2.,  3.,  6., 7.])  <- Hamogenaous   
In  [3] :  np.array( [2,  3,  6,  7+ij])   
Out [3] :  array([ 2.+0.j,  3.+0.j,  6.+0.j,  7.+1.j])

創(chuàng)建均勻間隔的數(shù)組

  • arange:
in[1]:np.arange(5)
Out [l]:array([0,1,2,3,4])

range(start, stop, step)的所有三個參數(shù)即起始值,結(jié)束值,步長都是可以用的 另外還有一個數(shù)據(jù)的dtype參數(shù)

  in[2]:np.arange(10,100,20,dtype = float)
  Out [2]:array([10.,30.,50.,70.,90.])
  • linspace(start,stop,num)返回數(shù)字間隔均勻的樣本,按區(qū)間[start,stop]計算:
  in[3]:np.linspace(0.,2.5,5)         
  Out [3]:array([0.,0.625,1.25,1.875,2.5])
  

這在生成plots圖表中非常有用。

  • 注釋:即從0開始,到2.5結(jié)束,然后分成5等份

多維數(shù)組矩陣 (Matrix by multidimensional array)

In [1] : a = np.array([[l, 2, 3]  [4, 5, 6]])
                          ^ 第一行 (Row 1)
In  [2] : a
Out [2] : array([[l, 2,  3] ,   [4,  5,  6]])

In  [3] : a.shape  #<- 行、列數(shù)等 (Number of rows, columns etc.)
Out [3] : (2,3)

In  [4] : a.ndim   #<- 維度數(shù)  (Number of dimensions)
Out [4] : 2

In  [5] : a,size   #<- 元素數(shù)量 (Total number of elements)
Out [5] : 6

形狀變化 (Shape changing)

import numpy as np

a = np .arange(0, 20, 1) #1維
b = a.reshape((4, 5))   #4行5列
c = a.reshape((20, 1))  #2維
d = a.reshape((-1, 4))  #-1:自動確定
#a.shape =(4, 5) #改變a的形狀

Size(N,),(N,1)和(1,N)是不同的!!!

  • Size(N, )表示數(shù)組是一維的。
  • Size(N,1)表示數(shù)組是維數(shù)為2, N列和1行。
  • Size(1,N)表示數(shù)組是維數(shù)為2, 1行和N列。

讓我們看一個例子,如下

例子 (Example)

import numpy as np

a = np.array([1,2,3,4,5])
b = a.copy ()

c1 =  np.dot(np.transpose(a), b)
print(c1)
c2  = np.dot(a, np.transpose(b))
print(c2)

ax  =  np.reshape(a, (5,1))
bx  =  np.reshape(b, (1,5))
c = np.dot(ax, bx)
print(c)

使用完全相同的元素填充數(shù)組 (Filling arrays with identical elements)

In [1] : np.zeros(3)              # zero(),全0填充數(shù)組
Out[l] : array([ 0., 0., 0.])

In [2] : np.zeros((2, 2), complex)
Out[2] : array([[ 0.+0.j, 0.+0.j],                
                [ 0.+0.j, 0.+0.j]])

In [3] : np.ones((2, 3))          # ones(),全1填充數(shù)組
Out[3] : array([[ 1., 1., 1.],
                [ 1., 1., 1.]])

使用隨機(jī)數(shù)字填充數(shù)組 (Filling arrays with random numbers)

  • rand: 0和1之間均勻分布的隨機(jī)數(shù) (random numbers uniformly distributed between 0 and 1)
   In [1] : np.random.rand(2, 4)   
   Out[1] : array([[ 0.373767 , 0.24377115, 0.1050342 , 0.16582644] , 
                   [ 0.31149806, 0.02596055, 0.42367316, 0.67975249l])
  • randn: 均值為0,標(biāo)準(zhǔn)差為1的標(biāo)準(zhǔn)(高斯)正態(tài)分布 {standard normal (Gaussian) distribution with mean 0 and variance 1}
  In [2]: np.random.randn(2, 4)  
  Out[2]: array([[ 0.87747152, 0.39977447, -0.83964985, -1.05129899], 
                 [-1.07933484, 0.49448873,   -1.32648606, -0.94193424]])
  • 其他標(biāo)準(zhǔn)分布也可以使用 (Other standard distributions are also available.)

數(shù)組切片(1D) (Array sliciing(1D))

  • 以格式start:stop可以用來提取數(shù)組的片段(從開始到不包括stop)
In [77]:a = np.array([0,1,2,3,4])
Out[77]:array([0,1,2,3,4])

In [78]:a [1:3]        #<--index從0開始 ,所以1是第二個數(shù)字,即對應(yīng)1到3結(jié)束,就是到第三個數(shù)字,對應(yīng)是2
Out[78]:array([1,2])
  • start可以省略,在這種情況下,它被設(shè)置為零(Notes:貌似留空更合適):
In [79]:a [:3]
Out[79]:array([0,1,2])
  • stop也可以省略,在這種情況下它被設(shè)置為數(shù)組長度:
In [80]:a [1:]
Out[80]:array([1,2,3,4])
  • 也可以使用負(fù)指數(shù),具有標(biāo)準(zhǔn)含義:
In [81]:a [1:-1]
Out[81]:array([1,2,3])      # <-- stop為-1表示倒數(shù)第二個數(shù)

數(shù)組切片(1D)

  • 整個數(shù)組:a或a [:]
In [77]:a = np.array([0,1,2,3,4])
Out[77]:array([0,1,2,3,4])
  • 要獲取,例如每個其他元素,您可以在第二個冒號后面指定第三個數(shù)字(步驟(step)):
In [79]:a [::2]
Out[79]:array([0,2,4]) 

In [80]:a [1:4:2]
Out[80]:array([l,3])
  • -1的這個步驟可用于反轉(zhuǎn)數(shù)組:
In [81]:a [::-1]
Out[81]:array([4,3,2,1,0])

數(shù)組索引(2D) (Array indexing (2D))

  • 對于多維數(shù)組,索引是整數(shù)元組:(For multidimensional arrays, indices are tuples of integers:)
In [93] :  a = np.arange(12) ; a.shape =  (3,  4);  a
Out[93] :  array([[0,  1,  2,  3],
                  [4,  5,  6,  7],
                  [8, 9,  10, 11]])

In [94] : a[1,2]
Out[94] : 6

In [95] : a[1,-1]
Out[95] : 7

數(shù)組切片(2D):單行和列 (Array slicing (2D): single rows and columns)

  • 索引的工作與列表完全相同:(Indexing works exactly like for lists:)
In [96] : a = np.arange(12); a.shape = (3, 4); a   
Out[96] : array([[0, 1, 2, 3],
                 [4, 5, 6, 7],
                 [8, 9,10,11]])

In [97] : a[:,1]
Out[97] : array([1,5,9])

In [98] : a[2,:]
Out[98] : array([ 8, 9, 10, 11])

In [99] : a[1][2]
Out[99] : 6
  • 不必明確提供尾隨的冒號:(Trailing colons need not be given explicitly:)
In [100] : a[2]
Out[100] : array([8,9,10,11]) 

數(shù)組索引 (Array indexing)


>>> a[0,3:5]
array( [3,4] )

>>> a[4:,4:]
array([[44, 45], 
       [54, 55]])

>>> a[:,2]
array([2,12,22,32,42,52])

>>> a[2: :2, ::2]
array([[20, 22, 24]       
       [40, 42, 44]])

mofang.jpg

副本(copy)和視圖(view)

  • 采用標(biāo)準(zhǔn)的list切片為其建立副本
  • 采用一個NumPy數(shù)組的切片可以在原始數(shù)組中創(chuàng)建一個視圖。 兩個數(shù)組都指向相同的內(nèi)存。因此,當(dāng)修改視圖時,原始數(shù)組也被修改:
In [30] : a = np.arange(5); a
Out[30] : array([0, 1, 2, 3, 4])

In [31] : b = a[2:]; b
Out[31] : array([2, 3, 4])

In [32] : b[0] = 100
In [33] : b

Out[33] : array([l00, 3, 4])
In [34] : a
Out[34] : array([0,1,100,3,4])

副本和視圖 (Copies and views)

  • 為避免修改原始數(shù)組,可以制作一個切片的副本 (To avoid modifying the original array, one can make a copy of a slice:)
In [30] : a = np.arange(5); a
Out[30] : array([0, 1, 2, 3, 4])

In [31] : b = a[2:].copy(); b
Out[31] : array([2, 3, 4])

In [32] : b[0] = 100
In [33] : b
Out[33] : array([100, 3, 4])

In [34] : a 
Out[34] : array([ 0,  1.  2,  3,  4])


矩陣乘法 (Matrix multiplication)

  • 運(yùn)算符 * 表示元素乘法,而不是矩陣乘法:(The * operator represents elementwise multiplication , not matrix multiplication:)

In [1]: A = np.array([[1, 2],[3, 4]])
In [2]: A
Out[2]: array([[1, 2],
               [3, 4]])

In [3]: A * A
Out[3]: array([[1, 4],
               [9, 16]])            
  • 使用dot()函數(shù)進(jìn)行矩陣乘法:(Matrix multiplication is done with the dot() function:)

In [4]: np.dot(A, A)
Out[4]: array([[ 7, 10],    
               [15, 22]])  

--

矩陣乘法

  • dot()方法也適用于矩陣向量(matrix-vector)乘法:

In [1]: A
Out[1]: array([[1, 2],[3, 4]])

In [2]: x = np.array([10, 20])
In [3]: np.dot(A, x)
Out[3]: array([ 50, 110])

In [4]: np.dot(x, A)
Out[4]: array([ 70, 100])


將數(shù)組保存到文件 (Saving arrays to files)

  • savetxt()將表保存到文本文件。 (savetxt() saves a table to a text file.)
In  [1]: a = np,linspace(0. 1, 12); a,shape ' (3, 4); a
Out [1] :
array([[ 0.  ,  0.09090909, 0.18181818,  0.27272727],
[  0.36363636,  0.45454545, 0.54545455,  0.63636364],
[  0.72727273,  0.81818182. 0.90909091,  1.]])

In [2] : np.savetxt("myfile.txt", a)
  • 其他可用的格式(參見API文檔) {Other formats of file are available (see documentation)}

  • save()將表保存為Numpy“.npy”格式的二進(jìn)制文件 (save() saves a table to a binary file in NumPy ".npy" format.)

  - In [3] : np.save("myfile" ,a)    
  • 生成一個二進(jìn)制文件myfile .npy,其中包含一個可以使用np.load()加載的文件。 {produces a binary file myfile .npy that contains a and that can be loaded with np.load().}

將文本文件讀入數(shù)組 (Reading text files into arrays)

  • loadtxt()將以文本文件存儲的表讀入數(shù)組。 (loadtxt() reads a table stored as a text file into an array.)

  • 默認(rèn)情況下,loadtxt()假定列是用空格分隔的。 您可以通過修改可選的參數(shù)進(jìn)行更改。 以散列(#)開頭的行將被忽略。 (By default, loadtxt() assumes that columns are separated with whitespace. You can change this by modifying optional parameters. Lines starting with hashes (#) are ignored.)

  • 示例文本文件data.txt: (Example text file data.txt:)

    |Year| Min temp.| Hax temp.|

    |1990| -1.5 | 25.3|

    |1991| -3.2| 21.2|

  • Code:
   In [1] : tabla = np.loadtxt("data.txt")
   In [2] : table
   Out[2] :
   array ([[ 1.99000000e+03,   -1.50000000e+00,   2.53000000e+01],    
   [ 1.9910000e+03,  -3.2000000e+00,  2.12000000e+01]


Numpy包含更高效率的功能

  • Numpy包含許多常用的數(shù)學(xué)函數(shù),例如:

    • np.log
    • np.maximum
    • np.sin
    • np.exp
    • np.abs
  • 在大多數(shù)情況下,Numpy函數(shù)比Math包中的類似函數(shù)更有效,特別是對于大規(guī)模數(shù)據(jù)。


Scipy (庫)

SciPy的結(jié)構(gòu)

  • scipy.integrate - >積分和普通微分方程
  • scipy.linalg - >線性代數(shù)
  • scipy.ndimage - >圖像處理
  • scipy.optimize - >優(yōu)化和根查找(root finding)
  • scipy.special - >特殊功能
  • scipy.stats - >統(tǒng)計功能
  • ...

要加載一個特定的模塊,請這樣使用, 例如 :

  • from scipy import linalg

線性代數(shù) (Linearalgebra)

  • 線性方程的解 (Solution of linear equations:)

import numpy as np
from scipy import linalg    

A = np.random.randn(5, 5)
b = np.random.randn(5)
x = linalg.solve(A, b)     # A x = b#print(x)    
eigen = linalg.eig(A)     # eigens#print(eigen)    
det = linalg.det(A)     # determinant    
print(det)            

  • linalg的其他有用的方法:eig()(特征值和特征向量),det()(行列式)。{Other useful functions from linalg: eig() (eigenvalues and eigenvectors), det() (determinant). }

數(shù)值整合 (Numerical integration)

  • integration.quad是一維積分的自適應(yīng)數(shù)值積分的函數(shù)。 (integrate.quad is a function for adaptive numerical quadrature of one-dimensional integrals.)

import numpy as np
from scipy import integrate

def fun(x):
    return np.log(x)

value, error = integrate.quad(fun,0,1)
print(value)
print(error)

用Scipy進(jìn)行統(tǒng)計 (Statistics in Scipy)

  • scipy具有用于統(tǒng)計功能的子庫,您可以導(dǎo)入它 (scipy has a sub-library for statistical functions, you can import it by)
from scipy import stats
  • 然后您可以使用一些有用的統(tǒng)計功能。 例如,給出標(biāo)準(zhǔn)正態(tài)分布的累積密度函數(shù)(Then you are able to use some useful statistical function. For example, the cummulative density function of a standard normal distribution is given like
  • 這個包,我們可以直接使用它,如下: (with this package, we can directly use it like)
from scipy import stats
y = stats.norm.cdf(1.2)

優(yōu)化:數(shù)據(jù)擬合 (Optimisation: Data fitting)


import numpy as np
from scipy.optimize import curve_fit
import matplotlib.pyplot as plt

def func(x, a, b, c):    
    return a * np.exp(-b * x) + c

x = np.linspace(0, 4, 50)
y = func(x, 2.5, 1.3, 0.5)
ydata = y+0.2*np.random.normal(size=len(x))
popt, pcov = curve_fit(func, x, ydata)
plt.plot(x, ydata, ’b*’)
plt.plot(x, func(x, popt[0], \ 
                    popt[1], popt[2]), ’r-’)
plt.title(’$f(x)=ae^{-bx}+c$ curve fitting’)

優(yōu)化:根搜索 (Optimisation: Root searching)


import numpy as np
from scipy import optimize

def fun(x):
    return np.exp(np.exp(x)) - x**2

# 通過初始化點(diǎn)0,找到興趣0 (find zero of fun with initial point 0)
# 通過Newton-Raphson方法 (by Newton-Raphson)
value1 = optimize.newton(fun, 0)

# 通過二分法找到介于(-5,5)之間的 (find zero between (-5,5) by bisection)
value2 = optimize.bisect(fun, -5, 5)


Matplotlib

最簡單的制圖 (The simplest plot)

  • 導(dǎo)入庫需要添加以下內(nèi)容

from matplotlib import pyplot as plt

  • 為了繪制一個函數(shù),我們操作如下 (To plot a function, we do:)

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 201)
#y = x ** 0.5
#plt.plot(x, y) # default plot
plt.figure(figsize = (3, 3)) # new fig
plt.plot(x, x**0.3, ’r--’) # red dashed
plt.plot(x, x-1, ’k-’) # continue plot
plt.plot(x, np.zeros_like(x), ’k-’)

  • 注意:您的x軸在plt.plot函數(shù)中應(yīng)與y軸的尺寸相同。 (Note: Your x-axis should be the same dimension to y-axis in plt.plot function.)

多個制圖圖例標(biāo)簽和標(biāo)題 (Multiple plotting, legends, labels and title)


import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 10, 201)
plt.figure(figsize = (4, 4))
for n in range(2, 5):
    y = x ** (1 / n)
    plt.plot(x, y, label=’x^(1/’ \
            + str(n) + ’)’)
plt.legend(loc = ’best’)
plt.xlabel(’X axis’)
plt.ylabel(’Y axis’)
plt.xlim(-2, 10)
plt.title(’Multi-plot e.g. ’, fontsize = 18)

  • Forinformations:See
help(plt.plot)  

繪制子圖 (Subplots )


import numpy as np’
import matplotlib.pyplot as plt

def pffcall(S, K):    
    return np.maximum(S - K, 0.0)
def pffput(S, K):
    return np.maximum(K - S, 0.0)    

S = np.linspace(50, 151, 100)
fig = plt.figure(figsize=(12, 6))  

sub1 = fig.add_subplot(121)     # col, row, num    
sub1.set_title('Call', fontsize = 18)
plt.plot(S, pffcall(S, 100), 'r-', lw = 4)
plt.plot(S, np.zeros_like(S), 'black',lw = 1)
sub1.grid(True)
sub1.set_xlim([60, 120])
sub1.set_ylim([-10, 40])    

sub2 = fig.add_subplot(122)
sub2.set_title('Put', fontsize = 18)
plt.plot(S, pffput(S, 100), 'r-', lw = 4)
plt.plot(S, np.zeros_like(S), 'black',lw = 1)
sub2.grid(True)
sub2.set_xlim([60, 120])
sub2.set_ylim([-10, 40])  

  • Figure: 一個子圖的例子
    (注釋:這里,可以把Figure,即fig理解為一張大畫布,你把它分成了兩個子區(qū)域(sub1和sub2),然后在每個子區(qū)域各畫了一幅圖。)

在繪制的圖上添加文本和注釋 (Adding texts to plots)


import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt

def call(S, K=100, T=0.5, vol=0.6, r=0.05):
    d1 = (np.log(S/K) + (r + 0.5 * vol**2) \
          *T) / np.sqrt(T) / vol
    d2 = (np.log(S/K) + (r - 0.5 * vol**2) \
          *T) / np.sqrt(T) / vol
    return S * norm.cdf(d1) - K * \
    np.exp(-r * T) * norm.cdf(d2)

def delta(S, K=100, T=0.5, vol=0.6, r=0.05):
    d1 = (np.log(S/K) + (r + 0.5 * vol**2)\
          *T) / np.sqrt(T) / vol
    return norm.cdf(d1)

(Code continues:)


S = np.linspace(40, 161, 100)
fig = plt.figure(figsize=(7, 6))
ax = fig.add_subplot(111)
plt.plot(S,(call(S)-call(100)),’r’,lw=1)
plt.plot(100, 0, ’ro’, lw=1)
plt.plot(S,np.zeros_like(S), ’black’, lw = 1)
plt.plot(S,call(S)-delta(100)*S- \
    (call(100)-delta(100)*100), ’y’, lw = 1)

(Code continues:)


ax.annotate(’$\Delta$ hedge’, xy=(100, 0), \
            xytext=(110, -10),arrowprops= \
            dict(headwidth =3,width = 0.5, \
            facecolor=’black’, shrink=0.05))
ax.annotate(’Original call’, xy= \
            (120,call(120)-call(100)),xytext\
            =(130,call(120)-call(100)),\
            arrowprops=dict(headwidth =10,\
            width = 3, facecolor=’cyan’, \
            shrink=0.05))
plt.grid(True)
plt.xlim(40, 160)
plt.xlabel(’Stock price’, fontsize = 18)
plt.ylabel(’Profits’, fontsize = 18)

兩個變量的函數(shù)3D制圖(3D plot of a function with 2 variables)


import numpy as np
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

x, y = np.mgrid[-5:5:100j, -5:5:100j]
z = x**2 + y**2
fig = plt.figure(figsize=(8, 6))
ax = plt.axes(projection='3d')
surf = ax.plot_surface(x, y, z, rstride=1,\
                       cmap=cm.coolwarm, cstride=1, \
                       linewidth=0)
fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('3D plot of $z = x^2 + y^2$')

3days_img016_3D_plot.jpg

實(shí)驗(yàn)3:atplotlib (Lab 3: Matplotlib)

  • 用藍(lán)線繪制以下函數(shù) (Plot the following function with blue line)

    • 然后用紅點(diǎn)標(biāo)記坐標(biāo)(1,2) (Then mark the coordinate (1, 2) with a red point.)
  • 使用np.linspace()使t ∈ [0,2π]。 然后給 (Use np.linspace0 to make t ∈ [0,2π]. Then give)

  • 針對X繪Y。 在這個情節(jié)中添加一個稱為“Heart”的標(biāo)題。 (Plot y against x. Add a title to this plot which is called "Heart" .)
  • 針對x∈[-10,10], y∈[-10,10], 繪制3D函數(shù) (Plot the 3D function for x∈[-10,10], y∈[-10,10])


Sympy

符號計算 (Symbolic computation)

  • 到目前為止,我們只考慮了數(shù)值計算。 (So far, we only considered the numerical computation.)

  • Python也可以通過模塊表征進(jìn)行符號計算。(Python can also work with symbolic computation via module sympy.)

  • 符號計算可用于計算方程,積分等的顯式解。 (Symbolic computation can be useful for calculating explicit solutions to equations, integrations and so on.)

聲明一個符號變量 (Declare a symbol variable)


import sympy as sy

#聲明x,y為變量
x = sy.Symbol('x')
y = sy.Symbol('y')
a, b = sy.symbols('a b')

#創(chuàng)建一個新符號(不是函數(shù)
f = x**2 + 2 - 2*x + x**2 -1
print(f)
#自動簡化
g = x**2 + 2 - 2*x + x**2 -1
print(g)

符號的使用1:求解方程 (Use of symbol 1: Solve equations)


import sympy as sy

x  = sy.Symbol ('x')
y  = sy.Symbol('y')

# 給定[-1,1]  (give [-1, 1])
print(sy.solve (x**2 - 1))

# 不能證解決 (no guarantee for solution)
print(sy.solve(x**3  +  0.5*x**2 - 1))

# 用x的表達(dá)式表示y     (exepress x in terms of y)
print (sy.solve(x**3  +  y**2))

# 錯誤:找不到算法 (error:  no  algorithm  can  be  found)
print(sy.solve(x**x + 2*x - 1))

符號的使用2:集成 (Use of symbol 2: Integration)

import sympy as sy

x = sy.Symbol('x')
y = sy.Symbol( 'y')
b = sy.symbols ( 'a b')

# 單變量 single  variable
f = sy.sin(x) + sy.exp(x)
print(sy.integrate(f, (x,  a,  b)))
print(sy.integrate(f, (x,  1,  2)))
print(sy.integrate(f, (x,  1.0,2.0)))
# 多變量 multi variables
g = sy.exp(x) + x * sy.sin(y)
print(sy.integrate(g, (y,a,b)))

符號的使用3:分化 (Use of symbol 3: Differentiation)

import sympy as sy
x =  sy.Symbol( 'x')
y =  sy.Symbol( 'y')
# 單變量 (single variable)
f = sy.cos(x) + x**x
print(sy . diff (f ,  x))
#  多變量  (multi variables)
g = sy.cos(y) * x + sy.log(y)
print(sy.diff (g,  y))

第二天結(jié)束,辛苦了

(傳送門--去第三天)
(傳送門--回第一天)

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容