多因子模型系列3-Fama Franch三因子及其拓展五因子模型

尽管很多人批评Fama-Franch欠缺理论基础,但是事实而言小市值和低pb确实具有alpha。关于小市值,我个人的理解出于三点:1、国内长期以来的壳价值,据估算,国内得到壳价值大约为15亿(特殊牌照加钱),当价格偏离过大时,具有回归的趋势。2、从80年代到今的科技公司的推动,多数人不具备筛选出‘’真金‘’的能力,从而带来了整体的高溢价,从而容易带动低市值股票价格的增长。3、船小好掉头,不确定收益更多。PS显然要容易解释的多,更少的货币资产可以买入更多的股权资产。

我个人而言,对于Fama-Franch三因子还是持有比较怀疑的,三维的回归比一维的回归效果更好并不值得新奇。所以个人而言,还是尽可能将其作为一个绩效分析的工具,而非作为alpha去构建组合。

In [2]:
import pandas as pd
import numpy as np
import datetime
import statsmodels.api as sm

import plotly.plotly as py
import plotly.graph_objs as go
import plotly.tools as tls
from plotly.graph_objs import *
import plotly.graph_objs as go
import cufflinks as cf

py.sign_in('DemoAccount','2qdyfjyr7o')

第一节:Fama-French三因子模型


Fama和French提出了一个和sharpe风格分析在理念伤非常接近的业绩分析方法,他们提出了用如下回归方程进行业绩分析。
$$r_p(t)= \alpha_p + \beta\cdot r_b(t) + \beta \cdot SMB(t) + \beta_v \cdot HML(t) + \epsilon_p(t) $$这看起来像是增加了额外两项的标准CAPM回归。SMB(t)是一个买入小盘股卖出大盘股的组合收益率。HML(t)是一个买入高净市率股票卖空低净市率股票的投资组合收益率。Fema和Franch的方法在两个维度进行了控制,同时使用了回归的方法。

In [3]:
# 拿到基准收益率
index_change_rate = get_price_change_rate('000001.XSHG',start_date='20160514', end_date='20170515')
# 拿到无风险利率
risk_free_rate = get_yield_curve(start_date='20160514', end_date='20170515', tenor=None, country='cn')['0S']
# 反年化处理
risk_free_rate = (risk_free_rate+1)**(1/244)-1
# 取与基准相同的交易日
risk_free_rate = risk_free_rate[list(index_change_rate.index)]
price_change_rate = pd.DataFrame()
price_change_rate['risk_free_rate'] = risk_free_rate
price_change_rate['000001.XSHG'] = index_change_rate
price_change_rate
Out[3]:
risk_free_rate 000001.XSHG
2016-05-16 0.000070 0.008402
2016-05-17 0.000070 -0.002518
2016-05-18 0.000070 -0.012719
2016-05-19 0.000070 -0.000217
2016-05-20 0.000070 0.006618
2016-05-23 0.000072 0.006428
2016-05-24 0.000072 -0.007729
2016-05-25 0.000074 -0.002332
2016-05-26 0.000076 0.002613
2016-05-27 0.000076 -0.000495
2016-05-30 0.000076 0.000498
2016-05-31 0.000074 0.033363
2016-06-01 0.000075 -0.001066
2016-06-02 0.000075 0.004023
2016-06-03 0.000075 0.004599
2016-06-06 0.000073 -0.001560
2016-06-07 0.000073 0.000664
2016-06-08 0.000073 -0.003026
2016-06-13 0.000073 -0.032143
2016-06-14 0.000071 0.003218
2016-06-15 0.000069 0.015840
2016-06-16 0.000069 -0.004985
2016-06-17 0.000069 0.004277
2016-06-20 0.000067 0.001284
2016-06-21 0.000068 -0.003549
2016-06-22 0.000068 0.009377
2016-06-23 0.000068 -0.004677
2016-06-24 0.000068 -0.013027
2016-06-27 0.000068 0.014510
2016-06-28 0.000072 0.005820
2017-03-30 0.000116 -0.009588
2017-03-31 0.000115 0.003824
2017-04-05 0.000112 0.014830
2017-04-06 0.000112 0.003272
2017-04-07 0.000110 0.001710
2017-04-10 0.000108 -0.005240
2017-04-11 0.000106 0.005987
2017-04-12 0.000107 -0.004602
2017-04-13 0.000100 0.000651
2017-04-14 0.000096 -0.009125
2017-04-17 0.000094 -0.007363
2017-04-18 0.000094 -0.007900
2017-04-19 0.000096 -0.008142
2017-04-20 0.000104 0.000446
2017-04-21 0.000105 0.000331
2017-04-24 0.000102 -0.013747
2017-04-25 0.000101 0.001609
2017-04-26 0.000101 0.002003
2017-04-27 0.000103 0.003610
2017-04-28 0.000106 0.000784
2017-05-02 0.000107 -0.003470
2017-05-03 0.000108 -0.002661
2017-05-04 0.000108 -0.002544
2017-05-05 0.000108 -0.007780
2017-05-08 0.000109 -0.007871
2017-05-09 0.000108 0.000622
2017-05-10 0.000108 -0.009006
2017-05-11 0.000106 0.002855
2017-05-12 0.000102 0.007190
2017-05-15 0.000099 0.002178

243 rows × 2 columns

In [4]:
# 取2016-05-15的估值数据作为SMB和HML的计算标准
all_stocks_value = get_fundamentals(
    query(
        fundamentals.eod_derivative_indicator.pb_ratio,
        fundamentals.eod_derivative_indicator.market_cap)
    , '2016-05-15', interval = '1d' ,report_quarter = False)
all_stocks_value = all_stocks_value.major_xs(all_stocks_value.major_axis[0])
all_stocks_value['bp_ratio'] = 1/all_stocks_value['pb_ratio']
del all_stocks_value['pb_ratio']
all_stocks_value = all_stocks_value.dropna(how = 'any')
all_stocks_value
Out[4]:
market_cap bp_ratio
000005.XSHE 7.47327e+09 0.152798
600602.XSHG 1.26845e+10 0.262
600651.XSHG 1.02955e+10 0.317914
600652.XSHG 1.14247e+10 0.182093
600654.XSHG 2.46982e+10 0.119852
600653.XSHG 7.64927e+09 0.291265
600601.XSHG 9.0649e+09 0.395977
000004.XSHE 3.09286e+09 0.0255849
000002.XSHE 2.69686e+11 0.373162
000001.XSHE 1.48095e+11 1.26662
000009.XSHE 1.95511e+10 0.228493
000012.XSHE 2.21438e+10 0.364804
600608.XSHG 2.9762e+09 0.00107698
600604.XSHG 1.79126e+10 0.162396
000016.XSHE 1.10043e+10 0.256575
600605.XSHG 2.66546e+09 0.209617
600606.XSHG 1.42246e+11 0.384793
000011.XSHE 7.22327e+09 0.290833
000017.XSHE 5.53553e+09 0.00215181
000007.XSHE 5.49467e+09 0.0686625
000006.XSHE 9.77396e+09 0.45436
000020.XSHE 5.66322e+09 0.0556839
000008.XSHE 3.21549e+10 0.174077
000014.XSHE 3.55001e+09 0.200064
000018.XSHE 1.95209e+10 0.0697408
600609.XSHG 4.8733e+09 0.0540941
600610.XSHG 1.45265e+10 0.0793393
600611.XSHG 1.7526e+10 0.506791
600612.XSHG 2.08986e+10 0.227713
600613.XSHG 7.51973e+09 0.297832
300503.XSHE 3.904e+09 0.160994
603520.XSHG 4.9488e+09 0.160671
603919.XSHG 7.8176e+09 0.193431
002789.XSHE 4.22971e+09 0.242442
300505.XSHE 3.73627e+09 0.152061
601020.XSHG 1.16376e+10 0.120376
300484.XSHE 8.79268e+09 0.0563768
603861.XSHG 9.65885e+09 0.182655
300506.XSHE 4.482e+09 0.114185
002792.XSHE 1.035e+10 0.167003
002791.XSHE 9.24963e+09 0.243582
300474.XSHE 1.35543e+10 0.0598795
603028.XSHG 5.04749e+09 0.129406
603798.XSHG 4.838e+09 0.143127
603701.XSHG 4.1552e+09 0.0704265
002793.XSHE 4.499e+09 0.0789129
603868.XSHG 2.09829e+10 0.0595444
300508.XSHE 5.25528e+09 0.0384578
603726.XSHG 3.75091e+09 0.121014
300509.XSHE 4.1096e+09 0.080525
603029.XSHG 3.42651e+09 0.148427
603822.XSHG 3.2208e+09 0.128284
002795.XSHE 4.566e+09 0.0496047
300507.XSHE 5.38027e+09 0.0665531
603528.XSHG 6.02886e+09 0.120557
300511.XSHE 7.0785e+09 0.0970676
300510.XSHE 2.47899e+09 0.124228
603101.XSHG 4.908e+09 0.133595
002796.XSHE 1.9864e+09 0.133518
002797.XSHE 4.05841e+10 0.153226

2835 rows × 2 columns

In [5]:
# 拿到所有股票的日收益率数据
all_price_change_rate = get_price_change_rate(list(all_stocks_value.index),start_date='20160514', end_date='20170515')
all_price_change_rate
Out[5]:
order_book_id 000001.XSHE 000002.XSHE 000004.XSHE 000005.XSHE 000006.XSHE 000007.XSHE 000008.XSHE 000009.XSHE 000010.XSHE 000011.XSHE 603968.XSHG 603969.XSHG 603979.XSHG 603988.XSHG 603989.XSHG 603993.XSHG 603996.XSHG 603997.XSHG 603998.XSHG 603999.XSHG
date
2016-05-16 0.000966 0.000000 0.000000 -0.004250 0.015193 0.0 0.002573 0.027687 0.013698 0.010726 0.021104 0.006473 0.011156 0.018755 0.017122 0.000000 -0.005135 0.036574 0.022205 0.025498
2016-05-17 -0.005792 0.000000 0.000000 -0.004267 0.004082 0.0 -0.023952 -0.003169 0.001228 0.024489 -0.010333 -0.008040 -0.008385 -0.023413 -0.002619 0.000000 0.059784 -0.013783 -0.014982 -0.002122
2016-05-18 0.000000 0.000000 0.000000 -0.044286 -0.025745 0.0 -0.041192 -0.037362 -0.058895 -0.035858 -0.083936 -0.030794 -0.027147 -0.041187 -0.037884 0.000000 -0.095374 -0.036890 -0.062358 -0.035855
2016-05-19 -0.004854 0.000000 0.000000 0.004485 0.001391 0.0 0.003656 0.002478 -0.006519 0.001655 -0.001315 0.010869 0.001830 0.000854 0.005848 0.000000 0.100046 0.005802 0.008111 0.006618
2016-05-20 0.004878 0.000000 0.000000 0.013393 0.002778 0.0 -0.002732 0.009884 0.001313 0.005774 -0.034679 0.010051 0.009589 -0.008115 0.021707 0.000000 0.099917 0.017312 0.006437 0.012523
2016-05-23 -0.001942 0.000000 0.000000 0.011747 0.015235 0.0 0.050228 0.012234 0.005242 0.011486 0.045475 0.039803 0.014925 0.002154 0.030728 0.000000 0.060808 0.018152 0.025578 0.020099
2016-05-24 -0.006809 0.000000 0.000000 -0.014514 -0.005457 0.0 0.009565 0.011281 -0.013038 -0.002450 -0.004784 -0.019140 -0.014260 0.000644 -0.003314 0.000000 0.029710 -0.025073 -0.027279 -0.018490
2016-05-25 0.001959 0.000000 0.000000 -0.002945 -0.009602 0.0 -0.022395 -0.016733 -0.001321 -0.010639 -0.010490 0.000000 0.001356 0.015671 0.016250 0.000000 -0.028172 0.012574 -0.013622 0.010809
2016-05-26 -0.000978 0.000000 0.000000 0.000000 -0.002770 0.0 0.004405 -0.000810 -0.013227 -0.011578 -0.015459 0.003252 0.000451 -0.000845 -0.019390 0.100886 0.063569 0.007333 0.029245 0.031470
2016-05-27 0.004892 0.000000 0.000000 0.004431 0.019444 0.0 0.001754 0.006488 0.009383 0.035147 0.000896 -0.008914 0.008574 -0.015655 -0.005704 0.035039 -0.003941 -0.000558 -0.012628 0.014810
2016-05-30 0.000974 0.000000 0.000000 -0.011764 -0.027248 0.0 -0.009632 -0.012087 -0.018593 -0.021020 -0.029135 -0.004088 -0.014318 0.006878 -0.017209 -0.039061 -0.073195 -0.013451 0.005595 -0.022183
2016-05-31 0.026265 0.000000 0.000000 0.034226 0.033614 0.0 0.022104 0.045677 0.047362 0.040463 0.073870 0.036126 0.040399 0.038847 0.055642 0.046069 0.063322 0.047726 0.054053 0.046269
2016-06-01 -0.006635 0.000000 0.000000 0.011510 0.001355 0.0 0.000000 0.025741 -0.001292 -0.000794 -0.001290 0.005543 0.000873 0.002877 0.005529 0.101040 0.006022 0.000000 0.064104 0.075606
2016-06-02 -0.001908 0.000000 0.000000 0.012803 0.017591 0.0 -0.000865 0.001521 0.010349 0.015884 0.004735 0.009457 0.020488 0.009834 0.059752 0.065879 0.100100 0.019520 0.000709 0.030077
2016-06-03 0.003824 0.000000 0.000000 0.000000 -0.001330 0.0 -0.003463 0.002278 0.000000 0.003911 0.014567 0.000000 0.005126 0.051531 0.099965 -0.017659 -0.024184 0.011170 -0.002834 -0.032248
2016-06-06 0.000952 0.000000 0.000000 -0.009832 -0.001332 0.0 0.007819 0.001515 0.003841 0.014796 0.029560 0.000000 -0.013175 0.006367 -0.022328 0.002247 0.006505 -0.012099 -0.015625 -0.004486
2016-06-07 0.000951 0.000000 0.000000 0.019858 -0.013333 0.0 0.047414 0.008321 0.003827 -0.013815 -0.008202 0.007807 0.034453 0.040837 0.003860 0.006726 0.042476 0.013844 -0.013708 0.046348
2016-06-08 -0.001901 0.000000 0.000000 -0.018080 -0.002703 0.0 0.001646 0.018755 -0.013977 -0.005446 0.002895 -0.010070 -0.018734 -0.004066 -0.000320 -0.024498 -0.047239 -0.011552 -0.002193 -0.030761
2016-06-13 -0.016190 0.000000 0.000000 -0.048158 -0.044715 0.0 -0.073131 -0.073638 -0.059278 -0.075119 -0.099795 -0.057902 -0.059822 -0.100000 -0.100000 -0.031962 -0.100094 -0.060574 -0.071115 -0.097747
2016-06-14 0.006776 0.000000 0.000000 0.099701 0.001418 0.0 0.028369 -0.005564 0.016438 0.007616 -0.025652 0.002492 0.006318 0.013606 0.012109 -0.009434 -0.013429 -0.006786 -0.001578 -0.005626
2016-06-15 0.003846 0.000000 0.000000 0.082544 0.018414 0.0 0.045690 0.072742 0.029650 0.025187 0.034320 0.026513 0.028251 0.020541 0.053131 0.057140 0.050960 0.034737 0.026878 0.039264
2016-06-16 -0.000292 0.000000 0.000000 -0.022500 -0.009736 0.0 -0.014015 0.017139 0.001309 -0.016379 0.003636 -0.006457 -0.011775 0.004186 0.027732 0.045043 0.041515 -0.004954 -0.013858 -0.018039
2016-06-17 0.001167 0.000000 0.000000 -0.007673 0.032856 0.0 0.000836 -0.000733 0.006537 0.041631 0.007247 0.007311 0.010591 0.018258 0.025682 -0.030171 -0.005103 0.030422 0.040595 0.013518
2016-06-20 0.002331 0.000000 0.000000 0.011598 -0.013831 0.0 -0.047619 0.003666 -0.022078 -0.020782 0.083633 0.026610 0.023581 0.008770 -0.003487 -0.015555 0.024680 0.009663 -0.007502 0.057113
2016-06-21 0.001163 0.000000 0.000000 -0.045860 -0.001403 0.0 -0.082456 0.005113 -0.025233 -0.013063 -0.030290 -0.012565 -0.020478 0.017389 -0.032442 -0.029344 -0.057555 -0.028177 0.018141 -0.023294
2016-06-22 0.013937 0.000000 0.000000 0.014687 0.019663 0.0 -0.001912 0.017443 0.025886 0.053764 0.005134 0.013521 0.018293 0.006266 0.038132 0.013953 0.053768 0.023520 -0.002228 0.036107
2016-06-23 -0.008018 0.000000 0.000000 -0.003947 -0.004132 0.0 -0.012452 -0.025000 -0.006641 0.005495 -0.027244 -0.012556 -0.015398 -0.032082 -0.006649 -0.025228 -0.041576 0.012293 -0.016369 -0.016625
2016-06-24 -0.010393 0.000000 0.000000 0.007925 0.015214 0.0 -0.023278 -0.028572 -0.008022 0.041374 -0.025383 -0.014309 -0.013901 -0.006822 -0.031241 -0.025881 -0.021689 -0.015309 -0.011347 -0.026658
2016-06-27 0.004667 0.000000 0.000000 0.009175 0.008175 0.0 0.014896 0.030166 0.014826 0.005248 0.019307 0.022578 0.018062 0.018256 0.078975 0.016907 0.019483 0.038067 0.019895 0.028725
2016-06-28 0.002323 0.000000 0.000000 0.002598 0.009459 0.0 0.009785 0.002929 0.038512 0.023862 0.004848 0.019717 0.012116 0.010797 -0.001526 -0.002375 0.011861 0.057850 0.099774 0.014935
2017-03-30 -0.003293 -0.022846 -0.025297 -0.025039 -0.035377 0.0 0.018868 -0.025532 -0.018868 -0.036070 -0.029750 -0.011157 -0.031461 -0.011911 -0.016460 -0.015389 -0.032747 0.028452 -0.007326 -0.030269
2017-03-31 0.009912 0.002435 -0.026764 0.004816 0.012225 0.0 0.011574 0.001091 0.002959 0.046451 -0.026166 -0.059382 0.010149 0.002614 0.006584 0.051342 0.011445 -0.048224 0.000000 0.005641
2017-04-05 0.004362 0.000000 0.000000 0.015974 0.020532 0.0 0.017163 0.018538 0.023599 0.012331 0.015114 0.099746 0.039699 0.025782 0.036250 0.099788 0.004713 0.014141 0.017220 0.017202
2017-04-06 -0.001086 0.010204 0.000000 0.001573 0.009467 0.0 0.033746 -0.001070 0.024495 0.026796 -0.001241 0.099887 -0.001449 0.000989 0.003156 -0.007722 -0.011729 0.013940 -0.000604 0.001105
2017-04-07 0.000000 0.000481 0.000000 0.004709 0.001172 0.0 -0.011969 0.000000 -0.007033 0.002965 -0.002072 0.100208 -0.027106 -0.003244 -0.012586 -0.007782 -0.007598 0.000382 0.009679 -0.004041
2017-04-10 -0.002174 -0.009615 0.000000 -0.015625 0.001171 0.0 -0.020925 0.015006 -0.002832 0.011236 -0.021576 0.100095 -0.034825 -0.012738 -0.017260 -0.037258 -0.044976 -0.000382 -0.013182 -0.028392
2017-04-11 -0.003268 0.004854 0.000000 0.044444 0.070176 0.0 0.017998 0.011616 0.048295 0.067836 0.022478 0.100043 0.010310 -0.003871 -0.013780 0.014261 0.019036 0.000382 -0.015178 0.011006
2017-04-12 -0.003279 0.015459 0.000000 0.021278 0.056831 0.0 -0.018784 0.012526 -0.012195 0.100218 -0.014933 -0.007448 -0.016837 -0.014678 -0.020274 0.010035 -0.007374 0.003056 -0.008015 -0.008258
2017-04-13 0.000000 -0.003806 0.000000 -0.011906 -0.032058 0.0 -0.007883 -0.009279 -0.026062 -0.040319 0.003790 0.044629 0.006224 -0.004527 0.002795 -0.007952 0.009908 -0.012944 -0.012431 0.000000
2017-04-14 -0.004386 -0.014327 0.000000 -0.028614 -0.043803 0.0 0.001135 -0.026014 -0.009859 -0.063278 -0.035236 -0.055199 -0.004125 -0.009976 0.001396 -0.008016 -0.001471 -0.006555 0.011959 0.000000
2017-04-17 0.002203 -0.003876 0.000000 -0.013953 -0.022347 0.0 0.006803 -0.004273 -0.028449 -0.030453 -0.007826 -0.092837 -0.042465 -0.035123 -0.016709 0.020204 -0.024559 0.001164 -0.015548 0.000000
2017-04-18 -0.005494 -0.004377 0.000000 -0.007862 -0.005714 0.0 -0.010135 -0.008584 -0.010250 -0.014849 -0.029361 0.011028 -0.015683 -0.009829 -0.001133 -0.025743 -0.043805 0.001554 -0.003159 -0.064724
2017-04-19 -0.015470 0.002931 0.000000 -0.019018 -0.016092 0.0 -0.010239 -0.016234 -0.025148 -0.002898 0.077654 0.099913 -0.022528 -0.033039 -0.010774 -0.060976 -0.014218 -0.001938 -0.100127 -0.004046
2017-04-20 0.001122 0.004871 0.000000 -0.004846 -0.016355 0.0 0.000000 0.006600 -0.003034 -0.024999 0.000837 -0.099961 0.002251 0.000963 0.001146 -0.004325 -0.006410 0.001167 0.013380 0.024786
2017-04-21 0.005605 0.002424 0.000000 0.004869 -0.002375 0.0 0.005747 -0.014207 0.001522 -0.027430 0.000838 -0.100044 0.007850 0.000000 0.007730 -0.023917 -0.002690 -0.001552 0.000696 -0.012687
2017-04-24 -0.004459 -0.012089 0.000000 -0.029079 -0.036905 0.0 -0.012571 -0.047672 -0.036474 -0.039240 0.016728 -0.030851 -0.006120 -0.008334 0.007387 -0.062358 -0.069003 0.001555 -0.020139 -0.057432
2017-04-25 0.007839 0.005874 0.000000 -0.009984 0.004945 0.0 -0.002315 0.002328 0.011041 0.021059 -0.002467 0.072765 0.001121 0.004364 0.025945 0.004747 0.001161 0.002710 0.038270 0.008096
2017-04-26 -0.001111 -0.009246 0.000000 0.000000 0.011070 0.0 -0.022042 0.001161 -0.021841 0.025000 -0.013197 0.058879 0.001115 0.008688 -0.007972 0.009456 0.010990 0.003093 0.008874 -0.015216
2017-04-27 -0.002225 -0.029470 0.000000 -0.025210 -0.002433 0.0 -0.024911 -0.025521 -0.003190 0.012196 0.021730 -0.031585 0.008381 -0.000160 0.020782 0.025766 -0.008585 0.000770 0.003383 -0.003432
2017-04-28 0.002230 -0.013158 0.000000 0.003449 0.014634 0.0 -0.017032 -0.001191 -0.003201 0.039155 0.002865 0.056500 -0.009972 0.006063 0.001357 0.004562 0.017314 -0.000385 0.000673 0.017657
2017-05-02 -0.005562 -0.015385 0.000000 -0.017182 -0.006010 0.0 -0.012377 0.028606 -0.006420 0.000000 0.012233 0.069566 -0.001678 -0.000317 0.042559 0.027279 -0.003972 -0.001543 0.039759 -0.008463
2017-05-03 -0.003356 -0.017708 0.000000 0.010488 0.014510 0.0 -0.007519 -0.008111 -0.006462 0.020870 -0.009265 0.031707 -0.023541 -0.005236 -0.005721 -0.003352 -0.008542 0.000000 0.000000 -0.012806
2017-05-04 -0.019080 0.008484 0.000000 0.000000 0.004768 0.0 -0.005050 -0.002337 -0.003253 -0.018739 -0.019114 -0.009851 -0.000577 0.000478 0.000263 -0.024602 -0.035613 -0.004239 -0.000649 0.000434
2017-05-05 -0.012586 -0.006835 0.000000 -0.025952 -0.033215 0.0 -0.043147 -0.032786 -0.004894 -0.022569 -0.039387 -0.059690 -0.009189 -0.009723 0.009411 -0.020646 -0.028588 -0.001552 -0.024643 -0.002595
2017-05-08 -0.006953 -0.022234 0.000000 -0.028418 -0.040491 0.0 -0.030504 -0.024213 -0.039344 -0.049734 -0.028054 -0.027083 0.000578 -0.014325 -0.014505 0.004687 -0.033108 0.000775 -0.029256 -0.019063
2017-05-09 0.008168 0.008121 0.000000 0.001827 0.011509 0.0 0.002736 0.002481 0.000000 0.025545 0.019982 0.100044 0.002320 0.010615 -0.012089 0.000000 0.022192 0.003490 -0.004794 0.007509
2017-05-10 0.003472 0.002685 0.000000 -0.038320 -0.020228 0.0 0.004093 -0.037129 -0.040955 0.003037 -0.016543 0.026887 -0.004048 -0.008080 0.024475 -0.034965 -0.026054 -0.003088 -0.013764 -0.017097
2017-05-11 0.003460 0.030530 0.000000 -0.022771 0.020645 0.0 0.008152 -0.005141 -0.037366 0.041793 0.014167 0.029266 0.008707 -0.003094 0.019476 0.007240 -0.004460 -0.003488 -0.025122 -0.032115
2017-05-12 0.022989 0.008316 0.000000 0.013593 0.011378 0.0 -0.009434 -0.006460 -0.011091 0.034884 -0.000874 0.099513 0.008058 0.055555 0.000000 -0.011988 -0.015355 0.004277 0.000715 -0.014745
2017-05-15 -0.004494 -0.003093 0.000000 -0.013411 -0.017500 0.0 0.001360 0.003901 -0.005608 -0.036517 0.003058 -0.004764 -0.001716 -0.001393 0.018338 0.014566 0.005848 -0.003872 -0.004291 -0.000936

243 rows × 2835 columns

In [6]:
# 去除nan
test = all_price_change_rate.T.dropna(how = 'any').T
test
Out[6]:
order_book_id 000001.XSHE 000002.XSHE 000004.XSHE 000005.XSHE 000006.XSHE 000007.XSHE 000008.XSHE 000009.XSHE 000010.XSHE 000011.XSHE 603968.XSHG 603969.XSHG 603979.XSHG 603988.XSHG 603989.XSHG 603993.XSHG 603996.XSHG 603997.XSHG 603998.XSHG 603999.XSHG
date
2016-05-16 0.000966 0.000000 0.000000 -0.004250 0.015193 0.0 0.002573 0.027687 0.013698 0.010726 0.021104 0.006473 0.011156 0.018755 0.017122 0.000000 -0.005135 0.036574 0.022205 0.025498
2016-05-17 -0.005792 0.000000 0.000000 -0.004267 0.004082 0.0 -0.023952 -0.003169 0.001228 0.024489 -0.010333 -0.008040 -0.008385 -0.023413 -0.002619 0.000000 0.059784 -0.013783 -0.014982 -0.002122
2016-05-18 0.000000 0.000000 0.000000 -0.044286 -0.025745 0.0 -0.041192 -0.037362 -0.058895 -0.035858 -0.083936 -0.030794 -0.027147 -0.041187 -0.037884 0.000000 -0.095374 -0.036890 -0.062358 -0.035855
2016-05-19 -0.004854 0.000000 0.000000 0.004485 0.001391 0.0 0.003656 0.002478 -0.006519 0.001655 -0.001315 0.010869 0.001830 0.000854 0.005848 0.000000 0.100046 0.005802 0.008111 0.006618
2016-05-20 0.004878 0.000000 0.000000 0.013393 0.002778 0.0 -0.002732 0.009884 0.001313 0.005774 -0.034679 0.010051 0.009589 -0.008115 0.021707 0.000000 0.099917 0.017312 0.006437 0.012523
2016-05-23 -0.001942 0.000000 0.000000 0.011747 0.015235 0.0 0.050228 0.012234 0.005242 0.011486 0.045475 0.039803 0.014925 0.002154 0.030728 0.000000 0.060808 0.018152 0.025578 0.020099
2016-05-24 -0.006809 0.000000 0.000000 -0.014514 -0.005457 0.0 0.009565 0.011281 -0.013038 -0.002450 -0.004784 -0.019140 -0.014260 0.000644 -0.003314 0.000000 0.029710 -0.025073 -0.027279 -0.018490
2016-05-25 0.001959 0.000000 0.000000 -0.002945 -0.009602 0.0 -0.022395 -0.016733 -0.001321 -0.010639 -0.010490 0.000000 0.001356 0.015671 0.016250 0.000000 -0.028172 0.012574 -0.013622 0.010809
2016-05-26 -0.000978 0.000000 0.000000 0.000000 -0.002770 0.0 0.004405 -0.000810 -0.013227 -0.011578 -0.015459 0.003252 0.000451 -0.000845 -0.019390 0.100886 0.063569 0.007333 0.029245 0.031470
2016-05-27 0.004892 0.000000 0.000000 0.004431 0.019444 0.0 0.001754 0.006488 0.009383 0.035147 0.000896 -0.008914 0.008574 -0.015655 -0.005704 0.035039 -0.003941 -0.000558 -0.012628 0.014810
2016-05-30 0.000974 0.000000 0.000000 -0.011764 -0.027248 0.0 -0.009632 -0.012087 -0.018593 -0.021020 -0.029135 -0.004088 -0.014318 0.006878 -0.017209 -0.039061 -0.073195 -0.013451 0.005595 -0.022183
2016-05-31 0.026265 0.000000 0.000000 0.034226 0.033614 0.0 0.022104 0.045677 0.047362 0.040463 0.073870 0.036126 0.040399 0.038847 0.055642 0.046069 0.063322 0.047726 0.054053 0.046269
2016-06-01 -0.006635 0.000000 0.000000 0.011510 0.001355 0.0 0.000000 0.025741 -0.001292 -0.000794 -0.001290 0.005543 0.000873 0.002877 0.005529 0.101040 0.006022 0.000000 0.064104 0.075606
2016-06-02 -0.001908 0.000000 0.000000 0.012803 0.017591 0.0 -0.000865 0.001521 0.010349 0.015884 0.004735 0.009457 0.020488 0.009834 0.059752 0.065879 0.100100 0.019520 0.000709 0.030077
2016-06-03 0.003824 0.000000 0.000000 0.000000 -0.001330 0.0 -0.003463 0.002278 0.000000 0.003911 0.014567 0.000000 0.005126 0.051531 0.099965 -0.017659 -0.024184 0.011170 -0.002834 -0.032248
2016-06-06 0.000952 0.000000 0.000000 -0.009832 -0.001332 0.0 0.007819 0.001515 0.003841 0.014796 0.029560 0.000000 -0.013175 0.006367 -0.022328 0.002247 0.006505 -0.012099 -0.015625 -0.004486
2016-06-07 0.000951 0.000000 0.000000 0.019858 -0.013333 0.0 0.047414 0.008321 0.003827 -0.013815 -0.008202 0.007807 0.034453 0.040837 0.003860 0.006726 0.042476 0.013844 -0.013708 0.046348
2016-06-08 -0.001901 0.000000 0.000000 -0.018080 -0.002703 0.0 0.001646 0.018755 -0.013977 -0.005446 0.002895 -0.010070 -0.018734 -0.004066 -0.000320 -0.024498 -0.047239 -0.011552 -0.002193 -0.030761
2016-06-13 -0.016190 0.000000 0.000000 -0.048158 -0.044715 0.0 -0.073131 -0.073638 -0.059278 -0.075119 -0.099795 -0.057902 -0.059822 -0.100000 -0.100000 -0.031962 -0.100094 -0.060574 -0.071115 -0.097747
2016-06-14 0.006776 0.000000 0.000000 0.099701 0.001418 0.0 0.028369 -0.005564 0.016438 0.007616 -0.025652 0.002492 0.006318 0.013606 0.012109 -0.009434 -0.013429 -0.006786 -0.001578 -0.005626
2016-06-15 0.003846 0.000000 0.000000 0.082544 0.018414 0.0 0.045690 0.072742 0.029650 0.025187 0.034320 0.026513 0.028251 0.020541 0.053131 0.057140 0.050960 0.034737 0.026878 0.039264
2016-06-16 -0.000292 0.000000 0.000000 -0.022500 -0.009736 0.0 -0.014015 0.017139 0.001309 -0.016379 0.003636 -0.006457 -0.011775 0.004186 0.027732 0.045043 0.041515 -0.004954 -0.013858 -0.018039
2016-06-17 0.001167 0.000000 0.000000 -0.007673 0.032856 0.0 0.000836 -0.000733 0.006537 0.041631 0.007247 0.007311 0.010591 0.018258 0.025682 -0.030171 -0.005103 0.030422 0.040595 0.013518
2016-06-20 0.002331 0.000000 0.000000 0.011598 -0.013831 0.0 -0.047619 0.003666 -0.022078 -0.020782 0.083633 0.026610 0.023581 0.008770 -0.003487 -0.015555 0.024680 0.009663 -0.007502 0.057113
2016-06-21 0.001163 0.000000 0.000000 -0.045860 -0.001403 0.0 -0.082456 0.005113 -0.025233 -0.013063 -0.030290 -0.012565 -0.020478 0.017389 -0.032442 -0.029344 -0.057555 -0.028177 0.018141 -0.023294
2016-06-22 0.013937 0.000000 0.000000 0.014687 0.019663 0.0 -0.001912 0.017443 0.025886 0.053764 0.005134 0.013521 0.018293 0.006266 0.038132 0.013953 0.053768 0.023520 -0.002228 0.036107
2016-06-23 -0.008018 0.000000 0.000000 -0.003947 -0.004132 0.0 -0.012452 -0.025000 -0.006641 0.005495 -0.027244 -0.012556 -0.015398 -0.032082 -0.006649 -0.025228 -0.041576 0.012293 -0.016369 -0.016625
2016-06-24 -0.010393 0.000000 0.000000 0.007925 0.015214 0.0 -0.023278 -0.028572 -0.008022 0.041374 -0.025383 -0.014309 -0.013901 -0.006822 -0.031241 -0.025881 -0.021689 -0.015309 -0.011347 -0.026658
2016-06-27 0.004667 0.000000 0.000000 0.009175 0.008175 0.0 0.014896 0.030166 0.014826 0.005248 0.019307 0.022578 0.018062 0.018256 0.078975 0.016907 0.019483 0.038067 0.019895 0.028725
2016-06-28 0.002323 0.000000 0.000000 0.002598 0.009459 0.0 0.009785 0.002929 0.038512 0.023862 0.004848 0.019717 0.012116 0.010797 -0.001526 -0.002375 0.011861 0.057850 0.099774 0.014935
2017-03-30 -0.003293 -0.022846 -0.025297 -0.025039 -0.035377 0.0 0.018868 -0.025532 -0.018868 -0.036070 -0.029750 -0.011157 -0.031461 -0.011911 -0.016460 -0.015389 -0.032747 0.028452 -0.007326 -0.030269
2017-03-31 0.009912 0.002435 -0.026764 0.004816 0.012225 0.0 0.011574 0.001091 0.002959 0.046451 -0.026166 -0.059382 0.010149 0.002614 0.006584 0.051342 0.011445 -0.048224 0.000000 0.005641
2017-04-05 0.004362 0.000000 0.000000 0.015974 0.020532 0.0 0.017163 0.018538 0.023599 0.012331 0.015114 0.099746 0.039699 0.025782 0.036250 0.099788 0.004713 0.014141 0.017220 0.017202
2017-04-06 -0.001086 0.010204 0.000000 0.001573 0.009467 0.0 0.033746 -0.001070 0.024495 0.026796 -0.001241 0.099887 -0.001449 0.000989 0.003156 -0.007722 -0.011729 0.013940 -0.000604 0.001105
2017-04-07 0.000000 0.000481 0.000000 0.004709 0.001172 0.0 -0.011969 0.000000 -0.007033 0.002965 -0.002072 0.100208 -0.027106 -0.003244 -0.012586 -0.007782 -0.007598 0.000382 0.009679 -0.004041
2017-04-10 -0.002174 -0.009615 0.000000 -0.015625 0.001171 0.0 -0.020925 0.015006 -0.002832 0.011236 -0.021576 0.100095 -0.034825 -0.012738 -0.017260 -0.037258 -0.044976 -0.000382 -0.013182 -0.028392
2017-04-11 -0.003268 0.004854 0.000000 0.044444 0.070176 0.0 0.017998 0.011616 0.048295 0.067836 0.022478 0.100043 0.010310 -0.003871 -0.013780 0.014261 0.019036 0.000382 -0.015178 0.011006
2017-04-12 -0.003279 0.015459 0.000000 0.021278 0.056831 0.0 -0.018784 0.012526 -0.012195 0.100218 -0.014933 -0.007448 -0.016837 -0.014678 -0.020274 0.010035 -0.007374 0.003056 -0.008015 -0.008258
2017-04-13 0.000000 -0.003806 0.000000 -0.011906 -0.032058 0.0 -0.007883 -0.009279 -0.026062 -0.040319 0.003790 0.044629 0.006224 -0.004527 0.002795 -0.007952 0.009908 -0.012944 -0.012431 0.000000
2017-04-14 -0.004386 -0.014327 0.000000 -0.028614 -0.043803 0.0 0.001135 -0.026014 -0.009859 -0.063278 -0.035236 -0.055199 -0.004125 -0.009976 0.001396 -0.008016 -0.001471 -0.006555 0.011959 0.000000
2017-04-17 0.002203 -0.003876 0.000000 -0.013953 -0.022347 0.0 0.006803 -0.004273 -0.028449 -0.030453 -0.007826 -0.092837 -0.042465 -0.035123 -0.016709 0.020204 -0.024559 0.001164 -0.015548 0.000000
2017-04-18 -0.005494 -0.004377 0.000000 -0.007862 -0.005714 0.0 -0.010135 -0.008584 -0.010250 -0.014849 -0.029361 0.011028 -0.015683 -0.009829 -0.001133 -0.025743 -0.043805 0.001554 -0.003159 -0.064724
2017-04-19 -0.015470 0.002931 0.000000 -0.019018 -0.016092 0.0 -0.010239 -0.016234 -0.025148 -0.002898 0.077654 0.099913 -0.022528 -0.033039 -0.010774 -0.060976 -0.014218 -0.001938 -0.100127 -0.004046
2017-04-20 0.001122 0.004871 0.000000 -0.004846 -0.016355 0.0 0.000000 0.006600 -0.003034 -0.024999 0.000837 -0.099961 0.002251 0.000963 0.001146 -0.004325 -0.006410 0.001167 0.013380 0.024786
2017-04-21 0.005605 0.002424 0.000000 0.004869 -0.002375 0.0 0.005747 -0.014207 0.001522 -0.027430 0.000838 -0.100044 0.007850 0.000000 0.007730 -0.023917 -0.002690 -0.001552 0.000696 -0.012687
2017-04-24 -0.004459 -0.012089 0.000000 -0.029079 -0.036905 0.0 -0.012571 -0.047672 -0.036474 -0.039240 0.016728 -0.030851 -0.006120 -0.008334 0.007387 -0.062358 -0.069003 0.001555 -0.020139 -0.057432
2017-04-25 0.007839 0.005874 0.000000 -0.009984 0.004945 0.0 -0.002315 0.002328 0.011041 0.021059 -0.002467 0.072765 0.001121 0.004364 0.025945 0.004747 0.001161 0.002710 0.038270 0.008096
2017-04-26 -0.001111 -0.009246 0.000000 0.000000 0.011070 0.0 -0.022042 0.001161 -0.021841 0.025000 -0.013197 0.058879 0.001115 0.008688 -0.007972 0.009456 0.010990 0.003093 0.008874 -0.015216
2017-04-27 -0.002225 -0.029470 0.000000 -0.025210 -0.002433 0.0 -0.024911 -0.025521 -0.003190 0.012196 0.021730 -0.031585 0.008381 -0.000160 0.020782 0.025766 -0.008585 0.000770 0.003383 -0.003432
2017-04-28 0.002230 -0.013158 0.000000 0.003449 0.014634 0.0 -0.017032 -0.001191 -0.003201 0.039155 0.002865 0.056500 -0.009972 0.006063 0.001357 0.004562 0.017314 -0.000385 0.000673 0.017657
2017-05-02 -0.005562 -0.015385 0.000000 -0.017182 -0.006010 0.0 -0.012377 0.028606 -0.006420 0.000000 0.012233 0.069566 -0.001678 -0.000317 0.042559 0.027279 -0.003972 -0.001543 0.039759 -0.008463
2017-05-03 -0.003356 -0.017708 0.000000 0.010488 0.014510 0.0 -0.007519 -0.008111 -0.006462 0.020870 -0.009265 0.031707 -0.023541 -0.005236 -0.005721 -0.003352 -0.008542 0.000000 0.000000 -0.012806
2017-05-04 -0.019080 0.008484 0.000000 0.000000 0.004768 0.0 -0.005050 -0.002337 -0.003253 -0.018739 -0.019114 -0.009851 -0.000577 0.000478 0.000263 -0.024602 -0.035613 -0.004239 -0.000649 0.000434
2017-05-05 -0.012586 -0.006835 0.000000 -0.025952 -0.033215 0.0 -0.043147 -0.032786 -0.004894 -0.022569 -0.039387 -0.059690 -0.009189 -0.009723 0.009411 -0.020646 -0.028588 -0.001552 -0.024643 -0.002595
2017-05-08 -0.006953 -0.022234 0.000000 -0.028418 -0.040491 0.0 -0.030504 -0.024213 -0.039344 -0.049734 -0.028054 -0.027083 0.000578 -0.014325 -0.014505 0.004687 -0.033108 0.000775 -0.029256 -0.019063
2017-05-09 0.008168 0.008121 0.000000 0.001827 0.011509 0.0 0.002736 0.002481 0.000000 0.025545 0.019982 0.100044 0.002320 0.010615 -0.012089 0.000000 0.022192 0.003490 -0.004794 0.007509
2017-05-10 0.003472 0.002685 0.000000 -0.038320 -0.020228 0.0 0.004093 -0.037129 -0.040955 0.003037 -0.016543 0.026887 -0.004048 -0.008080 0.024475 -0.034965 -0.026054 -0.003088 -0.013764 -0.017097
2017-05-11 0.003460 0.030530 0.000000 -0.022771 0.020645 0.0 0.008152 -0.005141 -0.037366 0.041793 0.014167 0.029266 0.008707 -0.003094 0.019476 0.007240 -0.004460 -0.003488 -0.025122 -0.032115
2017-05-12 0.022989 0.008316 0.000000 0.013593 0.011378 0.0 -0.009434 -0.006460 -0.011091 0.034884 -0.000874 0.099513 0.008058 0.055555 0.000000 -0.011988 -0.015355 0.004277 0.000715 -0.014745
2017-05-15 -0.004494 -0.003093 0.000000 -0.013411 -0.017500 0.0 0.001360 0.003901 -0.005608 -0.036517 0.003058 -0.004764 -0.001716 -0.001393 0.018338 0.014566 0.005848 -0.003872 -0.004291 -0.000936

243 rows × 2833 columns

In [7]:
stock_need_drop = list(set(all_price_change_rate.columns).difference(set(test.columns)))
stock_need_drop
Out[7]:
['600005.XSHG', '000748.XSHE']


有两支股票的日收益率数据含有nan,’000748.XSHE’, ‘600005.XSHG’。查询资料发现:
电脑(000066)和长城信息(000748)3月9日发布重大资产重组公告,长城电脑拟换股吸收合并长城信息,交易完成后,长城电脑将作为存续方,长城信息将注销法人资格,也将退市。
武钢股份(600005)此前发布公告称,经上交所上市委员会审核,决定对武钢股份予以终止上市,终止上市日期为2月14日。
两支含有nan的股票都退市,故没有数据。

In [8]:
# 在估值数据中将上述两支股票删除
all_stocks_value = all_stocks_value.T
for stock in stock_need_drop:
    del all_stocks_value[stock]
all_stocks_value = all_stocks_value.T


以市值中位数为界将所有股票分为两类—-S类(small,小盘股)和B类(big,大盘类)。同时对所有股票按照净市率排序。最后30%定义为L类,中间40%定义为M类,最高30%定义为H类。两个维度共计6类,计算6类的加权收益率。

In [9]:
copy = all_stocks_value.iloc[:,:]
all_stocks_value = all_stocks_value.sort_values('market_cap') #市值升序排布
S = all_stocks_value.index[:int(len(all_stocks_value.index)/2)]
B = all_stocks_value.index[int(len(all_stocks_value.index)/2):]
all_stocks_value = all_stocks_value.sort_values('bp_ratio') #净市率升序排列
L = all_stocks_value.index[:int(len(all_stocks_value.index)*0.3)]
M = all_stocks_value.index[int(len(all_stocks_value.index)*0.3):int(len(all_stocks_value.index)*0.7)]
H = all_stocks_value.index[int(len(all_stocks_value.index)*0.7):]
In [10]:
portfolio = {}
portfolio['SL'] = list(set(S).intersection(set(L)))
portfolio['SM'] = list(set(S).intersection(set(M)))
portfolio['SH'] = list(set(S).intersection(set(H)))
portfolio['BL'] = list(set(B).intersection(set(L)))
portfolio['BM'] = list(set(B).intersection(set(M)))
portfolio['BH'] = list(set(B).intersection(set(H)))
In [11]:
# 市值加权求出每个类别的日收益率时间序列
portfolio_return = {}
for por in portfolio:
    portfolio_return[por] = 0
    for stock in portfolio[por]:
        portfolio_return[por] += all_stocks_value['market_cap'][stock]*test[stock]
    portfolio_return[por] = portfolio_return[por]/np.sum(all_stocks_value['market_cap'][portfolio[por]])
In [12]:
SMB = (portfolio_return['SL']+portfolio_return['SM']+portfolio_return['SH'])/3-(portfolio_return['BL']+portfolio_return['BM']+portfolio_return['BH'])/3
HML = (portfolio_return['SH']+portfolio_return['BH'])/2-(portfolio_return['SL']+portfolio_return['BL'])/2
In [13]:
Rb = price_change_rate['000001.XSHG']-price_change_rate['risk_free_rate']

投资组合介绍;
在2016-05-12平均买入去除停牌的股票中市值最小的20支股票。

In [14]:
# 构建组合
q = query(
            fundamentals.eod_derivative_indicator.market_cap,
        ).order_by(
            fundamentals.eod_derivative_indicator.market_cap.asc()
        ).limit(21)
pa = get_fundamentals(q,entry_date = '20160512')
stocks = list(pa.major_xs(pa.major_axis[0]).index)
stocks.remove('600656.XSHG')
# 我们拥有200万资金,计算买入时各股的量,分摊到各股每股10万
price = np.array(get_price(stocks,start_date='20160512', end_date='20170515',fields = 'close'))
# 最小买入一手,计算买入的量
position = np.array(1000/price[0],dtype=int)*100
# 计算剩余现金
cash = 2e6-(price[0]*position).sum()

portfolio_value = (price*position).sum(axis = 1)+cash
# np.diff(portfolio_value)后一天组合总价值减去前一天,得到新的序列.然后用差值依次除以前一天的值,求得日收益率序列
portfolio_value_rate = (np.diff(portfolio_value)/(portfolio_value[:-1]))[1:]
portfolio_value_rate
Out[14]:
array([ 0.04690176,  0.00826282, -0.02241415,  0.03122727,  0.03896055,
        0.0363623 ,  0.0057301 ,  0.00595328,  0.01073387, -0.00453721,
        0.00028715,  0.04368306,  0.00901098,  0.01761658,  0.00756529,
        0.0061413 ,  0.00794898, -0.00466621, -0.06015439,  0.00636494,
        0.03680521,  0.00244591,  0.01676524,  0.00397737, -0.00014629,
        0.00964465, -0.00050164, -0.00938068,  0.02654241,  0.00940173,
        0.02530033, -0.00579989,  0.01571037,  0.03436924,  0.01746873,
       -0.0019608 ,  0.00388429, -0.01320044, -0.03841505,  0.01614038,
        0.00296689,  0.00659967,  0.00394035, -0.01939202,  0.00254277,
        0.00196447, -0.01378129, -0.00854916, -0.00800506,  0.01581144,
       -0.058468  ,  0.00561951, -0.0057696 , -0.03025341,  0.02275274,
        0.01823169,  0.00014883, -0.00404677,  0.00897074,  0.01700534,
       -0.00093012, -0.01713266,  0.01166762,  0.02811279,  0.00815158,
        0.02077147,  0.01349679, -0.00213392, -0.02615654,  0.01625438,
        0.00089884, -0.00257379, -0.00128746,  0.00063466, -0.00386035,
        0.00785068, -0.00887345, -0.00395449,  0.02027403,  0.01631168,
       -0.00641006,  0.0040704 , -0.00293442, -0.03838325,  0.01949461,
        0.01179365,  0.02356316,  0.00249913,  0.00050825,  0.00449336,
        0.00029063, -0.03076373, -0.00023486, -0.00102183,  0.00876477,
        0.00547108,  0.01840432,  0.01025487,  0.01705659,  0.01044656,
       -0.00994089, -0.01672001,  0.01595148, -0.00253827, -0.00142301,
       -0.00262072,  0.00310977,  0.00377454, -0.00666643,  0.0044867 ,
       -0.00980946,  0.00582684,  0.01871992, -0.00297613,  0.00696657,
        0.00371911,  0.00132873,  0.01029234, -0.00692149,  0.01511791,
        0.00788964,  0.01075627,  0.00214834, -0.0003685 , -0.01020754,
        0.01465225,  0.01498591,  0.00297053, -0.00798114, -0.01076315,
       -0.00813203, -0.0080655 , -0.02228117, -0.01079776,  0.01073463,
       -0.02298366, -0.00251261,  0.00582854,  0.013827  , -0.00796133,
       -0.00107606, -0.05417154,  0.00042612,  0.01153702,  0.01803304,
        0.00378542, -0.00740062,  0.01578713,  0.00156955,  0.00261571,
       -0.01721421,  0.01366435,  0.02432611,  0.00220118,  0.00102544,
       -0.01055659,  0.01635489,  0.00197147, -0.00758277, -0.01703242,
       -0.00070481,  0.00241459, -0.01344026, -0.01479331, -0.02315449,
       -0.06334497,  0.00987198, -0.00639078, -0.0064891 ,  0.02462263,
        0.01482894,  0.00189785,  0.0057214 ,  0.00329171, -0.00944135,
        0.01442143,  0.0053822 ,  0.00476526,  0.00926259, -0.00444799,
        0.00237533, -0.0007594 , -0.00952157,  0.00919402, -0.01368201,
        0.00053713,  0.01208925,  0.0083601 , -0.00704379,  0.01694042,
       -0.00077307,  0.00187013,  0.00738904, -0.0072635 ,  0.00541677,
        0.01679274, -0.00579622,  0.00283572,  0.00586468, -0.00323854,
        0.00255446, -0.00332872,  0.00105644,  0.00896265,  0.00170191,
        0.00381307, -0.00495849, -0.00292552, -0.0021091 , -0.00276153,
       -0.01202422, -0.00315326, -0.01717053, -0.03682951, -0.0021991 ,
        0.02183782,  0.00482149,  0.00141054, -0.00897655,  0.01940595,
       -0.01132633,  0.00602998, -0.00797925, -0.02112556, -0.00117125,
       -0.01371384, -0.00698914, -0.01202393, -0.01712621,  0.02033712,
        0.00786401,  0.0073981 ,  0.02608688,  0.01318002,  0.00128681,
       -0.00818612, -0.02154283, -0.01392595,  0.02213621, -0.01121129,
        0.00521375, -0.00481485,  0.01712803])

600656.XSHG在2016-05-12当日处于停牌状态

In [15]:
Rp = pd.Series(portfolio_value_rate,index = price_change_rate.index)-price_change_rate['risk_free_rate']

开始做回归

In [16]:
X = pd.DataFrame()
X['Rb'] = np.array(Rb)
X['SMB'] = np.array(SMB)
X['HML'] = np.array(HML)
X = sm.add_constant(X)
Y = np.array(Rp)
In [17]:
est=sm.OLS(Y,X).fit()
print(est.summary())
                            OLS Regression Results                            
==============================================================================
Dep. Variable:                      y   R-squared:                       0.768
Model:                            OLS   Adj. R-squared:                  0.765
Method:                 Least Squares   F-statistic:                     264.2
Date:                Sat, 22 Jul 2017   Prob (F-statistic):           1.37e-75
Time:                        15:46:36   Log-Likelihood:                 843.56
No. Observations:                 243   AIC:                            -1679.
Df Residuals:                     239   BIC:                            -1665.
Df Model:                           3                                         
Covariance Type:            nonrobust                                         
==============================================================================
                 coef    std err          t      P>|t|      [95.0% Conf. Int.]
------------------------------------------------------------------------------
const          0.0015      0.001      3.072      0.002         0.001     0.003
Rb             1.0038      0.074     13.609      0.000         0.859     1.149
SMB            1.2257      0.139      8.831      0.000         0.952     1.499
HML           -0.7168      0.126     -5.668      0.000        -0.966    -0.468
==============================================================================
Omnibus:                       11.937   Durbin-Watson:                   1.627
Prob(Omnibus):                  0.003   Jarque-Bera (JB):               12.513
Skew:                           0.485   Prob(JB):                      0.00192
Kurtosis:                       3.543   Cond. No.                         356.
==============================================================================

Warnings:
[1] Standard Errors assume that the covariance matrix of the errors is correctly specified.
In [45]:
est.params
Out[45]:
const    0.001540
Rb       1.003847
SMB      1.225742
HML     -0.716755
dtype: float64


上表主要看coef和t值。
1、SMB大于0,和过去的事实符合,小盘股具有较好的收益率
2、HML小于0,说明bp大的组合(即pb较小的组合)的组合为负的权重,价值投资不能片面追求较小的pb
3、t的绝对值大于2,我们一般认为系数显著。
$$Rp = 0.0015+1.0036Rb+1.2258SMB-0.7162HML$$
我们在附录位置详细描述了各个指标具体的含义:[请点击](#附录OLS指标)

第二节:Fama-French三因子策略


1、通过SMB和HML将所有股票分为了6份,我们选出其中总收益最好的一份所在的区域
2、选出当期区域内的股票
3、基本面分析继续筛选,缩小股票的范围

In [8]:
from rqalpha_plus.api import *
from rqalpha_plus import run_func
###############################################################################################################################################
# 可以自己import我们平台支持的第三方python模块,比如pandas、numpy等。
import numpy as np
import pandas as pd
from pandas import *
import datetime as dt

# 在这个方法中编写任何的初始化逻辑。context对象将会在你的算法策略的任何方法之间做传递。
def init(context):
    context.now
    context.last_month = 13
    context.buy_stocks = []

# before_trading此函数会在每天策略交易开始前被调用,当天只会被调用一次
def before_trading(context):
    # 是否调仓,每日更新为不调仓
    context.change = False
    context.buy_stocks = []
    if context.now.month == context.last_month:
        return None
    context.last_month = context.now.month
    aera = fin_alpha_area(context)
    ready_stocks = fin_stocks(aera,context)
    #stocks = get_buy_stock(ready_stocks,context)
    context.buy_stocks = get_my_stocks(ready_stocks,context)
    context.change = True


# 你选择的证券的数据更新将会触发此段逻辑,例如日或分钟历史数据切片或者是实时数据切片更新
def handle_bar(context, bar_dict):
    if context.change != True:
        return None
    for stock in context.portfolio.stock_account.positions:
        if stock not in context.buy_stocks:
            order_target_percent(stock,0)
    
    for stock in context.buy_stocks:
        order_target_percent(stock,1/len(context.buy_stocks))
        
# 彼得林奇
def get_my_stocks(stocks,context):
    df = get_fundamentals(
        query(fundamentals.financial_indicator.cash_flow_from_operations_per_share
        ).filter(
            fundamentals.financial_indicator.debt_to_asset_ratio <= 100 # 资产负债率小于等于25%
        ).filter(
            fundamentals.financial_indicator.cash_flow_from_operations_per_share > 0 # 每股净现金大于0
        ).filter(
            fundamentals.financial_indicator.annual_return_on_equity > 20 # 当前股价与每股自由现金流量比小于11
        ).filter( 
            financials.stockcode.in_(stocks))
    ).T
    if len(df.index) <= 2:
        return ['000012.XSHG']
    df = df.sort_values('cash_flow_from_operations_per_share',ascending=False)
    buy_stocks = [stock for stock in df.index if is_suspended(stock) != True]
    return buy_stocks[:20]
    
# 横盘的10支股票
def get_cheap_stocks(stocks,context):
    start_date = (context.now-dt.timedelta(days = 90)).strftime("%Y-%m-%d")
    end_date = (context.now-dt.timedelta(days = 1)).strftime("%Y-%m-%d")
    price = get_price(stocks,start_date = start_date,end_date = end_date,fields = ['close'],adjust_type='pre')
    price =np.abs(price.iloc[0,:]/price.iloc[-1,:]-1)
    price = price.sort_values(ascending=True)
    buy_stocks = [stock for stock in price.index if is_suspended(stock) != True]
    
    return buy_stocks[-20:-10]

# 买入roe最大的10支股票
def get_buy_stock(stocks,context):
    value = get_fundamentals( 
        query( 
            fundamentals.financial_indicator.annual_return_on_equity, 
        ).filter(financials.stockcode.in_(stocks)),
            entry_date = context.now - dt.timedelta(days = 1),interval = '1d', report_quarter = False).T
    value.sort_values('annual_return_on_equity',ascending=False, inplace=True)
    buy_stocks = [stock for stock in value.index if is_suspended(stock) != True]
    
    return buy_stocks[0:int(len(buy_stocks)/3)]
    

# after_trading函数会在每天交易结束后被调用,当天只会被调用一次
def after_trading(context):
    pass

def fin_stocks(aera,context):
    # 用查询一年前所有股票的基本面信息
    all_stocks_value = get_fundamentals( 
        query( 
            fundamentals.eod_derivative_indicator.pb_ratio, 
            fundamentals.eod_derivative_indicator.market_cap 
        ),
            entry_date = context.now - dt.timedelta(days = 1),interval = '1d', report_quarter = False).T
    all_stocks_value.dropna(how = 'any',inplace = True)
    all_stocks_value['bp_ratio'] = 1/all_stocks_value['pb_ratio']
    del all_stocks_value['pb_ratio']
    
    # 对股票进行分组
    calue_copy = all_stocks_value.iloc[:,:]
    lengh = len(all_stocks_value.index)
    all_stocks_value = all_stocks_value.sort_values('market_cap') #市值升序排布
    S = all_stocks_value.index[:int(lengh/2)]
    B = all_stocks_value.index[int(lengh/2):]
    all_stocks_value = all_stocks_value.sort_values('bp_ratio') #净市率升序排列
    L = all_stocks_value.index[:int(lengh*0.3)]
    M = all_stocks_value.index[int(lengh*0.3):int(lengh*0.7)]
    H = all_stocks_value.index[int(lengh*0.7):]
    
    # 分为6类别
    portfolio = pd.Series()
    portfolio['SL'] = list(set(S).intersection(set(L)))
    portfolio['SM'] = list(set(S).intersection(set(M)))
    portfolio['SH'] = list(set(S).intersection(set(H)))
    portfolio['BL'] = list(set(B).intersection(set(L)))
    portfolio['BM'] = list(set(B).intersection(set(M)))
    portfolio['BH'] = list(set(B).intersection(set(H)))
    
    return portfolio[aera]

def fin_alpha_area(context):
    last_year = context.now - dt.timedelta(days = 150)
    yesterday = context.now - dt.timedelta(days = 1)
    
    # 得到所有的股票
    sz = index_components('399107.XSHE')
    sh = index_components('000002.XSHG')
    sz.extend(sh)
    all_stocks = sz.copy()
    
    # 拿到所有股票日收益率变动
    all_price = get_price(all_stocks,start_date=last_year-dt.timedelta(days =1), end_date=yesterday,fields = 'close')
    all_price = ((all_price.T).dropna(how = 'any',inplace = False)).T
    all_stocks = all_price.columns.values
    all_price_change_rate = all_price.pct_change().dropna(how = 'any',inplace = False)
    
    # 用查询一年前所有股票的基本面信息
    all_stocks_value = get_fundamentals( 
        query( 
            fundamentals.eod_derivative_indicator.pb_ratio, 
            fundamentals.eod_derivative_indicator.market_cap 
        ).filter( 
            financials.stockcode.in_(all_stocks)),
            entry_date = last_year,interval = '1d', report_quarter = False).T
    all_stocks_value.dropna(how = 'any',inplace = True)
    all_stocks_value['bp_ratio'] = 1/all_stocks_value['pb_ratio']
    del all_stocks_value['pb_ratio']
    
    # 对股票进行分组
    calue_copy = all_stocks_value.iloc[:,:]
    lengh = len(all_stocks_value.index)
    all_stocks_value = all_stocks_value.sort_values('market_cap') #市值升序排布
    S = all_stocks_value.index[:int(lengh/2)]
    B = all_stocks_value.index[int(lengh/2):]
    all_stocks_value = all_stocks_value.sort_values('bp_ratio') #净市率升序排列
    L = all_stocks_value.index[:int(lengh*0.3)]
    M = all_stocks_value.index[int(lengh*0.3):int(lengh*0.7)]
    H = all_stocks_value.index[int(lengh*0.7):]
    
    # 分为6类别
    portfolio = {}
    portfolio['SL'] = list(set(S).intersection(set(L)))
    portfolio['SM'] = list(set(S).intersection(set(M)))
    portfolio['SH'] = list(set(S).intersection(set(H)))
    portfolio['BL'] = list(set(B).intersection(set(L)))
    portfolio['BM'] = list(set(B).intersection(set(M)))
    portfolio['BH'] = list(set(B).intersection(set(H)))
    
    # 计算每类平均收益
    return_ = pd.Series()
    for i in portfolio:
        return_[i] = np.array(all_price_change_rate[portfolio[i]]).mean()
    return_.sort_values(ascending=False, inplace=True)
    
    #print(return_)
    
    return return_.index[0]

config = {
  "base": {
    "start_date": "2016-01-01",
    "end_date": "2017-06-01",
    "benchmark": "000300.XSHG",
    'accounts': {
                 'stock': 100000},
  },
  "extra": {
    "log_level": "verbose",
  },
  "mod": {
    "sys_analyser": {
      "enabled": True,
      "plot": True
    }
  }
}

# 您可以指定您要传递的参数
run_func(init=init, before_trading=before_trading, handle_bar=handle_bar, config=config)

from rqdatac import *
[2017-07-19 17:18:19.911381] DEBUG: system_log: 
{'base': {'accounts': {'STOCK': 100000.0},
          'benchmark': '000300.XSHG',
          'data_bundle_path': '/home/user_303036/.rqalpha-plus/bundle',
          'end_date': datetime.date(2017, 6, 1),
          'frequency': '1d',
          'margin_multiplier': 1,
          'persist': False,
          'persist_mode': PERSIST_MODE.REAL_TIME,
          'resume_mode': False,
          'run_type': RUN_TYPE.BACKTEST,
          'source_code': None,
          'start_date': datetime.date(2016, 1, 1),
          'strategy_file': 'strategy.py'},
 'extra': {'context_vars': None,
           'dividend_reinvestment': False,
           'enable_profiler': False,
           'force_run_init_when_pt_resume': False,
           'is_hold': False,
           'locale': 'zh_Hans_CN',
           'log_level': 'verbose',
           'user_log_disabled': False,
           'user_system_log_disabled': False},
 'mod': {'indicator': {'enabled': True, 'lib': 'rqalpha_mod_indicator'},
         'ricequant_data': {'enabled': True,
                            'lib': 'rqalpha_mod_ricequant_data',
                            'night_trading': False,
                            'priority': 101,
                            'rqdata_client_addr': 'q-rqdatad',
                            'rqdata_client_password': 'research',
                            'rqdata_client_port': 16003,
                            'rqdata_client_retry_cnt': 30,
                            'rqdata_client_username': 'research'},
         'sys_accounts': {'enabled': True},
         'sys_analyser': {'enabled': True, 'plot': True},
         'sys_funcat': {'enabled': False},
         'sys_progress': {'enabled': True},
         'sys_risk': {'enabled': True},
         'sys_simulation': {'enabled': True},
         'sys_stock_realtime': {'enabled': False}},
 'validator': {'cash_return_by_stock_delisted': False, 'close_amount': True},
 'version': '0.1.6',
 'whitelist': ['base', 'extra', 'validator', 'mod']}
[2017-07-19 17:18:19.916930] DEBUG: system_log: 载入 Mod rqalpha_mod_ricequant_data
[2017-07-19 17:18:19.919563] DEBUG: system_log: 载入 Mod rqalpha_mod_indicator
[2017-07-19 17:18:19.922337] DEBUG: system_log: 载入 Mod rqalpha.mod.rqalpha_mod_sys_analyser
[2017-07-19 17:18:19.924950] DEBUG: system_log: 载入 Mod rqalpha.mod.rqalpha_mod_sys_accounts
[2017-07-19 17:18:19.927580] DEBUG: system_log: 载入 Mod rqalpha.mod.rqalpha_mod_sys_simulation
[2017-07-19 17:18:19.930364] DEBUG: system_log: 载入 Mod rqalpha.mod.rqalpha_mod_sys_risk
[2017-07-19 17:18:19.933089] DEBUG: system_log: 载入 Mod rqalpha.mod.rqalpha_mod_sys_progress
[2017-07-19 17:18:19.936268] INFO: system_log: rqdatac use socket ('q-rqdatad', 16003)
2016-04-01 WARN 600870.XSHG 在 2016-04-01 15:00:00 时停牌。
2016-05-03 WARN 600870.XSHG 在 2016-05-03 15:00:00 时停牌。
No record found
[2017-07-19 17:21:28.812819] DEBUG: system_log: 策略运行成功,正常退出

第三节:Fama-French因子风险暴露Factor Risk Exposure


运用多因子模型分析一个组合中风险和收益的来源,多因子模型对收益的分解如下:

$$R_i = a_i + b_{i1} F_1 + b_{i2} F_2 + \ldots + b_{iK} F_K + \epsilon_i$$

在风险分析中,我们常常对超额收益(相对基准的收益情况)建模,风险用超额收益(active Return)的标准误来体现。也叫做tracking error。

例如因子对超额收益风险平方的边际贡献(factors’ marginal contributions to active risk squared,FMCAR ) 对于因子 $j$, 这个指标是这样计算的:

$$ \text{FMCAR}_j = \frac{b_j^a \sum_{i=1}^K b_i^a Cov(F_j, F_i)}{(\text{Active risk})^2} $$

$b_i^a$ 是组合对因子$i$的风险暴露。这项指标告诉我们了,假设其他条件不变,暴露在因子$j$下我们增加了多少风险。

  在上文的基础上,我们计算SMB和HML的累计收益率

In [ ]:
SMB_cu = pd.Series(index = SMB.index)
HML_cu = SMB_cu.copy()

for i in range(len(SMB)):
    if i == 0:
        print("ok")
        SMB_cu[i] = 1+SMB[i]
        HML_cu[i] = 1+HML[i]
    else:
        SMB_cu[i] = SMB_cu[i-1]*(SMB[i]+1)
        HML_cu[i] = HML_cu[i-1]*(HML[i]+1)
df = pd.DataFrame()
df['SMB_cu'] = SMB_cu
df['HML_cu'] = HML_cu
df.iplot(kind='scatter', filename='累计收益率')

  SMB(t)是一个买入小盘股卖出大盘股的组合收益率。HML(t)是一个买入高净市率股票(低pb)卖空低净市率(高pb)股票的投资组合收益率。

计算风险暴露程度

  下面我们运用多因素模型和线性回归工具来计算某只股票的回报率相对于这些因子的风险暴露程度。我们以某个资产组合的超额收益作为被解释变量,对因子做回归,一个因子对超额收益贡献越大,那么这个资产组合的超额收益对于该因子的暴露程度也越高。我们前面已经存在了一个小市值的股票组合了

In [ ]:
def FMACR(SMB,HML,Rb,Rp):
    X = pd.DataFrame()
    X['Rb'] = np.array(Rb)
    X['SMB'] = np.array(SMB)
    X['HML'] = np.array(HML)
    X = sm.add_constant(X)
    Y = np.array(Rp)
    est=sm.OLS(Y,X).fit()
    active = Rp-est.params['Rb']*Rb
    
    cov = np.cov(SMB, HML)
    ar_squared = (active.std())**2
    SMB_fmcar = (est.params['SMB']*(est.params['HML']*cov[0,1] + est.params['SMB']*cov[0,0]))/ar_squared
    HML_fmcar = (est.params['HML']*(est.params['SMB']*cov[0,1] + est.params['HML']*cov[1,1]))/ar_squared
    
    return SMB_fmcar,HML_fmcar

fmcar = pd.DataFrame(index = Rp.index[30:],columns = ['SMB_fmcar','HML_fmcar'])
for i in range(30,len(Rp)):
    fmcar['SMB_fmcar'][i-30],fmcar['HML_fmcar'][i-30] = FMACR(SMB.iloc[i-30:i],HML.iloc[i-30:i],Rb.iloc[i-30:i],Rp.iloc[i-30:i])
fmcar.iplot(kind='scatter', filename='FMACR')

  了解历史数据中组合对各个因子的暴露程度是很有趣的,但只有将它用在对未来收益率的预测上时,它才有用武之地。但我们不是总能够放心地认为未来的情况与现在相同,由于随时间会变化,对风险暴露程度取平均值也很容易出现问题。我们可以给均值加上一个置信区间,但只有当收益率的分布是正态分布或者表现很稳健才行。我们来看看Jarque-Bera测验的结果。

In [ ]:
data = [go.Histogram(x=np.array(fmcar['SMB_fmcar'])),go.Histogram(x=np.array(fmcar['HML_fmcar']))]
data[0].name = 'SMB_fmcar'
data[1].name = 'HML_fmcar'
py.iplot(data, filename='SMB_FMCAR')
In [21]:
from statsmodels.stats.stattools import jarque_bera
JB_SMB, _, _, _ = jarque_bera(fmcar['SMB_fmcar'])
JB_HML, _, _, _ = jarque_bera(fmcar['HML_fmcar'])

print ('JB SMB_FMCAR is normally distributed', JB_SMB)
print ('JB HML_FMCAR is normally distributed', JB_HML)
JB SMB_FMCAR is normally distributed 4.628242740982365
JB HML_FMCAR is normally distributed 0.06063453785474304

第四节:Fama五因素模型


由Eugene F. Fama和Kenneth R. French撰写Journal of Financial Economics2015年第4期论文“A five-factor asset pricing model”对原有的Fama-French(1993)三因素模型进行了改进,在原有的市场、公司市值(即SML,small minus large)以及账面市值比(即HML,high minus low)三因子的基础上,加入了盈利能力(profitability)因子(即RMW,robust minus weak)和投资模式(investment patterns)因子(即CMA,conservative minus aggressive),从而能够更好地解释股票横截面收益率的差异。
对于这个新的模型,其基本特性和一些要素总结如下:

  • 定义盈利能力因子(profitability)为高/低盈利股票投资组合的回报之差(Robust Minus Weak)
  • 定义投资模式因子(investment pattern)为高/低投资比例公司股票投资组合的回报之差(Conservative Minus Aggressive)
  • 五因子模型比三因子模型能更好地解释股票的回报
  • 五因子模型存在的问题是对于高投资比例低盈利小盘股的回报解释不甚理想
  • 加上了盈利能力和投资模式两个新因子之后,原先的价值因子似乎变得多余
In [23]:
# 取2016-05-15的估值数据作为SMB和HML的计算标准
all_stocks_value = get_fundamentals(
    query(
        fundamentals.eod_derivative_indicator.pb_ratio,
        fundamentals.eod_derivative_indicator.market_cap, 
        fundamentals.financial_indicator.annual_return_on_equity, 
        fundamentals.financial_indicator.inc_total_asset)
    , '2016-05-15', interval = '1d' ,report_quarter = False)
all_stocks_value = all_stocks_value.major_xs(all_stocks_value.major_axis[0])
all_stocks_value['bp_ratio'] = 1/all_stocks_value['pb_ratio']
del all_stocks_value['pb_ratio']
all_stocks_value = all_stocks_value.dropna(how = 'any')
all_stocks_value.head()
Out[23]:
market_cap annual_return_on_equity inc_total_asset bp_ratio
000005.XSHE 7.47327e+09 -2.3836 -3.7934 0.152798
600602.XSHG 1.26845e+10 3.6792 -2.5571 0.262
600651.XSHG 1.02955e+10 2.5172 40.3337 0.317914
600652.XSHG 1.14247e+10 1.5756 3.2331 0.182093
600654.XSHG 2.46982e+10 7.4944 -7.3252 0.119852
In [24]:
# 拿到所有股票的日收益率数据
all_price_change_rate = get_price_change_rate(list(all_stocks_value.index),start_date='20160514', end_date='20170515')
all_price_change_rate.head()
Out[24]:
order_book_id 000001.XSHE 000002.XSHE 000004.XSHE 000005.XSHE 000006.XSHE 000007.XSHE 000008.XSHE 000009.XSHE 000010.XSHE 000011.XSHE 603968.XSHG 603969.XSHG 603979.XSHG 603988.XSHG 603989.XSHG 603993.XSHG 603996.XSHG 603997.XSHG 603998.XSHG 603999.XSHG
date
2016-05-16 0.000966 0.0 0.0 -0.004250 0.015193 0.0 0.002573 0.027687 0.013698 0.010726 0.021104 0.006473 0.011156 0.018755 0.017122 0.0 -0.005135 0.036574 0.022205 0.025498
2016-05-17 -0.005792 0.0 0.0 -0.004267 0.004082 0.0 -0.023952 -0.003169 0.001228 0.024489 -0.010333 -0.008040 -0.008385 -0.023413 -0.002619 0.0 0.059784 -0.013783 -0.014982 -0.002122
2016-05-18 0.000000 0.0 0.0 -0.044286 -0.025745 0.0 -0.041192 -0.037362 -0.058895 -0.035858 -0.083936 -0.030794 -0.027147 -0.041187 -0.037884 0.0 -0.095374 -0.036890 -0.062358 -0.035855
2016-05-19 -0.004854 0.0 0.0 0.004485 0.001391 0.0 0.003656 0.002478 -0.006519 0.001655 -0.001315 0.010869 0.001830 0.000854 0.005848 0.0 0.100046 0.005802 0.008111 0.006618
2016-05-20 0.004878 0.0 0.0 0.013393 0.002778 0.0 -0.002732 0.009884 0.001313 0.005774 -0.034679 0.010051 0.009589 -0.008115 0.021707 0.0 0.099917 0.017312 0.006437 0.012523

5 rows × 2823 columns

In [25]:
# 去除nan
test = all_price_change_rate.T.dropna(how = 'any').T
test.head()
Out[25]:
order_book_id 000001.XSHE 000002.XSHE 000004.XSHE 000005.XSHE 000006.XSHE 000007.XSHE 000008.XSHE 000009.XSHE 000010.XSHE 000011.XSHE 603968.XSHG 603969.XSHG 603979.XSHG 603988.XSHG 603989.XSHG 603993.XSHG 603996.XSHG 603997.XSHG 603998.XSHG 603999.XSHG
date
2016-05-16 0.000966 0.0 0.0 -0.004250 0.015193 0.0 0.002573 0.027687 0.013698 0.010726 0.021104 0.006473 0.011156 0.018755 0.017122 0.0 -0.005135 0.036574 0.022205 0.025498
2016-05-17 -0.005792 0.0 0.0 -0.004267 0.004082 0.0 -0.023952 -0.003169 0.001228 0.024489 -0.010333 -0.008040 -0.008385 -0.023413 -0.002619 0.0 0.059784 -0.013783 -0.014982 -0.002122
2016-05-18 0.000000 0.0 0.0 -0.044286 -0.025745 0.0 -0.041192 -0.037362 -0.058895 -0.035858 -0.083936 -0.030794 -0.027147 -0.041187 -0.037884 0.0 -0.095374 -0.036890 -0.062358 -0.035855
2016-05-19 -0.004854 0.0 0.0 0.004485 0.001391 0.0 0.003656 0.002478 -0.006519 0.001655 -0.001315 0.010869 0.001830 0.000854 0.005848 0.0 0.100046 0.005802 0.008111 0.006618
2016-05-20 0.004878 0.0 0.0 0.013393 0.002778 0.0 -0.002732 0.009884 0.001313 0.005774 -0.034679 0.010051 0.009589 -0.008115 0.021707 0.0 0.099917 0.017312 0.006437 0.012523

5 rows × 2821 columns

In [26]:
stock_need_drop = list(set(all_price_change_rate.columns).difference(set(test.columns)))
stock_need_drop
Out[26]:
['600005.XSHG', '000748.XSHE']
In [27]:
# 在估值数据中将上述两支股票删除
all_stocks_value = all_stocks_value.T
for stock in stock_need_drop:
    del all_stocks_value[stock]
all_stocks_value = all_stocks_value.T
In [28]:
short = int(len(all_stocks_value.index)*0.3)
long = int(len(all_stocks_value.index)*0.7)

all_stocks_value.sort_values('market_cap',ascending=True, inplace=True)
SMB = all_price_change_rate[all_stocks_value.index[:short]].T.mean()-all_price_change_rate[all_stocks_value.index[long:]].T.mean()

all_stocks_value.sort_values('bp_ratio',ascending=False, inplace=True)
HML = all_price_change_rate[all_stocks_value.index[:short]].T.mean()-all_price_change_rate[all_stocks_value.index[long:]].T.mean()

all_stocks_value.sort_values('annual_return_on_equity',ascending=False, inplace=True)
RMW = all_price_change_rate[all_stocks_value.index[:short]].T.mean()-all_price_change_rate[all_stocks_value.index[long:]].T.mean()

all_stocks_value.sort_values('inc_total_asset',ascending=False, inplace=True)
CMA = all_price_change_rate[all_stocks_value.index[:short]].T.mean()-all_price_change_rate[all_stocks_value.index[long:]].T.mean()
In [ ]:
SMB_cu = pd.Series(index = SMB.index)
HML_cu = SMB_cu.copy()
RMW_cu = SMB_cu.copy()
CMA_cu = SMB_cu.copy()
 
for i in range(len(SMB)):
    if i == 0:
        print("ok")
        SMB_cu[i] = 1+SMB[i]
        HML_cu[i] = 1+HML[i]
        RMW_cu[i] = 1+RMW[i]
        CMA_cu[i] = 1+CMA[i]
    else:
        SMB_cu[i] = SMB_cu[i-1]*(SMB[i]+1)
        HML_cu[i] = HML_cu[i-1]*(HML[i]+1)
        RMW_cu[i] = RMW_cu[i-1]*(RMW[i]+1)
        CMA_cu[i] = CMA_cu[i-1]*(CMA[i]+1)
df = pd.DataFrame()
df['SMB_cu'] = SMB_cu
df['HML_cu'] = HML_cu
df['RMW_cu'] = RMW_cu
df['CMA_cu'] = CMA_cu
df.iplot(kind='scatter', filename='累计收益率')

  对比上述的图,我们可以发现,同样是SMB平均仓位买入和按庄重买入有完全不同效果,按权重买入,我们在大市值的公司暴露度较好,而平均仓位买入在17年4月份,我们面临一个极大的回调,与此相对因的低pb的公司则收益见好。当然,使用模型不必拘谨于模型本身。

附录:


Dep.variable: 因变量,随自变量的变动而变动

Model: 模型类型(此处为线性回归模型)

Method: 参数估计方法(此处为最小二乘法)

No.observation:样本数量

Df.residuals:残差的自由度,也就是说当用样本来估计整体残差的时候,样本中独立能自由变化的数据的个数

Df.model: 统计模型的自由度,也就等于能自由取值的自变量的个数

Covariance type: 协方差类型

R-squared: 决定系数,即R^2,意味着模型的拟合度的好坏, R-squared误差取值范围为0到1,这个值越接近1说明模型的拟合度越好。 $R-squared=SSR/SST$(SSR是预测数据与原始数据均值之差的平方和,SST是原始数据和均值之差的平方和)

Adj.R-squared:调整后的决定系数,$$Adj.R-squared=1-\frac{(1-R^2)(n-1)}{n-k-1}$$ ($n$为自变量数目,$k$为解释变量的数目)

F-statistique: F 检验统计量,是模型总体显著性检验的指标,它越大,模型越好。$F=\frac{R^2/k}{(1-R^2)/(n-k-1)}$

Prob(F-statistique): F检验统计量对应的概率

Log likelihood: 对数似然比检验的值,值越高,说明模型越精准。其公式为$F=\frac{-n}{2}log(2п) – \frac{n}{2} logσ^2- \frac{n}{2}$

AIC: 赤池信息量即Akaike information criterion,是衡量统计模型拟合优良性的一种标准。
在一般的情况下,AIC可以表示为: $AIC=2k-2ln(L)$,其中k是参数数量,L是似然函数。假设条件是模型的误差服从独立正态分布。 让n为观察数,SSR(SUM SQAURE OF RESIDUE)为残差平方和,那么AIC变为: $AIC=2k+nln(SSR/n)$。增加自由参数的数目提高了拟合的优良性,AIC鼓励数据拟合的优良性但是尽量避免出现过度拟合(Overfitting)的情况。所以优先考虑的模型应是AIC值最小的那一个。

BIC: Bayesian information criterion,贝叶斯信息度量。 $BIC=kln(n)-2ln(L)$。其中n是模型中未知参数的数量。 BIC相比AIC在大数据量时对模型参数惩罚得更多,导致BIC更倾向于选择参数少的简单模型。
Coef: 回归系数的估计值。 $β^=(X^T X)^{-1}$ $X^TY$

Std err: 回归系数估计量的标准差

t: T检验的统计量,即样本平均数与总体平均数的离差统计量。因为样本x符合正太分布,那么 $t=\frac{X ̅-μ}{σ/√(n-1)}$ 符合自由度为n-2的T分布,其中t为样本平均数与总体平均数的离差统计量,X ̅为样本平均数,μ为总体平均数,σ为样本标准差,n为样本容量.。当t大于自由度为n-2的T分别的临界分位点时,我们拒绝零假设

P>|t|: t对应的T分布的概率,当此概率小于临界值的概率(通常是5%),我们拒绝零假设

Omnibus: 模型的总的全局检验,为似然比检验.

Prob(omnibus):

Skew: 偏度系数。当分布对称时,偏度系数为0.当偏度系数为正值,可以判断为右偏。反之判断为左偏。 $Skew=\frac{1}{n-1}$ $\sum_{i=1}^n\frac{(x_i-X ̅ )^3}{S^3}$,其中S为标准差

Kurtosis: 峰度系数。是对数据分布平峰或尖峰程度的测度。峰度是针对正态分布而言的。峰度系数为0,表明数据为正态分布。若峰度系数大于0,则数据为尖峰分布;否则为平峰分布。$Kurtosis=\frac{1}{n-1}$ $\sum_{i=1}^n\frac{(x_i-X ̅ )^4}{S^4}-3$
Durbin-Watson: 检验残差中是否存在自相关。自相关表示相邻观测值是相关的。 如果它们是相关的,那么最小二乘回归低估了系数的标准误;此时,您的预测变量似乎非常显著,其实可能是不显著的。例如,来自每日股票价格数据回归的残差可能取决于以前的观测值,因为前一天的股票价格会影响第二天的价格。 Durbin-Watson 统计量以观测值的顺序(行)为条件。Minitab 假设观测值遵循有意义的顺序(如时间顺序)。Durbin-Watson 统计量确定相邻误差项之间的相关性是否为零。要从检验中得出结论,需要将显示的统计量与表中的上下限进行比较。如果 D > 上限,表示不存在相关性;如果 D < 下限,表示存在正相关性;如果 D 在上下限之间,则无法从检验中得出结论。

Jarque-Bera(JB): Jarque-Bera检验基于数据样本的偏度和峰度,评价给定数据服从未知均值和方差正态分布的假设是否成立。
$JB=\frac{n-k}{6}$($S^2$+$\frac{(k-3)^2}{4}$) ,其中n为样本容量,k为自由度, S为标准差。

Prob(JB): JB统计量的相伴概率,若小于设定的概率水平,则拒绝原假设,不认样本概率服从正态分布。

多因子模型系列目录

1.多因子模型系列1-数据预处理之离群值处理
2. 多因子模型系列2-多因子模型的步骤梳理
当前阅读> 3. 多因子模型系列3-Fama Franch三因子及其拓展五因子模型
4. 多因子模型系列4-验证Fama French三因子分解的有效性
5. 多因子模型系列5-套利定价模型的应用
6. 多因子模型系列6-沪深300指数的风格因子暴露度分析
7. 多因子模型系列7-多因子模型水平测试题试答
8. 多因子模型系列8-基于组合权重优化的风格中性多因子选股策略框架
9. 多因子模型系列9-阿里巴巴与101个alpha
10. 多因子模型系列10-因子分析
11. 多因子模型系列11-绩效分析之Brinson模型

发表评论

邮箱地址不会被公开。 必填项已用*标注