indicatorCalculator.dos 59 KB

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