An example of using Pandas for regression

An example of using Pandas for regression

这个例子来自这本书 - "Python for Data Analysis", 这本书的做者 Wes McKinney 就是pandas的做者。数组

pandas提供了一些很方便的功能,好比最小二乘法(OLS),能够用来计算回归方程式的各个参数。 同时pandas还能够输出相似ANOVA的汇总信息,好比决定系数(R平方), F 统计量等。dom

OK,直接上例子。code

数据准备

首先建立1000只股票,股票代码(5个字符)经过随机方式生成。orm

In [29]: import string

In [32]: import random

In [33]: random.seed(0)

In [34]: N = 1000

In [35]: def rands(n):
   ....:     choices = string.ascii_uppercase
   ....:     return ''.join([random.choice(choices) for _ in xrange(n)])
   ....:

In [36]: tickers = np.array([rands(5) for x in xrange(N)])

回归分析

假设如今有个 multiple factor model, 以下所示:blog

y = 0.7 * x1 - 1.2 * x2 + 0.3 * x3 + random value

按照这个模型建立一个portfolio, 而后咱们再拿实际获得的值来跟这3个factor来作下回归分析,看获得的系数是否是跟上面的这个model比较接近。ip

首先建立三个随机数组(每一个大小都为1000, 对应刚才建立的1000只股票),分别为fac1, fac2, 和fac3.ci

In [58]: from numpy.random import rand

In [59]: fac1, fac2, fac3 = np.random.rand(3, 1000)

In [62]: ticker_subset = tickers.take(np.random.permutation(N)[:1000])

用选择的1000只股票按照上面的model建立portfolio, 获得的一组值也就是因变量y.string

In [64]: port = Series(0.7*fac1 - 1.2*fac2 + 0.3*fac3 + rand(1000), index=ticker_subset)

如今咱们用实际获得y和x1/x2/x3来作下回归。 首先把三个factors 构建成DataFrame.pandas

In [65]: factors = DataFrame({'f1':fac1, 'f2':fac2, 'f3':fac3}, index=ticker_subset)

而后就直接调用pd.ols方法来进行回归 -io

In [70]: pd.ols(y=port, x=factors)
Out[70]:

-------------------------Summary of Regression Analysis-------------------------

Formula: Y ~ <f1> + <f2> + <f3> + <intercept>

Number of Observations:         1000
Number of Degrees of Freedom:   4

R-squared:         0.6867
Adj R-squared:     0.6857

Rmse:              0.2859

F-stat (3, 996):   727.6383, p-value:     0.0000

Degrees of Freedom: model 3, resid 996

-----------------------Summary of Estimated Coefficients------------------------
      Variable       Coef    Std Err     t-stat    p-value    CI 2.5%   CI 97.5%
--------------------------------------------------------------------------------
            f1     0.6968     0.0311      22.44     0.0000     0.6359     0.7577
            f2    -1.2672     0.0312     -40.64     0.0000    -1.3283    -1.2061
            f3     0.3345     0.0310      10.80     0.0000     0.2738     0.3952
     intercept     0.5018     0.0275      18.28     0.0000     0.4480     0.5557
---------------------------------End of Summary---------------------------------

In [71]:

根据回归结果,获得的方程式是 -

y = 0.5018 + 0.6968 * f1 - 1.2672 * f2 + 0.3345 * f3

对比下实际的model -

y = 0.7 * x1 - 1.2 * x2 + 0.3 * x3 + random value

能够看出仍是比较match的。这个从每一个参数p-value也能够看出来。

另外,若是只想关注每一个系数,能够直接读取beta.

In [71]: pd.ols(y=port, x=factors).beta
Out[71]:
f1           0.696817
f2          -1.267172
f3           0.334505
intercept    0.501836
dtype: float64

怎么样,感受pandas是否是棒棒哒!

相关文章
相关标签/搜索