import pandas as pd import numpy as np from scipy import stats import akshare as ak def get_return(code,startdate,endate): df=ak.stock_zh_a_daily(code, start_date=startdate, end_date=endate, adjust="qfq") p1=np.array(df.close[1:]) p0=np.array(df.close[:-1]) logret = np.log(p1/p0) rate=pd.DataFrame() rate[code]=logret rate.index=df['date'][1:] return rate
收益率函数;从akshare下载数据;
导入系数:
startdate="20201103" endate="20211103" code="sz000905" get_return(code,startdate,endate)
结果:
一、阿尔法和贝塔计算
贝塔与中证500的收益率做对比,中证500股票代码:sz000905
定义阿尔法和贝塔函数:
def alpha_beta(code,startdate,endate): mkt_ret=get_return("sz000905",startdate,endate) stock_ret=get_return(code,startdate,endate) df=pd.merge(mkt_ret,stock_ret,left_index=True,right_index=True) x=df.iloc[:,0] y=df.iloc[:,1] beta,alpha,r_value,p_value,std_err=stats.linregress(x,y) return (alpha,beta)
导入系数:
startdate="20201103" endate="20211103" code="sh600519" alpha_beta(code,startdate,endate)
结果:(0.0002538222146195239, -0.14144412140986778)
二、计算多个股票的阿尔法和贝塔
def stocks_alpha_beta(stocks,startdate,endate): df=pd.DataFrame() alpha=[] beta=[] for code in stocks.values(): a,b=alpha_beta(code,startdate,endate) alpha.append(float('%.4f'%a)) beta.append(float('%.2f'%b)) df['alpha']=alpha df['beta']=beta df.index=stocks.keys() return df
导入系数:
startdate="20201103" endate="20211103" stocks={"中国平安":"sh601318","格力电器":"sh600036"} stocks_alpha_beta(stocks,startdate,endate)
结果:
标签:贝塔,code,startdate,df,阿尔法,beta,计算,alpha,endate From: https://www.cnblogs.com/leon507/p/17167671.html