indicatorCalculator.dos 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853
  1. module fundit::indicatorCalculator
  2. use fundit::dataPuller
  3. use fundit::returnCalculator
  4. use fundit::navCalculator
  5. /*
  6. * Annulized multiple
  7. */
  8. def get_annulization_multiple(freq) {
  9. ret = 1;
  10. if (freq == 'd') {
  11. ret = 252; // We have differences here between Java and DolphinDB, Java uses 365.25 days
  12. } else if (freq == 'w') {
  13. ret = 52;
  14. } else if (freq == 'm') {
  15. ret = 12;
  16. } else if (freq == 'q') {
  17. ret = 4;
  18. } else if (freq == 's') {
  19. ret = 2;
  20. } else if (freq == 'a') {
  21. ret = 1;
  22. }
  23. return ret;
  24. }
  25. /*
  26. * 取主基准和BFI的历史月收益率
  27. *
  28. * @param benchmarks <TABLE>: entity-benchmark 的对应关系表
  29. * @param end_day <DATE>: 收益的截止日期
  30. *
  31. * @return <TABLE>: benchmark_id, end_date, ret
  32. *
  33. */
  34. def get_benchmark_return(benchmarks, end_day) {
  35. s_index_ids = '';
  36. s_factor_ids = '';
  37. if(benchmarks.isVoid() || benchmarks.size() == 0) { return null; }
  38. // 前缀为 IN 的 benchmark id
  39. t_index_id = SELECT DISTINCT benchmark_id FROM benchmarks WHERE benchmark_id LIKE 'IN%';
  40. s_index_ids = iif(isVoid(t_index_id), "", "'" + t_index_id.benchmark_id.concat("','") + "'");
  41. // 前缀为 FA 的 benchmark id
  42. t_factor_id = SELECT DISTINCT benchmark_id FROM benchmarks WHERE benchmark_id LIKE 'FA%';
  43. s_factor_ids = iif(isVoid(t_factor_id), "", "'" + t_factor_id.benchmark_id.concat("','") + "'");
  44. // 目前指数的月度业绩存在 fund_performance 表
  45. t_bmk = SELECT fund_id AS benchmark_id, temporalParse(end_date, 'yyyy-MM') AS end_date, ret FROM get_monthly_ret('IX', s_index_ids, 1990.01.01, end_day, true);
  46. // 而因子的月度业绩存在 cm_factor_performance 表
  47. INSERT INTO t_bmk SELECT factor_id, temporalParse(end_date, 'yyyy-MM') AS end_date, ret FROM get_monthly_ret('FA', s_factor_ids, 1990.01.01, end_day, true);
  48. return t_bmk;
  49. }
  50. /*
  51. * Trailing Return, Standard Deviation, Skewness, Kurtosis, Max Drawdown, VaR, CVaR
  52. * @param ret: 收益表,需要有 entity_id, price_dat, end_date, nav
  53. * @param freq: 数据频率,d, w, m, q, s, a
  54. *
  55. * NOTE: standard deviation of Java version is noncompliant-GIPS annulized number
  56. *
  57. * Create: 20240904 Joey
  58. * TODO: var and cvar are silightly off compared with Java version
  59. *
  60. */
  61. def cal_basic_performance(ret, freq) {
  62. t = SELECT entity_id, max(end_date) AS end_date, max(price_date) AS price_date, min(price_date) AS min_date,
  63. //(nav.last() \ nav.first() - 1).round(6) AS trailing_ret,
  64. ((1+ret).prod()-1).round(6) AS trailing_ret,
  65. iif(price_date.max().month()-price_date.min().month()>12,
  66. //(nav.last() \ nav.first()).pow(365 \(max(price_date) - min(price_date)))-1,
  67. //(nav.last() \ nav.first() - 1)).round(6) AS trailing_ret_a,
  68. ((1+ret).prod()-1) * sqrt(get_annulization_multiple(freq)),
  69. ((1+ret).prod()-1)).round(6) AS trailing_ret_a,
  70. ret.std() AS std_dev,
  71. ret.skew(false) AS skewness,
  72. ret.kurtosis(false) - 3 AS kurtosis,
  73. ret.min() AS wrst_month,
  74. max( 1 - nav \ nav.cummax() ) AS drawdown
  75. FROM ret
  76. GROUP BY entity_id;
  77. // var & cvar require return NOT NULL
  78. // NOTE: DolphinDB supports 4 different ways: normal, logNormal, historical, monteCarlo. we use historical
  79. t1 = SELECT entity_id, max(end_date) AS end_date, max(price_date) AS price_date,
  80. ret.VaR('historical', 0.95) AS var,
  81. ret.CVaR('historical', 0.95) AS cvar
  82. FROM ret
  83. WHERE ret.ret > - 1
  84. GROUP BY entity_id;
  85. return (SELECT * FROM t LEFT JOIN t1 ON t.entity_id = t1.entity_id AND t.end_date = t1.end_date AND t.price_date = t1.price_date);
  86. }
  87. /*
  88. * Lower Partial Moment
  89. * NOTE: risk free rate is used as Minimal Accepted Rate (MAR) here
  90. *
  91. */
  92. def cal_LPM(ret, risk_free) {
  93. t = SELECT *, count(entity_id) AS cnt FROM ret WHERE ret > -1 CONTEXT BY entity_id;
  94. lpm = SELECT t.entity_id, max(t.end_date) AS end_date,
  95. (sum (rfr.ret - t.ret) \ (t.cnt[0])).pow(1\1) AS lpm1,
  96. (sum2(rfr.ret - t.ret) \ (t.cnt[0])).pow(1\2) AS lpm2,
  97. (sum3(rfr.ret - t.ret) \ (t.cnt[0])).pow(1\3) AS lpm3
  98. FROM t
  99. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  100. WHERE t.ret < rfr.ret
  101. GROUP BY t.entity_id;
  102. return lpm;
  103. }
  104. /*
  105. * Downside Devision, Omega Ratio, Sortino Ratio, Kappa Ratio
  106. *
  107. * TODO: Java version of Downside Deviation (LPM2) uses cnt-1 as denominator to calculate mean excess return, which might be wrong
  108. * Java version of Omega could be wrong because Java uses annualized returns and cnt-1
  109. * Java'version of Kappa could be very wrong
  110. *
  111. */
  112. def cal_omega_sortino_kappa(ret, risk_free) {
  113. lpm = cal_LPM(ret, risk_free);
  114. tb = SELECT t.entity_id,
  115. l.lpm2[0] AS ds_dev,
  116. (t.ret - rfr.ret ).mean() \ l.lpm1[0] + 1 AS omega,
  117. (t.ret - rfr.ret ).mean() \ l.lpm2[0] AS sortino,
  118. (t.ret - rfr.ret ).mean() \ l.lpm3[0] AS kappa
  119. FROM ret t
  120. INNER JOIN lpm l ON t.entity_id = l.entity_id
  121. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  122. GROUP BY t.entity_id;
  123. return tb;
  124. }
  125. /*
  126. * Alpha & Beta
  127. * NOTE: alpha of Java version is noncompliant-GIPS annulized number
  128. */
  129. def cal_alpha_beta(ret, benchmarks, bmk_ret, risk_free) {
  130. t = SELECT t.entity_id, t.end_date, t.ret, bm.benchmark_id, bmk.ret AS ret_bmk
  131. FROM ret t
  132. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id
  133. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  134. WHERE t.ret > -1
  135. AND bmk.ret > -1;
  136. beta = SELECT entity_id, benchmark_id, ret.beta(ret_bmk) AS beta FROM t GROUP BY entity_id, benchmark_id;
  137. alpha = SELECT t.entity_id, t.benchmark_id, beta.beta[0] AS beta, (t.ret - rfr.ret).mean() - beta.beta[0] * (t.ret_bmk - rfr.ret).mean() AS alpha
  138. FROM t
  139. INNER JOIN beta beta ON t.entity_id = beta.entity_id AND t.benchmark_id = beta.benchmark_id
  140. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  141. GROUP BY t.entity_id, t.benchmark_id;
  142. return alpha;
  143. }
  144. /*
  145. * Winning Ratio, Tracking Error, Information Ratio
  146. * TODO: Information Ratio is way off!
  147. * Not sure how to describe a giant number("inf"), for now 999 is used
  148. */
  149. def cal_benchmark_tracking(ret, benchmarks, bmk_ret) {
  150. t0 = SELECT t.entity_id, t.end_date, t.price_date,
  151. t.ret, bmk.ret AS ret_bmk, count(t.entity_id) AS cnt, (t.ret - bmk.ret) AS exc_ret, bm.benchmark_id
  152. FROM ret t
  153. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id
  154. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  155. WHERE t.ret > -1
  156. AND bmk.ret > -1
  157. CONTEXT BY t.entity_id, bm.benchmark_id;
  158. t = SELECT entity_id, end_date.max() AS end_date, price_date.max() AS price_date, price_date.min() AS min_date, benchmark_id,
  159. exc_ret.bucketCount(0:999, 1) \ cnt[0] AS winrate,
  160. exc_ret.std() AS track_error,
  161. iif(exc_ret.std() == 0, null, exc_ret.mean() / exc_ret.std()) AS info
  162. FROM t0 GROUP BY entity_id, benchmark_id;
  163. return t;
  164. }
  165. /*
  166. * Upside/Down Capture Return/Ratio
  167. *
  168. */
  169. def cal_capture_ratio(ret, benchmarks, bmk_ret) {
  170. t1 = SELECT t.entity_id, (1+t.ret).prod() AS upside_ret, (1+bmk.ret).prod() AS bmk_upside_ret, bmk.end_date.count() AS bmk_upside_cnt, bm.benchmark_id
  171. FROM ret t
  172. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id
  173. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  174. WHERE t.ret > -1
  175. AND bmk.ret >= 0
  176. GROUP BY t.entity_id, bm.benchmark_id;
  177. t2 = SELECT t.entity_id, (1+t.ret).prod() AS downside_ret, (1+bmk.ret).prod() AS bmk_downside_ret, bmk.end_date.count() AS bmk_downside_cnt, bm.benchmark_id
  178. FROM ret t
  179. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id
  180. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  181. WHERE t.ret > -1
  182. AND bmk.ret < 0
  183. GROUP BY t.entity_id, bm.benchmark_id;
  184. t = SELECT iif(isNull(t1.entity_id), t2.entity_id, t1.entity_id) AS entity_id,
  185. iif(isNull(t1.benchmark_id), t2.benchmark_id, t1.benchmark_id) AS benchmark_id,
  186. t1.upside_ret.pow(1 \ t1.bmk_upside_cnt)-1 AS upside_capture_ret,
  187. (t1.upside_ret.pow(1 \ t1.bmk_upside_cnt)-1)/(t1.bmk_upside_ret.pow(1 \ t1.bmk_upside_cnt)-1) AS upside_capture_ratio,
  188. t2.downside_ret.pow(1 \ t2.bmk_downside_cnt)-1 AS downside_capture_ret,
  189. (t2.downside_ret.pow(1 \ t2.bmk_downside_cnt)-1)/(t2.bmk_downside_ret.pow(1 \ t2.bmk_downside_cnt)-1) AS downside_capture_ratio
  190. FROM t1 FULL JOIN t2 ON t1.entity_id = t2.entity_id AND t1.benchmark_id = t2.benchmark_id;
  191. return t;
  192. }
  193. /*
  194. * Sharpe Ratio
  195. * NOTE: Java version is noncompliant-GIPS annulized number
  196. */
  197. def cal_sharpe(ret, std_dev, risk_free) {
  198. sharpe = SELECT t.entity_id, (t.ret - rfr.ret).mean() / std.std_dev[0] AS sharpe
  199. FROM ret t
  200. INNER JOIN std_dev std ON t.entity_id = std.entity_id
  201. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  202. WHERE std.std_dev[0] <> 0
  203. GROUP BY t.entity_id;
  204. return sharpe;
  205. }
  206. /*
  207. * Treynor Ratio
  208. */
  209. def cal_treynor(ret, risk_free, beta) {
  210. t = SELECT *, count(entity_id) AS cnt
  211. FROM ret t
  212. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  213. WHERE t.ret > -1
  214. AND rfr.ret > -1
  215. CONTEXT BY t.entity_id;
  216. treynor = SELECT t.entity_id, beta.benchmark_id,
  217. ((1 + t.ret).prod().pow(12\iif(t.cnt[0]<12, 12, t.cnt[0])) - (1 + t.rfr_ret).prod().pow(12\iif(t.cnt[0]<12, 12, t.cnt[0]))) / beta.beta[0] AS treynor
  218. FROM t
  219. INNER JOIN beta AS beta ON t.entity_id = beta.entity_id
  220. GROUP BY t.entity_id, beta.benchmark_id;
  221. return treynor;
  222. }
  223. /*
  224. * Jensen's Alpha
  225. * TODO: the result is slightly off
  226. */
  227. def cal_jensen(ret, bmk_ret, risk_free, beta) {
  228. jensen = SELECT t.entity_id, t.ret.mean() - rfr.ret.mean() - beta.beta[0] * (bmk.ret.mean() - rfr.ret.mean()) AS jensen, beta.benchmark_id
  229. FROM ret t
  230. INNER JOIN beta beta ON t.entity_id = beta.entity_id
  231. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND beta.benchmark_id = bmk.benchmark_id
  232. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  233. GROUP BY t.entity_id, beta.benchmark_id;
  234. return jensen;
  235. }
  236. /*
  237. * Calmar Ratio
  238. * TODO: the result is off
  239. *
  240. */
  241. def cal_calmar(ret_a){
  242. calmar = SELECT entity_id, trailing_ret_a \ drawdown AS calmar
  243. FROM ret_a;
  244. return calmar;
  245. }
  246. /*
  247. * Modigliani Modigliani Measure (M2)
  248. * NOTE: M2 = sharpe * std(benchmark) + risk_free_rate
  249. * NOTE: Java version is noncompliant-GIPS annulized number
  250. */
  251. def cal_m2(ret, benchmarks, bmk_ret, risk_free) {
  252. m2 = SELECT t.entity_id, (t.ret - rfr.ret).mean() / t.ret.std() * bmk.ret.std() + rfr.ret.mean() AS m2, bm.benchmark_id
  253. FROM ret t
  254. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id
  255. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  256. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  257. GROUP BY t.entity_id, bm.benchmark_id;
  258. return m2;
  259. }
  260. /*
  261. * Morningstar Return, Morningstar Risk-Adjusted Return
  262. *
  263. * TODO: Tax and loads are NOT taken care of
  264. * TODO: Assume Chinese methodology using 3, 5, 10 as number of traling years
  265. *
  266. * NOTE: Morningstar methodology requires monthly return for calculation, so that "12" is hard-coded here
  267. *
  268. *
  269. */
  270. def cal_ms_return(ret, risk_free) {
  271. r = SELECT t.entity_id, t.end_date.max() AS end_date, t.price_date.max() AS price_date, t.price_date.min() AS min_date,
  272. ((1 + t.ret)\(1 + rfr.ret)).prod().pow(12\(t.end_date.max() - t.end_date.min()))-1 AS ms_ret_a,
  273. (1 + t.ret).pow(-2).mean().pow(-12/2)-1 AS ms_rar_a
  274. FROM ret t
  275. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  276. GROUP BY t.entity_id;
  277. return r;
  278. }
  279. /*
  280. * Calculation for monthly indicators which need benchmark
  281. * @param ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  282. * @param benchmarks <TABLE>: entity-benchmark mapping table
  283. * @param index_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  284. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  285. *
  286. * @return: indicators table
  287. *
  288. *
  289. * Create 20240904 模仿Java & python代码在Dolphin中实现,具体计算逻辑可能会有不同 Joey
  290. * TODO: some datapoints require more data, we need a way to disable calculation for them
  291. *
  292. */
  293. def cal_indicators_with_benchmark(mutable ret, benchmarks, index_ret, risk_free) {
  294. // sorting for correct first() and last() value
  295. ret.sortBy!(['entity_id', 'price_date'], [1, 1]);
  296. // alpha, beta
  297. alpha_beta = cal_alpha_beta(ret, benchmarks, index_ret, risk_free);
  298. // 胜率、跟踪误差、信息比率
  299. bmk_tracking = cal_benchmark_tracking(ret, benchmarks, index_ret);
  300. // 特雷诺
  301. treynor = cal_treynor(ret, risk_free, alpha_beta);
  302. // 詹森指数
  303. jensen = cal_jensen(ret, index_ret, risk_free, alpha_beta);
  304. // M2
  305. m2 = cal_m2(ret, benchmarks, index_ret, risk_free);
  306. // 上下行捕获率、收益
  307. capture_r = cal_capture_ratio(ret, benchmarks, index_ret);
  308. r = SELECT * FROM bmk_tracking a1
  309. LEFT JOIN alpha_beta ON a1.entity_id = alpha_beta.entity_id AND a1.benchmark_id = alpha_beta.benchmark_id
  310. LEFT JOIN treynor ON a1.entity_id = treynor.entity_id AND a1.benchmark_id = treynor.benchmark_id
  311. LEFT JOIN jensen ON a1.entity_id = jensen.entity_id AND a1.benchmark_id = jensen.benchmark_id
  312. LEFT JOIN m2 ON a1.entity_id = m2.entity_id AND a1.benchmark_id = m2.benchmark_id
  313. LEFT JOIN capture_r ON a1.entity_id = capture_r.entity_id AND a1.benchmark_id = capture_r.benchmark_id;
  314. // 年化各数据点
  315. // GIPS RULE: NO annulization for data less than 1 year
  316. plainAnnu = get_annulization_multiple('m');
  317. sqrtAnnu = sqrt(get_annulization_multiple('m'));
  318. r.addColumn(['alpha_a', 'jensen_a', 'track_error_a', 'info_a', 'm2_a'],
  319. [DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE]);
  320. UPDATE r
  321. SET alpha_a = alpha * iif(price_date.month() - min_date.month() >= 11, plainAnnu, 1),
  322. jensen_a = jensen * iif(price_date.month() - min_date.month() >= 11, plainAnnu, 1),
  323. track_error_a = track_error * iif(price_date.month() - min_date.month() >= 11, sqrtAnnu, 1),
  324. info_a = info * iif(price_date.month() - min_date.month() >= 11, sqrtAnnu, 1),
  325. m2_a = m2 * iif(price_date.month() - min_date.month() >= 11, plainAnnu, 1);
  326. return r.dropColumns!(['end_date', 'price_date', 'min_date']);
  327. }
  328. /*
  329. * Monthly standard indicator calculation
  330. * @param ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  331. * @param benchmarks <TABLE>: entity-benchmark mapping table
  332. * @param benchmark_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  333. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  334. *
  335. * @return: indicators table
  336. *
  337. *
  338. * Create 20240904 模仿Java & python代码在Dolphin中实现,具体计算逻辑可能会有不同 Joey
  339. * TODO: some datapoints require more data, we need a way to disable calculation for them
  340. *
  341. */
  342. def cal_indicators(mutable ret, benchmarks, benchmark_ret, risk_free) {
  343. // sorting for correct first() and last() value
  344. ret.sortBy!(['entity_id', 'price_date'], [1, 1]);
  345. // 收益、标准差、偏度、峰度、最大回撤、VaR, CVaR
  346. rtn = cal_basic_performance(ret, 'm');
  347. // 夏普
  348. sharpe = cal_sharpe(ret, rtn, risk_free);
  349. // 卡玛比率
  350. calmar = cal_calmar(rtn);
  351. // 整合后的下行标准差、欧米伽、索提诺、卡帕
  352. lpms = cal_omega_sortino_kappa(ret, risk_free);
  353. // 需要基准的指标们
  354. indicator_with_benchmark = cal_indicators_with_benchmark(ret, benchmarks, benchmark_ret, risk_free);
  355. r = SELECT * FROM rtn a1
  356. LEFT JOIN sharpe ON a1.entity_id = sharpe.entity_id
  357. LEFT JOIN calmar ON a1.entity_id = calmar.entity_id
  358. LEFT JOIN lpms ON a1.entity_id = lpms.entity_id
  359. LEFT JOIN indicator_with_benchmark ON a1.entity_id = indicator_with_benchmark.entity_id;
  360. // 年化各数据点
  361. // GIPS RULE: NO annulization for data less than 1 year
  362. plainAnnu = get_annulization_multiple('m');
  363. sqrtAnnu = sqrt(get_annulization_multiple('m'));
  364. r.addColumn(['std_dev_a', 'ds_dev_a', 'sharpe_a', 'sortino_a'],
  365. [DOUBLE, DOUBLE, DOUBLE, DOUBLE]);
  366. UPDATE r
  367. SET std_dev_a = std_dev * iif(price_date.month() - min_date.month() >= 11, sqrtAnnu, 1),
  368. ds_dev_a = ds_dev * iif(price_date.month() - min_date.month() >= 11, sqrtAnnu, 1),
  369. sharpe_a = sharpe * iif(price_date.month() - min_date.month() >= 11, sqrtAnnu, 1),
  370. sortino_a = sortino * iif(price_date.month() - min_date.month() >= 11, sqrtAnnu, 1);
  371. return r;
  372. }
  373. /*
  374. * Monthly BFI indicator calculation
  375. * @param ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  376. * @param benchmarks <TABLE>: entity-benchmark mapping table
  377. * @param benchmark_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  378. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  379. *
  380. * @return: BFI indicators table
  381. *
  382. *
  383. * Create 20240914 Joey
  384. *
  385. */
  386. def cal_bfi_indicators(mutable ret, benchmarks, benchmark_ret, risk_free) {
  387. // 需要基准的指标们
  388. r = cal_indicators_with_benchmark(ret, benchmarks, benchmark_ret, risk_free);
  389. return r;
  390. }
  391. /*
  392. * Monthly Morningstar indicator calculation
  393. *
  394. * @param ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  395. * @param benchmarks <USELESS>:
  396. * @param benchmark_ret <USELESS>:
  397. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  398. *
  399. */
  400. def cal_ms_indicators(mutable ret, benchmarks, benchmark_ret, risk_free) {
  401. r = cal_ms_return(ret, risk_free);
  402. return r;
  403. }
  404. /*
  405. * Calculate trailing 6m, ytd, 1y, 2y, 3y, 4y, 5y, 10y and since inception datapoints
  406. *
  407. * @param: func <FUNCTION>: the calculation function
  408. * @param: entity_info <TABLE>: basic information of entity, NEED COLUMNS entity_id, inception_date
  409. * @param benchmarks <TABLE>: entity-benchmark mapping table
  410. * @param: ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  411. * @param: end_day <DATE>: 计算截止日期
  412. * @param bmk_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  413. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  414. * @param periods <BOOL VECTOR>: 是否计算的区间向量,分别对应 incep, ytd, 6m, 1y, 2y, 3y, 4y, 5y, 10y
  415. *
  416. * Example: cal_trailing(
  417. *
  418. */
  419. def cal_trailing(func, entity_info, benchmarks, mutable tb_ret, end_day, bmk_ret, risk_free_rate, periods) {
  420. r_incep = null;
  421. r_ytd = null;
  422. r_6m = null;
  423. r_1y = null;
  424. r_2y = null;
  425. r_3y = null;
  426. r_4y = null;
  427. r_5y = null;
  428. r_10y = null;
  429. // since inception
  430. if(tb_ret.size() > 0 && periods[0] == 1) {
  431. r_incep = func(tb_ret, benchmarks, bmk_ret, risk_free_rate);
  432. }
  433. // ytd
  434. tb_ret_ytd = SELECT * FROM tb_ret WHERE end_date >= end_day.yearBegin().month();
  435. if(tb_ret_ytd.size() > 0 && periods[1] == 1) {
  436. r_ytd = func(tb_ret_ytd, benchmarks, bmk_ret, risk_free_rate);
  437. }
  438. // trailing 6m
  439. tb_ret_6m = SELECT * FROM tb_ret r INNER JOIN entity_info ei ON r.entity_id = ei.entity_id
  440. WHERE r.end_date > end_day.month()-6 AND (end_day.month() - ei.inception_date.month()) >= 6;
  441. if(tb_ret_6m.size() > 0 && periods[2] == 1) {
  442. r_6m = func(tb_ret_6m, benchmarks, bmk_ret, risk_free_rate);
  443. }
  444. // trailing 1y
  445. tb_ret_1y = SELECT * FROM tb_ret r INNER JOIN entity_info ei ON r.entity_id = ei.entity_id
  446. WHERE r.end_date > end_day.month()-12 AND (end_day.month() - ei.inception_date.month()) >= 12;
  447. if(tb_ret_1y.size() > 0 && periods[3] == 1) {
  448. r_1y = func(tb_ret_1y, benchmarks, bmk_ret, risk_free_rate);
  449. }
  450. // trailing 2y
  451. tb_ret_2y = SELECT * FROM tb_ret r INNER JOIN entity_info ei ON r.entity_id = ei.entity_id
  452. WHERE r.end_date > end_day.month()-24 AND (end_day.month() - ei.inception_date.month()) >= 24;
  453. if(tb_ret_2y.size() > 0 && periods[4] == 1) {
  454. r_2y = func(tb_ret_2y, benchmarks, bmk_ret, risk_free_rate);
  455. }
  456. // trailing 3y
  457. tb_ret_3y = SELECT * FROM tb_ret r INNER JOIN entity_info ei ON r.entity_id = ei.entity_id
  458. WHERE r.end_date > end_day.month()-36 AND (end_day.month() - ei.inception_date.month()) >= 36;
  459. if(tb_ret_3y.size() > 0 && periods[5] == 1) {
  460. r_3y = func(tb_ret_3y, benchmarks, bmk_ret, risk_free_rate);
  461. }
  462. // trailing 4y
  463. tb_ret_4y = SELECT * FROM tb_ret r INNER JOIN entity_info ei ON r.entity_id = ei.entity_id
  464. WHERE r.end_date > end_day.month()-48 AND (end_day.month() - ei.inception_date.month()) >= 48;
  465. if(tb_ret_4y.size() > 0 && periods[6] == 1) {
  466. r_4y = func(tb_ret_4y, benchmarks, bmk_ret, risk_free_rate);
  467. }
  468. // trailing 5y
  469. tb_ret_5y = SELECT * FROM tb_ret r INNER JOIN entity_info ei ON r.entity_id = ei.entity_id
  470. WHERE r.end_date > end_day.month()-60 AND (end_day.month() - ei.inception_date.month()) >= 60;
  471. if(tb_ret_5y.size() > 0 && periods[7] == 1) {
  472. r_5y = func(tb_ret_5y, benchmarks, bmk_ret, risk_free_rate);
  473. }
  474. // trailing 10y
  475. tb_ret_10y = SELECT * FROM tb_ret r INNER JOIN entity_info ei ON r.entity_id = ei.entity_id
  476. WHERE r.end_date > end_day.month()-120 AND (end_day.month() - ei.inception_date.month()) >= 120;
  477. if(tb_ret_10y.size() > 0 && periods[8] == 1) {
  478. r_10y = func(tb_ret_10y, benchmarks, bmk_ret, risk_free_rate);
  479. }
  480. return r_incep, r_ytd, r_6m, r_1y, r_2y, r_3y, r_4y, r_5y, r_10y;
  481. }
  482. /*
  483. * Calculate trailing 6m, ytd, 1y, 2y, 3y, 4y, 5y, 10y and since inception standard indicators
  484. *
  485. * @param: entity_info <TABLE>: basic information of entity, NEED COLUMNS entity_id, inception_date
  486. * @param benchmarks <TABLE>: entity-benchmark mapping table
  487. * @param: ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  488. * @param: end_day <DATE>: 计算截止日期
  489. * @param bmk_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  490. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  491. *
  492. */
  493. def cal_trailing_indicators(entity_info, benchmarks, mutable tb_ret, end_day, bmk_ret, risk_free_rate) {
  494. return cal_trailing(cal_indicators, entity_info, benchmarks, tb_ret, end_day, bmk_ret, risk_free_rate, [1,1,1,1,1,1,1,1,1]);
  495. }
  496. /*
  497. * Calculate trailing 6m, ytd, 1y, 2y, 3y, 4y, 5y, 10y and since inception bfi indicators
  498. *
  499. * @param: entity_info <TABLE>: basic information of entity, NEED COLUMNS entity_id, inception_date
  500. * @param benchmarks <TABLE>: entity-benchmark mapping table
  501. * @param: ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  502. * @param: end_day <DATE>: 计算截止日期
  503. * @param bmk_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  504. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  505. *
  506. *
  507. */
  508. def cal_trailing_bfi_indicators(entity_info, benchmarks, mutable tb_ret, end_day, bmk_ret, risk_free_rate) {
  509. return cal_trailing(cal_bfi_indicators, entity_info, benchmarks, tb_ret, end_day, bmk_ret, risk_free_rate, [1,1,1,1,1,1,1,1,1]);
  510. }
  511. /*
  512. * Calculate trailing 3y, 5y, 10y Morningstar Return, Risk-Adjested Return and Risk
  513. *
  514. */
  515. def cal_trailing_ms_indicators(entity_info, mutable tb_ret, end_day, risk_free_rate) {
  516. return cal_trailing(cal_ms_indicators, entity_info, , tb_ret, end_day, , risk_free_rate, periods=[0,0,0,0,0,1,0,1,1]);
  517. }
  518. /*
  519. * Calculate fund indicators for one date
  520. *
  521. * @param entity_type <STRING>: MF, HF
  522. * @param fund_ids <STRING>: 逗号和单引号分隔的fund_id
  523. * @param end_day <DATE>: 要计算的日期
  524. * @param isFromNav <BOOL>: 用净值实时计算还是从表中取月收益
  525. * @param isFromSQL <BOOL>: TODO: 从MySQL还是本地DolphinDB取净值/收益数据
  526. *
  527. * @return <DICT TABLE>: ['PBI-INCEP', 'PBI-YTD', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y', 'MS-3Y', 'MS-5Y', 'MS-10Y']
  528. *
  529. * TODO: primary_benchmark_id seems not be used as benchmark, when it is FA00000VNB
  530. *
  531. * Example: cal_fund_indicators('HF', "'HF000004KN','HF000103EU','HF00018WXG'", 2024.06.28, true);
  532. *
  533. */
  534. def cal_fund_indicators(entity_type, fund_ids, end_day, isFromNav) {
  535. very_old_date = 1990.01.01;
  536. fund_info = get_fund_info(fund_ids);
  537. if(fund_info.isVoid() || fund_info.size() == 0) { return null };
  538. fund_info.rename!('fund_id', 'entity_id');
  539. if(isFromNav == true) {
  540. // 从净值开始计算收益
  541. tb_ret = SELECT * FROM cal_fund_monthly_returns(entity_type, fund_ids, true) WHERE price_date <= end_day;
  542. tb_ret.rename!(['fund_id', 'cumulative_nav'], ['entity_id', 'nav']);
  543. } else {
  544. // 从fund_performance表里读月收益
  545. tb_ret = get_monthly_ret('FD', fund_ids, very_old_date, end_day, true);
  546. tb_ret.rename!(['fund_id'], ['entity_id']);
  547. }
  548. // 取基金和基准的对照表
  549. primary_benchmark = SELECT entity_id, iif(benchmark_id.isNull(), 'IN00000008', benchmark_id) AS benchmark_id FROM fund_info;
  550. // 取所有出现的基准月收益
  551. bmk_ret = get_benchmark_return(primary_benchmark, end_day);
  552. risk_free_rate = SELECT fund_id, temporalParse(end_date, 'yyyy-MM') AS end_date, ret FROM get_risk_free_rate(very_old_date, end_day);
  553. // 标准的指标
  554. t0 = cal_trailing_indicators(fund_info, primary_benchmark, tb_ret, end_day, bmk_ret, risk_free_rate);
  555. // Morningstar 指标
  556. t1 = cal_trailing_ms_indicators(fund_info, tb_ret, end_day, risk_free_rate);
  557. // PBI stands for "Primary Benchmark Index", MS stands for "MorningStar"
  558. v_table_name = ['PBI-INCEP', 'PBI-YTD', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y', 'MS-3Y', 'MS-5Y', 'MS-10Y'];
  559. return dict(v_table_name, t0 <- t1[5] <- t1[7] <- t1[8]);
  560. }
  561. /*
  562. * Calculate fund BFI indicators for one date
  563. *
  564. * @param entity_type <STRING>: MF, HF
  565. * @param fund_ids <STRING>: 逗号和单引号分隔的fund_id
  566. * @param end_day <DATE>: 要计算的日期
  567. * @param isFromNav <BOOL>: 用净值实时计算还是从表中取月收益
  568. * @param isFromSQL <BOOL>: TODO: 从MySQL还是本地DolphinDB取净值/收益数据
  569. *
  570. * @return <DICT TABLE>: ['BFI-INCEP', 'BFI-YTD', 'BFI-6M', 'BFI-1Y', 'BFI-2Y', 'BFI-3Y', 'BFI-4Y', 'BFI-5Y', 'BFI-10Y']
  571. *
  572. * TODO: primary_benchmark_id seems not be used as benchmark, when it is FA00000VNB
  573. * TODO: intergrate with cal_fund_indicators
  574. *
  575. * Example: cal_fund_bfi_indicators('MF', "'MF00003PW2', 'MF00003PW1', 'MF00003PXO'", 2024.08.31, true);
  576. *
  577. */
  578. def cal_fund_bfi_indicators(entity_type, fund_ids, end_day, isFromNav) {
  579. very_old_date = 1990.01.01;
  580. fund_info = get_fund_info(fund_ids);
  581. if(fund_info.isVoid() || fund_info.size() == 0) { return null };
  582. fund_info.rename!('fund_id', 'entity_id');
  583. if(isFromNav == true) {
  584. // 从净值开始计算收益
  585. tb_ret = SELECT * FROM cal_fund_monthly_returns(entity_type, fund_ids, true) WHERE price_date <= end_day;
  586. tb_ret.rename!(['fund_id', 'cumulative_nav'], ['entity_id', 'nav']);
  587. } else {
  588. // 从fund_performance表里读月收益
  589. tb_ret = get_monthly_ret('FD', fund_ids, very_old_date, end_day, true);
  590. tb_ret.rename!(['fund_id'], ['entity_id']);
  591. }
  592. // 取基金和基准的对照表
  593. bfi_benchmark = SELECT fund_id AS entity_id, factor_id AS benchmark_id FROM get_fund_bfi_factors(fund_ids, end_day.temporalFormat('yyyy-MM'));
  594. if(bfi_benchmark.isVoid() || bfi_benchmark.size() == 0) { return null; }
  595. bmk_ret = get_benchmark_return(bfi_benchmark, end_day);
  596. risk_free_rate = SELECT fund_id, temporalParse(end_date, 'yyyy-MM') AS end_date, ret FROM get_risk_free_rate(very_old_date, end_day);
  597. t0 = cal_trailing_bfi_indicators(fund_info, bfi_benchmark, tb_ret, end_day, bmk_ret, risk_free_rate);
  598. // BFI stands for "Best Fit Index"
  599. v_table_name = ['BFI-INCEP', 'BFI-YTD', 'BFI-6M', 'BFI-1Y', 'BFI-2Y', 'BFI-3Y', 'BFI-4Y', 'BFI-5Y', 'BFI-10Y'];
  600. return dict(v_table_name, t0);
  601. }
  602. /*
  603. * Calculate portfolio indicators for one date
  604. *
  605. * @param portfolio_ids <STRING>: comma-delimited portfolio ids
  606. * @param end_day <DATE>: the date
  607. * @param cal_method <INT>: calculate based on cumulative nav (1) or nav (2)
  608. * @param isFromNav <BOOL>: calculate returns from NAV on-the-fly (true) or get from monthly return table (false)
  609. *
  610. * Example: cal_portfolio_indicators('166002,166114', 2024.08.31, 1, true);
  611. *
  612. */
  613. def cal_portfolio_indicators(portfolio_ids, end_day, cal_method, isFromNav) {
  614. very_old_date = 1990.01.01;
  615. portfolio_info = get_portfolio_info(portfolio_ids);
  616. if(portfolio_info.isVoid() || portfolio_info.size() == 0) { return null };
  617. portfolio_info.rename!('portfolio_id', 'entity_id');
  618. if(isFromNav == true) {
  619. // 从净值开始计算收益
  620. tb_raw_ret = SELECT * FROM cal_portfolio_nav(portfolio_ids, very_old_date, cal_method) WHERE price_date <= end_day;
  621. // funky thing is you can't use "AS" for the grouping columns?
  622. tb_ret = SELECT portfolio_id, price_date.month(), price_date.last() AS price_date, (1+ret).prod()-1 AS ret, nav.last() AS nav
  623. FROM tb_raw_ret
  624. WHERE price_date <= end_day
  625. GROUP BY portfolio_id, price_date.month();
  626. tb_ret.rename!(['portfolio_id', 'month_price_date'], ['entity_id', 'end_date']);
  627. } else {
  628. // 从pf_portfolio_performance表里读月收益
  629. tb_ret = get_monthly_ret('PF', portfolio_ids, very_old_date, end_day, true);
  630. tb_ret.rename!(['portfolio_id'], ['entity_id']);
  631. }
  632. // 沪深300做基准,同SQL保持一致
  633. primary_benchmark = SELECT entity_id, 'IN00000008' AS benchmark_id FROM portfolio_info;
  634. // 取所有出现的基准月收益
  635. bmk_ret = get_benchmark_return(primary_benchmark, end_day);
  636. risk_free_rate = SELECT fund_id, temporalParse(end_date, 'yyyy-MM') AS end_date, ret FROM get_risk_free_rate(very_old_date, end_day);
  637. t0 = cal_trailing_indicators(portfolio_info, primary_benchmark, tb_ret, end_day, bmk_ret, risk_free_rate);
  638. v_table_name = ['PBI-INCEP', 'PBI-YTD', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y'];
  639. return dict(v_table_name, t0);
  640. }
  641. /*
  642. * Calculate portfolio bfi indicators for one date
  643. *
  644. * @param portfolio_ids <STRING>: comma-delimited portfolio ids
  645. * @param end_day <DATE>: the date
  646. * @param cal_method <INT>: calculate based on cumulative nav (1) or nav (2)
  647. * @param isFromNav <BOOL>: calculate returns from NAV on-the-fly (true) or get from monthly return table (false)
  648. *
  649. * TODO: intergrate with cal_portfolio_indicators
  650. *
  651. * Example: cal_portfolio_bfi_indicators('166002,166114', 2024.08.31, 1, true);
  652. *
  653. */
  654. def cal_portfolio_bfi_indicators(portfolio_ids, end_day, cal_method, isFromNav) {
  655. very_old_date = 1990.01.01;
  656. portfolio_info = get_portfolio_info(portfolio_ids);
  657. if(portfolio_info.isVoid() || portfolio_info.size() == 0) { return null };
  658. portfolio_info.rename!('portfolio_id', 'entity_id');
  659. if(isFromNav == true) {
  660. // 从净值开始计算收益
  661. tb_raw_ret = SELECT * FROM cal_portfolio_nav(portfolio_ids, very_old_date, cal_method) WHERE price_date <= end_day;
  662. // funky thing is you can't use "AS" for the grouping columns?
  663. tb_ret = SELECT portfolio_id, price_date.month(), price_date.last() AS price_date, (1+ret).prod()-1 AS ret, nav.last() AS nav
  664. FROM tb_raw_ret
  665. WHERE price_date <= end_day
  666. GROUP BY portfolio_id, price_date.month();
  667. tb_ret.rename!(['portfolio_id', 'month_price_date'], ['entity_id', 'end_date']);
  668. } else {
  669. // 从pf_portfolio_performance表里读月收益
  670. tb_ret = get_monthly_ret('PF', portfolio_ids, very_old_date, end_day, true);
  671. tb_ret.rename!(['portfolio_id'], ['entity_id']);
  672. }
  673. // 取组合和基准的对照表
  674. bfi_benchmark = SELECT portfolio_id AS entity_id, factor_id AS benchmark_id FROM get_portfolio_bfi_factors(portfolio_ids, end_day.temporalFormat('yyyy-MM'));
  675. if(bfi_benchmark.isVoid() || bfi_benchmark.size() == 0) { return null; }
  676. bmk_ret = get_benchmark_return(bfi_benchmark, end_day);
  677. risk_free_rate = SELECT fund_id, temporalParse(end_date, 'yyyy-MM') AS end_date, ret FROM get_risk_free_rate(very_old_date, end_day);
  678. t0 = cal_trailing_bfi_indicators(portfolio_info, bfi_benchmark, tb_ret, end_day, bmk_ret, risk_free_rate);
  679. v_table_name = ['PBI-INCEP', 'PBI-YTD', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y'];
  680. return dict(v_table_name, t0);
  681. }