因子模型(2)——因子的计算(groupby, merge)
2019-11-21 本文已影响0人
micovey
理论基础
在分析之前,首先要计算每只股票在特定时间段内的日收益。
在学术上,通常采用对数收益率,满足可加性。
首先看一下原始数据
有同学可能想,直接相减,然后删去2019.5.24日对应的所有数据
但是这样是不可行的,因为每个公司的数据长度不一定相同(停牌无数据)
因此需要用groupby函数
数据准备
首先是获得数据,然后是准备因子的分组(可关注观看之前文章)
- daily.py:自动更新规定时间内的日度数据,可以自行修改数据期间。默认为半年前至当日。以便后续分析
- factor.py :下载三因子所需数据,但日期需要自行更改,一般需要两年,6月底分组
- factor_cal.py:将股票进行分组,以便后续计算因子
- return_cal.py:计算对数收益率
- factor_merge.py: 收益率、因子等将匹配
groupby函数:
简单来讲,将数据分块,如图所示
image分组后,group[0]是公司的名称(本案例中)
我们用group[1]来提取数据框(整体不是dataframe格式,需要提取)
计算步骤:
- 我们将收盘价向下错后一行
- 删掉空值所在行
- 分别计算收盘价对数。(不能直接用math.log(序列),要[math.log(x) for x in 序列])
- 将两列相减,得到收益率
- 将每个公司的结果append。
计算因子的思路:
- 将数据按照日期、因子的虚拟变量分组(小市值为1,大市值为0)
- 计算每个公司在该分组下,按照市值所确定是权重
- 将收益率按照权重求和
- 如果虚拟变量分组为1(证明是小市值)
- 将该数据加到 日期,小市值两个list
- 如果虚拟变量分组为0(证明是大市值)
- 将该数据加到大市值list
- 合并三个list
- 将小市值收益-大市值收益得到因子
同理,计算账面市值比因子
merge函数
df_3 = pd.merge(数据框1,数据框2, on=['一样名字的列1','一样名字的列2'])
首先,我们的数据是5-11月,因此5,6月应当对应2018年的分组,7月后对应2019年的分组
因此我们根据季度,将第二季度的year由2019替换为2018,然后与2018分组merge
第三、四季度的year本身为2019,与2019的分组merge
on=['code','year']
将两个数据框合并
然后将各个因子对应的数据框按照date合并
最终数据的形式如下:
image如果有兴趣可以关注一下
image代码:
##计算对数收益率
import pandas as pd
import math
print('请输入地址')
global file_place
file_place='D:\\'
fff=file_place+'\\Quantify\\daily\\daily'+str(2019)+'.csv'
##计算收益率
def cal_return(group):
group=pd.DataFrame(group[1])##提取数据框
group['close_down1']= group['close'].shift(periods=1)
group = group.dropna(axis=0, how='any')
group["close"] = [math.log(x) for x in group["close"]]
group['close_down1'] = [math.log(x) for x in group['close_down1']]
group['ret'] = (group['close']-group['close_down1'])*100
group=group[['date','code','quarter','year','ret','marketvalue']]
return(group)
daily_data = pd.read_csv(file_place+'Quantify\\daily\\daily'+str(2019)+'.csv')
returndata=pd.DataFrame(columns=['date','code','quarter','year','ret','marketvalue'])
g=pd.DataFrame(columns=['date','code','quarter','year','ret','marketvalue'])
print(g)
for group in daily_data.groupby(['code']):
g=cal_return(group)
returndata=returndata.append(g)
print(group[0])
#returndata.to_csv(file_place+'Quantify\\daily\\daily_ret'+str(2019)+'.csv', header=True,index=False)
计算因子
import pandas as pd
import baostock as bs
import datetime
import math
now_time=datetime.datetime.now().strftime('%Y-%m-%d')
now_time=datetime.datetime.strptime(now_time,'%Y-%m-%d')
year=int(now_time.year)
print('请输入地址')
global file_place
file_place='D:\\'
fl = 'Quantify\\idcode.csv'
filee=file_place+fl
fff=file_place+'\\Quantify\\daily\\daily'+str(2019)+'.csv'
returndata = pd.read_csv(file_place+'Quantify\\daily\\daily_ret'+str(2019)+'.csv')
factor_data2019=pd.read_csv(file_place+'Quantify\\factor\\factor_sort'+str(2019)+'.csv')
factor_data2019["year"] =2019
factor_data2018=pd.read_csv(file_place+'Quantify\\factor\\factor_sort'+str(2018)+'.csv')
factor_data2018["year"] =2018
returndata ["year"] = [2018 if x <3 else 2019 for x in returndata ["quarter"]]
half_1= pd.merge(returndata, factor_data2018, on=['code','year'])
half_2= pd.merge(returndata, factor_data2019, on=['code','year'])
half_1=half_1.append(half_2)
factor3=half_1[["date","code","ret","smb_dum","hml_dum","marketvalue"]]
small=[]
day=[]
big=[]
##计算因子
for group in factor3.groupby(['date','smb_dum']):
group=group[1]
group["sum_m"] = group['marketvalue'].sum()
group["ret_w"] = group['marketvalue']/group['sum_m']*group['ret']
group["ret_group"]=group['ret_w'].sum()
group=group[["date","smb_dum","ret_group"]]
if group.iloc[0,1]==1:
small.append(group.iloc[0,2])
day.append(group.iloc[0,0])
else:
big.append(group.iloc[0,2])
df_smb=pd.DataFrame({'date':day,'small':small,'big':big})
df_smb["smb"]=df_smb["small"]-df_smb["big"]
df_smb=df_smb[["date","smb"]]
#print(df_smb)
#df_smb.to_csv(file_place+'Quantify\\daily\\smb'+str(2019)+'.csv', header=True,index=False)
high=[]
low=[]
day=[]
for group in factor3.groupby(['date','hml_dum']):
group=group[1]
group["sum_m"] = group['marketvalue'].sum()
group["ret_w"] = group['marketvalue']/group['sum_m']*group['ret']
group["ret_group"]=group['ret_w'].sum()
group=group[["date","hml_dum","ret_group"]]
if group.iloc[0,1]==2:
low.append(group.iloc[0,2])
day.append(group.iloc[0,0])
elif group.iloc[0,1]==0:
high.append(group.iloc[0,2])
else:
continue
df_hml=pd.DataFrame({'date':day,'high':high,'low':low})
df_hml["hml"]=df_hml["high"]-df_hml["low"]
df_hml=df_hml[["date","hml"]]
#print(df_hml)
#df_hml.to_csv(file_place+'Quantify\\daily\\hml'+str(2019)+'.csv', header=True,index=False)
returndata['date']=[datetime.datetime.strptime(x,'%Y/%m/%d') for x in returndata['date']]
start_date = df_hml['date'].min()
start_date = datetime.datetime.strptime(start_date, '%Y/%m/%d')
start_date = start_date + datetime.timedelta(days=-1)
start_date = str(datetime.datetime.strftime(start_date, '%Y-%m-%d'))
end_date=str(datetime.datetime.now().strftime('%Y-%m-%d'))
##寻找大盘指数
#### 登陆系统 ####
lg = bs.login()
rs = bs.query_history_k_data_plus("sh.000001",
"date,code,open,high,low,close,preclose,volume,amount,pctChg",
start_date=start_date, end_date=end_date, frequency="d")
data_list = []
while (rs.error_code == '0') & rs.next():
data_list.append(rs.get_row_data())
ret_m = pd.DataFrame(data_list, columns=rs.fields)
ret_m=ret_m[["date","close"]]
ret_m['close_down1'] = ret_m['close'].shift(periods=1)
ret_m = ret_m.dropna(axis=0, how='any')
ret_m["close"] = [math.log(float(x)) for x in ret_m["close"]]
ret_m['close_down1'] = [math.log(float(x)) for x in ret_m['close_down1']]
ret_m['ret_m'] = (ret_m['close'] - ret_m['close_down1']) * 100
ret_m['date']=[datetime.datetime.strptime(x,'%Y-%m-%d') for x in ret_m['date']]
ret_m['date']=[datetime.datetime.strftime(x,'%Y/%m/%d') for x in ret_m['date']]
print(ret_m)
# 登出系统
bs.logout()
df_3 = pd.merge(factor3,ret_m, on=['date'])
df_2 = pd.merge(df_hml,df_smb, on=['date'])
df_1 = pd.merge(df_3, df_2, on=['date'])
df_1 = df_1 [["date","code","ret","ret_m","smb","hml"]]
df_1.to_csv(file_place+'Quantify\\factor\\factor_1_2019.csv', header=True,index=False)
编辑于 12:22