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是否是棒棒噠!

相關文章
相關標籤/搜索