统计分为描述统计和推断统计,我们在这一章里,主要讲解描述性统计。我们用到的数据如下所示:
上图中,gsyh代表工商银行收益率,pfyh代表浦发银行收益率,zglt代表中国联通收益率,我们仅以工商银行收益为例计算各个统计量。
1.频数分布
我们以2014年工商银行股票的收益率为例,来看频数分布。我们将收益率(下图中ysgh列)按0.025为一段,统计收益率落在该段内的天数,就可以得到频数分布,我们可以按照直方图来进行绘制。如下所示:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def startup():
''' 创建时间序列示例 '''
rs = pd.read_csv('../datas/retdata.csv')
gsyh = rs.gsyh
print(type(gsyh))
plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
plt.title('工商银行收益率频数分布图')
plt.xlabel('收益率')
plt.ylabel('天数')
plt.hist(gsyh)
plt.show()
if '__main__' == __name__:
startup()
运行结果为:
2.数据统计
2.1.数据位置
2.1.1.样本平均数
算数平均数可以用在各种数据分析中,定义为:
几何平均数最常用于收益率计算,假设共有k个元素,定义为:
2.1.2.中位数
中位数定义为其至少大于等于50%的数据,同时小于等于50%的数据。
2.1.3.众数
一组数据中出现最多的数值。
2.1.4.百分位数
假设百分比为如25,则表示至少%的数小于该值,同时至少%的数大于该值。
下面我们还以工商银行收益率为例,求出这几个值:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def startup():
''' 数据位置分析 '''
rs = pd.read_csv('../datas/retdata.csv')
gsyh = rs.gsyh
print('平均数:{0}'.format(gsyh.mean()))
print('中位数:{0}'.format(gsyh.median()))
gsyhMode = gsyh.mode()
print('众数:{0}; {1}'.format(gsyhMode, type(gsyhMode)))
print('百分位数:{0}'.format(gsyh.quantile(0.3)))
if '__main__' == __name__:
startup()
运行结果如下所示:
2.2.数据离散度
数据离散度描述数据相对于中心位置的偏离程度,常用的指标有极差、平均绝对误差、方差和标准差。
2.2.1.极差
序列中最大值与最小值之差。
2.2.2.平均绝对误差
2.2.3.方差和标准差
计算离散度程序如下所示:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
def startup():
''' 数据位置分析 '''
rs = pd.read_csv('../datas/retdata.csv')
gsyh = rs.gsyh
print('极差:{0}'.format(gsyh.max() - gsyh.min()))
print('平均绝对误差:{0}'.format(gsyh.mad()))
print('方差:{0}'.format(gsyh.var()))
print('标准差:{0}'.format(gsyh.std()))
if '__main__' == __name__:
startup()
运行结果为: