获取任一股票数据,建立CAPM模型,估计基于CAPM模型的预期收益率与实际收益率,结果以图形的形式展示。
import tushare as ts
import pandas as pdimport statsmodels.api as sm
mydf=ts.get_hist_data('sz',ktype='W',start='2016-01-01',end='2017-01-01')
mydf.p_change
ZGLT=ts.get_hist_data('600050',ktype='W',start='2016-01-01',end='2017-01-01')
ZGLT.p_change
#无风险收益率
rf=1.0385**(1/365)-1
Return=pd.merge(pd.DataFrame(mydf.p_change),pd.DataFrame(ZGLT.p_change),left_index=True,right_index=True,how='inner')
Eret=Return-rf
#拟合CAPM模型
model=sm.OLS(Eret.p_change_y[1:],sm.add_constant(Eret.p_change_x[1:]))
result=model.fit()
print(result.summary())
#根据拟合结果计算预期收益率
Premydf=mydf.p_change-rf
PreZGLT=ZGLT.p_change-rf
ActualZGLT=1.0511+0.9757*Premydf
#画折线图
import matplotlib.pyplot as plt
plt.plot(PreZGLT, marker='o', label='PreZGLT')
plt.plot(ActualZGLT, marker='*',label='ActualZGLT')
plt.legend()
plt.show()