python量化交易笔记---13.描述性统计
統(tǒng)計(jì)分為描述統(tǒng)計(jì)和推斷統(tǒng)計(jì),我們?cè)谶@一章里,主要講解描述性統(tǒng)計(jì)。我們用到的數(shù)據(jù)如下所示:
上圖中,gsyh代表工商銀行收益率,pfyh代表浦發(fā)銀行收益率,zglt代表中國(guó)聯(lián)通收益率,我們僅以工商銀行收益為例計(jì)算各個(gè)統(tǒng)計(jì)量。
1.頻數(shù)分布
我們以2014年工商銀行股票的收益率為例,來(lái)看頻數(shù)分布。我們將收益率(下圖中ysgh列)按0.025為一段,統(tǒng)計(jì)收益率落在該段內(nèi)的天數(shù),就可以得到頻數(shù)分布,我們可以按照直方圖來(lái)進(jìn)行繪制。如下所示:
import numpy as np import pandas as pd import matplotlib.pyplot as pltdef startup():''' 創(chuàng)建時(shí)間序列示例 '''rs = pd.read_csv('../datas/retdata.csv')gsyh = rs.gsyhprint(type(gsyh))plt.rcParams['font.sans-serif'] = ['SimHei']plt.rcParams['axes.unicode_minus'] = Falseplt.title('工商銀行收益率頻數(shù)分布圖')plt.xlabel('收益率')plt.ylabel('天數(shù)')plt.hist(gsyh)plt.show()if '__main__' == __name__:startup() codes/c13c001.py運(yùn)行結(jié)果為:
2.數(shù)據(jù)統(tǒng)計(jì)
2.1.數(shù)據(jù)位置
2.1.1.樣本平均數(shù)
算數(shù)平均數(shù)可以用在各種數(shù)據(jù)分析中,定義為:
xˉ=x1+x2+...+xnn\bar{x}=\frac{x_1+x_2+...+x_n}{n} xˉ=nx1?+x2?+...+xn??
幾何平均數(shù)最常用于收益率計(jì)算,假設(shè)共有k個(gè)元素,定義為:
xˉ=[∏i=1kxi]1k\bar{x}=\bigg[ \prod_{i=1}^{k} x_i \bigg]^{\frac{1}{k}} xˉ=[i=1∏k?xi?]k1?
2.1.2.中位數(shù)
中位數(shù)定義為其至少大于等于50%的數(shù)據(jù),同時(shí)小于等于50%的數(shù)據(jù)。
2.1.3.眾數(shù)
一組數(shù)據(jù)中出現(xiàn)最多的數(shù)值。
2.1.4.百分位數(shù)
假設(shè)百分比為α\alphaα如25,則表示至少α\alphaα%的數(shù)小于該值,同時(shí)至少(100?α)(100-\alpha)(100?α)%的數(shù)大于該值。
下面我們還以工商銀行收益率為例,求出這幾個(gè)值:
import numpy as np import pandas as pd import matplotlib.pyplot as pltdef startup():''' 數(shù)據(jù)位置分析 '''rs = pd.read_csv('../datas/retdata.csv')gsyh = rs.gsyhprint('平均數(shù):{0}'.format(gsyh.mean()))print('中位數(shù):{0}'.format(gsyh.median()))gsyhMode = gsyh.mode()print('眾數(shù):{0}; {1}'.format(gsyhMode, type(gsyhMode)))print('百分位數(shù):{0}'.format(gsyh.quantile(0.3)))if '__main__' == __name__:startup() codes/c13c002.py運(yùn)行結(jié)果如下所示:
2.2.數(shù)據(jù)離散度
數(shù)據(jù)離散度描述數(shù)據(jù)相對(duì)于中心位置的偏離程度,常用的指標(biāo)有極差、平均絕對(duì)誤差、方差和標(biāo)準(zhǔn)差。
2.2.1.極差
序列中最大值與最小值之差。
2.2.2.平均絕對(duì)誤差
MAD=1n∑i=1n∣(xi?xˉ)∣MAD=\frac{1}{n}\sum_{i=1}^{n} \bigg \vert (x_i-\bar{x}) \bigg\vert MAD=n1?i=1∑n?∣∣∣∣?(xi??xˉ)∣∣∣∣?
2.2.3.方差和標(biāo)準(zhǔn)差
σ2=1n?1∑i=1n(xi?xˉ)2\sigma ^{2} = \frac{1}{n-1} \sum_{i=1}^{n} (x_i-\bar{x})^{2} σ2=n?11?i=1∑n?(xi??xˉ)2
σ=1n?1∑i=1n(xi?xˉ)2\sigma = \sqrt{\frac{1}{n-1} \sum_{i=1}^{n} (x_i-\bar{x})^{2} } σ=n?11?i=1∑n?(xi??xˉ)2?
計(jì)算離散度程序如下所示:
import numpy as np import pandas as pd import matplotlib.pyplot as pltdef startup():''' 數(shù)據(jù)位置分析 '''rs = pd.read_csv('../datas/retdata.csv')gsyh = rs.gsyhprint('極差:{0}'.format(gsyh.max() - gsyh.min()))print('平均絕對(duì)誤差:{0}'.format(gsyh.mad()))print('方差:{0}'.format(gsyh.var()))print('標(biāo)準(zhǔn)差:{0}'.format(gsyh.std()))if '__main__' == __name__:startup() codes/c13c003.py運(yùn)行結(jié)果為:
總結(jié)
以上是生活随笔為你收集整理的python量化交易笔记---13.描述性统计的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 为什么C语言永远不会过时?
- 下一篇: 编程小白的愿望