import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import stats
import statsmodels.api as sm
import warnings
warnings.filterwarnings("ignore")
plt.rcParams['font.sans-serif'] = ['KaiTi'] # 指定默认字体
plt.rcParams['axes.unicode_minus'] = False # 解决保存图像是负号'-'显示为方块的问题
def get_data():
#获取沪深300收益率数列
HS300 = pd.read_excel('stocks.xlsx',sheet_name='510300',index_col=0)
# print(HS300)
HS300RET = HS300.loc[:, 'close'].pct_change()
HS300RET = HS300RET[~np.isnan(HS300RET)]
HS300RET = HS300RET * 100
ZZ500 = pd.read_excel('stocks.xlsx',sheet_name='399905',index_col=0)
ZZ500RET = ZZ500.loc[:, 'close'].pct_change()
ZZ500RET = ZZ500RET[~np.isnan(ZZ500RET)]
ZZ500RET = ZZ500RET * 100
return HS300RET,ZZ500RET
hs300,zz500= get_data()
stocks = pd.DataFrame(hs300)
stocks.columns = ['hs300',]
stocks.loc[:,'zz500'] = zz500
print(stocks.head(10))
hs = stocks.loc[:,'hs300']
zz = stocks.loc[:,'zz500']
model = sm.OLS(hs,sm.add_constant(zz)).fit()
print(model.summary())
plt.scatter(model.fittedvalues,model.resid)
plt.xlabel('拟合值')
plt.ylabel('残差')
plt.show()
sm.qqplot(model.resid_pearson,stats.norm,line='45')
plt.show()