PDF下载 下载

多因子选股(股票)

阅读 29469
  1. # coding=utf-8
  2. from __future__ import print_function, absolute_import, unicode_literals
  3. import numpy as np
  4. from gm.api import *
  5. from pandas import DataFrame
  6. '''
  7. 本策略每隔1个月定时触发,根据Fama-French三因子模型对每只股票进行回归,得到其alpha值。
  8. 假设Fama-French三因子模型可以完全解释市场,则alpha为负表明市场低估该股,因此应该买入。
  9. 策略思路:
  10. 计算市场收益率、个股的账面市值比和市值,并对后两个进行了分类,
  11. 根据分类得到的组合分别计算其市值加权收益率、SMB和HML.
  12. 对各个股票进行回归(假设无风险收益率等于0)得到alpha值.
  13. 选取alpha值小于0并为最小的10只股票进入标的池
  14. 平掉不在标的池的股票并等权买入在标的池的股票
  15. 回测数据:SHSE.000300的成份股
  16. 回测时间:2017-07-01 08:00:00到2017-10-01 16:00:00
  17. '''
  18. def init(context):
  19. # 每月第一个交易日的09:40 定时执行algo任务
  20. schedule(schedule_func=algo, date_rule='1m', time_rule='09:40:00')
  21. # 数据滑窗
  22. context.date = 20
  23. # 设置开仓的最大资金量
  24. context.ratio = 0.8
  25. # 账面市值比的大/中/小分类
  26. context.BM_BIG = 3.0
  27. context.BM_MID = 2.0
  28. context.BM_SMA = 1.0
  29. # 市值大/小分类
  30. context.MV_BIG = 2.0
  31. context.MV_SMA = 1.0
  32. # 计算市值加权的收益率,MV为市值的分类,BM为账目市值比的分类
  33. def market_value_weighted(stocks, MV, BM):
  34. select = stocks[(stocks.NEGOTIABLEMV == MV) & (stocks.BM == BM)]
  35. market_value = select['mv'].values
  36. mv_total = np.sum(market_value)
  37. mv_weighted = [mv / mv_total for mv in market_value]
  38. stock_return = select['return'].values
  39. # 返回市值加权的收益率的和
  40. return_total = []
  41. for i in range(len(mv_weighted)):
  42. return_total.append(mv_weighted[i] * stock_return[i])
  43. return_total = np.sum(return_total)
  44. return return_total
  45. def algo(context):
  46. # 获取上一个交易日的日期
  47. last_day = get_previous_trading_date(exchange='SHSE', date=context.now)
  48. # 获取沪深300成份股
  49. context.stock300 = get_history_constituents(index='SHSE.000300', start_date=last_day,
  50. end_date=last_day)[0]['constituents'].keys()
  51. # 获取当天有交易的股票
  52. not_suspended = get_history_instruments(symbols=context.stock300, start_date=last_day, end_date=last_day)
  53. not_suspended = [item['symbol'] for item in not_suspended
  54. if not item['is_suspended'] and item['symbol']!= 'SHSE.601313'] # 601313 为退市股票
  55. fin = get_fundamentals(table='trading_derivative_indicator', symbols=not_suspended,
  56. start_date=last_day, end_date=last_day,fields='PB,NEGOTIABLEMV', df=True)
  57. # 计算账面市值比,为P/B的倒数
  58. fin['PB'] = (fin['PB'] ** -1)
  59. # 计算市值的50%的分位点,用于后面的分类
  60. size_gate = fin['NEGOTIABLEMV'].quantile(0.50)
  61. # 计算账面市值比的30%和70%分位点,用于后面的分类
  62. bm_gate = [fin['PB'].quantile(0.30), fin['PB'].quantile(0.70)]
  63. fin.index = fin.symbol
  64. x_return = []
  65. # 对未停牌的股票进行处理
  66. for symbol in not_suspended:
  67. # 计算收益率
  68. close = history_n(symbol=symbol, frequency='1d', count=context.date + 1, end_time=last_day, fields='close',
  69. skip_suspended=True, fill_missing='Last', adjust=ADJUST_PREV, df=True)['close'].values
  70. stock_return = close[-1] / close[0] - 1
  71. pb = fin['PB'][symbol]
  72. market_value = fin['NEGOTIABLEMV'][symbol]
  73. # 获取[股票代码. 股票收益率, 账面市值比的分类, 市值的分类, 流通市值]
  74. if pb < bm_gate[0]:
  75. if market_value < size_gate:
  76. label = [symbol, stock_return, context.BM_SMA, context.MV_SMA, market_value]
  77. else:
  78. label = [symbol, stock_return, context.BM_SMA, context.MV_BIG, market_value]
  79. elif pb < bm_gate[1]:
  80. if market_value < size_gate:
  81. label = [symbol, stock_return, context.BM_MID, context.MV_SMA, market_value]
  82. else:
  83. label = [symbol, stock_return, context.BM_MID, context.MV_BIG, market_value]
  84. elif market_value < size_gate:
  85. label = [symbol, stock_return, context.BM_BIG, context.MV_SMA, market_value]
  86. else:
  87. label = [symbol, stock_return, context.BM_BIG, context.MV_BIG, market_value]
  88. if len(x_return) == 0:
  89. x_return = label
  90. else:
  91. x_return = np.vstack([x_return, label])
  92. stocks = DataFrame(data=x_return, columns=['symbol', 'return', 'BM', 'NEGOTIABLEMV', 'mv'])
  93. stocks.index = stocks.symbol
  94. columns = ['return', 'BM', 'NEGOTIABLEMV', 'mv']
  95. for column in columns:
  96. stocks[column] = stocks[column].astype(np.float64)
  97. # 计算SMB.HML和市场收益率
  98. # 获取小市值组合的市值加权组合收益率
  99. smb_s = (market_value_weighted(stocks, context.MV_SMA, context.BM_SMA) +
  100. market_value_weighted(stocks, context.MV_SMA, context.BM_MID) +
  101. market_value_weighted(stocks, context.MV_SMA, context.BM_BIG)) / 3
  102. # 获取大市值组合的市值加权组合收益率
  103. smb_b = (market_value_weighted(stocks, context.MV_BIG, context.BM_SMA) +
  104. market_value_weighted(stocks, context.MV_BIG, context.BM_MID) +
  105. market_value_weighted(stocks, context.MV_BIG, context.BM_BIG)) / 3
  106. smb = smb_s - smb_b
  107. # 获取大账面市值比组合的市值加权组合收益率
  108. hml_b = (market_value_weighted(stocks, context.MV_SMA, 3) +
  109. market_value_weighted(stocks, context.MV_BIG, context.BM_BIG)) / 2
  110. # 获取小账面市值比组合的市值加权组合收益率
  111. hml_s = (market_value_weighted(stocks, context.MV_SMA, context.BM_SMA) +
  112. market_value_weighted(stocks, context.MV_BIG, context.BM_SMA)) / 2
  113. hml = hml_b - hml_s
  114. close = history_n(symbol='SHSE.000300', frequency='1d', count=context.date + 1,
  115. end_time=last_day, fields='close', skip_suspended=True,
  116. fill_missing='Last', adjust=ADJUST_PREV, df=True)['close'].values
  117. market_return = close[-1] / close[0] - 1
  118. coff_pool = []
  119. # 对每只股票进行回归获取其alpha值
  120. for stock in stocks.index:
  121. x_value = np.array([[market_return], [smb], [hml], [1.0]])
  122. y_value = np.array([stocks['return'][stock]])
  123. # OLS估计系数
  124. coff = np.linalg.lstsq(x_value.T, y_value)[0][3]
  125. coff_pool.append(coff)
  126. # 获取alpha最小并且小于0的10只的股票进行操作(若少于10只则全部买入)
  127. stocks['alpha'] = coff_pool
  128. stocks = stocks[stocks.alpha < 0].sort_values(by='alpha').head(10)
  129. symbols_pool = stocks.index.tolist()
  130. positions = context.account().positions()
  131. # 平不在标的池的股票
  132. for position in positions:
  133. symbol = position['symbol']
  134. if symbol not in symbols_pool:
  135. order_target_percent(symbol=symbol, percent=0, order_type=OrderType_Market,
  136. position_side=PositionSide_Long)
  137. print('市价单平不在标的池的', symbol)
  138. # 获取股票的权重
  139. percent = context.ratio / len(symbols_pool)
  140. # 买在标的池中的股票
  141. for symbol in symbols_pool:
  142. order_target_percent(symbol=symbol, percent=percent, order_type=OrderType_Market,
  143. position_side=PositionSide_Long)
  144. print(symbol, '以市价单调多仓到仓位', percent)
  145. if __name__ == '__main__':
  146. '''
  147. strategy_id策略ID,由系统生成
  148. filename文件名,请与本文件名保持一致
  149. mode实时模式:MODE_LIVE回测模式:MODE_BACKTEST
  150. token绑定计算机的ID,可在系统设置-密钥管理中生成
  151. backtest_start_time回测开始时间
  152. backtest_end_time回测结束时间
  153. backtest_adjust股票复权方式不复权:ADJUST_NONE前复权:ADJUST_PREV后复权:ADJUST_POST
  154. backtest_initial_cash回测初始资金
  155. backtest_commission_ratio回测佣金比例
  156. backtest_slippage_ratio回测滑点比例
  157. '''
  158. run(strategy_id='strategy_id',
  159. filename='main.py',
  160. mode=MODE_BACKTEST,
  161. token='token_id',
  162. backtest_start_time='2017-07-01 08:00:00',
  163. backtest_end_time='2017-10-01 16:00:00',
  164. backtest_adjust=ADJUST_PREV,
  165. backtest_initial_cash=10000000,
  166. backtest_commission_ratio=0.0001,
  167. backtest_slippage_ratio=0.0001)

多因子选股(股票)

0 篇笔记