indicatorCalculator.dos 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  1. module fundit::indicatorCalculator
  2. /*
  3. * Annulized multiple
  4. */
  5. def get_annulization_multiple(freq) {
  6. ret = 1;
  7. if (freq == 'd') {
  8. ret = 252; // We have differences here between Java and DolphinDB, Java uses 365.25 days
  9. } else if (freq == 'w') {
  10. ret = 52;
  11. } else if (freq == 'm') {
  12. ret = 12;
  13. } else if (freq == 'q') {
  14. ret = 4;
  15. } else if (freq == 's') {
  16. ret = 2;
  17. } else if (freq == 'a') {
  18. ret = 1;
  19. }
  20. return ret;
  21. }
  22. /*
  23. * Trailing Return, Standard Deviation, Skewness, Kurtosis, Max Drawdown, VaR, CVaR
  24. * @param ret: 收益表,需要有 entity_id, price_dat, end_date, nav
  25. * @param freq: 数据频率,d, w, m, q, s, a
  26. *
  27. * Create: 20240904 Joey
  28. * TODO: var and cvar are silightly off compared with Java version
  29. *
  30. */
  31. def cal_basic_performance(ret) {
  32. t = SELECT entity_id, max(end_date) AS end_date, max(price_date) AS price_date, min(price_date) AS min_date,
  33. (nav.last() \ nav.first() - 1).round(6) AS trailing_ret,
  34. iif(price_date.max().month()-price_date.min().month()>12,
  35. (nav.last() \ nav.first()).pow(365 \(max(price_date) - min(price_date)))-1,
  36. (nav.last() \ nav.first() - 1)).round(6) AS trailing_ret_a,
  37. ret.std() AS std_dev,
  38. ret.skew(false) AS skewness,
  39. ret.kurtosis(false) - 3 AS kurtosis,
  40. ret.min() AS wrst_month,
  41. max( 1 - nav \ nav.cummax() ) AS drawdown
  42. FROM ret
  43. GROUP BY entity_id;
  44. // var & cvar require return NOT NULL
  45. // NOTE: DolphinDB supports 4 different ways: normal, logNormal, historical, monteCarlo. we use historical
  46. t1 = SELECT entity_id, max(end_date) AS end_date, max(price_date) AS price_date,
  47. ret.VaR('historical', 0.95) AS var,
  48. ret.CVaR('historical', 0.95) AS cvar
  49. FROM ret
  50. WHERE ret.ret > - 1
  51. GROUP BY entity_id;
  52. 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);
  53. }
  54. /*
  55. * Lower Partial Moment
  56. * NOTE: risk free rate is used as Minimal Accepted Rate (MAR) here
  57. *
  58. */
  59. def cal_LPM(ret, risk_free_rate) {
  60. t = SELECT *, count(entity_id) AS cnt FROM ret WHERE ret > -1 CONTEXT BY entity_id;
  61. lpm = SELECT t.entity_id, max(t.end_date) AS end_date,
  62. (sum (rfr.ret - t.ret) \ (t.cnt[0])).pow(1\1) AS lpm1,
  63. (sum2(rfr.ret - t.ret) \ (t.cnt[0])).pow(1\2) AS lpm2,
  64. (sum3(rfr.ret - t.ret) \ (t.cnt[0])).pow(1\3) AS lpm3
  65. FROM t
  66. INNER JOIN risk_free_rate rfr ON t.end_date = rfr.end_date
  67. WHERE t.ret < rfr.ret
  68. GROUP BY t.entity_id;
  69. return lpm;
  70. }
  71. /*
  72. * Downside Devision, Omega Ratio, Sortino Ratio, Kappa Ratio
  73. *
  74. * TODO: Java version of Downside Deviation (LPM2) uses cnt-1 as denominator to calculate mean excess return, which might be wrong
  75. * Java version of Omega could be wrong because Java uses annualized returns and cnt-1
  76. * Java'version of Kappa could be very wrong
  77. *
  78. */
  79. def cal_omega_sortino_kappa(ret, risk_free_rate) {
  80. lpm = cal_LPM(ret, risk_free_rate);
  81. tb = SELECT t.entity_id,
  82. l.lpm2[0] AS ds_dev,
  83. (t.ret - rfr.ret ).mean() \ l.lpm1[0] + 1 AS omega,
  84. (t.ret - rfr.ret ).mean() \ l.lpm2[0] AS sortino,
  85. (t.ret - rfr.ret ).mean() \ l.lpm3[0] AS kappa
  86. FROM ret t
  87. INNER JOIN lpm l ON t.entity_id = l.entity_id
  88. INNER JOIN risk_free_rate rfr ON t.end_date = rfr.end_date
  89. GROUP BY t.entity_id;
  90. return tb;
  91. }
  92. /*
  93. * Alpha & Beta
  94. *
  95. */
  96. def cal_alpha_beta(ret, bmk_ret, risk_free) {
  97. t = SELECT t.entity_id, t.end_date, t.ret, bmk.ret AS ret_bmk
  98. FROM ret t
  99. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date
  100. WHERE t.ret > -1
  101. AND bmk.ret > -1;
  102. beta = SELECT ret.beta(ret_bmk) AS beta FROM t GROUP BY entity_id;
  103. alpha = SELECT t.entity_id, (t.ret - rfr.ret).mean() - beta.beta[0] * (t.ret_bmk - rfr.ret).mean() AS alpha
  104. FROM t
  105. INNER JOIN beta beta ON t.entity_id = beta.entity_id
  106. INNER JOIN risk_free_rate rfr ON t.end_date = rfr.end_date
  107. GROUP BY t.entity_id;
  108. return ( SELECT * FROM beta AS b INNER JOIN alpha AS a ON a.entity_id = b.entity_id );
  109. }
  110. /*
  111. * Winning Ratio, Tracking Error, Information Ratio
  112. * TODO: Information Ratio is way off!
  113. * Not sure how to describe a giant number("inf"), for now 999 is used
  114. */
  115. def cal_benchmark_tracking(ret, bmk_ret) {
  116. t0 = SELECT t.entity_id, t.end_date, t.ret, bmk.ret AS ret_bmk, count(entity_id) AS cnt, (t.ret - bmk.ret) AS exc_ret
  117. FROM ret t
  118. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date
  119. WHERE t.ret > -1
  120. AND bmk.ret > -1
  121. CONTEXT BY t.entity_id;
  122. t = SELECT entity_id,
  123. exc_ret.bucketCount(0:999, 1) \ cnt[0] AS winrate,
  124. exc_ret.std() AS track_error,
  125. exc_ret.mean() / exc_ret.std() AS info
  126. FROM t0 GROUP BY entity_id
  127. return t;
  128. }
  129. /*
  130. * Sharpe Ratio
  131. */
  132. def cal_sharpe(ret, std_dev, risk_free_rate) {
  133. sharpe = SELECT t.entity_id, (t.ret - rfr.ret).mean() / std.std_dev[0] AS sharpe
  134. FROM ret t
  135. INNER JOIN std_dev std ON t.entity_id = std.entity_id
  136. INNER JOIN risk_free_rate rfr ON t.end_date = rfr.end_date
  137. GROUP BY t.entity_id;
  138. return sharpe;
  139. }
  140. /*
  141. * Treynor Ratio
  142. */
  143. def cal_treynor(ret, risk_free_rate, beta) {
  144. t = SELECT *, count(entity_id) AS cnt
  145. FROM ret t
  146. INNER JOIN risk_free_rate rfr ON t.end_date = rfr.end_date
  147. WHERE t.ret > -1
  148. AND rfr.ret > -1
  149. CONTEXT BY t.entity_id;
  150. treynor = SELECT t.entity_id, ((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
  151. FROM t
  152. INNER JOIN beta AS beta ON t.entity_id = beta.entity_id
  153. GROUP BY t.entity_id;
  154. return treynor;
  155. }
  156. /*
  157. * Jensen's Alpha
  158. * TODO: the result is slightly off
  159. */
  160. def cal_jensen(ret, bmk_ret, risk_free_rate, beta) {
  161. jensen = SELECT t.entity_id, t.ret.mean() - rfr.ret.mean() - beta.beta[0] * (bmk.ret.mean() - rfr.ret.mean()) AS jensen
  162. FROM ret t
  163. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date
  164. INNER JOIN risk_free_rate rfr ON t.end_date = rfr.end_date
  165. INNER JOIN beta beta ON t.entity_id = beta.entity_id
  166. GROUP BY t.entity_id;
  167. return jensen;
  168. }
  169. /*
  170. * Calmar Ratio
  171. * TODO: the result is off
  172. *
  173. */
  174. def cal_calmar(ret_a){
  175. calmar = SELECT entity_id, trailing_ret_a \ drawdown AS calmar
  176. FROM ret_a;
  177. return calmar;
  178. }
  179. /*
  180. * Modigliani Modigliani Measure (M2)
  181. * NOTE: M2 = sharpe * std(benchmark) + risk_free_rate
  182. */
  183. def cal_m2(ret, bmk_ret, risk_free_rate) {
  184. m2 = SELECT t.entity_id, (t.ret - rfr.ret).mean() / t.ret.std() * bmk.ret.std() + rfr.ret.mean() AS m2
  185. FROM ret t
  186. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date
  187. INNER JOIN risk_free_rate rfr ON t.end_date = rfr.end_date
  188. GROUP BY t.entity_id;
  189. return m2;
  190. }
  191. /*
  192. * Monthly Since_inception_date Indicator Calculation
  193. * @param: ret: historical return table
  194. * index_ret: historical benchmark return table
  195. * risk_free: historical risk free rate table
  196. *
  197. * @return: indicators table
  198. *
  199. *
  200. * Create 20240904 模仿Java & python代码在Dolphin中实现,具体计算逻辑可能会有不同 Joey
  201. * TODO: some datapoints require more data, we need a way to disable calculation for them
  202. *
  203. */
  204. def cal_indicators(mutable ret, index_ret, risk_free, freq) {
  205. if (! freq IN ['d', 'w', 'm', 'q', 's', 'a']) return null;
  206. // sorting for correct first() and last() value
  207. ret.sortBy!(['entity_id', 'price_date'], [1, 1]);
  208. // 收益、标准差、偏度、峰度、最大回撤、VaR, CVaR
  209. rtn = cal_basic_performance(ret);
  210. // alpha, beta
  211. alpha_beta = cal_alpha_beta(ret, index_ret, risk_free);
  212. // 胜率、跟踪误差、信息比率
  213. bmk_tracking = cal_benchmark_tracking(ret, index_ret);
  214. // 夏普
  215. sharpe = cal_sharpe(ret, rtn, risk_free);
  216. // 特雷诺
  217. treynor = cal_treynor(ret, risk_free, alpha_beta);
  218. // 詹森指数
  219. jensen = cal_jensen(ret, index_ret, risk_free, alpha_beta);
  220. // 卡玛比率
  221. calmar = cal_calmar(rtn);
  222. // 整合后的下行标准差、欧米伽、索提诺、卡帕
  223. lpms = cal_omega_sortino_kappa(ret, risk_free);
  224. // M2
  225. m2 = cal_m2(ret, index_ret, risk_free);
  226. r = SELECT * FROM rtn a1
  227. LEFT JOIN alpha_beta ON a1.entity_id = alpha_beta.entity_id
  228. LEFT JOIN bmk_tracking ON a1.entity_id = bmk_tracking.entity_id
  229. LEFT JOIN sharpe ON a1.entity_id = sharpe.entity_id
  230. LEFT JOIN treynor ON a1.entity_id = treynor.entity_id
  231. LEFT JOIN jensen ON a1.entity_id = jensen.entity_id
  232. LEFT JOIN calmar ON a1.entity_id = calmar.entity_id
  233. LEFT JOIN lpms ON a1.entity_id = lpms.entity_id
  234. LEFT JOIN m2 ON a1.entity_id = m2.entity_id
  235. // 年化各数据点
  236. // GIPS RULE: NO annulization for data less than 1 year
  237. plainAnnu = get_annulization_multiple(freq);
  238. sqrtAnnu = sqrt(get_annulization_multiple(freq));
  239. r.addColumn(['ds_dev_a', 'alpha_a', 'sharpe_a', 'sortino_a', 'jensen_a', 'track_error_a', 'info_a', 'm2_a'], [DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE]);
  240. UPDATE r
  241. SET ds_dev_a = ds_dev * sqrtAnnu,
  242. alpha_a = alpha * plainAnnu,
  243. sharpe_a = sharpe * sqrtAnnu,
  244. sortino_a = sortino * sqrtAnnu,
  245. jensen_a = jensen * plainAnnu,
  246. track_error_a = track_error * sqrtAnnu,
  247. info_a = info * sqrtAnnu,
  248. m2_a = m2 * plainAnnu
  249. WHERE price_date.month() - min_date.month() >= 12;
  250. return r;
  251. }