indicatorCalculator.dos 59 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381
  1. module fundit::indicatorCalculator
  2. use fundit::sqlUtilities
  3. use fundit::operationDataPuller
  4. use fundit::performanceDataPuller
  5. use fundit::ms_dataPuller
  6. use fundit::returnCalculator
  7. use fundit::navCalculator
  8. /*
  9. * 将VaR包裹一层,使之成为系统认可的聚集函数
  10. * @param returns <DOUBLE VECTOR>: 非空收益率
  11. * @param method <STRING>: 'normal', 'logNormal', 'historical', 'monteCarlo'
  12. * @param confidenceLevel <DOUBLE>: 置信水平,取值区间(0, 1)
  13. *
  14. */
  15. defg aggVaR(returns, method, confidenceLevel) {
  16. if(returns.form() != 1) return null;
  17. return returns.VaR(method, confidenceLevel);
  18. }
  19. /*
  20. * 将CVaR包裹一层,使之成为系统认可的聚集函数
  21. * @param returns <DOUBLE VECTOR>: 非空收益率
  22. * @param method <STRING>: 'normal', 'logNormal', 'historical', 'monteCarlo'
  23. * @param confidenceLevel <DOUBLE>: 置信水平,取值区间(0, 1)
  24. *
  25. */
  26. defg aggCVaR(returns, method, confidenceLevel) {
  27. if(returns.form() != 1) return null;
  28. return returns.CVaR(method, confidenceLevel);
  29. }
  30. /*
  31. * 最大回撤
  32. *
  33. *
  34. */
  35. defg maxDrawdown(navs) {
  36. return max(1 - navs \ cummax(navs));
  37. }
  38. /*
  39. * 几何平均值
  40. *
  41. */
  42. defg geometricMean(x){
  43. return x.log().avg().exp()
  44. }
  45. /*
  46. * Trailing Monthly Return, Standard Deviation, Skewness, Kurtosis, Max Drawdown, VaR, CVaR, Calmar Ratio
  47. *
  48. * @param entity_info <TABLE>: xxx_information表,NEED COLUMNS entity_id, inception_date
  49. * @param ret <TABLE>: 收益表,需要有 entity_id, price_dat, end_date, nav
  50. * @param trailing_month <STRING>: trailing X month or ytd, incep
  51. *
  52. * NOTE: standard deviation of Java version is noncompliant-GIPS annulized number
  53. *
  54. * Create: 20240904 Joey
  55. * TODO: SQL is wrong for max drawdowns
  56. * TODO: var, cvar, calmar are off; std dev, skewness, kurtosis are slightly off
  57. * TODO: SQL is missing for portfolio since inception date return
  58. * TODO: Java calculates max drawdown even there is no nav
  59. * TODO: Java ytd worst month could be wrong (i.e. portfolio 166002, 2024-03)
  60. * TODO: arith_mean & gerom_mean ARE NOT TESTED
  61. *
  62. */
  63. def cal_basic_performance(entity_info, ret, trailing_month) {
  64. // accumulate 版的 skewness, kurtosis, var, cvar 似乎都不对劲,只好找个笨办法来实现
  65. if(trailing_month == 'incep') {
  66. // 需要至少6个数才计算标准差、峰度、偏度
  67. t0 = SELECT price_date.max() AS price_date, nav, ret,
  68. ret.mean() AS arith_mean, (1+ret).prod().pow(1\count(entity_id))-1 AS geom_mean,
  69. iif(count(entity_id) > 5, std(ret), null) AS std_dev,
  70. iif(count(entity_id) > 5, skew(ret, false), null) AS skewness,
  71. iif(count(entity_id) > 5, kurtosis(ret, false), null)-3 AS kurtosis,
  72. min(ret) AS wrst_month
  73. FROM ret
  74. WHERE ret > -1
  75. GROUP BY entity_id
  76. CGROUP BY end_date
  77. ORDER BY entity_id, end_date;
  78. // 年化收益(给后面计算Calmar用)
  79. t0.addColumn(['trailing_ret', 'trailing_ret_a'], [DOUBLE, DOUBLE]);
  80. // MySQL 有bug导致首月ret_1m为空,所以用 prod(1+ret)-1算的有时不对
  81. UPDATE t0
  82. SET trailing_ret = nav\ini_value - 1,
  83. trailing_ret_a = iif(t0.end_date - ei.inception_date.month() > 12, (nav\ini_value).pow(12\(t0.end_date - ei.inception_date.month())) - 1, nav\ini_value - 1)
  84. FROM ej(t0, entity_info ei, 'entity_id');
  85. // 不会用上面的办法算最大回撤, VaR, CVaR
  86. t_var = SELECT entity_id, end_date, ret,
  87. cummax(1 - nav \ cummax(nav)) AS drawdown,
  88. - cumpercentile(ret, 5, 'linear') AS var
  89. FROM ret WHERE ret > -1
  90. CONTEXT BY entity_id;
  91. t_cvar = SELECT entity_id, end_date, drawdown, var,
  92. - cumavg(iif(ret <= -var, ret, null)) AS cvar
  93. FROM t_var
  94. CONTEXT BY entity_id;
  95. t1 = SELECT t0.*, t_cvar.drawdown, t_cvar.var, t_cvar.cvar
  96. FROM t0 LEFT JOIN t_cvar ON t0.entity_id = t_cvar.entity_id AND t0.end_date = t_cvar.end_date
  97. ORDER BY t0.entity_id, t0.end_date;
  98. } else if(trailing_month == 'ytd') {
  99. t1 = SELECT entity_id, end_date, price_date.cummax() AS price_date, nav, ret,
  100. ret.cumavg() AS arith_mean, (1+ret).cumprod().pow(1\cumcount(entity_id))-1 AS geom_mean,
  101. cumprod(1+ret)-1 AS trailing_ret,
  102. cumprod(1+ret)-1 AS trailing_ret_a, // no need annulization for ytd
  103. iif(cumcount(entity_id) > 5, cumstd(ret), null) AS std_dev,
  104. iif(cumcount(entity_id) > 5, tmoving(skew{, false}, end_date, ret, 12), null) AS skewness,
  105. iif(cumcount(entity_id) > 5, tmoving(kurtosis{, false}, end_date, ret, 12)-3, null) AS kurtosis,
  106. cummin(ret) AS wrst_month,
  107. cummax(1 - nav \ cummax(nav)) AS drawdown
  108. FROM ret WHERE ret > -1
  109. CONTEXT BY entity_id, end_date.year()
  110. ORDER BY entity_id, end_date;
  111. // trailing x month
  112. } else {
  113. // 先转成STRING,避免单字符被认为是CHAR而导致转整型出错的结果
  114. win = trailing_month$STRING$INT;
  115. t1 = SELECT entity_id, end_date, price_date.mmax(win) AS price_date, nav, ret,
  116. ret.mavg(win) AS arith_mean, (1+ret).mprod(win).pow(1\mcount(entity_id, win))-1 AS geom_mean,
  117. mprod(1+ret, win)-1 AS trailing_ret,
  118. iif(win > 12,
  119. mprod(1+ret, win).pow(12\win)-1,
  120. mprod(1+ret, win)-1) AS trailing_ret_a,
  121. mstd(ret, win) AS std_dev,
  122. mskew(ret, win, false) AS skewness,
  123. mkurtosis(ret, win, false) - 3 AS kurtosis,
  124. mmin(ret, win) AS wrst_month,
  125. moving(maxDrawdown, nav, win) AS drawdown,
  126. moving(aggVaR{, 'historical', 0.95}, ret, win) AS var,
  127. moving(aggCVaR{, 'historical', 0.95}, ret, win) AS cvar
  128. FROM ret WHERE ret > -1
  129. CONTEXT BY entity_id
  130. ORDER BY entity_id, end_date;
  131. }
  132. t1.addColumn('calmar', DOUBLE);
  133. UPDATE t1 SET calmar = iif(drawdown == 0, null, trailing_ret_a\drawdown);
  134. return t1;
  135. }
  136. /*
  137. * Lower Partial Moment
  138. * NOTE: risk free rate is used as Minimal Accepted Rate (MAR) here
  139. *
  140. */
  141. def cal_LPM(ret, risk_free, trailing_month) {
  142. t = SELECT *, cumcount(entity_id) AS cnt FROM ret WHERE ret > -1 CONTEXT BY entity_id;
  143. if(trailing_month == 'incep') {
  144. lpm = SELECT entity_id, end_date,
  145. iif(cumcount(end_date) > 5, (cumsum (iif(rfr.ret > t.ret, rfr.ret - t.ret, 0)) \ cumcount(end_date)).pow(1\1), null) AS lpm1,
  146. iif(cumcount(end_date) > 5, (cumsum2 (iif(rfr.ret > t.ret, rfr.ret - t.ret, 0)) \ cumcount(end_date)).pow(1\2), null) AS lpm2,
  147. iif(cumcount(end_date) > 5, (cumsum3 (iif(rfr.ret > t.ret, rfr.ret - t.ret, 0)) \ cumcount(end_date)).pow(1\3), null) AS lpm3
  148. FROM t
  149. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  150. CONTEXT BY entity_id
  151. ORDER BY entity_id, end_date;
  152. } else if(trailing_month == 'ytd') {
  153. lpm = SELECT entity_id, end_date,
  154. iif(cumcount(end_date) > 5, (cumsum (iif(rfr.ret > t.ret, rfr.ret - t.ret, 0)) \ cumcount(end_date)).pow(1\1), null) AS lpm1,
  155. iif(cumcount(end_date) > 5, (cumsum2 (iif(rfr.ret > t.ret, rfr.ret - t.ret, 0)) \ cumcount(end_date)).pow(1\2), null) AS lpm2,
  156. iif(cumcount(end_date) > 5, (cumsum3 (iif(rfr.ret > t.ret, rfr.ret - t.ret, 0)) \ cumcount(end_date)).pow(1\3), null) AS lpm3
  157. FROM t
  158. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  159. CONTEXT BY entity_id, end_date.year()
  160. ORDER BY entity_id, end_date;
  161. } else {
  162. win = trailing_month$STRING$INT;
  163. lpm = SELECT t.entity_id, t.end_date,
  164. (msum (iif(rfr.ret > t.ret, rfr.ret - t.ret, 0), win) \ mcount(end_date, win)).pow(1\1) AS lpm1,
  165. (msum2(iif(rfr.ret > t.ret, rfr.ret - t.ret, 0), win) \ mcount(end_date, win)).pow(1\2) AS lpm2,
  166. (moving(sum3, iif(rfr.ret > t.ret, rfr.ret - t.ret, 0), win) \ mcount(end_date, win)).pow(1\3) AS lpm3
  167. FROM t
  168. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  169. CONTEXT BY t.entity_id
  170. ORDER BY entity_id, end_date;
  171. }
  172. return lpm;
  173. }
  174. /*
  175. * Downside Devision, Omega Ratio, Sortino Ratio, Kappa Ratio
  176. *
  177. * TODO: Java version of Downside Deviation (LPM2) uses cnt-1 as denominator to calculate mean excess return, which might be wrong
  178. * Java version of Omega could be wrong because Java uses annualized returns and cnt-1
  179. * Java'version of Kappa could be very wrong
  180. *
  181. */
  182. def cal_omega_sortino_kappa(ret, risk_free, trailing_month) {
  183. lpm = cal_LPM(ret, risk_free, trailing_month);
  184. if(trailing_month == 'incep') {
  185. tb = SELECT t.entity_id, t.end_date,
  186. l.lpm2 AS ds_dev,
  187. iif(l.lpm1.round(4) == 0, NULL, (t.ret - rfr.ret ).cumavg() \ l.lpm1 + 1) AS omega,
  188. iif(l.lpm2.round(4) == 0, NULL, (t.ret - rfr.ret ).cumavg() \ l.lpm2) AS sortino,
  189. iif(l.lpm3.round(4) == 0, NULL, (t.ret - rfr.ret ).cumavg() \ l.lpm3) AS kappa
  190. FROM ret t
  191. INNER JOIN lpm l ON t.entity_id = l.entity_id AND t.end_date = l.end_date
  192. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  193. WHERE t.ret > -1
  194. CONTEXT BY t.entity_id;
  195. } else if(trailing_month == 'ytd') {
  196. tb = SELECT t.entity_id, t.end_date,
  197. l.lpm2 AS ds_dev,
  198. iif(l.lpm1.round(4) == 0, NULL, (t.ret - rfr.ret ).cumavg() \ l.lpm1 + 1) AS omega,
  199. iif(l.lpm2.round(4) == 0, NULL, (t.ret - rfr.ret ).cumavg() \ l.lpm2) AS sortino,
  200. iif(l.lpm3.round(4) == 0, NULL, (t.ret - rfr.ret ).cumavg() \ l.lpm3) AS kappa
  201. FROM ret t
  202. INNER JOIN lpm l ON t.entity_id = l.entity_id AND t.end_date = l.end_date
  203. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  204. WHERE t.ret > -1
  205. CONTEXT BY t.entity_id, t.end_date.year();
  206. } else {
  207. win = trailing_month$STRING$INT;
  208. tb = SELECT t.entity_id, t.end_date,
  209. l.lpm2 AS ds_dev,
  210. iif(l.lpm1.round(4) == 0, NULL, (t.ret - rfr.ret ).mavg(win) \ l.lpm1 + 1) AS omega,
  211. iif(l.lpm2.round(4) == 0, NULL, (t.ret - rfr.ret ).mavg(win) \ l.lpm2) AS sortino,
  212. iif(l.lpm3.round(4) == 0, NULL, (t.ret - rfr.ret ).mavg(win) \ l.lpm3) AS kappa
  213. FROM ret t
  214. INNER JOIN lpm l ON t.entity_id = l.entity_id AND t.end_date = l.end_date
  215. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  216. WHERE t.ret > -1
  217. CONTEXT BY t.entity_id;
  218. }
  219. return tb;
  220. }
  221. /*
  222. * Winning Ratio, Tracking Error, Information Ratio
  223. *
  224. * NOTE: mcount is very unique in mFun, because it doesn't support minPeriods(BUG?), while others default minPeriods = window.
  225. * As a result, we have to delete records having winrate but no tracking error and info ratio for the sake of consisence
  226. *
  227. * TODO: Win Rate incept is off, because Java incorrectly takes all end_date as denominator even when benchmark has no price
  228. * Information Ratio is way off!
  229. * Not sure how to describe a giant number("inf"), for now 999 is used
  230. */
  231. def cal_benchmark_tracking(ret, benchmarks, bmk_ret, trailing_month) {
  232. if(trailing_month == 'incep') {
  233. t0 = SELECT t.entity_id, t.end_date, t.price_date,
  234. t.ret, bmk.ret AS ret_bmk,
  235. t.entity_id.cumcount() AS cnt,
  236. t.ret - bmk.ret AS exc_ret, bm.benchmark_id
  237. FROM ret t
  238. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id AND t.end_date = bm.end_date
  239. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  240. WHERE t.ret > -1
  241. AND bmk.ret > -1
  242. CONTEXT BY t.entity_id, bm.benchmark_id;
  243. t = SELECT entity_id, end_date, benchmark_id,
  244. iif(cnt > 5, cumcount(iif(exc_ret >= 0, 1, null)) \ cnt, null) AS winrate,
  245. iif(cnt > 5, exc_ret.cumstd(), null) AS track_error,
  246. iif(cnt > 5, iif(exc_ret.cumstd() == 0, null, exc_ret.cumavg() \ exc_ret.cumstd()), 5) AS info
  247. FROM t0
  248. CONTEXT BY entity_id, benchmark_id
  249. ORDER BY entity_id, end_date, benchmark_id;
  250. } else if(trailing_month == 'ytd') {
  251. t0 = SELECT t.entity_id, t.end_date, t.price_date,
  252. t.ret, bmk.ret AS ret_bmk,
  253. t.entity_id.cumcount() AS cnt, t.ret - bmk.ret AS exc_ret, bm.benchmark_id
  254. FROM ret t
  255. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id AND t.end_date = bm.end_date
  256. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  257. WHERE t.ret > -1
  258. AND bmk.ret > -1
  259. CONTEXT BY t.entity_id, bm.benchmark_id, t.end_date.year();
  260. t = SELECT entity_id, end_date, benchmark_id,
  261. iif(cnt > 5, cumcount(iif(exc_ret >= 0, 1, null)) \ cnt, null) AS winrate,
  262. iif(cnt > 5, exc_ret.cumstd(), null) AS track_error,
  263. iif(cnt > 5, iif(exc_ret.cumstd() == 0, null, exc_ret.cumavg() \ exc_ret.cumstd()), null) AS info
  264. FROM t0
  265. CONTEXT BY entity_id, benchmark_id, end_date.year()
  266. ORDER BY entity_id, end_date, benchmark_id;
  267. } else {
  268. win = trailing_month$STRING$INT;
  269. t0 = SELECT t.entity_id, t.end_date, t.price_date,
  270. t.ret, bmk.ret AS ret_bmk,
  271. t.entity_id.mcount(win) AS cnt,
  272. t.ret - bmk.ret AS exc_ret, bm.benchmark_id
  273. FROM ret t
  274. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id AND t.end_date = bm.end_date
  275. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  276. WHERE t.ret > -1
  277. AND bmk.ret > -1
  278. CONTEXT BY t.entity_id, bm.benchmark_id;
  279. t = SELECT entity_id, end_date, benchmark_id,
  280. iif(cnt > 5, mcount(iif(exc_ret >= 0, 1, null), win) \ cnt, null) AS winrate,
  281. iif(cnt > 5, mstd(exc_ret, win), null) AS track_error,
  282. iif(cnt > 5, iif(mstd(exc_ret, win) == 0, null, mavg(exc_ret, win) \ mstd(exc_ret, win)), null) AS info
  283. FROM t0
  284. CONTEXT BY entity_id, benchmark_id
  285. ORDER BY entity_id, end_date, benchmark_id;
  286. }
  287. return t; //SELECT * FROM t WHERE track_error IS NOT NULL;
  288. }
  289. /*
  290. * Alpha & Beta
  291. * NOTE: alpha of Java version is wrong because it doesn't use risk free rate
  292. */
  293. def cal_alpha_beta(ret, benchmarks, bmk_ret, risk_free, trailing_month) {
  294. t = SELECT t.entity_id, t.end_date, t.ret, bm.benchmark_id, bmk.ret AS ret_bmk
  295. FROM ret t
  296. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id AND t.end_date = bm.end_date
  297. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  298. WHERE t.ret > -1
  299. AND bmk.ret > -1;
  300. if(trailing_month == 'incep') {
  301. beta = SELECT entity_id, end_date, benchmark_id,
  302. iif(cumcount(end_date) > 5, ret.cumbeta(ret_bmk), null) AS beta
  303. FROM t CONTEXT BY entity_id, benchmark_id;
  304. alpha = SELECT t.entity_id, t.end_date, t.benchmark_id, beta.beta AS beta,
  305. (t.ret - rfr.ret).cumavg() - beta.beta * (t.ret_bmk - rfr.ret).cumavg() AS alpha
  306. FROM t
  307. INNER JOIN beta beta ON t.entity_id = beta.entity_id AND t.benchmark_id = beta.benchmark_id AND t.end_date = beta.end_date
  308. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  309. CONTEXT BY t.entity_id, t.benchmark_id
  310. ORDER BY t.entity_id, t.end_date, t.benchmark_id;
  311. } else if(trailing_month == 'ytd') {
  312. beta = SELECT entity_id, end_date, benchmark_id,
  313. iif(cumcount(end_date) > 5, ret.cumbeta(ret_bmk), null) AS beta
  314. FROM t CONTEXT BY entity_id, benchmark_id, end_date.year();
  315. alpha = SELECT t.entity_id, t.end_date, t.benchmark_id, beta.beta AS beta,
  316. (t.ret - rfr.ret).cumavg() - beta.beta * (t.ret_bmk - rfr.ret).cumavg() AS alpha
  317. FROM t
  318. INNER JOIN beta beta ON t.entity_id = beta.entity_id AND t.benchmark_id = beta.benchmark_id AND t.end_date = beta.end_date
  319. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  320. CONTEXT BY t.entity_id, t.benchmark_id, t.end_date.year()
  321. ORDER BY t.entity_id, t.end_date, t.benchmark_id;
  322. } else {
  323. win = trailing_month$STRING$INT;
  324. beta = SELECT entity_id, end_date, benchmark_id,
  325. iif(mcount(end_date, win) > 5, ret.mbeta(ret_bmk, win), null) AS beta
  326. FROM t CONTEXT BY entity_id, benchmark_id;
  327. alpha = SELECT t.entity_id, t.end_date, t.benchmark_id, beta.beta AS beta,
  328. (t.ret - rfr.ret).mavg(win) - beta.beta * (t.ret_bmk - rfr.ret).mavg(win) AS alpha
  329. FROM t
  330. INNER JOIN beta beta ON t.entity_id = beta.entity_id AND t.benchmark_id = beta.benchmark_id AND t.end_date = beta.end_date
  331. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  332. CONTEXT BY t.entity_id, t.benchmark_id
  333. ORDER BY t.entity_id, t.end_date, t.benchmark_id;
  334. }
  335. return alpha;
  336. }
  337. /*
  338. * Upside/Down Capture Return/Ratio
  339. *
  340. * TODO: trailing x month values are way off!
  341. *
  342. */
  343. def cal_capture_ratio(ret, benchmarks, bmk_ret, trailing_month) {
  344. if(trailing_month == 'incep') {
  345. t1 = SELECT t.entity_id, t.end_date,
  346. (1 + iif(bmk.ret >= 0, t.ret, 0)).cumprod() AS upside_ret,
  347. (1 + iif(bmk.ret >= 0, bmk.ret, 0)).cumprod() AS bmk_upside_ret,
  348. cumcount(iif(bmk.ret >= 0, 1, null)) AS bmk_upside_cnt,
  349. (1 + iif(bmk.ret < 0, t.ret, 0)).cumprod() AS downside_ret,
  350. (1 + iif(bmk.ret < 0, bmk.ret, 0)).cumprod() AS bmk_downside_ret,
  351. cumcount(iif(bmk.ret < 0, 1, null)) AS bmk_downside_cnt,
  352. bm.benchmark_id
  353. FROM ret t
  354. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id AND t.end_date = bm.end_date
  355. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id AND t.end_date = bmk.end_date
  356. WHERE t.ret > -1
  357. AND bmk.ret > -1
  358. CONTEXT BY t.entity_id, bm.benchmark_id;
  359. } else if(trailing_month == 'ytd') {
  360. t1 = SELECT t.entity_id, t.end_date,
  361. (1 + iif(bmk.ret >= 0, t.ret, 0)).cumprod() AS upside_ret,
  362. (1 + iif(bmk.ret >= 0, bmk.ret, 0)).cumprod() AS bmk_upside_ret,
  363. cumcount(iif(bmk.ret >= 0, 1, null)) AS bmk_upside_cnt,
  364. (1 + iif(bmk.ret < 0, t.ret, 0)).cumprod() AS downside_ret,
  365. (1 + iif(bmk.ret < 0, bmk.ret, 0)).cumprod() AS bmk_downside_ret,
  366. cumcount(iif(bmk.ret < 0, 1, null)) AS bmk_downside_cnt,
  367. bm.benchmark_id
  368. FROM ret t
  369. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id AND t.end_date = bm.end_date
  370. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id AND t.end_date = bmk.end_date
  371. WHERE t.ret > -1
  372. AND bmk.ret > -1
  373. CONTEXT BY t.entity_id, bm.benchmark_id, t.end_date.year();
  374. } else {
  375. win = trailing_month$STRING$INT;
  376. t1 = SELECT t.entity_id, t.end_date,
  377. (1 + iif(bmk.ret >= 0, t.ret, 0)).mprod(win) AS upside_ret,
  378. (1 + iif(bmk.ret >= 0, bmk.ret, 0)).mprod(win) AS bmk_upside_ret,
  379. mcount(iif(bmk.ret >= 0, 1, null), win) AS bmk_upside_cnt,
  380. (1 + iif(bmk.ret < 0, t.ret, 0)).mprod(win) AS downside_ret,
  381. (1 + iif(bmk.ret < 0, bmk.ret, 0)).mprod(win) AS bmk_downside_ret,
  382. mcount(iif(bmk.ret < 0, 1, null), win) AS bmk_downside_cnt,
  383. bm.benchmark_id
  384. FROM ret t
  385. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id AND t.end_date = bm.end_date
  386. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id AND t.end_date = bmk.end_date
  387. WHERE t.ret > -1
  388. AND bmk.ret > -1
  389. CONTEXT BY t.entity_id, bm.benchmark_id;
  390. }
  391. t = SELECT entity_id, end_date, benchmark_id,
  392. iif(t1.bmk_upside_cnt == 0, NULL, t1.upside_ret.pow(1 \ t1.bmk_upside_cnt)-1) AS upside_capture_ret,
  393. iif(t1.bmk_upside_cnt == 0, NULL, (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,
  394. iif(t1.bmk_downside_cnt == 0, NULL, t1.downside_ret.pow(1 \ t1.bmk_downside_cnt)-1) AS downside_capture_ret,
  395. iif(t1.bmk_downside_cnt == 0, NULL, (t1.downside_ret.pow(1 \ t1.bmk_downside_cnt)-1)/(t1.bmk_downside_ret.pow(1 \ t1.bmk_downside_cnt)-1)) AS downside_capture_ratio
  396. FROM t1
  397. ORDER BY entity_id, benchmark_id, end_date;
  398. return t;
  399. }
  400. /*
  401. * Sharpe Ratio
  402. * NOTE: Java version is noncompliant-GIPS annulized number
  403. */
  404. def cal_sharpe(ret, std_dev, risk_free, trailing_month) {
  405. if(trailing_month == 'incep') {
  406. sharpe = SELECT t.entity_id, t.end_date, (t.ret - rfr.ret).cumavg() \ std.std_dev AS sharpe
  407. FROM ret t
  408. INNER JOIN std_dev std ON t.entity_id = std.entity_id AND t.end_date = std.end_date
  409. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  410. WHERE std.std_dev.round(4) <> 0 AND t.ret > -1
  411. CONTEXT BY t.entity_id;
  412. } else if(trailing_month == 'ytd') {
  413. sharpe = SELECT t.entity_id, t.end_date, (t.ret - rfr.ret).cumavg() \ std.std_dev AS sharpe
  414. FROM ret t
  415. INNER JOIN std_dev std ON t.entity_id = std.entity_id AND t.end_date = std.end_date
  416. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  417. WHERE std.std_dev.round(4) <> 0 AND t.ret > -1
  418. CONTEXT BY t.entity_id, t.end_date.year();
  419. } else {
  420. win = trailing_month$STRING$INT;
  421. sharpe = SELECT t.entity_id, t.end_date, (t.ret - rfr.ret).mavg(win) \ std.std_dev AS sharpe
  422. FROM ret t
  423. INNER JOIN std_dev std ON t.entity_id = std.entity_id AND t.end_date = std.end_date
  424. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  425. WHERE std.std_dev.round(4) <> 0 AND t.ret > -1
  426. CONTEXT BY t.entity_id;
  427. }
  428. return sharpe;
  429. }
  430. /*
  431. * Treynor Ratio = annulized excess return / beta
  432. *
  433. * TODO: ytd is off because Java uses non-GIPS rule to annulize return
  434. */
  435. def cal_treynor(ret, risk_free, beta, trailing_month) {
  436. if(trailing_month == 'incep') {
  437. t = SELECT *, cumcount(entity_id) AS cnt
  438. FROM ret t
  439. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  440. WHERE t.ret > -1
  441. AND rfr.ret > -1
  442. CONTEXT BY t.entity_id;
  443. treynor = SELECT t.entity_id, t.end_date, beta.benchmark_id,
  444. iif(beta.beta.round(4) == 0, NULL,
  445. ((1 + t.ret).cumprod().pow(12\iif(t.cnt<12, 12, t.cnt)) - (1 + t.rfr_ret).cumprod().pow(12\iif(t.cnt<12, 12, t.cnt))) \ beta.beta) AS treynor
  446. FROM t
  447. INNER JOIN beta AS beta ON t.entity_id = beta.entity_id AND t.end_date = beta.end_date
  448. CONTEXT BY t.entity_id, beta.benchmark_id;
  449. } else if(trailing_month == 'ytd') {
  450. t = SELECT *, cumcount(entity_id) AS cnt
  451. FROM ret t
  452. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  453. WHERE t.ret > -1
  454. AND rfr.ret > -1
  455. CONTEXT BY t.entity_id, t.end_date.year();
  456. treynor = SELECT t.entity_id, t.end_date, beta.benchmark_id,
  457. iif(beta.beta.round(4) == 0, NULL,
  458. ((1 + t.ret).cumprod().pow(12\iif(t.cnt<12, 12, t.cnt)) - (1 + t.rfr_ret).cumprod().pow(12\iif(t.cnt<12, 12, t.cnt))) \ beta.beta) AS treynor
  459. FROM t
  460. INNER JOIN beta AS beta ON t.entity_id = beta.entity_id AND t.end_date = beta.end_date
  461. CONTEXT BY t.entity_id, beta.benchmark_id, t.end_date.year();
  462. } else {
  463. win = trailing_month$STRING$INT;
  464. t = SELECT *, mcount(entity_id, win) AS cnt
  465. FROM ret t
  466. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  467. WHERE t.ret > -1
  468. AND rfr.ret > -1
  469. CONTEXT BY t.entity_id;
  470. treynor = SELECT t.entity_id, t.end_date, beta.benchmark_id,
  471. iif(beta.beta.round(4) == 0, NULL,
  472. ((1 + t.ret).mprod(win).pow(12\iif(t.cnt<12, 12, t.cnt)) - (1 + t.rfr_ret).mprod(win).pow(12\iif(t.cnt<12, 12, t.cnt))) \ beta.beta) AS treynor
  473. FROM t
  474. INNER JOIN beta AS beta ON t.entity_id = beta.entity_id AND t.end_date = beta.end_date
  475. CONTEXT BY t.entity_id, beta.benchmark_id;
  476. }
  477. return treynor;
  478. }
  479. /*
  480. * Jensen's Alpha
  481. * TODO: the result is slightly off
  482. */
  483. def cal_jensen(ret, bmk_ret, risk_free, beta, trailing_month) {
  484. if(trailing_month == 'incep') {
  485. jensen = SELECT t.entity_id, t.end_date, t.ret.cumavg() - rfr.ret.cumavg() - beta.beta * (bmk.ret.cumavg() - rfr.ret.cumavg()) AS jensen, beta.benchmark_id
  486. FROM ret t
  487. INNER JOIN beta beta ON t.entity_id = beta.entity_id AND t.end_date = beta.end_date
  488. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND beta.benchmark_id = bmk.benchmark_id
  489. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  490. WHERE t.ret > -1
  491. CONTEXT BY t.entity_id, beta.benchmark_id;
  492. } else if(trailing_month == 'ytd') {
  493. jensen = SELECT t.entity_id, t.end_date, t.ret.cumavg() - rfr.ret.cumavg() - beta.beta * (bmk.ret.cumavg() - rfr.ret.cumavg()) AS jensen, beta.benchmark_id
  494. FROM ret t
  495. INNER JOIN beta beta ON t.entity_id = beta.entity_id AND t.end_date = beta.end_date
  496. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND beta.benchmark_id = bmk.benchmark_id
  497. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  498. WHERE t.ret > -1
  499. CONTEXT BY t.entity_id, beta.benchmark_id, t.end_date.year();
  500. } else {
  501. win = trailing_month$STRING$INT;
  502. jensen = SELECT t.entity_id, t.end_date, t.ret.mavg(win) - rfr.ret.mavg(win) - beta.beta * (bmk.ret.mavg(win) - rfr.ret.mavg(win)) AS jensen, beta.benchmark_id
  503. FROM ret t
  504. INNER JOIN beta beta ON t.entity_id = beta.entity_id AND t.end_date = beta.end_date
  505. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND beta.benchmark_id = bmk.benchmark_id
  506. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  507. WHERE t.ret > -1
  508. CONTEXT BY t.entity_id, beta.benchmark_id;
  509. }
  510. return jensen;
  511. }
  512. /*
  513. * Modigliani Modigliani Measure (M2)
  514. * NOTE: M2 = sharpe * std(benchmark) + risk_free_rate
  515. * NOTE: Java version is noncompliant-GIPS annulized number
  516. */
  517. def cal_m2(ret, benchmarks, bmk_ret, risk_free, trailing_month) {
  518. if(trailing_month == 'incep') {
  519. m2 = SELECT t.entity_id, t.end_date,
  520. iif(t.entity_id.cumcount() > 5,
  521. iif(t.ret.cumstd().round(4) == 0, NULL, (t.ret - rfr.ret).cumavg() \ t.ret.cumstd() * bmk.ret.cumstd() + rfr.ret.cumavg()),
  522. NULL) AS m2, bm.benchmark_id
  523. FROM ret t
  524. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id AND t.end_date = bm.end_date
  525. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  526. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  527. WHERE t.ret > -1
  528. CONTEXT BY t.entity_id, bm.benchmark_id;
  529. } else if(trailing_month == 'ytd') {
  530. m2 = SELECT t.entity_id, t.end_date,
  531. iif(t.entity_id.cumcount() > 5,
  532. iif(t.ret.cumstd().round(4) == 0, NULL, (t.ret - rfr.ret).cumavg() \ t.ret.cumstd() * bmk.ret.cumstd() + rfr.ret.cumavg()),
  533. NULL) AS m2, bm.benchmark_id
  534. FROM ret t
  535. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id AND t.end_date = bm.end_date
  536. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  537. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  538. WHERE t.ret > -1
  539. CONTEXT BY t.entity_id, bm.benchmark_id, t.end_date.year();
  540. } else {
  541. win = trailing_month$STRING$INT;
  542. m2 = SELECT t.entity_id, t.end_date,
  543. iif(t.entity_id.mcount(win) > 5,
  544. iif(t.ret.mstd(win) == 0, NULL, (t.ret - rfr.ret).mavg(win) \ t.ret.mstd(win) * bmk.ret.mstd(win) + rfr.ret.mavg(win)),
  545. NULL) AS m2, bm.benchmark_id
  546. FROM ret t
  547. INNER JOIN benchmarks bm ON t.entity_id = bm.entity_id AND t.end_date = bm.end_date
  548. INNER JOIN bmk_ret bmk ON t.end_date = bmk.end_date AND bm.benchmark_id = bmk.benchmark_id
  549. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  550. WHERE t.ret > -1
  551. CONTEXT BY t.entity_id, bm.benchmark_id;
  552. }
  553. return m2;
  554. }
  555. /*
  556. * Morningstar Return, Morningstar Risk-Adjusted Return
  557. *
  558. * TODO: Tax and loads are NOT taken care of
  559. * TODO: Assume Chinese methodology using 3, 5, 10 as number of traling years
  560. * TODO: need verify with reliable results
  561. *
  562. * NOTE: Morningstar methodology requires monthly return for calculation, so that "12" is hard-coded here
  563. *
  564. *
  565. */
  566. def cal_ms_return(ret, risk_free, trailing_month) {
  567. win = trailing_month$STRING$INT;
  568. r = SELECT t.entity_id, t.end_date,
  569. iif(t.end_date.mmax(win) == t.end_date.mmin(win), NULL,
  570. ((1 + t.ret)\(1 + rfr.ret)).mprod(win).pow(12\(t.end_date.mmax(win) - t.end_date.mmin(win)))-1) AS ms_ret_a,
  571. (1 + t.ret).pow(-2).mavg(win).pow(-12/2)-1 AS ms_rar_a
  572. FROM ret t
  573. INNER JOIN risk_free rfr ON t.end_date = rfr.end_date
  574. WHERE t.ret > -1
  575. CONTEXT BY t.entity_id;
  576. return r;
  577. }
  578. /*
  579. * 有效主体-基准对应表
  580. *
  581. * @param benchmarks <TABLE>: entity-benchmark 的对应关系表 NEED COLUMNS: entity_id, end_date, benchmark_id
  582. * @param end_day <DATE>:
  583. * @param trailing_month <STRING>:
  584. * @param isEffectiveOnly <BOOL>: false时与Java相同; true:多了个限制条件:如果区间内有效基准数少于1/2,不做计算
  585. * 比如过去12个月中某BFI只出现2次,小于需要的6次,此BFI不参与 trailing 1 year 计算
  586. *
  587. */
  588. def get_effective_benchmarks(benchmarks, end_day, trailing_month, isEffectiveOnly) {
  589. min_pct = 0.5;
  590. if(isEffectiveOnly) {
  591. t_dates = SELECT DISTINCT entity_id, end_date FROM benchmarks WHERE end_date <= end_day.month();
  592. if(trailing_month == 'incep') {
  593. t = SELECT entity_id, end_date, end_date.cumcount() AS cnt FROM t_dates CONTEXT BY entity_id;
  594. bmk = SELECT bmk.* FROM benchmarks bmk
  595. INNER JOIN t ON bmk.entity_id = t.entity_id AND bmk.end_date = t.end_date
  596. CONTEXT BY bmk.entity_id, bmk.benchmark_id
  597. HAVING bmk.end_date.cumcount() >= t.cnt * min_pct;
  598. } else if(trailing_month == 'ytd') {
  599. t = SELECT entity_id, end_date, end_date.cumcount() AS cnt FROM t_dates CONTEXT BY entity_id, end_date.year();
  600. bmk = SELECT bmk.* FROM benchmarks bmk
  601. INNER JOIN t ON bmk.entity_id = t.entity_id AND bmk.end_date = t.end_date
  602. CONTEXT BY entity_id, benchmark_id, end_date.year()
  603. HAVING bmk.end_date.cumcount() >= t.cnt * min_pct;
  604. } else {
  605. win = trailing_month$STRING$INT;
  606. t = SELECT entity_id, end_date, end_date.mcount(win) AS cnt FROM t_dates CONTEXT BY entity_id;
  607. bmk = SELECT bmk.* FROM benchmarks bmk
  608. INNER JOIN t ON bmk.entity_id = t.entity_id AND bmk.end_date = t.end_date
  609. CONTEXT BY entity_id, benchmark_id
  610. HAVING bmk.end_date.mcount(win) >= t.cnt * min_pct;
  611. }
  612. } else {
  613. bmk = SELECT * FROM benchmarks WHERE end_date <= end_day.month();
  614. }
  615. return bmk;
  616. }
  617. /*
  618. * Calculation for monthly indicators which need benchmark
  619. *
  620. * @param entity_info <TABLE>: xxx_information表,NEED COLUMNS entity_id, inception_date
  621. * @param benchmark_mapping <TABLE>: entity-benchmark mapping table, NEED COLUMNS entity_id, end_date, benchmark_id
  622. * @param end_day <DATE>;
  623. * @param tb_ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  624. * @param index_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  625. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  626. * @param month <INT>: trailing x month
  627. *
  628. * @return: indicators table
  629. *
  630. *
  631. * Create 20240904 模仿Java & python代码在Dolphin中实现,具体计算逻辑可能会有不同 Joey
  632. * TODO: some datapoints require more data, we need a way to disable calculation for them
  633. *
  634. */
  635. def cal_indicators_with_benchmark(entity_info, benchmark_mapping, end_day, tb_ret, index_ret, risk_free, month) {
  636. if(entity_info.isVoid() || entity_info.size() == 0 || benchmark_mapping.isVoid() || benchmark_mapping.size() == 0 ) return null;
  637. if(tb_ret.isVoid() || tb_ret.size() == 0 || index_ret.isVoid() || index_ret.size() == 0 || risk_free.isVoid() || risk_free.size() == 0 ) return null;
  638. // sorting for correct first() and last() value
  639. ret = SELECT * FROM tb_ret WHERE ret > -1 AND end_date <= end_day.month() ORDER BY entity_id, price_date;
  640. // get the effective benchmarks
  641. benchmarks = get_effective_benchmarks(benchmark_mapping, end_day, month, true);
  642. if(ret.isVoid() || ret.size() == 0 || benchmarks.isVoid() || benchmarks.size() == 0) return null;
  643. // alpha, beta
  644. alpha_beta = cal_alpha_beta(ret, benchmarks, index_ret, risk_free, month);
  645. // 胜率、跟踪误差、信息比率
  646. bmk_tracking = cal_benchmark_tracking(ret, benchmarks, index_ret, month);
  647. // 特雷诺
  648. treynor = cal_treynor(ret, risk_free, alpha_beta, month);
  649. // 詹森指数
  650. jensen = cal_jensen(ret, index_ret, risk_free, alpha_beta, month);
  651. // M2
  652. m2 = cal_m2(ret, benchmarks, index_ret, risk_free, month);
  653. // 上下行捕获率、收益
  654. capture_r = cal_capture_ratio(ret, benchmarks, index_ret, month);
  655. r = SELECT * FROM bmk_tracking a1
  656. LEFT JOIN alpha_beta ON a1.entity_id = alpha_beta.entity_id AND a1.benchmark_id = alpha_beta.benchmark_id AND a1.end_date = alpha_beta.end_date
  657. LEFT JOIN treynor ON a1.entity_id = treynor.entity_id AND a1.benchmark_id = treynor.benchmark_id AND a1.end_date = treynor.end_date
  658. LEFT JOIN jensen ON a1.entity_id = jensen.entity_id AND a1.benchmark_id = jensen.benchmark_id AND a1.end_date = jensen.end_date
  659. LEFT JOIN m2 ON a1.entity_id = m2.entity_id AND a1.benchmark_id = m2.benchmark_id AND a1.end_date = m2.end_date
  660. LEFT JOIN capture_r ON a1.entity_id = capture_r.entity_id AND a1.benchmark_id = capture_r.benchmark_id AND a1.end_date = capture_r.end_date;
  661. // 年化各数据点
  662. // GIPS RULE: NO annulization for data less than 1 year
  663. plainAnnu = get_annulization_multiple('m');
  664. sqrtAnnu = sqrt(get_annulization_multiple('m'));
  665. r.addColumn(['alpha_a', 'jensen_a', 'track_error_a', 'info_a', 'm2_a'],
  666. [DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE]);
  667. UPDATE r
  668. SET alpha_a = alpha * iif(end_date - inception_date.month() > 12, plainAnnu, 1),
  669. jensen_a = jensen * iif(end_date - inception_date.month() > 12, plainAnnu, 1),
  670. track_error_a = track_error * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1),
  671. info_a = info * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1),
  672. m2_a = m2 * iif(end_date - inception_date.month() > 12, plainAnnu, 1)
  673. FROM ej(r, entity_info, 'entity_id');
  674. return r;
  675. }
  676. /*
  677. * Monthly standard indicator calculation
  678. *
  679. * @param entity_info <TABLE>:
  680. * @param benchmarks <TABLE>: entity-benchmark mapping table
  681. * @param end_day <DATE>:
  682. * @param tb_ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  683. * @param benchmark_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  684. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  685. * @param month <STRING>:
  686. *
  687. * @return: indicators table
  688. *
  689. *
  690. * Create 20240904 模仿Java & python代码在Dolphin中实现,具体计算逻辑可能会有不同 Joey
  691. *
  692. */
  693. def cal_indicators(entity_info, benchmarks, end_day, tb_ret, benchmark_ret, risk_free, month) {
  694. if(entity_info.isVoid() || entity_info.size() == 0 || benchmarks.isVoid() || benchmarks.size() == 0 ) return null;
  695. if(tb_ret.isVoid() || tb_ret.size() == 0 || benchmark_ret.isVoid() || benchmark_ret.size() == 0 || risk_free.isVoid() || risk_free.size() == 0 ) return null;
  696. // sorting for correct first() and last() value
  697. ret = SELECT * FROM tb_ret WHERE end_date <= end_day.month() ORDER BY entity_id, price_date;
  698. // 收益、标准差、偏度、峰度、最大回撤、VaR, CVaR、卡玛比率
  699. rtn = cal_basic_performance(entity_info, ret, month);
  700. // 夏普
  701. sharpe = cal_sharpe(ret, rtn, risk_free, month);
  702. // 整合后的下行标准差、欧米伽、索提诺、卡帕
  703. lpms = cal_omega_sortino_kappa(ret, risk_free, month);
  704. // 需要基准的指标们
  705. indicator_with_benchmark = cal_indicators_with_benchmark(entity_info, benchmarks, end_day, ret, benchmark_ret, risk_free, month);
  706. r = SELECT * FROM rtn a1
  707. LEFT JOIN sharpe ON a1.entity_id = sharpe.entity_id AND a1.end_date = sharpe.end_date
  708. LEFT JOIN lpms ON a1.entity_id = lpms.entity_id AND a1.end_date = lpms.end_date
  709. LEFT JOIN indicator_with_benchmark bmk ON a1.entity_id = bmk.entity_id AND a1.end_date = bmk.end_date;
  710. // 晨星收益和风险
  711. if(month$STRING in ['36', '60', '120']) {
  712. ms = cal_ms_return(ret, risk_free, month);
  713. r = SELECT * FROM r LEFT JOIN ms ON r.entity_id = ms.entity_id AND r.end_date = ms.end_date;
  714. }
  715. // 年化各数据点
  716. // GIPS RULE: NO annulization for data less than 1 year
  717. plainAnnu = get_annulization_multiple('m');
  718. sqrtAnnu = sqrt(get_annulization_multiple('m'));
  719. r.addColumn(['std_dev_a', 'ds_dev_a', 'sharpe_a', 'sortino_a'],
  720. [DOUBLE, DOUBLE, DOUBLE, DOUBLE]);
  721. UPDATE r
  722. SET std_dev_a = std_dev * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1),
  723. ds_dev_a = ds_dev * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1),
  724. sharpe_a = sharpe * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1),
  725. sortino_a = sortino * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1)
  726. FROM ej(r, entity_info, 'entity_id');
  727. return r;
  728. }
  729. /*
  730. * Calculate trailing 3m, 6m, ytd, 1y, 2y, 3y, 4y, 5y, 10y and since inception datapoints
  731. *
  732. * @param: func <FUNCTION>: the calculation function
  733. * @param: entity_info <TABLE>: basic information of entity, NEED COLUMNS entity_id, inception_date
  734. * @param benchmarks <TABLE>: entity-benchmark mapping table
  735. * @param: end_day <DATE>: 计算截止日期
  736. * @param: ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  737. * @param bmk_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  738. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  739. *
  740. *
  741. */
  742. def cal_trailing(func, entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate ) {
  743. r_incep = null;
  744. r_ytd = null;
  745. r_3m = null;
  746. r_6m = null;
  747. r_1y = null;
  748. r_2y = null;
  749. r_3y = null;
  750. r_4y = null;
  751. r_5y = null;
  752. r_10y = null;
  753. // incep
  754. r_incep = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, 'incep');
  755. // ytd
  756. r_ytd = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, 'ytd');
  757. // 3m 只需要支持收益计算
  758. r_3m = cal_basic_performance(entity_info, tb_ret, '3');
  759. // 6m
  760. r_6m = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '6');
  761. // 1y
  762. r_1y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '12');
  763. // 2y
  764. r_2y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '24');
  765. // 3y
  766. r_3y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '36');
  767. // 4y
  768. r_4y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '48');
  769. // 5y
  770. r_5y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '60');
  771. // 10y
  772. r_10y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '120');
  773. return r_incep, r_ytd, r_3m, r_6m, r_1y, r_2y, r_3y, r_4y, r_5y, r_10y;
  774. }
  775. /*
  776. * Calculate trailing ytd, 3m, 6m, 1y, 2y, 3y, 4y, 5y, 10y and since inception standard indicators
  777. *
  778. * @param: entity_info <TABLE>: basic information of entity, NEED COLUMNS entity_id, inception_date
  779. * @param benchmarks <TABLE>: entity-benchmark mapping table
  780. * @param: ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  781. * @param: end_day <DATE>: 计算截止日期
  782. * @param bmk_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  783. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  784. *
  785. */
  786. def cal_trailing_indicators(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate) {
  787. return cal_trailing(cal_indicators, entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate);
  788. }
  789. /*
  790. * Calculate trailing ytd, 3m, 6m, 1y, 2y, 3y, 4y, 5y, 10y and since inception bfi indicators
  791. *
  792. * @param: entity_info <TABLE>: basic information of entity, NEED COLUMNS entity_id, inception_date
  793. * @param benchmarks <TABLE>: entity-benchmark mapping table
  794. * @param: ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  795. * @param: end_day <DATE>: 计算截止日期
  796. * @param bmk_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  797. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  798. *
  799. * NOTE: 3m 的所有指标没有意义
  800. *
  801. *
  802. */
  803. def cal_trailing_bfi_indicators(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate) {
  804. return cal_trailing(cal_indicators_with_benchmark, entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate);
  805. }
  806. /*
  807. * 通用月度指标计算
  808. *
  809. * @param entity_type <STRING>:
  810. * @param indicator_type <STRING>: PBI, BFI
  811. * @param monthly_returns <TABLE>: NEED COLUMN: entity_id, end_date, price_date, nav, ret
  812. *
  813. * @return <DICT TABLE>: ['PBI-INCEP', 'PBI-YTD', 'PBI-3M', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y']
  814. *
  815. */
  816. def cal_monthly_indicators(entity_type, indicator_type, monthly_returns) {
  817. if(find(['MF', 'HF', 'PF', 'MI', 'FI'], entity_type) < 0) return null;
  818. if(monthly_returns.isVoid() || monthly_returns.size() < 1) return null;
  819. oldest_date = EXEC price_date.min() FROM monthly_returns;
  820. v_entity_ids = EXEC DISTINCT entity_id FROM monthly_returns;
  821. entity_info = get_entity_info(entity_type, v_entity_ids);
  822. if(entity_info.isVoid() || entity_info.size() == 0) { return null };
  823. end_day = today();
  824. // 取基金和基准的对照表
  825. if(indicator_type == 'BFI') {
  826. benchmark = SELECT entity_id, end_date.temporalParse('yyyy-MM') AS end_date, factor_id AS benchmark_id
  827. FROM get_entity_bfi_factors(entity_type, v_entity_ids, oldest_date.month(), end_day.month());
  828. } else {
  829. // 主基准, 对应 xxx_info 中的 primary_benchmark_id
  830. benchmark = SELECT entity_id, end_date, iif(benchmark_id.isNull(), 'IN00000008', benchmark_id) AS benchmark_id
  831. FROM get_entity_primary_benchmark(entity_type, v_entity_ids, oldest_date.temporalFormat('yyyy-MM'), end_day.temporalFormat('yyyy-MM')) ;
  832. }
  833. // 取所有出现的基准月收益
  834. bmk_ret = get_benchmark_return(benchmark, end_day);
  835. if(bmk_ret.isVoid() || bmk_ret.size() == 0) { return null; }
  836. // TODO: risk free指数月收益存在fund_performance表,所以先将就用 fund_id 表示。之后统一改为更准确的名字
  837. risk_free_rate = SELECT entity_id AS fund_id, temporalParse(end_date, 'yyyy-MM') AS end_date, ret FROM get_risk_free_rate(oldest_date, end_day);
  838. if(risk_free_rate.isVoid() || risk_free_rate.size() == 0) { return null; }
  839. // 指标计算
  840. if(indicator_type == 'BFI') {
  841. t0 = cal_trailing_bfi_indicators(entity_info, benchmark, end_day, monthly_returns, bmk_ret, risk_free_rate);
  842. v_table_name = ['BFI-INCEP', 'BFI-YTD', 'BFI-3M', 'BFI-6M', 'BFI-1Y', 'BFI-2Y', 'BFI-3Y', 'BFI-4Y', 'BFI-5Y', 'BFI-10Y'];
  843. } else {
  844. t0 = cal_trailing_indicators(entity_info, benchmark, end_day, monthly_returns, bmk_ret, risk_free_rate);
  845. v_table_name = ['PBI-INCEP', 'PBI-YTD', 'PBI-3M', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y'];
  846. }
  847. return dict(v_table_name, t0);
  848. }
  849. /*
  850. * Calculate historcial fund trailing indicators
  851. *
  852. * @param entity_type <STRING>: MF, HF
  853. * @param fund_ids <STRING>: 逗号和单引号分隔的fund_id
  854. * @param end_day <DATE>: 要计算的日期
  855. * @param isFromNav <BOOL>: 用净值实时计算还是从表中取月收益
  856. * @param isFromSQL <BOOL>: TODO: 从MySQL还是本地DolphinDB取净值/收益数据
  857. *
  858. * @return <DICT TABLE>: ['PBI-INCEP', 'PBI-YTD', 'PBI-3M', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y', 'MS-3Y', 'MS-5Y', 'MS-10Y']
  859. *
  860. *
  861. * Example: cal_fund_indicators('HF', "'HF000004KN','HF000103EU','HF00018WXG'", 2024.06.28, true);
  862. *
  863. */
  864. def cal_fund_indicators(entity_type, fund_ids, end_day, isFromNav) {
  865. very_old_date = 1990.01.01;
  866. if(isFromNav == true) {
  867. // 从净值开始计算收益
  868. tb_ret = SELECT * FROM cal_fund_monthly_returns(entity_type, fund_ids, true) WHERE price_date <= end_day;
  869. tb_ret.rename!(['fund_id', 'cumulative_nav'], ['entity_id', 'nav']);
  870. } else {
  871. // 从fund_performance表里读月收益
  872. tb_ret = get_monthly_ret(entity_type, fund_ids, very_old_date, end_day, true);
  873. v_end_date = tb_ret.end_date.temporalParse('yyyy-MM');
  874. tb_ret.replaceColumn!('end_date', v_end_date);
  875. }
  876. if(tb_ret.isVoid() || tb_ret.size() == 0) { return null; }
  877. // 标准的指标
  878. d = cal_monthly_indicators(entity_type, 'PBI', tb_ret);
  879. return d;
  880. }
  881. /*
  882. * Calculate historcial fund trailing BFI indicators
  883. *
  884. * @param entity_type <STRING>: MF, HF
  885. * @param fund_ids <STRING>: 逗号和单引号分隔的fund_id
  886. * @param end_day <DATE>: 要计算的日期
  887. * @param isFromNav <BOOL>: 用净值实时计算还是从表中取月收益
  888. * @param isFromSQL <BOOL>: TODO: 从MySQL还是本地DolphinDB取净值/收益数据
  889. *
  890. * @return <DICT TABLE>: ['BFI-INCEP', 'BFI-YTD', 'BFI-3M', 'BFI-6M', 'BFI-1Y', 'BFI-2Y', 'BFI-3Y', 'BFI-4Y', 'BFI-5Y', 'BFI-10Y']
  891. *
  892. *
  893. * Example: cal_fund_bfi_indicators('MF', "'MF00003PW2', 'MF00003PW1', 'MF00003PXO'", 2024.08.31, true);
  894. *
  895. */
  896. def cal_fund_bfi_indicators(entity_type, fund_ids, end_day, isFromNav) {
  897. very_old_date = 1990.01.01;
  898. if(isFromNav == true) {
  899. // 从净值开始计算收益
  900. tb_ret = SELECT * FROM cal_fund_monthly_returns(entity_type, fund_ids, true) WHERE price_date <= end_day;
  901. tb_ret.rename!(['fund_id', 'cumulative_nav'], ['entity_id', 'nav']);
  902. } else {
  903. // 从fund_performance表里读月收益
  904. tb_ret = get_monthly_ret(entity_type, fund_ids, very_old_date, end_day, true);
  905. tb_ret.rename!(['fund_id'], ['entity_id']);
  906. v_end_date = tb_ret.end_date.temporalParse('yyyy-MM');
  907. tb_ret.replaceColumn!('end_date', v_end_date);
  908. }
  909. if(tb_ret.isVoid() || tb_ret.size() == 0) { return null; }
  910. // BFI指标
  911. d = cal_monthly_indicators(entity_type, 'BFI', tb_ret);
  912. return d;
  913. }
  914. /*
  915. * Calculate historcial portfolio trailing indicators
  916. *
  917. * @param portfolio_ids <STRING>: comma-delimited portfolio ids
  918. * @param end_day <DATE>: the date
  919. * @param cal_method <INT>: calculate based on cumulative nav (1) or nav (2)
  920. * @param isFromNav <BOOL>: calculate returns from NAV on-the-fly (true) or get from monthly return table (false)
  921. *
  922. * Example: cal_portfolio_indicators('166002,166114', 2024.08.31, 1, true);
  923. *
  924. def cal_portfolio_indicators(portfolio_ids, end_day, cal_method, isFromNav) {
  925. very_old_date = 1990.01.01;
  926. start_month = very_old_date.month();
  927. portfolio_info = get_portfolio_info(portfolio_ids);
  928. if(portfolio_info.isVoid() || portfolio_info.size() == 0) { return null };
  929. portfolio_info.rename!('portfolio_id', 'entity_id');
  930. if(isFromNav == true) {
  931. // 从净值开始计算收益
  932. tb_raw_ret = SELECT * FROM cal_portfolio_nav(portfolio_ids, very_old_date, cal_method) WHERE price_date <= end_day;
  933. if(tb_raw_ret.isVoid() || tb_raw_ret.size() == 0) return null;
  934. // funky thing is you can't use "AS" for the grouping columns?
  935. tb_ret = SELECT portfolio_id, price_date.month(), price_date.last() AS price_date, (1+ret).prod()-1 AS ret, nav.last() AS nav
  936. FROM tb_raw_ret
  937. WHERE price_date <= end_day
  938. GROUP BY portfolio_id, price_date.month();
  939. tb_ret.rename!(['portfolio_id', 'month_price_date'], ['entity_id', 'end_date']);
  940. } else {
  941. // 从pf_portfolio_performance表里读月收益
  942. tb_ret = get_monthly_ret('PF', portfolio_ids, very_old_date, end_day, true);
  943. tb_ret.rename!(['portfolio_id'], ['entity_id']);
  944. v_end_date = tb_ret.end_date.temporalParse('yyyy-MM');
  945. tb_ret.replaceColumn!('end_date', v_end_date);
  946. }
  947. if(tb_ret.isVoid() || tb_ret.size() == 0) return null;
  948. // 混合因子做基准,同SQL保持一致
  949. t_dates = table(start_month..end_day.month() AS end_date);
  950. primary_benchmark = SELECT ei.entity_id, dt.end_date, 'FA00000VNB' AS benchmark_id
  951. FROM portfolio_info ei JOIN t_dates dt
  952. WHERE dt.end_date >= ei.inception_date.month();
  953. if(primary_benchmark.isVoid() || primary_benchmark.size() == 0) { return null; }
  954. // 取所有出现的基准月收益
  955. bmk_ret = get_benchmark_return(primary_benchmark, end_day);
  956. if(bmk_ret.isVoid() || bmk_ret.size() == 0) { return null; }
  957. // TODO: risk free指数月收益存在fund_performance表,所以先将就用 fund_id 表示。之后统一改为更准确的名字
  958. risk_free_rate = SELECT entity_id AS fund_id, temporalParse(end_date, 'yyyy-MM') AS end_date, ret FROM get_risk_free_rate(very_old_date, end_day);
  959. if(risk_free_rate.isVoid() || risk_free_rate.size() == 0) { return null; }
  960. t0 = cal_trailing_indicators(portfolio_info, primary_benchmark, end_day, tb_ret, bmk_ret, risk_free_rate);
  961. v_table_name = ['PBI-INCEP', 'PBI-YTD', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y'];
  962. return dict(v_table_name, t0);
  963. }
  964. * Calculate historcial portfolio trailing BFI indicators
  965. *
  966. * @param portfolio_ids <STRING>: comma-delimited portfolio ids
  967. * @param end_day <DATE>: the date
  968. * @param cal_method <INT>: calculate based on cumulative nav (1) or nav (2)
  969. * @param isFromNav <BOOL>: calculate returns from NAV on-the-fly (true) or get from monthly return table (false)
  970. *
  971. * TODO: intergrate with cal_portfolio_indicators
  972. *
  973. * Example: cal_portfolio_bfi_indicators('166002,166114', 2024.08.31, 1, true);
  974. *
  975. def cal_portfolio_bfi_indicators(portfolio_ids, end_day, cal_method, isFromNav) {
  976. very_old_date = 1990.01.01;
  977. start_month = 1990.01M;
  978. portfolio_info = get_portfolio_info(portfolio_ids);
  979. if(portfolio_info.isVoid() || portfolio_info.size() == 0) { return null };
  980. portfolio_info.rename!('portfolio_id', 'entity_id');
  981. if(isFromNav == true) {
  982. // 从净值开始计算收益
  983. tb_raw_ret = SELECT * FROM cal_portfolio_nav(portfolio_ids, very_old_date, cal_method) WHERE price_date <= end_day;
  984. if(tb_raw_ret.isVoid() || tb_raw_ret.size() == 0) return null;
  985. // funky thing is you can't use "AS" for the grouping columns?
  986. tb_ret = SELECT portfolio_id, price_date.month(), price_date.last() AS price_date, (1+ret).prod()-1 AS ret, nav.last() AS nav
  987. FROM tb_raw_ret
  988. WHERE price_date <= end_day
  989. GROUP BY portfolio_id, price_date.month();
  990. tb_ret.rename!(['portfolio_id', 'month_price_date'], ['entity_id', 'end_date']);
  991. } else {
  992. // 从pf_portfolio_performance表里读月收益
  993. tb_ret = get_monthly_ret('PF', portfolio_ids, very_old_date, end_day, true);
  994. tb_ret.rename!(['portfolio_id'], ['entity_id']);
  995. v_end_date = tb_ret.end_date.temporalParse('yyyy-MM');
  996. tb_ret.replaceColumn!('end_date', v_end_date);
  997. }
  998. if(tb_ret.isVoid() || tb_ret.size() == 0) return null;
  999. // 取组合和基准的对照表
  1000. bfi_benchmark = SELECT portfolio_id AS entity_id, end_date.temporalParse('yyyy-MM') AS end_date, factor_id AS benchmark_id
  1001. FROM get_portfolio_bfi_factors(portfolio_ids, start_month.temporalFormat('yyyy-MM'), end_day.temporalFormat('yyyy-MM'));
  1002. if(bfi_benchmark.isVoid() || bfi_benchmark.size() == 0) { return null; }
  1003. bmk_ret = get_benchmark_return(bfi_benchmark, end_day);
  1004. if(bmk_ret.isVoid() || bmk_ret.size() == 0) { return null; }
  1005. // TODO: risk free指数月收益存在fund_performance表,所以先将就用 fund_id 表示。之后统一改为更准确的名字
  1006. risk_free_rate = SELECT entity_id AS fund_id, temporalParse(end_date, 'yyyy-MM') AS end_date, ret FROM get_risk_free_rate(very_old_date, end_day);
  1007. if(risk_free_rate.isVoid() || risk_free_rate.size() == 0) { return null; }
  1008. t0 = cal_trailing_bfi_indicators(portfolio_info, bfi_benchmark, end_day, tb_ret, bmk_ret, risk_free_rate);
  1009. v_table_name = ['PBI-INCEP', 'PBI-YTD', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y'];
  1010. return dict(v_table_name, t0);
  1011. }
  1012. */
  1013. /*
  1014. * 【Morningstar Integration】通用月度指标计算
  1015. *
  1016. * @param entity_type <STRING>:
  1017. * @param indicator_type <STRING>: PBI, BFI
  1018. * @param monthly_returns <TABLE>: NEED COLUMN: entity_id, end_date, price_date, nav, ret
  1019. *
  1020. * @return <DICT TABLE>: ['PBI-INCEP', 'PBI-YTD', 'PBI-3M', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y']
  1021. *
  1022. */
  1023. def ms_cal_monthly_indicators(entity_type, indicator_type, monthly_returns) {
  1024. if(find(['MF', 'HF', 'PF'], entity_type) < 0) return null;
  1025. if(monthly_returns.isVoid() || monthly_returns.size() < 1) return null;
  1026. oldest_date = EXEC price_date.min() FROM monthly_returns;
  1027. v_entity_ids = (SELECT DISTINCT entity_id FROM monthly_returns).entity_id;
  1028. entity_info = get_entity_info(entity_type, v_entity_ids);
  1029. if(entity_info.isVoid() || entity_info.size() == 0) { return null };
  1030. end_day = today();
  1031. // 取基金和基准的对照表
  1032. if(indicator_type == 'BFI') {
  1033. benchmark = SELECT entity_id, end_date.temporalParse('yyyy-MM') AS end_date, factor_id AS benchmark_id
  1034. FROM get_entity_bfi_factors(entity_type, v_entity_ids, oldest_date.month(), end_day.month());
  1035. } else if(indicator_type == 'CAI') {
  1036. benchmark = SELECT fund_id AS entity_id, end_date.temporalParse('yyyy-MM') AS end_date, factor_id AS benchmark_id
  1037. FROM ms_get_fund_category_average(v_entity_ids, oldest_date.temporalFormat('yyyy-MM'), end_day.temporalFormat('yyyy-MM'));
  1038. } else {
  1039. // 主基准, 对应 xxx_info 中的 primary_benchmark_id
  1040. benchmark = SELECT entity_id, end_date, iif(benchmark_id.isNull(), 'IN00000008', benchmark_id) AS benchmark_id
  1041. FROM ms_get_entity_primary_benchmark(entity_type, v_entity_ids, oldest_date.temporalFormat('yyyy-MM'), end_day.temporalFormat('yyyy-MM')) ;
  1042. }
  1043. // 取所有出现的基准月收益
  1044. bmk_ret = get_benchmark_return(benchmark, end_day);
  1045. if(bmk_ret.isVoid() || bmk_ret.size() == 0) { return null; }
  1046. // TODO: risk free指数月收益存在fund_performance表,所以先将就用 fund_id 表示。之后统一改为更准确的名字
  1047. risk_free_rate = SELECT entity_id AS fund_id, temporalParse(end_date, 'yyyy-MM') AS end_date, ret FROM ms_get_risk_free_rate(oldest_date, end_day);
  1048. if(risk_free_rate.isVoid() || risk_free_rate.size() == 0) { return null; }
  1049. // 指标计算
  1050. if(indicator_type == 'BFI') {
  1051. t0 = cal_trailing_bfi_indicators(entity_info, benchmark, end_day, monthly_returns, bmk_ret, risk_free_rate);
  1052. v_table_name = ['BFI-INCEP', 'BFI-YTD', 'BFI-3M', 'BFI-6M', 'BFI-1Y', 'BFI-2Y', 'BFI-3Y', 'BFI-4Y', 'BFI-5Y', 'BFI-10Y'];
  1053. } else if(indicator_type == 'CAI') {
  1054. t0 = cal_trailing_bfi_indicators(entity_info, benchmark, end_day, monthly_returns, bmk_ret, risk_free_rate);
  1055. v_table_name = ['CAI-INCEP', 'CAI-YTD', 'CAI-3M', 'CAI-6M', 'CAI-1Y', 'CAI-2Y', 'CAI-3Y', 'CAI-4Y', 'CAI-5Y', 'CAI-10Y'];
  1056. } else {
  1057. t0 = cal_trailing_indicators(entity_info, benchmark, end_day, monthly_returns, bmk_ret, risk_free_rate);
  1058. v_table_name = ['PBI-INCEP', 'PBI-YTD', 'PBI-3M', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y'];
  1059. }
  1060. return dict(v_table_name, t0);
  1061. }