bfiMatcher.dos 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. module fundit::bfiMatcher
  2. use fundit::sqlUtilities;
  3. use fundit::operationDataPuller;
  4. use fundit::performanceDataPuller;
  5. use fundit::dataSaver;
  6. /*
  7. * 返回预设的指标最小值
  8. *
  9. * NOTE: 对数据量的要求, Java 计算coe相关性表时用48,但计算bfi时用10,这里统一用10
  10. *
  11. */
  12. def get_min_threshold(data_name) {
  13. d = dict(STRING, FLOAT);
  14. d['correlation'] = 0.64;
  15. d['data_count'] = 10;
  16. d['beta'] = 0.64;
  17. d['t_value'] = 2.58;
  18. d['r2'] = 0.64;
  19. d['r2_neutral'] = 0.04;
  20. return d[data_name];
  21. }
  22. /*
  23. * T-value 的聚合函数版
  24. *
  25. */
  26. defg regressionT(y, x) {
  27. r = SELECT beta, tstat FROM ols(y, x, true, 1) WHERE rowNo(beta) = 1;
  28. return r[0]['tstat'];
  29. }
  30. /*
  31. * 计算 correlation & bfi-matching 所需要的数据指标(周数据计算,返回月度结果)
  32. *
  33. * NOTE: 与 Java BFI 不同,这里为了与RBSA保持统一,用收益率来计算相关性;转化成月度时用了各周平均值
  34. */
  35. def cal_monthly_closity0(nav1, nav2, win) {
  36. n1 = nav1;
  37. n1.sortBy!(['entity_id', 'price_date'], [1, 1]);
  38. n2 = nav2;
  39. n2.sortBy!(['benchmark_id', 'price_date'], [1, 1]);
  40. t0 = SELECT entity_id, end_date, n1.price_date, n1.nav AS nav1, n1.nav.ratios()-1 AS ret1,
  41. n2.nav AS nav2, n2.nav.ratios()-1 AS ret2, tmoving(count, end_date, end_date, win) AS data_count
  42. FROM n1
  43. INNER JOIN n2 ON n1.end_date = n2.end_date
  44. ORDER BY end_date;
  45. t = SELECT entity_id, end_date, price_date,
  46. tmcorr(t0.end_date, ret1, ret2, win) AS corr,
  47. iif(tmstd(end_date, ret1-ret2, win) == 0, null, tmavg(end_date, ret1-ret2, win)\tmstd(end_date, ret1-ret2, win)) AS info, // 貌似没用
  48. iif(data_count >= get_min_threshold('data_count'), tmoving(regressionT, end_date, [ret1, ret2], win), double(NULL)) AS t_value,
  49. iif(data_count >= get_min_threshold('data_count'), tmbeta(end_date, ret1, ret2, win), double(NULL)) AS beta // 用 ols() 算的值和这个一样
  50. FROM t0
  51. ORDER BY price_date;
  52. // 将每月各周的数据平均值作为月度数据返回
  53. return SELECT entity_id, price_date.month().last() AS end_date, price_date.last() AS price_date,
  54. corr.avg() AS corr,
  55. info.avg() AS info,
  56. t_value.avg() AS t_value,
  57. beta.avg() AS beta
  58. FROM t
  59. GROUP BY entity_id, price_date.month();
  60. }
  61. /*
  62. * 计算 correlation & bfi-matching 所需要的数据指标(周数据计算,返回月度结果)
  63. *
  64. * NOTE: 与 Java BFI 不同,这里为了与RBSA保持统一,用收益率来计算相关性;转化成月度时用了各周平均值
  65. */
  66. def cal_monthly_closity(entity, nav1, nav2, win) {
  67. n1 = nav1;
  68. n1.sortBy!(['entity_id', 'price_date'], [1, 1]);
  69. n2 = nav2;
  70. n2.sortBy!(['benchmark_id', 'price_date'], [1, 1]);
  71. t_dates = SELECT entity_id, end_date FROM nav1 WHERE end_date >= entity.price_date.weekEnd();
  72. t0 = SELECT entity_id, end_date, n1.price_date, n1.nav AS nav1, n1.nav.ratios()-1 AS ret1,
  73. n2.nav AS nav2, n2.nav.ratios()-1 AS ret2, tmoving(count, end_date, end_date, win) AS data_count
  74. FROM n1
  75. INNER JOIN n2 ON n1.end_date = n2.end_date
  76. ORDER BY end_date;
  77. t_rt = table(100:0, ['entity_id', 'end_date', 'price_date', 'corr', 'info', 't_value', 'beta'],
  78. [entity.entity_id.type(), MONTH, DATE, DOUBLE, DOUBLE, DOUBLE, DOUBLE]);
  79. for(dt in t_dates.end_date) {
  80. if( (EXEC data_count FROM t0 WHERE end_date = dt)[0] >= get_min_threshold('data_count') ){
  81. rets = EXEC ret1, ret2 FROM t0 WHERE end_date BETWEEN(dt.temporalAdd(duration('-' + win$STRING)):dt);
  82. cor = corr(rets.ret1, rets.ret2);
  83. info = mean(rets.ret1 - rets.ret2) \ std(rets.ret1 - rets.ret2); // 貌似没用
  84. t_value = regressionT(rets.ret1, rets.ret2);
  85. bta = beta(rets.ret1, rets.ret2); // 用 ols() 算的值和这个一样
  86. INSERT INTO t_rt VALUES (entity.entity_id, dt, entity.price_date, cor, info, t_value, bta);
  87. }
  88. }
  89. // 将每月各周的数据平均值作为月度数据返回
  90. return SELECT entity_id, price_date.month().last() AS end_date, price_date.last() AS price_date,
  91. corr.avg() AS corr,
  92. info.avg() AS info,
  93. t_value.avg() AS t_value,
  94. beta.avg() AS beta
  95. FROM t_rt
  96. GROUP BY entity_id, price_date.month();
  97. }
  98. /*
  99. * 计算目标和各资产类别指数及BFI因子的累计净值相关系数
  100. *
  101. * @param entity_info <TABLE>: [COLUMNS] entity_id, price_date
  102. *
  103. * NOTE: 整合 Java中 TampCalcCorrelationServiceImpl 和 BestFitIndexServiceImpl 做的计算, 但只支持周数据计算
  104. *
  105. * Example: cal_entity_index_coe('MF', get_fund_info(['MF00003PW1', 'MF00003PW2', 'MF00003RZI']).join(take(2024.09.30, 3) AS price_date).rename!('fund_id', 'entity_id'));
  106. * cal_entity_index_coe('PF', get_portfolio_info([166002]).join(take(2024.09.30, 1) AS price_date).rename!('portfolio_id', 'entity_id'));
  107. *
  108. */
  109. def cal_entity_index_coe(entity_type, entity_info) {
  110. // entity_type = 'PF'
  111. // entity_info = get_portfolio_info([166002]).join(take(2024.09.30, 1) AS price_date).rename!('portfolio_id', 'entity_id');
  112. // entity_type = 'MF'
  113. // entity_info = get_fund_info(['MF00003PW1', 'MF00003PW2', 'MF00003RZI']).join(take(2024.09.30, 3) AS price_date).rename!('fund_id', 'entity_id');
  114. // entity_info = tb_cal_entity[i : min(size, i+batch_size)]
  115. // entity_type = 'HF'
  116. // entity_info = get_fund_info(['HF0000A134', 'HF0000A12R', 'HF00017JVX']).join(take(2024.05.30, 3) AS price_date).rename!('fund_id', 'entity_id');
  117. if(entity_info.isVoid() || entity_info.size() == 0) return null;
  118. // 取数据集中最早日期作为因子的起始日期
  119. start_day = entity_info.price_date.min();
  120. // 取数据集每个基金组合指定日期之前5年至今的周净值
  121. s_json = (SELECT entity_id AS sec_id, price_date.temporalAdd(-5y) AS price_date FROM entity_info).toStdJson();
  122. nav_entity = get_nav_for_return_calculation(entity_type, 'w', s_json);
  123. if(nav_entity.isVoid() || nav_entity.size() == 0) return null;
  124. // 取相关性计算及BFI用得到的指数/因子列表
  125. // 只有基金需要单独做相关性计算,目的是为基金推荐做数据准备
  126. if(entity_type in ('MF', 'HF'))
  127. v_indexes = (get_bfi_index_list().factor_id <- get_correlation_index_list().entity_id).distinct();
  128. else {
  129. v_indexes = get_bfi_index_list().factor_id;
  130. // Portfolio_id 改回整型
  131. v_port_id = nav_entity.sec_id$INT;
  132. nav_entity.replaceColumn!('sec_id', v_port_id);
  133. }
  134. s_json2 = table(v_indexes AS sec_id, take(start_day.temporalAdd(-5y), v_indexes.size()) AS price_date).toStdJson();
  135. // 取指数及因子周点位
  136. nav_index = get_nav_for_return_calculation('FA', 'w', s_json2).unionAll(get_nav_for_return_calculation('MI', 'w', s_json2));
  137. if(nav_index.isVoid() || nav_index.size() == 0) return null;
  138. // 按照SQL 建表
  139. entity_coe = create_entity_index_coe();
  140. // 两次循环遍历所有entity和指数
  141. for(entity in entity_info) {
  142. //entity= entity_info[0]
  143. nav1 = SELECT sec_id AS entity_id, weekEnd(price_date) AS end_date, price_date, nav
  144. FROM nav_entity WHERE sec_id = entity.entity_id;
  145. for(index in v_indexes) {
  146. //index=v_indexes[0]
  147. nav2 = SELECT sec_id AS benchmark_id, weekEnd(price_date) AS end_date, price_date, nav
  148. FROM nav_index WHERE sec_id = index;
  149. if(nav2.isVoid() || nav2.size() == 0) continue; // 忽略已经停止更新的指数,或者是特殊的无风险利率 IN0000000M
  150. closity_1y = cal_monthly_closity(entity, nav1, nav2, 1y);
  151. closity_3y = cal_monthly_closity(entity, nav1, nav2, 3y);
  152. closity_5y = cal_monthly_closity(entity, nav1, nav2, 5y);
  153. INSERT INTO entity_coe
  154. SELECT c1.entity_id, c1.end_date, index,
  155. c1.corr AS coe_1y, c3.corr AS coe_3y, c5.corr AS coe_5y,
  156. //c1.corr2 AS coe_1y_2, c3.corr2 AS coe_3y_2, c5.corr2 AS coe_5y_2,
  157. c1.info AS info_ratio_1y, c3.info AS info_ratio_3y, c5.info AS info_ratio_5y,
  158. c1.t_value AS t_value_1y, c3.t_value AS t_value_3y, c5.t_value AS t_value_5y,
  159. c1.beta AS beta_1y, c3.beta AS beta_3y, c5.beta AS beta_5y
  160. FROM closity_1y c1
  161. LEFT JOIN closity_3y c3 ON c1.end_date = c3.end_date
  162. LEFT JOIN closity_5y c5 ON c1.end_date = c5.end_date;
  163. }
  164. }
  165. return entity_coe;
  166. }
  167. /*
  168. * 匹配BFI, 逻辑和 Java BestFitIndexServiceImpl 类似
  169. *
  170. * @param entity_info <TABLE>: [COLUMNS] entity_id, strategy
  171. * @param entity_coe <TABLE>: [COLUMNS] entity_id, end_date, index_id, coe_1y, t_value_1y, beta_1y
  172. *
  173. * NOTE: Java 中的 rule2 还包括 FA00000VN7 (100%中证全指 IN0000007N) 是不对的,而且漏掉了CTA和FOF。已将DEV数据库中此因子划入category_group 74;另外找r2最小的因子也离谱
  174. * rule3 FA00000VMX (100%中证转债 中证转债)漏掉了公募债券(FOF, 相对价值(套利),多策略,公募混合是否要加?怕会和股票打架,待研究)
  175. *
  176. UPDATE pfdb.`cm_factor_information`
  177. SET category_group_id = 74, category='全市场', factor_name='全市场', category_group='规模', strategy=',101,102,103,107,', maximum_num=1, updaterid=123, updatetime='2024-11-25'
  178. WHERE factor_id = 'FA00000VN7';
  179. UPDATE pfdb.`cm_factor_information`
  180. SET category_group_id = 78, category_group='配置', maximum_num=1, updaterid=123, updatetime='2024-11-25'
  181. WHERE factor_id = 'FA00000VNB' AND category_group_id = 80;
  182. UPDATE pfdb.`cm_factor_information`
  183. SET category_group_id = 78, category_group='配置', maximum_num=1, updaterid=123, updatetime='2024-11-25'
  184. WHERE factor_id = 'FA00000VND' AND category_group_id = 76;
  185. *
  186. */
  187. def match_entity_bfi(entity_type, entity_info, entity_coe) {
  188. // 特殊因子:现金,可被应用于所有策略
  189. v_factor_cash = ['FA000000MJ'];
  190. //有一些特殊的因子只会被部分策略所用, 否则会引起歧义
  191. v_factor_1 = ['FA00000VMY', 'FA00000VMZ', 'FA00000VN0', 'FA00000VN1', 'FA00000VN2', 'FA00000VN3', 'FA00000VN4', 'FA00000VN5', 'FA00000VN6'];
  192. v_strategy_1 = [3, 7, 8, 105]; // 私募CTA, 私募FOF, 私募多策略, 公募商品
  193. v_factor_2 = ['FA00000SMB', 'FA00000VMG'];
  194. v_strategy_2 = [1, 3, 5, 7, 8]; // 私募股票(多空),CTA, 相对价值,私募FOF, 私募多策略
  195. v_factor_3 = ['FA00000VMX'];
  196. v_strategy_3 = [6, 103]; // 私募固收,公募债券
  197. // 只需要BFI因子的相关性数据
  198. coe = SELECT *
  199. FROM ej(entity_info, ej(entity_coe, get_bfi_index_list(), 'index_id', 'factor_id'), 'entity_id')
  200. ORDER BY entity_id, end_date, category_group_id, coe_1y DESC, order_id;
  201. t_bfi_raw = table(1000:0,
  202. ['entity_id', 'end_date', 'category_group_id', 'factor_id', 'rank', 'coe_1y', 'r2',
  203. //'rank2', 'coe_1y_2', 'r2_2',
  204. 'performance_flag', 't_value_1y', 'beta_1y', 'maximum_num', 'order_id', 'factor_name'],
  205. [iif(entity_type=='PF', INT, SYMBOL), MONTH, SHORT, SYMBOL, SHORT, DOUBLE, DOUBLE,
  206. //SHORT, DOUBLE, DOUBLE,
  207. STRING, DOUBLE, DOUBLE, SHORT, SHORT, STRING]);
  208. // 首先处理特殊情况 TODO: java treats rule2 differently by finding min R2 without checking t_value & corr
  209. v_special_rule = [v_factor_1, v_factor_2, v_factor_3];
  210. v_special_strategy = [v_strategy_1, v_strategy_2, v_strategy_3];
  211. for(i in 0..v_special_rule.size()-1) {
  212. INSERT INTO t_bfi_raw
  213. SELECT * FROM (
  214. SELECT entity_id, end_date, category_group_id, index_id AS factor_id,
  215. coe_1y.rank(false) AS rank, coe_1y, square(coe_1y) AS r2,
  216. 'w', t_value_1y, beta_1y,
  217. maximum_num, order_id, factor_name
  218. FROM entity_info ei
  219. INNER JOIN coe ON ei.entity_id = coe.entity_id
  220. WHERE ei.strategy IN v_special_strategy[i]
  221. AND coe.index_id IN v_special_rule[i].join(v_factor_cash)
  222. AND t_value_1y >= get_min_threshold('t_value')
  223. AND coe_1y >= get_min_threshold('correlation')
  224. AND order_id IS NOT NULL
  225. CONTEXT BY entity_id, end_date, category_group_id )
  226. WHERE rank < maximum_num;
  227. DELETE FROM coe WHERE index_id IN v_special_rule[i];
  228. }
  229. INSERT INTO t_bfi_raw
  230. SELECT * FROM (
  231. SELECT entity_id, end_date, category_group_id, index_id AS factor_id,
  232. coe_1y.rank(false) AS rank, coe_1y, square(coe_1y) AS r2,
  233. 'w', t_value_1y, beta_1y,
  234. maximum_num, order_id, factor_name
  235. FROM entity_info ei
  236. INNER JOIN coe ON ei.entity_id = coe.entity_id
  237. WHERE t_value_1y >= get_min_threshold('t_value')
  238. AND coe_1y >= get_min_threshold('correlation')
  239. AND order_id IS NOT NULL
  240. CONTEXT BY entity_id, end_date, category_group_id )
  241. WHERE rank < maximum_num;
  242. return SELECT * FROM t_bfi_raw ORDER BY entity_id, end_date, category_group_id;
  243. }