盈利预增事件

来源:https://uqer.io/community/share/5642c69af9f06c78612190b5

每次建仓等权重买入上季度净利润预增(盈利且盈利增加)的股票

  1. import pandas as pd
  2. import numpy as np
  3. from CAL.PyCAL import *
  4. from pandas import DataFrame,Series
  5. from datetime import datetime, timedelta
  6. start = '2013-01-01' # 回测起始时间
  7. end = (datetime.today() - timedelta(days=1)).strftime('%Y%m%d') # 截止日期
  8. benchmark = 'HS300' # 策略参考标准
  9. universe = set_universe('HS300') # 证券池,支持股票和基金
  10. capital_base = 1000000 # 起始资金
  11. freq = 'd' # 策略类型,'d'表示日间策略使用日线回测,'m'表示日内策略使用分钟线回测
  12. refresh_rate = 63 # 调仓频率,表示执行handle_data的时间间隔,若freq = 'd'时间间隔的单位为交易日,若freq = 'm'时间间隔为分钟
  13. cal = Calendar('China.SSE')
  14. def initialize(account): # 初始化虚拟账户状态
  15. pass
  16. def handle_data(account): # 每个交易日的买入卖出指令
  17. today = account.current_date.strftime('%Y%m%d')
  18. yesterday = cal.advanceDate(account.current_date, '-1B', BizDayConvention.Following).strftime('%Y%m%d')
  19. yester_refresh_day = cal.advanceDate(account.current_date, '-62B' , BizDayConvention.Following).strftime('%Y%m%d')
  20. total_money = account.referencePortfolioValue
  21. prices = account.referencePrice
  22. # 去除新上市或复牌的股票
  23. opn = account.get_attribute_history('openPrice', 1)
  24. account.universe = [s for s in account.universe if not (np.isnan(opn.get(s, 0)[0]) or opn.get(s, 0)[0] == 0 )]
  25. buylist =[]
  26. for s in account.universe :
  27. try :
  28. temp=DataAPI.FdmtEfGet(secID = s,forecastType ='22',publishDateBegin= yester_refresh_day , publishDateEnd = yesterday,field=['secID','publishDate','NIncAPChgrLL', 'NIncAPChgrUPL'],pandas="1")
  29. buylist.append(s)
  30. except :
  31. continue
  32. sell_list = [x for x in account.valid_secpos if x not in buylist]
  33. for s in sell_list :
  34. order_to(s,0)
  35. for s in buylist :
  36. order_to(s, int(total_money*0.99/len(buylist)/prices[s]/100)*100)

盈利预增事件 - 图1

  1. # 统计代码 不用看啰
  2. from pandas import DataFrame
  3. data = DataFrame()
  4. for s in range(len(set_universe('A'))/100 + 1) :
  5. if s == len(set_universe('A'))/100 :
  6. temp_list = set_universe('A')[s*100:]
  7. else :
  8. temp_list = set_universe('A')[s*100:(s+1)*100]
  9. try:
  10. if not temp_list == 0 :
  11. data_temp = DataAPI.FdmtEfGet(secID = temp_list,field=['secID','publishDate','NIncAPChgrLL', 'NIncAPChgrUPL'],pandas="1")
  12. except :
  13. print '错误!'
  14. data = pd.concat([data,data_temp])
  15. data['publishDate'] = pd.to_datetime(data['publishDate'])
  16. list1 = []
  17. data07 = data[data['publishDate'] < '20080101']
  18. data07.drop_duplicates('secID' , inplace = True)
  19. list1.append(len(data07))
  20. data08 = data[(data['publishDate'] < '20090101') & (data['publishDate'] >= '20080101')]
  21. data08.drop_duplicates('secID' , inplace = True)
  22. list1.append(len(data08))
  23. data09 = data[(data['publishDate'] < '20100101') & (data['publishDate'] >= '20090101')]
  24. data09.drop_duplicates('secID' , inplace = True)
  25. list1.append(len(data09))
  26. data10 = data[(data['publishDate'] < '20110101') & (data['publishDate'] >= '20100101')]
  27. data10.drop_duplicates('secID' , inplace = True)
  28. list1.append(len(data10))
  29. data11 = data[(data['publishDate'] < '20120101') & (data['publishDate'] >= '20110101')]
  30. data11.drop_duplicates('secID' , inplace = True)
  31. list1.append(len(data11))
  32. data12 = data[(data['publishDate'] < '20130101') & (data['publishDate'] >= '20120101')]
  33. data12.drop_duplicates('secID' , inplace = True)
  34. list1.append(len(data12))
  35. data13 = data[(data['publishDate'] < '20140101') & (data['publishDate'] >= '20130101')]
  36. data13.drop_duplicates('secID' , inplace = True)
  37. list1.append(len(data13))
  38. data14 = data[(data['publishDate'] < '20150101') & (data['publishDate'] >= '20140101')]
  39. data14.drop_duplicates('secID' , inplace = True)
  40. list1.append(len(data14))
  41. data15 = data[(data['publishDate'] < '20160101') & (data['publishDate'] >= '20150101')]
  42. data15.drop_duplicates('secID' , inplace = True)
  43. list1.append(len(data15))
  44. data2 = DataFrame()
  45. for s in range(len(set_universe('A'))/100 + 1) :
  46. if s == len(set_universe('A'))/100 :
  47. temp_list = set_universe('A')[s*100:]
  48. else :
  49. temp_list = set_universe('A')[s*100:(s+1)*100]
  50. try:
  51. if not temp_list == 0 :
  52. data_temp = DataAPI.FdmtEfGet(secID = temp_list,forecastType= '22' ,field=['secID','publishDate','NIncAPChgrLL', 'NIncAPChgrUPL'],pandas="1")
  53. except :
  54. print '错误!'
  55. data2 = pd.concat([data2,data_temp])
  56. data2['publishDate'] = pd.to_datetime(data2['publishDate'])
  57. list2 = []
  58. data07 = data2[data2['publishDate'] < '20080101']
  59. data07.drop_duplicates('secID' , inplace = True)
  60. list2.append(len(data07))
  61. data08 = data2[(data2['publishDate'] < '20090101') & (data2['publishDate'] >= '20080101')]
  62. data08.drop_duplicates('secID' , inplace = True)
  63. list2.append(len(data08))
  64. data09 = data2[(data2['publishDate'] < '20100101') & (data2['publishDate'] >= '20090101')]
  65. data09.drop_duplicates('secID' , inplace = True)
  66. list2.append(len(data09))
  67. data10 = data2[(data2['publishDate'] < '20110101') & (data2['publishDate'] >= '20100101')]
  68. data10.drop_duplicates('secID' , inplace = True)
  69. list2.append(len(data10))
  70. data11 = data2[(data2['publishDate'] < '20120101') & (data2['publishDate'] >= '20110101')]
  71. data11.drop_duplicates('secID' , inplace = True)
  72. list2.append(len(data11))
  73. data12 = data2[(data2['publishDate'] < '20130101') & (data2['publishDate'] >= '20120101')]
  74. data12.drop_duplicates('secID' , inplace = True)
  75. list2.append(len(data12))
  76. data13 = data2[(data2['publishDate'] < '20140101') & (data2['publishDate'] >= '20130101')]
  77. data13.drop_duplicates('secID' , inplace = True)
  78. list2.append(len(data13))
  79. data14 = data2[(data2['publishDate'] < '20150101') & (data2['publishDate'] >= '20140101')]
  80. data14.drop_duplicates('secID' , inplace = True)
  81. list2.append(len(data14))
  82. data15 = data2[(data2['publishDate'] < '20160101') & (data2['publishDate'] >= '20150101')]
  83. data15.drop_duplicates('secID' , inplace = True)
  84. list2.append(len(data15))
  • 红柱表示年间发布过业绩预告的公司数量
  • 黄柱表示年间发布过盈利预增的公司数量
  1. # plot Statistics
  2. import numpy as np
  3. import matplotlib.pyplot as plt
  4. N = 9
  5. ind = np.arange(N)
  6. width = 0.35
  7. fig = plt.figure(figsize=(12,12))
  8. ax = fig.add_subplot(211)
  9. rects1 = ax.bar(ind, list1, width, color='r')
  10. rects2 = ax.bar(ind+width, list2, width, color='y')
  11. # add some
  12. ax.set_ylabel('Number')
  13. ax.set_title('Statistics A shares')
  14. ax.set_xticks(ind+width)
  15. ax.set_xticklabels( ('2007', '2008', '2009', '2010', '2011','2012','2013','2014','2015/11') )
  16. ax.legend((rects1[0], rects2[0]), ('ALL', 'Profit_inc') , loc = '1')
  17. def autolabel(rects):
  18. # attach some text labels
  19. for rect in rects:
  20. height = rect.get_height()
  21. ax.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),
  22. ha='center', va='bottom')
  23. autolabel(rects1)
  24. autolabel(rects2)
  25. plt.show()

盈利预增事件 - 图2

  • 构造一个事件驱动策略看下盈利预增效应是否长期有效

  • 策略思想 : 以企业净利润预增预报为事件驱动,卖出同期持仓(上个换仓期到本次换仓)中收益率最low的股票,买入盈利预增的股票。

  • 回测区间 : 07年 —— 今

  1. import pandas as pd
  2. import numpy as np
  3. from CAL.PyCAL import *
  4. from pandas import DataFrame,Series
  5. from datetime import datetime, timedelta
  6. start = '20070801' # 回测起始时间
  7. end = (datetime.today() - timedelta(days=1)).strftime('%Y%m%d') # 截止日期
  8. benchmark = 'HS300' # 策略参考标准
  9. universe = set_universe('HS300') # 证券池,支持股票和基金
  10. capital_base = 1000000 # 起始资金
  11. freq = 'd' # 策略类型,'d'表示日间策略使用日线回测,'m'表示日内策略使用分钟线回测
  12. refresh_rate = 1 # 调仓频率,表示执行handle_data的时间间隔,若freq = 'd'时间间隔的单位为交易日,若freq = 'm'时间间隔为分钟
  13. cal = Calendar('China.SSE')
  14. def initialize(account): # 初始化虚拟账户状态
  15. account.last_refreshtime = start
  16. def handle_data(account): # 每个交易日的买入卖出指令
  17. today = account.current_date.strftime('%Y%m%d')
  18. yesterday = cal.advanceDate(account.current_date, '-1B', BizDayConvention.Following).strftime('%Y%m%d')
  19. last_day = (account.current_date - timedelta(days=1)).strftime('%Y%m%d')
  20. yester_refresh_day = cal.advanceDate(account.current_date, '-62B' , BizDayConvention.Following).strftime('%Y%m%d')
  21. total_money = account.referencePortfolioValue
  22. prices = account.referencePrice
  23. buylist =[]
  24. # 去除新上市或复牌的股票
  25. opn = account.get_attribute_history('openPrice', 1)
  26. account.universe = [s for s in account.universe if not (np.isnan(opn.get(s, 0)[0]) or opn.get(s, 0)[0] == 0 )]
  27. # 初始建仓(选当前净利润最高的20只股票):
  28. if len(account.valid_secpos) == 0 :
  29. # 净利润增长率
  30. NetProfitGrowRate = DataAPI.MktStockFactorsOneDayGet(tradeDate=yesterday,secID=account.universe,field=u"secID,NetProfitGrowRate",pandas="1")
  31. NetProfitGrowRate = NetProfitGrowRate.sort('NetProfitGrowRate',ascending = False).drop_duplicates('secID')
  32. buylist = list(NetProfitGrowRate['secID'].values[0:20])
  33. for s in buylist :
  34. order_to(s, int(total_money*0.99/len(buylist)/prices[s]/100)*100)
  35. account.last_refreshtime = today
  36. return
  37. # 获取业绩预增的股票,最多取20只
  38. try :
  39. temp = DataAPI.FdmtEfGet(secID = account.universe , forecastType ='22',publishDateBegin= yesterday , publishDateEnd = last_day , field=['secID','publishDate','NIncAPChgrLL', 'NIncAPChgrUPL'],pandas="1")
  40. temp['meanGrowRate'] = (temp['NIncAPChgrLL'] + temp['NIncAPChgrUPL']) / 2
  41. temp.sort('meanGrowRate', ascending=False).drop_duplicates('secID' ,inplace = True)
  42. buylist = list(temp['secID'].values[0:20])
  43. except :
  44. return
  45. change_stock = [x for x in account.valid_secpos if x not in buylist]
  46. buylist = [x for x in buylist if x not in account.valid_secpos]
  47. # 换仓
  48. price1 = DataAPI.MktEqudAdjGet(secID=change_stock, tradeDate=account.last_refreshtime , field=u"secID,openPrice",pandas="1")
  49. price2 = DataAPI.MktEqudAdjGet(secID=change_stock, tradeDate=yesterday , field=u"secID,closePrice",pandas="1")
  50. # 计算持仓股这段时间的涨幅
  51. price1['stock_returns'] = price2['closePrice'] / price1['openPrice']
  52. price1.sort('stock_returns',ascending = True,inplace = True)
  53. # 剔除上个换仓日到现在最挫的股票 :
  54. sell_list = price1['secID'].values[0:len(buylist)]
  55. for s in sell_list :
  56. account.cash += prices[s] * account.valid_secpos.get(s)
  57. order_to(s,0)
  58. for s in buylist :
  59. order(s, int(account.cash / len(buylist)/prices[s]/100)*100)
  60. #更变最新调仓日期
  61. account.last_refreshtime = today

盈利预增事件 - 图3

  • 从回测结果来看业绩预增事件在熊市中效应并不显著,12年以前跑得也没之后的好。
  • 从统计数据来看,07年后逐年有更多的上市公司以业绩预告的方式与公司股东进行互动交流,股民朋友们也越来越注重业绩预告,并在二级市场给予及时的回应。
  • 呀!才发现回测有新功能了——回测详情,有更多统计信息了!!!好棒!
  • PS:从回测详情看好多业绩预增的公司报告发布后第二天开板涨停啊!看回测详情数据~新技能get.