风险因子(离散类)

来源:https://uqer.io/community/share/54d2cee9f9f06c276f651a67

本代码用于计算风险因子

  • 先根据DataAPI.ThemeTickersGet得到每个主题相关的个股
  • 计算个股在前7天的每天涨跌幅,从而计算主题的每天涨跌幅(市值加权)
  • 计算个股前7天的涨跌停次数,计算主题涨跌停比例
  • 对每个股票,按照股票市值占主题总市值的比例,计算涨跌幅和涨跌停比例(均为7日),将两个指标进行排名,个股有两个排名得分
  • 再取两个排名得分的平均,对个股再次排名 排名越高,波动越大,风险越大
  1. datetime.today()
  2. datetime.datetime(2015, 2, 4, 22, 18, 57, 402881)

此处定义了几个函数,方便调用

  1. def GetThemeInfo(thm_id_list):
  2. #由于ThemeTickersGet对于数据量有限制,一次调用1000个主题数据
  3. num = 1000 #每一次调取多少个主题的信息
  4. cnt_num = len(thm_id_list)/num #一次调取num个主题,要调用num次
  5. beginDate = '20140601' #开始时间
  6. endDate = '20150123' #结束时间
  7. if cnt_num>0:
  8. thm_tk_pd = pd.DataFrame({})
  9. for i in range(cnt_num):
  10. info_sub = DataAPI.ThemeTickersGet(beginDate=beginDate,endDate=endDate,themeID=thm_id_list[i*num:(i+1)*num]) #获取主题相关的个股
  11. thm_tk_pd = pd.concat([thm_tk_pd,info_sub]) #将数据连接
  12. info_sub = DataAPI.ThemeTickersGet(beginDate=beginDate,endDate=endDate,themeID=thm_id_list[(i+1)*num:])
  13. thm_tk_pd = pd.concat([thm_tk_pd,info_sub])
  14. else:
  15. thm_tk_pd = DataAPI.ThemeTickersGet(beginDate=beginDate,endDate=endDate,themeID=thm_id_list)
  16. return thm_tk_pd
  17. def GetMktInfo(tk_list,beginDate,endDate,field_mkt): #获得个股的日线行情数据
  18. num = 50
  19. cnt_num = len(tk_list)/num
  20. if cnt_num>0:
  21. tk_mkt_info = pd.DataFrame({})
  22. for i in range(cnt_num):
  23. sub_info = DataAPI.MktEqudGet(ticker=tk_list[i*num:(i+1)*num],beginDate=beginDate,endDate=endDate,field=field_mkt)
  24. tk_mkt_info = pd.concat([tk_mkt_info,sub_info])
  25. sub_info = DataAPI.MktEqudGet(ticker=tk_list[(i+1)*num:],beginDate=beginDate,endDate=endDate,field=field_mkt)
  26. tk_mkt_info = pd.concat([tk_mkt_info,sub_info])
  27. else:
  28. tk_mkt_info = DataAPI.MktEqudGet(ticker=tk_list,beginDate=beginDate,endDate=endDate,field=field_mkt)
  29. return tk_mkt_info
  30. def GetDate(n): #获得最近7个交易日的日期
  31. cal = Calendar("China.SSE")
  32. today_cal = Date.todaysDate()
  33. today_dtime = datetime.today()
  34. if cal.isBizDay(today_cal): #如果今天是交易日
  35. today_ymd = today_dtime.strftime("%Y%m%d")
  36. hms = " 15:05:00"
  37. ben_time = datetime.strptime(today_ymd+hms,"%Y%m%d %H:%M:%S")
  38. if today_dtime>ben_time: #如果当前时间晚于15:05分,则可以获取到今日行情数据
  39. end_date = today_ymd
  40. else:
  41. cal_wd = cal.advanceDate(today_cal, '-1B', BizDayConvention.Preceding) #获得前一个工作日Date格式
  42. end_date = cal_wd.toISO().replace('-','') #转换成字符串格式‘20140102’
  43. else:
  44. cal_wd = cal.advanceDate(today_cal, '-1B', BizDayConvention.Preceding) #获得前一个工作日Date格式
  45. end_date = cal_wd.toISO().replace('-','') #转换成字符串格式‘20140102’
  46. end_date_cal = Date.parseISO('-'.join([end_date[0:4],end_date[4:6],end_date[6:8]])) #更改日期格式为“2014-03-02”
  47. prd = '-'+str(n-1)+'B' #起始日期和终止日期间隔的天数
  48. begin_date_cal = cal.advanceDate(end_date_cal, prd , BizDayConvention.Preceding) #获得6天前的工作日
  49. begin_date = begin_date_cal.toISO().replace('-','')
  50. return begin_date,end_date

读取主题id文件,先对个股和主题进行筛选,然后获得个股的行情数据

  1. #Main
  2. import pandas as pd
  3. f1 = read('20140601_20150203theme_list.txt') #从这个文档中读取所有的主题id
  4. thm_id_list = f1.split(',')
  5. thm_tk_pd = GetThemeInfo(thm_id_list=thm_id_list) #获得主题对应个股的信息
  6. thm_tk_pd = thm_tk_pd[(thm_tk_pd['ticker'].str.len()==6) & (thm_tk_pd['ticker'].apply(lambda x:x[0]=='0' or x[0]=='6'))] #过滤港股和新三板,因为拿不到行情数据
  7. grouped_thmid = thm_tk_pd.groupby('themeID') #根据主题id分类,得到每个主题对应的个股
  8. ###对主题进行过滤如果该主题所包含的个股《5,则舍弃
  9. fld_thmid_list = []
  10. for name,group in grouped_thmid:
  11. if len(group)>=5:
  12. fld_thmid_list.append(name)
  13. thm_tk_pd = thm_tk_pd[thm_tk_pd['themeID'].isin(fld_thmid_list)]
  14. ThmId_Nm_dic = dict(zip(thm_tk_pd['themeID'],thm_tk_pd['themeName'])) #获得主题id与主题名称的对应
  15. TkId_Nm_dic = dict(zip(thm_tk_pd['ticker'],thm_tk_pd['secShortName'])) #获得个股id与个股名称的对应
  16. thm_tk_pd = thm_tk_pd[['themeID','ticker']]
  17. tk_list = list(set(thm_tk_pd['ticker'])) #获得所有的个股
  18. n_prd =7
  19. beginDate,endDate = GetDate(n_prd) #获取n_prd个交易日的具体日期
  20. field_mkt = ['ticker','openPrice','closePrice','highestPrice','lowestPrice','marketValue','preClosePrice ']
  21. tk_mktinfo_pd = GetMktInfo(tk_list,beginDate,endDate,field_mkt) #获得所有个股的行情数据
  22. tk_mktinfo_pd['return'] = (tk_mktinfo_pd['closePrice']-tk_mktinfo_pd['preClosePrice'])/tk_mktinfo_pd['preClosePrice'] #计算所有个股每天的涨跌幅

计算主题的涨跌幅(绝对值)和涨跌停比例

  1. grouped_thmid = thm_tk_pd.groupby('themeID') #根据主题id分类,得到每个主题对应的个股
  2. grouped_tkid = thm_tk_pd.groupby('ticker') #根据ticker分类,得到每个个股对应的主题
  3. thm_rtn_dic, thm_gb_dic, thm_mkv_dic = {},{},{} #主题的日涨幅,主题的日涨跌停比例,主题的市值
  4. #获得主题的日收益的绝对值的平均
  5. for thm,group_thm in grouped_thmid:
  6. sub_tk_list = list(group_thm['ticker'])
  7. sub_tk_mkt_pd = tk_mktinfo_pd[tk_mktinfo_pd['ticker'].isin(sub_tk_list)] #获得该主题下个股的行情数据
  8. thm_rtn = (sub_tk_mkt_pd['marketValue']*abs(sub_tk_mkt_pd['return'])).sum()/sub_tk_mkt_pd['marketValue'].sum() #计算主题在这7天的平均每天绝对收益
  9. thm_rtn_dic[thm] = thm_rtn
  10. thm_mkv_dic[thm] = sub_tk_mkt_pd['marketValue'].sum() #记录每个主题的市值(7天的和)
  11. num_gb = len(sub_tk_mkt_pd[(abs((sub_tk_mkt_pd['closePrice']-sub_tk_mkt_pd['preClosePrice']))/sub_tk_mkt_pd['preClosePrice']).round(2)==0.1]) #涨跌停的个股数目
  12. thm_gb_dic[thm] = num_gb/n_prd #主题涨跌停比例7日均值

由主题涨跌幅和涨跌停比例,计算个股的涨跌幅和涨跌停比例

  1. tk_inc_gb_dic = {} #由主题计算的个股的涨幅和涨跌停比例
  2. for tk,group_tk in grouped_tkid:
  3. tk_mkv = tk_mktinfo_pd['marketValue'][tk_mktinfo_pd['ticker']==tk].sum() #得到个股市值(7天的和)
  4. thm_list = group_tk['themeID']
  5. inc,gb_ratio = 0,0
  6. for thm in thm_list:
  7. pro = tk_mkv/thm_mkv_dic[thm] #个股占该主题的比例
  8. inc += thm_rtn_dic[thm]*pro
  9. gb_ratio += thm_gb_dic[thm]*pro
  10. tk_inc_gb_dic[tk] = (inc,gb_ratio) #记录个股的涨幅和涨跌停比例

根据个股的涨跌幅和涨跌停比例进行排名,再将这两个排名进行平均,再排名

  1. sort1 = sorted(tk_inc_gb_dic.keys(), key = lambda x:tk_inc_gb_dic[x][0], reverse=True) #根据个股的涨幅排名,涨幅大的排名在前
  2. sort2 = sorted(tk_inc_gb_dic.keys(), key = lambda x:tk_inc_gb_dic[x][1], reverse=True) #根据个股的涨跌停比例排名,涨跌停比例高的排名在前
  3. rank = lambda x:(sort1.index(x)+sort2.index(x))*1.0/2+1
  4. id2name = lambda x:TkId_Nm_dic[x]
  5. df = pd.DataFrame({'ticker':tk_list})
  6. df['name'] = pd.Series(map(id2name,tk_list))
  7. df['ranking_score'] = pd.Series(map(rank,tk_list))
  8. df_sort = df.sort(columns=['ranking_score'],ascending = True)
  9. df_sort.reset_index(inplace=True,drop=True)
  10. print "最近个股风险因子排名:"
  11. df_sort
  1. datetime.today()
  2. datetime.datetime(2015, 2, 4, 22, 19, 15, 638752)