<ruby id="bdb3f"></ruby>

    <p id="bdb3f"><cite id="bdb3f"></cite></p>

      <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
        <p id="bdb3f"><cite id="bdb3f"></cite></p>

          <pre id="bdb3f"></pre>
          <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

          <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
          <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

          <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                <ruby id="bdb3f"></ruby>

                ??一站式輕松地調用各大LLM模型接口,支持GPT4、智譜、豆包、星火、月之暗面及文生圖、文生視頻 廣告
                # 量化分析師的Python日記【第3天:一大波金融Library來襲之numpy篇】 > 來源:https://uqer.io/community/share/54ca15f9f9f06c276f651a56 接下來要給大家介紹的系列中包含了Python在量化金融中運用最廣泛的幾個Library: + numpy + scipy + pandas + matplotlib 會給初學者一一介紹 NumPy 簡介 ## 一、NumPy是什么? 量化分析的工作涉及到大量的數值運算,一個高效方便的科學計算工具是必不可少的。Python語言一開始并不是設計為科學計算使用的語言,隨著越來越多的人發現Python的易用性,逐漸出現了關于Python的大量外部擴展,NumPy (Numeric Python)就是其中之一。NumPy提供了大量的數值編程工具,可以方便地處理向量、矩陣等運算,極大地便利了人們在科學計算方面的工作。另一方面,Python是免費,相比于花費高額的費用使用Matlab,NumPy的出現使Python得到了更多人的青睞。 我們可以簡單看一下如何開始使用NumPy: ```py import numpy numpy.version.full_version '1.8.0' ``` 我們使用了`import`命令導入了NumPy,并使用`numpy.version.full_version`查出了量化實驗室里使用的NumPy版本為1.8.0。在往后的介紹中,我們將大量使用NumPy中的函數,每次都添加`numpy`在函數前作為前綴比較費勁,在之前的介紹中,我們提及了引入外部擴展模塊時的小技巧,可以使用`from numpy import *`解決這一問題。 那么問題解決了?慢!Python的外部擴展成千上萬,在使用中很可能會`import`好幾個外部擴展模塊,如果某個模塊包含的屬性和方法與另一個模塊同名,就必須使用`import module`來避免名字的沖突。即所謂的名字空間(namespace)混淆了,所以這前綴最好還是帶上。 那有沒有簡單的辦法呢?有的,我們可以在`import`擴展模塊時添加模塊在程序中的別名,調用時就不必寫成全名了,例如,我們使用`np`作為別名并調用`version.full_version`函數: ```py import numpy as np np.version.full_version '1.8.0' ``` ## 二、初窺NumPy對象:數組 NumPy中的基本對象是同類型的多維數組(homogeneous multidimensional array),這和C++中的數組是一致的,例如字符型和數值型就不可共存于同一個數組中。先上例子: ```py a = np.arange(20) ``` 這里我們生成了一個一維數組`a`,從0開始,步長為1,長度為20。Python中的計數是從0開始的,R和Matlab的使用者需要小心。可以使用`print`查看: ```py print a numpy.ndarray ``` 通過函數`reshape`,我們可以重新構造一下這個數組,例如,我們可以構造一個`4*5`的二維數組,其中`reshape`的參數表示各維度的大小,且按各維順序排列(兩維時就是按行排列,這和R中按列是不同的): ```py a = a.reshape(4, 5) print a [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] ``` 構造更高維的也沒問題: ```py a = a.reshape(2, 2, 5) print a [[[ 0 1 2 3 4] [ 5 6 7 8 9]] [[10 11 12 13 14] [15 16 17 18 19]]] ``` 既然`a`是`array`,我們還可以調用`array`的函數進一步查看`a`的相關屬性:`ndim`查看維度;`shape`查看各維度的大小;`size`查看全部的元素個數,等于各維度大小的乘積;`dtype`可查看元素類型;`dsize`查看元素占位(bytes)大小。 ```py a.ndim 3 ``` ```py a.shape (2, 2, 5) ``` ```py a.size 20 ``` ```py a.dtype dtype('int64') ``` ## 三、創建數組 數組的創建可通過轉換列表實現,高維數組可通過轉換嵌套列表實現: ```py raw = [0,1,2,3,4] a = np.array(raw) a array([0, 1, 2, 3, 4]) ``` ```py raw = [[0,1,2,3,4], [5,6,7,8,9]] b = np.array(raw) b array([[0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]) ``` 一些特殊的數組有特別定制的命令生成,如`4*5`的全零矩陣: ```py d = (4, 5) np.zeros(d) array([[ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0.]]) ``` 默認生成的類型是浮點型,可以通過指定類型改為整型: ```py d = (4, 5) np.ones(d, dtype=int) array([[1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1], [1, 1, 1, 1, 1]]) ``` `[0, 1)`區間的隨機數數組: ```py np.random.rand(5) array([ 0.93807818, 0.45307847, 0.90732828, 0.36099623, 0.71981451]) ``` ## 四、數組操作 簡單的四則運算已經重載過了,全部的`+`,`-`,`*`,`/`運算都是基于全部的數組元素的,以加法為例: ```py a = np.array([[1.0, 2], [2, 4]]) print "a:" print a b = np.array([[3.2, 1.5], [2.5, 4]]) print "b:" print b print "a+b:" print a+b a: [[ 1. 2.] [ 2. 4.]] b: [[ 3.2 1.5] [ 2.5 4. ]] a+b: [[ 4.2 3.5] [ 4.5 8. ]] ``` 這里可以發現,`a`中雖然僅有一個與元素是浮點數,其余均為整數,在處理中Python會自動將整數轉換為浮點數(因為數組是同質的),并且,兩個二維數組相加要求各維度大小相同。當然,NumPy里這些運算符也可以對標量和數組操作,結果是數組的全部元素對應這個標量進行運算,還是一個數組: ```py print "3 * a:" print 3 * a print "b + 1.8:" print b + 1.8 3 * a: [[ 3. 6.] [ 6. 12.]] b + 1.8: [[ 5. 3.3] [ 4.3 5.8]] ``` 類似C++,`+=`、`-=`、`*=`、`/=`操作符在NumPy中同樣支持: ```py a /= 2 print a [[ 0.5 1. ] [ 1. 2. ]] ``` 開根號求指數也很容易: ```py print "a:" print a print "np.exp(a):" print np.exp(a) print "np.sqrt(a):" print np.sqrt(a) print "np.square(a):" print np.square(a) print "np.power(a, 3):" print np.power(a, 3) a: [[ 0.5 1. ] [ 1. 2. ]] np.exp(a): [[ 1.64872127 2.71828183] [ 2.71828183 7.3890561 ]] np.sqrt(a): [[ 0.70710678 1. ] [ 1. 1.41421356]] np.square(a): [[ 0.25 1. ] [ 1. 4. ]] np.power(a, 3): [[ 0.125 1. ] [ 1. 8. ]] ``` 需要知道二維數組的最大最小值怎么辦?想計算全部元素的和、按行求和、按列求和怎么辦?`for`循環嗎?不,NumPy的`ndarray`類已經做好函數了: ```py a = np.arange(20).reshape(4,5) print "a:" print a print "sum of all elements in a: " + str(a.sum()) print "maximum element in a: " + str(a.max()) print "minimum element in a: " + str(a.min()) print "maximum element in each row of a: " + str(a.max(axis=1)) print "minimum element in each column of a: " + str(a.min(axis=0)) a: [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] sum of all elements in a: 190 maximum element in a: 19 minimum element in a: 0 maximum element in each row of a: [ 4 9 14 19] minimum element in each column of a: [0 1 2 3 4] ``` 科學計算中大量使用到矩陣運算,除了數組,NumPy同時提供了矩陣對象(`matrix`)。矩陣對象和數組的主要有兩點差別:一是矩陣是二維的,而數組的可以是任意正整數維;二是矩陣的`*`操作符進行的是矩陣乘法,乘號左側的矩陣列和乘號右側的矩陣行要相等,而在數組中`*`操作符進行的是每一元素的對應相乘,乘號兩側的數組每一維大小需要一致。數組可以通過`asmatrix`或者`mat`轉換為矩陣,或者直接生成也可以: ```py a = np.arange(20).reshape(4, 5) a = np.asmatrix(a) print type(a) b = np.matrix('1.0 2.0; 3.0 4.0') print type(b) <class 'numpy.matrixlib.defmatrix.matrix'> <class 'numpy.matrixlib.defmatrix.matrix'> ``` 再來看一下矩陣的乘法,這使用`arange`生成另一個矩陣`b`,`arange`函數還可以通過`arange(起始,終止,步長)`的方式調用生成等差數列,注意含頭不含尾。 ```py b = np.arange(2, 45, 3).reshape(5, 3) b = np.mat(b) print b [[ 2 5 8] [11 14 17] [20 23 26] [29 32 35] [38 41 44]] ``` 有人要問了,`arange`指定的是步長,如果想指定生成的一維數組的長度怎么辦?好辦,`linspace`就可以做到: ```py np.linspace(0, 2, 9) array([ 0. , 0.25, 0.5 , 0.75, 1. , 1.25, 1.5 , 1.75, 2. ]) ``` 回到我們的問題,矩陣`a`和`b`做矩陣乘法: ```py print "matrix a:" print a print "matrix b:" print b c = a * b print "matrix c:" print c print c 查看全部 matrix a: [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] matrix b: [[ 2 5 8] [11 14 17] [20 23 26] [29 32 35] [38 41 44]] matrix c: [[ 290 320 350] [ 790 895 1000] [1290 1470 1650] [1790 2045 2300]] ``` ## 五、數組元素訪問 數組和矩陣元素的訪問可通過下標進行,以下均以二維數組(或矩陣)為例: ```py a = np.array([[3.2, 1.5], [2.5, 4]]) print a[0][1] print a[0, 1] 1.5 1.5 ``` 可以通過下標訪問來修改數組元素的值: ```py b = a a[0][1] = 2.0 print "a:" print a print "b:" print b a: [[ 3.2 2. ] [ 2.5 4. ]] b: [[ 3.2 2. ] [ 2.5 4. ]] ``` 現在問題來了,明明改的是`a[0][1]`,怎么連`b[0][1]`也跟著變了?這個陷阱在Python編程中很容易碰上,其原因在于Python不是真正將`a`復制一份給`b`,而是將`b`指到了`a`對應數據的內存地址上。想要真正的復制一份`a`給`b`,可以使用`copy`: ```py a = np.array([[3.2, 1.5], [2.5, 4]]) b = a.copy() a[0][1] = 2.0 print "a:" print a print "b:" print b a: [[ 3.2 2. ] [ 2.5 4. ]] b: [[ 3.2 1.5] [ 2.5 4. ]] ``` 若對`a`重新賦值,即將`a`指到其他地址上,`b`仍在原來的地址上: ```py a = np.array([[3.2, 1.5], [2.5, 4]]) b = a a = np.array([[2, 1], [9, 3]]) print "a:" print a print "b:" print b a: [[2 1] [9 3]] b: [[ 3.2 1.5] [ 2.5 4. ]] ``` 利用`:`可以訪問到某一維的全部數據,例如取矩陣中的指定列: ```py a = np.arange(20).reshape(4, 5) print "a:" print a print "the 2nd and 4th column of a:" print a[:,[1,3]] a: [[ 0 1 2 3 4] [ 5 6 7 8 9] [10 11 12 13 14] [15 16 17 18 19]] the 2nd and 4th column of a: [[ 1 3] [ 6 8] [11 13] [16 18]] ``` 稍微復雜一些,我們嘗試取出滿足某些條件的元素,這在數據的處理中十分常見,通常用在單行單列上。下面這個例子是將第一列大于5的元素(10和15)對應的第三列元素(12和17)取出來: ```py a[:, 2][a[:, 0] > 5] array([12, 17]) ``` 可使用`where`函數查找特定值在數組中的位置: ```py loc = numpy.where(a==11) print loc print a[loc[0][0], loc[1][0]] (array([2]), array([1])) 11 ``` ## 六、數組操作 還是拿矩陣(或二維數組)作為例子,首先來看矩陣轉置: ```py a = np.random.rand(2,4) print "a:" print a a = np.transpose(a) print "a is an array, by using transpose(a):" print a b = np.random.rand(2,4) b = np.mat(b) print "b:" print b print "b is a matrix, by using b.T:" print b.T a: [[ 0.17571282 0.98510461 0.94864387 0.50078988] [ 0.09457965 0.70251658 0.07134875 0.43780173]] a is an array, by using transpose(a): [[ 0.17571282 0.09457965] [ 0.98510461 0.70251658] [ 0.94864387 0.07134875] [ 0.50078988 0.43780173]] b: [[ 0.09653644 0.46123468 0.50117363 0.69752578] [ 0.60756723 0.44492537 0.05946373 0.4858369 ]] b is a matrix, by using b.T: [[ 0.09653644 0.60756723] [ 0.46123468 0.44492537] [ 0.50117363 0.05946373] [ 0.69752578 0.4858369 ]] ``` 矩陣求逆: ```py import numpy.linalg as nlg a = np.random.rand(2,2) a = np.mat(a) print "a:" print a ia = nlg.inv(a) print "inverse of a:" print ia print "a * inv(a)" print a * ia a: [[ 0.86211266 0.6885563 ] [ 0.28798536 0.70810425]] inverse of a: [[ 1.71798445 -1.6705577 ] [-0.69870271 2.09163573]] a * inv(a) [[ 1. 0.] [ 0. 1.]] ``` 求特征值和特征向量 ```py a = np.random.rand(3,3) eig_value, eig_vector = nlg.eig(a) print "eigen value:" print eig_value print "eigen vector:" print eig_vector eigen value: [ 1.35760609 0.43205379 -0.53470662] eigen vector: [[-0.76595379 -0.88231952 -0.07390831] [-0.55170557 0.21659887 -0.74213622] [-0.33005418 0.41784829 0.66616169]] ``` 按列拼接兩個向量成一個矩陣: ```py a = np.array((1,2,3)) b = np.array((2,3,4)) print np.column_stack((a,b)) [[1 2] [2 3] [3 4]] ``` 在循環處理某些數據得到結果后,將結果拼接成一個矩陣是十分有用的,可以通過`vstack`和`hstack`完成: ```py a = np.random.rand(2,2) b = np.random.rand(2,2) print "a:" print a print "b:" print a c = np.hstack([a,b]) d = np.vstack([a,b]) print "horizontal stacking a and b:" print c print "vertical stacking a and b:" print d a: [[ 0.6738195 0.4944045 ] [ 0.25702675 0.15422012]] b: [[ 0.6738195 0.4944045 ] [ 0.25702675 0.15422012]] horizontal stacking a and b: [[ 0.6738195 0.4944045 0.28058267 0.0967197 ] [ 0.25702675 0.15422012 0.55191041 0.04694485]] vertical stacking a and b: [[ 0.6738195 0.4944045 ] [ 0.25702675 0.15422012] [ 0.28058267 0.0967197 ] [ 0.55191041 0.04694485]] ``` ## 七、缺失值 缺失值在分析中也是信息的一種,NumPy提供`nan`作為缺失值的記錄,通過`isnan`判定。 ```py a = np.random.rand(2,2) a[0, 1] = np.nan print np.isnan(a) [[False True] [False False]] ``` `nan_to_num`可用來將`nan`替換成0,在后面會介紹到的更高級的模塊`pandas`時,我們將看到`pandas`提供能指定`nan`替換值的函數。 ```py print np.nan_to_num(a) [[ 0.58144238 0. ] [ 0.26789784 0.48664306]] ``` NumPy還有很多的函數,想詳細了解可參考鏈接 http://wiki.scipy.org/Numpy_Example_List 和 http://docs.scipy.org/doc/numpy 最后獻上NumPy SciPy Pandas Cheat Sheet ![](https://box.kancloud.cn/2016-07-31_579d79fe1c48a.jpg)
                  <ruby id="bdb3f"></ruby>

                  <p id="bdb3f"><cite id="bdb3f"></cite></p>

                    <p id="bdb3f"><cite id="bdb3f"><th id="bdb3f"></th></cite></p><p id="bdb3f"></p>
                      <p id="bdb3f"><cite id="bdb3f"></cite></p>

                        <pre id="bdb3f"></pre>
                        <pre id="bdb3f"><del id="bdb3f"><thead id="bdb3f"></thead></del></pre>

                        <ruby id="bdb3f"><mark id="bdb3f"></mark></ruby><ruby id="bdb3f"></ruby>
                        <pre id="bdb3f"><pre id="bdb3f"><mark id="bdb3f"></mark></pre></pre><output id="bdb3f"></output><p id="bdb3f"></p><p id="bdb3f"></p>

                        <pre id="bdb3f"><del id="bdb3f"><progress id="bdb3f"></progress></del></pre>

                              <ruby id="bdb3f"></ruby>

                              哎呀哎呀视频在线观看