navCalculator.dos 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. module fundit::navCalculator
  2. use fundit::sqlUtilities
  3. use fundit::operationDataPuller
  4. use fundit::performanceDataPuller
  5. use fundit::portfolioDataPuller
  6. /*
  7. * 转交易表为交易日的持仓截面表
  8. * NOTE: 假定所有基金证券都是T+1买入,也就是第一天没有收益
  9. * 返回每个有交易的日期,以及当天会被纳入净值收益计算的各持仓份额(比如买入基金当天的份额数为0,卖出基金当天的份额是卖前份额)
  10. *
  11. * Example: convert_transaction_to_snapshot("166002,166114", 2024.10.31);
  12. */
  13. def convert_transaction_to_snapshot(portfolio_ids, end_day) {
  14. s_portfolio_ids = ids_to_string(portfolio_ids);
  15. // 取数据库中的持仓交易表
  16. tb_transaction = get_portfolio_holding_history(s_portfolio_ids);
  17. // 所有交易日期
  18. tb_date = SELECT DISTINCT portfolio_id, holding_date FROM tb_transaction;
  19. // 所有基金证券id
  20. tb_id = SELECT DISTINCT portfolio_id, fund_id FROM tb_transaction;
  21. tmp = SELECT tb_date.portfolio_id, tb_date.holding_date, tb_id.fund_id FROM ej(tb_date, tb_id, 'portfolio_id');
  22. // 取各交易日期时的持仓截面, Window Join 的上限设成-1d 是因为买入基金当日无收益,所以计算份额时要排除掉
  23. tb = wj(tmp, tb_transaction.sortBy!('holding_date'), duration('-50y'):duration('-1d'), <[t.fund_share.sum() AS shares]>, ['portfolio_id', 'fund_id', 'holding_date']);
  24. tb.addColumn('nav', DOUBLE);
  25. // 买入的基金份额记为0, 保留原始买入净值
  26. UPDATE tb
  27. SET shares = 0, nav = tb_transaction.nav
  28. FROM ej(tb, tb_transaction, ['portfolio_id', 'holding_date', 'fund_id'],, isNull(tb.shares));
  29. // 删除没用的数据;防一手脏数据
  30. DELETE FROM tb WHERE shares IS NULL OR shares.round(0) < 0;
  31. // 补上个虚拟的未来截面,以免buy-n-hold的证券信息损失;用0当NAV也是没办法,DolphinDB不能SELECT出个全NULL的列
  32. INSERT INTO tb
  33. SELECT portfolio_id, end_day, fund_id, fund_share.sum(), 0
  34. FROM tb_transaction
  35. GROUP BY portfolio_id, fund_id
  36. HAVING fund_share.sum().round(0) > 0;
  37. return tb.sortBy!(['portfolio_id', 'holding_date', 'fund_id'], [1, 1, 1]);
  38. }
  39. /*
  40. * 通用净值计算,由收益反推
  41. *
  42. * @param entity_type <STRING>:
  43. * @param entity_ret <TABLE>: [COLUMNS] entity_id, price_date, ret
  44. * @param freq <STRING>: d, w, m
  45. *
  46. * NOTE: 如果没有成立日,则无法计算
  47. */
  48. def cal_entity_nav_by_return(entity_type, entity_ret, freq) {
  49. t_nav = table(1000:0, ['entity_id', 'price_date', 'ret', 'nav' ], [iif(entity_type=='PF', INT, SYMBOL), DATE, DOUBLE, DOUBLE]);
  50. if(entity_ret.isVoid() || entity_ret.size() == 0) return t_nav;
  51. t_entity_info = get_entity_info(entity_type, entity_ret.entity_id.distinct());
  52. UPDATE t_entity_info SET inception_date = 1900.01.01 WHERE inception_date IS NULL;
  53. // 筛掉早于成立日的脏数据
  54. t_ret = SELECT * FROM ej(entity_ret, t_entity_info, 'entity_id') WHERE price_date >= inception_date;
  55. s_json = (SELECT entity_id.last() AS sec_id, price_date.min() AS price_date FROM t_ret GROUP BY entity_id).toStdJson();
  56. // 取净值前值
  57. t_pre_nav = get_nav_for_return_calculation(entity_type, freq, s_json, 1);
  58. INSERT INTO t_nav
  59. SELECT entity_id, price_date, ret, double(NULL) FROM t_ret;
  60. // 设置成立日当天的净值和收益
  61. UPDATE t_nav
  62. SET nav = ini_value, ret = NULL
  63. FROM ej(t_nav, t_entity_info, ['entity_id', 'price_date'], ['entity_id', 'inception_date']);
  64. // 没有前值时,做一个假记录,把成立日净值和日期填入
  65. INSERT INTO t_pre_nav
  66. SELECT entity_id AS sec_id, price_date, nav AS cumulative_nav, nav
  67. FROM t_nav
  68. WHERE nav > 0
  69. AND NOT exists ( SELECT * FROM tb_pre_nav
  70. WHERE t_nav.entity_id = tb_pre_nav.sec_id );
  71. // 通过收益反算净值: nav_i = nav_0 * ∏(1 + ret_i)
  72. UPDATE t_nav
  73. SET nav = (t_pre_nav.cumulative_nav * (1+ret).cumprod()).round(6)
  74. FROM ej(t_nav, t_pre_nav, 'entity_id', 'sec_id')
  75. CONTEXT BY entity_id;
  76. return t_nav;
  77. }
  78. /*
  79. * 根据持仓收益计算组合净值
  80. *
  81. * @param entity_cal_dates <TABLE>: 组合净值计算时间区间表,记录 [COLUMNS] entity_id, first_cal_date, latest_cal_date
  82. * @parm holdings <TABLE>:带有各证券净值前值的截面持仓表 [COLUMNS] entity_id, price_date, sec_id, ret, weight
  83. *
  84. * @return <TABLE>: [COLUMNS] entity_id, price_date, ret
  85. */
  86. def cal_nav_by_return(entity_type, entity_cal_dates, holdings) {
  87. // entity_type = 'PF'
  88. // entity_cal_dates=tb_port_first_cal_date
  89. // holdings = tb_holdings
  90. // 组合收益计算: RET = ∑( weight_i * ret_i )
  91. tb_portfolio_ret = SELECT entity_id, price_date, (weight * ret).sum() AS ret
  92. FROM holdings
  93. GROUP BY entity_id, price_date;
  94. // 取组合净值前值
  95. s_json = (SELECT entity_id, price_date.max() AS price_date
  96. FROM ej(tb_portfolio_ret, entity_cal_dates, 'entity_id')
  97. WHERE tb_portfolio_ret.price_date < entity_cal_dates.first_cal_date
  98. GROUP BY entity_id).toStdJson();
  99. tb_pre_nav = get_entity_nav_by_date(entity_type, s_json, true);
  100. INSERT INTO tb_pre_nav
  101. SELECT entity_id, first_cal_date, double(NULL) AS cumulative_nav, double(NULL) AS nav
  102. FROM entity_cal_dates
  103. WHERE NOT exists( SELECT * FROM tb_pre_nav WHERE tb_pre_nav.entity_id = entity_cal_dates.entity_id);
  104. tb_portfolio_ret.addColumn('nav', DOUBLE);
  105. // start_cal_date 是最早净值日期
  106. UPDATE tb_portfolio_ret
  107. SET nav = 1, ret = 0
  108. FROM ej(tb_portfolio_ret, ej(entity_cal_dates, tb_pre_nav, 'entity_id'), ['entity_id', 'price_date'], ['entity_id', 'first_cal_date'])
  109. WHERE tb_pre_nav.cumulative_nav IS NULL;
  110. // start_cal_date 是最早净值日期,用它作为初始净值日期
  111. UPDATE tb_pre_nav
  112. SET price_date = first_cal_date, cumulative_nav = 1
  113. FROM ej(tb_pre_nav, entity_cal_dates, 'entity_id')
  114. WHERE cumulative_nav IS NULL;
  115. tb_portfolio_ret.sortBy!(['entity_id', 'price_date'], [1, 1]);
  116. // 通过收益反算净值: nav_i = nav_0 * ∏(1 + ret_i)
  117. UPDATE tb_portfolio_ret
  118. SET nav = (tb_pre_nav.cumulative_nav * (1+ret).cumprod()).round(6)
  119. FROM ej(tb_portfolio_ret, tb_pre_nav, 'entity_id')
  120. CONTEXT BY entity_id;
  121. // 返回有用的数据
  122. return (SELECT DISTINCT tb_portfolio_ret.*
  123. FROM ej(tb_portfolio_ret, entity_cal_dates, 'entity_id')
  124. WHERE price_date >= first_cal_date AND price_date <= latest_cal_date
  125. ORDER BY entity_id, price_date);
  126. }
  127. /*
  128. * 计算FOF类组合净值
  129. * NOTE: 与MySQL逻辑一致,用户界面输入的交易净值会被暂时忽略,因为我们无法确保同一基金同一时间被输入的净值是相同的;
  130. * 忽略手工净值会导致收益不精确或无法计算的问题,但可能错误的净值将导致错误的结果,两害取其轻。
  131. *
  132. *
  133. * Create: 20241101 用于代替 sp_cal_portfolio_nav Joey
  134. *
  135. * @param portfolio_info <TABLE>: NEED COLUMNS portfolio_id, sec_id, start_cal_date, end_cal_date, org_id
  136. *
  137. * Example:cal_portfolio_nav(get_portfolio_list_by_fund_nav_updatetime([166002,166114], 2024.10.28, true));
  138. *
  139. */
  140. def cal_portfolio_nav(portfolio_info) {
  141. if(portfolio_info.isVoid() || portfolio_info.size() == 0) return NULL;
  142. // 取持仓截面get_nav_for_return_calculation
  143. tb_snapshot = convert_transaction_to_snapshot(portfolio_info.portfolio_id, today()).rename!('fund_id', 'sec_id');
  144. if(tb_snapshot.isVoid() || tb_snapshot.size() == 0) return NULL;
  145. // 分别对应:私募,公募,私有基金,股票,市场指数,图译指数,私有指数,图译因子
  146. v_universe = ['HF', 'MF', 'CF', 'EQ', 'MI', 'FI', 'CI', 'FA'];
  147. v_prefix = ['HF%', 'MF%', 'CF%', 'EQ%', 'IN%', 'IN%', 'CI%', 'FA%'];
  148. d_universe = dict(v_universe, v_prefix);
  149. tb_nav = table(100:0, ['sec_id', 'price_date', 'cumulative_nav', 'nav'], [SYMBOL, DATE, DOUBLE, DOUBLE]);
  150. // 取计算所需的所有持仓净值数据
  151. for(u in d_universe.keys()) {
  152. // 取涉及到的所有基金证券最早持仓日期
  153. s_json = (SELECT sec_id, start_cal_date.min() AS price_date FROM portfolio_info WHERE sec_id LIKE d_universe[u] GROUP BY sec_id).toStdJson();
  154. // 取涉及到的所有基金证券有用净值
  155. // TODO: need consider inception date nav
  156. tmp_nav = get_nav_for_return_calculation(u, 'd', s_json);
  157. if(tmp_nav.isVoid() || tmp_nav.size() == 0) continue;
  158. INSERT INTO tb_nav SELECT * FROM tmp_nav;
  159. }
  160. // 补一下最新截面(虽然是个”假的”截面)
  161. tb_latest_snapshot = SELECT sec_id, holding_date, nav.mean().round(6) AS nav
  162. FROM tb_snapshot
  163. WHERE holding_date = today()
  164. AND NOT EXISTS ( SELECT 1 FROM tb_nav WHERE sec_id = tb_snapshot.sec_id AND price_date = tb_snapshot.holding_date )
  165. GROUP BY sec_id, holding_date;
  166. // Funky DolphinDB, INSERT INTO Table1 (Columns) SELECT Columns FROM Table2 会报列数不匹配的奇葩错误
  167. // this is the way to get around it
  168. INSERT INTO tb_nav (sec_id, price_date, cumulative_nav) VALUES (tb_latest_snapshot.sec_id, tb_latest_snapshot.holding_date, tb_latest_snapshot.nav);
  169. // 在各证券持仓时段中,填充所有无净值的但其它证券有净值的合理日期
  170. // 比如 2024-01-10 ~ 2024-01-20区间,组合持有基金A和基金B,基金A有每日净值
  171. // 而基金B只有01-12和01-19两期周五净值,那么基金B需要填充除这两天以外的所有日期
  172. tb_holding_date_range = SELECT p.portfolio_id, p.sec_id, n.price_date.max() AS oldest_date, today() AS latest_date
  173. FROM portfolio_info p
  174. INNER JOIN tb_nav n ON n.sec_id = p.sec_id
  175. WHERE n.price_date < p.start_cal_date
  176. GROUP BY p.portfolio_id, p.sec_id;
  177. // 所有净值日期+前值日期
  178. tb_date = SELECT DISTINCT dr.portfolio_id, n.price_date
  179. FROM tb_holding_date_range dr
  180. INNER JOIN tb_nav n ON dr.sec_id = n.sec_id
  181. WHERE n.price_date >= dr.oldest_date
  182. AND n.price_date <= dr.latest_date;
  183. // 所有基金证券id
  184. tb_id = SELECT DISTINCT portfolio_id, sec_id FROM tb_snapshot;
  185. // NOTE: 因为同一个组合下的持仓私募基金的净值前值日期会不一样, 所以在 tb_date里会混入多余的脏数据,导致某些私募的净值前值及日期被赋予错误的数据
  186. // 好消息是最后返回的收益及净值会把这些错误的前值筛掉,但最好想个办法在这里清除掉
  187. tb_holdings = SELECT id.portfolio_id, dt.price_date, id.sec_id, n.cumulative_nav, n.nav
  188. FROM tb_id id
  189. INNER JOIN tb_date dt ON id.portfolio_id = dt.portfolio_id
  190. INNER JOIN tb_holding_date_range dr ON dr.portfolio_id = id.portfolio_id AND dr.sec_id = id.sec_id
  191. LEFT JOIN tb_nav n ON n.sec_id = id.sec_id AND n.price_date = dt.price_date
  192. WHERE dt.price_date >= dr.oldest_date AND dt.price_date <= dr.latest_date
  193. ORDER BY id.portfolio_id, dt.price_date, id.sec_id;
  194. // 清一下内存
  195. tb_nav = null;
  196. // 为收益计算填充净值
  197. UPDATE tb_holdings SET cumulative_nav = cumulative_nav.ffill(), nav = nav.ffill()
  198. CONTEXT BY portfolio_id, sec_id;
  199. tb_holdings.addColumn(['ret', 'shares', 'market_value', 'total_mkt_value', 'weight'], [DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE]);
  200. // 计算各持仓证券收益
  201. UPDATE tb_holdings SET ret = cumulative_nav.ratios()-1
  202. CONTEXT BY portfolio_id, sec_id;
  203. // 把交易日截面的份额数用于组合收益表
  204. UPDATE tb_holdings
  205. SET shares = ss.shares
  206. FROM ej(tb_holdings AS pr, tb_snapshot AS ss, ['portfolio_id', 'price_date', 'sec_id'], ['portfolio_id', 'holding_date', 'sec_id']);
  207. // 填充份额数为空的无交易日期,这段时间所有证券基金处于 buy-n-hold
  208. UPDATE tb_holdings
  209. SET shares = shares.bfill()
  210. CONTEXT BY portfolio_id, sec_id;
  211. // 记录每个组合最早的净值计算日期
  212. tb_port_first_cal_date = SELECT portfolio_id, start_cal_date.min() AS first_cal_date, end_cal_date.max() AS latest_cal_date, org_id[0] AS org_id
  213. FROM portfolio_info GROUP BY portfolio_id;
  214. // 计算各日期的持仓资产及总资产
  215. UPDATE tb_holdings
  216. SET market_value = (cumulative_nav * shares).round(6)
  217. FROM ej(tb_holdings, tb_port_first_cal_date, 'portfolio_id')
  218. WHERE org_id = '1';
  219. UPDATE tb_holdings
  220. SET market_value = (nav * shares).round(6)
  221. FROM ej(tb_holdings, tb_port_first_cal_date, 'portfolio_id')
  222. WHERE org_id = '2';
  223. UPDATE tb_holdings
  224. SET total_mkt_value = market_value.sum()
  225. CONTEXT BY portfolio_id, price_date;
  226. // 计算各持仓的权重
  227. UPDATE tb_holdings
  228. SET weight = (market_value \ total_mkt_value).round(6)
  229. WHERE total_mkt_value <> 0;
  230. // 通过持仓收益反算组合收益,再计算组合净值
  231. tb_port_first_cal_date.rename!('portfolio_id', 'entity_id');
  232. tb_holdings.rename!('portfolio_id', 'entity_id');
  233. return cal_nav_by_return('PF', tb_port_first_cal_date, tb_holdings);
  234. }
  235. /*
  236. * 通用净值计算,由收益反推
  237. *
  238. * @param entity_type <STRING>: PL, CO
  239. * @param entity_ret <TABLE>: [COLUMNS] entity_id, curve_type, strategy, effective_date <STRING>, ret
  240. *
  241. * NOTE: 1) 如果没有成立日,则无法计算
  242. * 2) monthly 时 effective_date 对应MySQL里的 end_date; weekly时对应 year_week
  243. */
  244. def cal_mc_nav_by_return(entity_type, entity_ret, freq='m') {
  245. t_nav = table(1000:0, ['entity_id', 'curve_type', 'strategy', 'effective_date', 'ret', 'nav'], [SYMBOL, INT, INT, STRING, DOUBLE, DOUBLE]);
  246. if(!(entity_type IN ['PL', 'CO'])) return t_nav;
  247. if(entity_ret.isVoid() || entity_ret.size() == 0) return t_nav;
  248. s_json = (SELECT entity_id AS entity_id, curve_type, strategy, effective_date.min() AS effective_date
  249. FROM entity_ret
  250. GROUP BY entity_id, curve_type, strategy).toStdJson();
  251. t_nav = entity_ret.join(take(double(NULL), entity_ret.size()) AS nav);
  252. // 取净值前值
  253. t_pre_nav = get_mc_nav_for_return_calculation(entity_type, s_json, 1, freq);
  254. if(t_pre_nav.size() == 0) {
  255. // 没有前值时候, 做一个假记录,把净值1和日期填入
  256. INSERT INTO t_pre_nav
  257. SELECT entity_id, curve_type, strategy, effective_date.min() AS effective_date, 1 AS cumulative_nav
  258. FROM entity_ret
  259. GROUP BY entity_id, curve_type, strategy;
  260. // 设置初始净值为1,收益为0
  261. UPDATE t_nav n
  262. SET ret = 0, nav = 1
  263. FROM ej(t_nav, t_pre_nav, ['entity_id', 'effective_date']);
  264. }
  265. // 通过收益反算净值: nav_i = nav_0 * ∏(1 + ret_i)
  266. UPDATE t_nav
  267. SET nav = (t_pre_nav.cumulative_nav * (1+ret).cumprod()).round(6)
  268. FROM ej(t_nav, t_pre_nav, 'entity_id')
  269. CONTEXT BY entity_id;
  270. return t_nav;
  271. }