indicatorCalculator.dos 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257
  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.round(4) == 0, null, iif(trailing_ret_a\drawdown > 99999, 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, iif(std.std_dev.round(4) == 0, null, (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, iif(std.std_dev.round(4) ==0, null, (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, iif(std.std_dev.round(4) == 0, null, (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).round(4) == 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\(1+t.end_date.mmax(win) - t.end_date.mmin(win)))-1) AS ms_ret_a,
  571. ((1 + t.ret)\(1 + rfr.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. r.addColumn('ms_risk_a', DOUBLE);
  577. UPDATE r SET ms_risk_a = ms_ret_a - ms_rar_a;
  578. return r;
  579. }
  580. /*
  581. * 有效主体-基准对应表
  582. *
  583. * @param benchmarks <TABLE>: entity-benchmark 的对应关系表 NEED COLUMNS: entity_id, end_date, benchmark_id
  584. * @param end_day <DATE>:
  585. * @param trailing_month <STRING>:
  586. * @param isEffectiveOnly <BOOL>: false时与Java相同; true:多了个限制条件:如果区间内有效基准数少于1/2,不做计算
  587. * 比如过去12个月中某BFI只出现2次,小于需要的6次,此BFI不参与 trailing 1 year 计算
  588. *
  589. */
  590. def get_effective_benchmarks(benchmarks, end_day, trailing_month, isEffectiveOnly) {
  591. min_pct = 0.5;
  592. if(isEffectiveOnly) {
  593. t_dates = SELECT DISTINCT entity_id, end_date FROM benchmarks WHERE end_date <= end_day.month();
  594. if(trailing_month == 'incep') {
  595. t = SELECT entity_id, end_date, end_date.cumcount() AS cnt FROM t_dates CONTEXT BY entity_id;
  596. bmk = SELECT bmk.* FROM benchmarks bmk
  597. INNER JOIN t ON bmk.entity_id = t.entity_id AND bmk.end_date = t.end_date
  598. CONTEXT BY bmk.entity_id, bmk.benchmark_id
  599. HAVING bmk.end_date.cumcount() >= t.cnt * min_pct;
  600. } else if(trailing_month == 'ytd') {
  601. t = SELECT entity_id, end_date, end_date.cumcount() AS cnt FROM t_dates CONTEXT BY entity_id, end_date.year();
  602. bmk = SELECT bmk.* FROM benchmarks bmk
  603. INNER JOIN t ON bmk.entity_id = t.entity_id AND bmk.end_date = t.end_date
  604. CONTEXT BY entity_id, benchmark_id, end_date.year()
  605. HAVING bmk.end_date.cumcount() >= t.cnt * min_pct;
  606. } else {
  607. win = trailing_month$STRING$INT;
  608. t = SELECT entity_id, end_date, end_date.mcount(win) AS cnt FROM t_dates CONTEXT BY entity_id;
  609. bmk = SELECT bmk.* FROM benchmarks bmk
  610. INNER JOIN t ON bmk.entity_id = t.entity_id AND bmk.end_date = t.end_date
  611. CONTEXT BY entity_id, benchmark_id
  612. HAVING bmk.end_date.mcount(win) >= t.cnt * min_pct;
  613. }
  614. } else {
  615. bmk = SELECT * FROM benchmarks WHERE end_date <= end_day.month();
  616. }
  617. return bmk;
  618. }
  619. /*
  620. * Calculation for monthly indicators which need benchmark
  621. *
  622. * @param entity_info <TABLE>: xxx_information表,NEED COLUMNS entity_id, inception_date
  623. * @param benchmark_mapping <TABLE>: entity-benchmark mapping table, NEED COLUMNS entity_id, end_date, benchmark_id
  624. * @param end_day <DATE>;
  625. * @param tb_ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  626. * @param index_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  627. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  628. * @param month <INT>: trailing x month
  629. *
  630. * @return: indicators table
  631. *
  632. *
  633. * Create 20240904 模仿Java & python代码在Dolphin中实现,具体计算逻辑可能会有不同 Joey
  634. * TODO: some datapoints require more data, we need a way to disable calculation for them
  635. *
  636. */
  637. def cal_indicators_with_benchmark(entity_info, benchmark_mapping, end_day, tb_ret, index_ret, risk_free, month) {
  638. r = table(1000:0,
  639. ['entity_id', 'end_date', 'benchmark_id', 'winrate', 'track_error', 'info', 'beta', 'alpha', 'treynor', 'jensen', 'm2',
  640. 'upside_capture_ret', 'upside_capture_ratio', 'downside_capture_ret', 'downside_capture_ratio',
  641. 'alpha_a', 'jensen_a', 'track_error_a', 'info_a', 'm2_a'],
  642. [entity_info.entity_id[0].type(), MONTH, SYMBOL, DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE,
  643. DOUBLE, DOUBLE, DOUBLE, DOUBLE,
  644. DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE]);
  645. if(entity_info.isVoid() || entity_info.size() == 0 || benchmark_mapping.isVoid() || benchmark_mapping.size() == 0 ) return r;
  646. if(tb_ret.isVoid() || tb_ret.size() == 0 || index_ret.isVoid() || index_ret.size() == 0 || risk_free.isVoid() || risk_free.size() == 0 ) return r;
  647. // sorting for correct first() and last() value
  648. ret = SELECT * FROM tb_ret WHERE ret > -1 AND end_date <= end_day.month() ORDER BY entity_id, price_date;
  649. // get the effective benchmarks
  650. benchmarks = get_effective_benchmarks(benchmark_mapping, end_day, month, true);
  651. if(ret.isVoid() || ret.size() == 0 || benchmarks.isVoid() || benchmarks.size() == 0) return r;
  652. // alpha, beta
  653. alpha_beta = cal_alpha_beta(ret, benchmarks, index_ret, risk_free, month);
  654. // 胜率、跟踪误差、信息比率
  655. bmk_tracking = cal_benchmark_tracking(ret, benchmarks, index_ret, month);
  656. // 特雷诺
  657. treynor = cal_treynor(ret, risk_free, alpha_beta, month);
  658. // 詹森指数
  659. jensen = cal_jensen(ret, index_ret, risk_free, alpha_beta, month);
  660. // M2
  661. m2 = cal_m2(ret, benchmarks, index_ret, risk_free, month);
  662. // 上下行捕获率、收益
  663. capture_r = cal_capture_ratio(ret, benchmarks, index_ret, month);
  664. r = SELECT * FROM bmk_tracking a1
  665. 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
  666. LEFT JOIN treynor ON a1.entity_id = treynor.entity_id AND a1.benchmark_id = treynor.benchmark_id AND a1.end_date = treynor.end_date
  667. LEFT JOIN jensen ON a1.entity_id = jensen.entity_id AND a1.benchmark_id = jensen.benchmark_id AND a1.end_date = jensen.end_date
  668. LEFT JOIN m2 ON a1.entity_id = m2.entity_id AND a1.benchmark_id = m2.benchmark_id AND a1.end_date = m2.end_date
  669. 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;
  670. // 年化各数据点
  671. // GIPS RULE: NO annulization for data less than 1 year
  672. plainAnnu = get_annulization_multiple('m');
  673. sqrtAnnu = sqrt(get_annulization_multiple('m'));
  674. r.addColumn(['alpha_a', 'jensen_a', 'track_error_a', 'info_a', 'm2_a'],
  675. [DOUBLE, DOUBLE, DOUBLE, DOUBLE, DOUBLE]);
  676. UPDATE r
  677. SET alpha_a = alpha * iif(end_date - inception_date.month() > 12, plainAnnu, 1),
  678. jensen_a = jensen * iif(end_date - inception_date.month() > 12, plainAnnu, 1),
  679. track_error_a = track_error * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1),
  680. info_a = info * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1),
  681. m2_a = m2 * iif(end_date - inception_date.month() > 12, plainAnnu, 1)
  682. FROM ej(r, entity_info, 'entity_id');
  683. return r;
  684. }
  685. /*
  686. * Monthly standard indicator calculation
  687. *
  688. * @param entity_info <TABLE>:
  689. * @param benchmarks <TABLE>: entity-benchmark mapping table
  690. * @param end_day <DATE>:
  691. * @param tb_ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  692. * @param benchmark_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  693. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  694. * @param month <STRING>:
  695. *
  696. * @return: indicators table
  697. *
  698. * TODO: 目前只能使用单一无风险利率,无法根据基金信息自由选择更匹配的指数
  699. *
  700. * Create 20240904 模仿Java & python代码在Dolphin中实现,具体计算逻辑可能会有不同 Joey
  701. *
  702. */
  703. def cal_indicators(entity_info, benchmarks, end_day, tb_ret, benchmark_ret, risk_free, month) {
  704. if(entity_info.isVoid() || entity_info.size() == 0 || benchmarks.isVoid() || benchmarks.size() == 0 ) return null;
  705. if(tb_ret.isVoid() || tb_ret.size() == 0 || benchmark_ret.isVoid() || benchmark_ret.size() == 0 || risk_free.isVoid() || risk_free.size() == 0 ) return null;
  706. // sorting for correct first() and last() value
  707. ret = SELECT * FROM tb_ret WHERE end_date <= end_day.month() ORDER BY entity_id, price_date;
  708. // 收益、标准差、偏度、峰度、最大回撤、VaR, CVaR、卡玛比率
  709. rtn = cal_basic_performance(entity_info, ret, month);
  710. // 夏普
  711. sharpe = cal_sharpe(ret, rtn, risk_free, month);
  712. // 整合后的下行标准差、欧米伽、索提诺、卡帕
  713. lpms = cal_omega_sortino_kappa(ret, risk_free, month);
  714. // 需要基准的指标们
  715. indicator_with_benchmark = cal_indicators_with_benchmark(entity_info, benchmarks, end_day, ret, benchmark_ret, risk_free, month);
  716. r = SELECT * FROM rtn a1
  717. LEFT JOIN sharpe ON a1.entity_id = sharpe.entity_id AND a1.end_date = sharpe.end_date
  718. LEFT JOIN lpms ON a1.entity_id = lpms.entity_id AND a1.end_date = lpms.end_date
  719. LEFT JOIN indicator_with_benchmark bmk ON a1.entity_id = bmk.entity_id AND a1.end_date = bmk.end_date;
  720. // 晨星收益和风险
  721. if(month$STRING in ['36', '60', '120']) {
  722. ms = cal_ms_return(ret, risk_free, month);
  723. r = SELECT * FROM r LEFT JOIN ms ON r.entity_id = ms.entity_id AND r.end_date = ms.end_date;
  724. }
  725. // 年化各数据点
  726. // GIPS RULE: NO annulization for data less than 1 year
  727. plainAnnu = get_annulization_multiple('m');
  728. sqrtAnnu = sqrt(get_annulization_multiple('m'));
  729. r.addColumn(['std_dev_a', 'ds_dev_a', 'sharpe_a', 'sortino_a'],
  730. [DOUBLE, DOUBLE, DOUBLE, DOUBLE]);
  731. UPDATE r
  732. SET std_dev_a = std_dev * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1),
  733. ds_dev_a = ds_dev * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1),
  734. sharpe_a = sharpe * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1),
  735. sortino_a = sortino * iif(end_date - inception_date.month() > 12, sqrtAnnu, 1)
  736. FROM ej(r, entity_info, 'entity_id');
  737. return r;
  738. }
  739. /*
  740. * Calculate trailing 3m, 6m, ytd, 1y, 2y, 3y, 4y, 5y, 10y and since inception datapoints
  741. *
  742. * @param: func <FUNCTION>: the calculation function
  743. * @param: entity_info <TABLE>: basic information of entity, NEED COLUMNS entity_id, inception_date
  744. * @param benchmarks <TABLE>: entity-benchmark mapping table
  745. * @param: end_day <DATE>: 计算截止日期
  746. * @param: ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  747. * @param bmk_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  748. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  749. *
  750. *
  751. */
  752. def cal_trailing(func, entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate ) {
  753. r_incep = null;
  754. r_ytd = null;
  755. r_3m = null;
  756. r_6m = null;
  757. r_1y = null;
  758. r_2y = null;
  759. r_3y = null;
  760. r_4y = null;
  761. r_5y = null;
  762. r_10y = null;
  763. // incep
  764. r_incep = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, 'incep');
  765. // ytd
  766. r_ytd = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, 'ytd');
  767. // 3m 只需要支持收益计算
  768. r_3m = cal_basic_performance(entity_info, tb_ret, '3');
  769. // 6m
  770. r_6m = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '6');
  771. // 1y
  772. r_1y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '12');
  773. // 2y
  774. r_2y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '24');
  775. // 3y
  776. r_3y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '36');
  777. // 4y
  778. r_4y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '48');
  779. // 5y
  780. r_5y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '60');
  781. // 10y
  782. r_10y = func(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate, '120');
  783. return r_incep, r_ytd, r_3m, r_6m, r_1y, r_2y, r_3y, r_4y, r_5y, r_10y;
  784. }
  785. /*
  786. * Calculate trailing ytd, 3m, 6m, 1y, 2y, 3y, 4y, 5y, 10y and since inception standard indicators
  787. *
  788. * @param: entity_info <TABLE>: basic information of entity, NEED COLUMNS entity_id, inception_date
  789. * @param benchmarks <TABLE>: entity-benchmark mapping table
  790. * @param: ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  791. * @param: end_day <DATE>: 计算截止日期
  792. * @param bmk_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  793. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  794. *
  795. */
  796. def cal_trailing_indicators(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate) {
  797. return cal_trailing(cal_indicators, entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate);
  798. }
  799. /*
  800. * Calculate trailing ytd, 3m, 6m, 1y, 2y, 3y, 4y, 5y, 10y and since inception bfi indicators
  801. *
  802. * @param: entity_info <TABLE>: basic information of entity, NEED COLUMNS entity_id, inception_date
  803. * @param benchmarks <TABLE>: entity-benchmark mapping table
  804. * @param: ret <TABLE>: 收益表,NEED COLUMNS entity_id, price_dat, end_date, nav
  805. * @param: end_day <DATE>: 计算截止日期
  806. * @param bmk_ret <TABLE>: historical benchmark return table, NEED COLUMNS fund_id, end_date, ret
  807. * @param risk_free <TABLE>: historical risk free rate table, NEED COLUMNS fund_id, end_date, ret
  808. *
  809. * NOTE: 3m 的所有指标没有意义
  810. *
  811. *
  812. */
  813. def cal_trailing_bfi_indicators(entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate) {
  814. return cal_trailing(cal_indicators_with_benchmark, entity_info, benchmarks, end_day, tb_ret, bmk_ret, risk_free_rate);
  815. }
  816. /*
  817. * 通用月度指标计算
  818. *
  819. * @param entity_type <STRING>:
  820. * @param indicator_type <STRING>: PBI, BFI
  821. * @param monthly_returns <TABLE>: NEED COLUMN: entity_id, end_date, price_date, nav, ret
  822. *
  823. * @return <DICT TABLE>: ['PBI-INCEP', 'PBI-YTD', 'PBI-3M', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y']
  824. *
  825. */
  826. def cal_monthly_indicators(entity_type, indicator_type, monthly_returns) {
  827. if(find(['MF', 'HF', 'PF', 'MI', 'FI', 'FA'], entity_type) < 0) return null;
  828. if(monthly_returns.isVoid() || monthly_returns.size() < 1) return null;
  829. oldest_date = EXEC price_date.min() FROM monthly_returns;
  830. v_entity_ids = EXEC DISTINCT entity_id FROM monthly_returns;
  831. entity_info = get_entity_info(entity_type, v_entity_ids);
  832. if(entity_info.isVoid() || entity_info.size() == 0) { return null };
  833. end_day = today();
  834. // 取基金和基准的对照表
  835. if(indicator_type == 'BFI') {
  836. benchmark = SELECT entity_id, end_date.temporalParse('yyyy-MM') AS end_date, factor_id AS benchmark_id
  837. FROM get_entity_bfi_factors(entity_type, v_entity_ids, oldest_date.month(), end_day.month());
  838. } else {
  839. // 主基准, 对应 xxx_info 中的 primary_benchmark_id; TODO: 没有基准用沪深300顶,哪怕很多情况下不那么正确
  840. benchmark = SELECT entity_id, end_date, iif(benchmark_id.isVoid(), 'IN00000008', benchmark_id) AS benchmark_id
  841. FROM get_entity_primary_benchmark(entity_type, v_entity_ids, oldest_date.temporalFormat('yyyy-MM'), end_day.temporalFormat('yyyy-MM')) ;
  842. }
  843. // 取所有出现的基准月收益
  844. bmk_ret = get_benchmark_return(benchmark, end_day);
  845. //if(bmk_ret.isVoid() || bmk_ret.size() == 0) { return null; }
  846. // TODO: risk free指数月收益存在fund_performance表,所以先将就用 fund_id 表示。之后统一改为更准确的名字
  847. 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);
  848. if(risk_free_rate.isVoid() || risk_free_rate.size() == 0) { return null; }
  849. // 指标计算
  850. if(indicator_type == 'BFI') {
  851. t0 = cal_trailing_bfi_indicators(entity_info, benchmark, end_day, monthly_returns, bmk_ret, risk_free_rate);
  852. v_table_name = ['BFI-INCEP', 'BFI-YTD', 'BFI-3M', 'BFI-6M', 'BFI-1Y', 'BFI-2Y', 'BFI-3Y', 'BFI-4Y', 'BFI-5Y', 'BFI-10Y'];
  853. } else {
  854. t0 = cal_trailing_indicators(entity_info, benchmark, end_day, monthly_returns, bmk_ret, risk_free_rate);
  855. v_table_name = ['PBI-INCEP', 'PBI-YTD', 'PBI-3M', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y'];
  856. }
  857. return dict(v_table_name, t0);
  858. }
  859. /*
  860. * 通用基金经理/公司月度指标计算
  861. *
  862. * @param entity_type <STRING>:
  863. * @param indicator_type <STRING>: PBI, BFI
  864. * @param monthly_returns <TABLE>: NEED COLUMN: entity_id, curve_type, strategy, end_date, price_date, nav, ret
  865. *
  866. * @return <DICT TABLE>: ['PBI-INCEP', 'PBI-YTD', 'PBI-3M', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y']
  867. *
  868. */
  869. def cal_mc_monthly_indicators(entity_type, indicator_type, monthly_returns) {
  870. if(find(['PL', 'CO'], entity_type) < 0) return null;
  871. if(monthly_returns.isVoid() || monthly_returns.size() < 1) return null;
  872. oldest_date = EXEC price_date.min() FROM monthly_returns;
  873. v_entity_ids = EXEC DISTINCT entity_id FROM monthly_returns;
  874. if(entity_type == 'PL') {
  875. entity_info = get_personnel_info_for_perf(v_entity_ids);
  876. entity_info.rename!('manager_id', 'entity_id');
  877. }
  878. else {
  879. entity_info = get_company_info_for_perf(v_entity_ids);
  880. entity_info.rename!('company_id', 'entity_id');
  881. }
  882. if(entity_info.isVoid() || entity_info.size() == 0) { return null };
  883. end_day = today();
  884. // 取基金和基准的对照表
  885. if(indicator_type == 'BFI') {
  886. benchmark = SELECT DISTINCT entity_id, curve_type, strategy, end_date.temporalParse('yyyy-MM') AS end_date, factor_id AS benchmark_id
  887. FROM get_mc_bfi_factors(entity_type, v_entity_ids, oldest_date.month(), end_day.month());
  888. } else {
  889. // 主基准, 对应公募混合基金平均 FA00000VNB
  890. benchmark = SELECT DISTINCT entity_id, curve_type, strategy, end_date, iif(benchmark_id.isVoid(), 'FA00000VNB', benchmark_id) AS benchmark_id
  891. FROM ej(entity_info, monthly_returns, ['entity_id', 'curve_type', 'strategy']) ;
  892. }
  893. // 取所有出现的基准月收益
  894. bmk_ret = get_benchmark_return(benchmark, end_day);
  895. //if(bmk_ret.isVoid() || bmk_ret.size() == 0) { return null; }
  896. // TODO: risk free指数月收益存在fund_performance表,所以先将就用 fund_id 表示。之后统一改为更准确的名字
  897. 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);
  898. if(risk_free_rate.isVoid() || risk_free_rate.size() == 0) { return null; }
  899. // 指标计算,因为 cal_traling_xxx 不支持 curve_type & strategy, 所以做个循环
  900. d_rt = dict(STRING, ANY);
  901. v_curve_type = [1, 4, 7];
  902. for(cur in v_curve_type) {
  903. t_ei = SELECT entity_id, inception_date, benchmark_id, ini_value FROM entity_info WHERE curve_type = cur AND strategy = 0;
  904. t_mr = SELECT entity_id, end_date, price_date, ret, nav FROM monthly_returns WHERE curve_type = cur AND strategy = 0;
  905. t_bk = SELECT entity_id, end_date, benchmark_id FROM benchmark WHERE curve_type = cur AND strategy = 0;
  906. if(t_ei.isVoid() || t_ei.size() == 0 || t_mr.isVoid() || t_mr.size() == 0) continue;
  907. if(indicator_type == 'BFI') {
  908. v_indicators = cal_trailing_bfi_indicators(t_ei, t_bk, end_day, t_mr, bmk_ret, risk_free_rate);
  909. for(tb in v_indicators)
  910. UPDATE tb SET curve_type = cur, strategy = 0;
  911. v_table_name = ['BFI-INCEP', 'BFI-YTD', 'BFI-3M', 'BFI-6M', 'BFI-1Y', 'BFI-2Y', 'BFI-3Y', 'BFI-4Y', 'BFI-5Y', 'BFI-10Y'];
  912. } else {
  913. v_indicators = cal_trailing_indicators(t_ei, t_bk, end_day, t_mr, bmk_ret, risk_free_rate);
  914. for(tb in v_indicators)
  915. UPDATE tb SET curve_type = cur, strategy = 0;
  916. v_table_name = ['PBI-INCEP', 'PBI-YTD', 'PBI-3M', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y'];
  917. }
  918. d_indicator = dict(v_table_name, v_indicators);
  919. d_rt[cur$STRING] = d_indicator;
  920. }
  921. return d_rt;
  922. }
  923. /*
  924. * 【Morningstar Integration】通用月度指标计算
  925. *
  926. * @param entity_type <STRING>:
  927. * @param indicator_type <STRING>: PBI, BFI
  928. * @param monthly_returns <TABLE>: NEED COLUMN: entity_id, end_date, price_date, nav, ret
  929. *
  930. * @return <DICT TABLE>: ['PBI-INCEP', 'PBI-YTD', 'PBI-3M', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y']
  931. *
  932. */
  933. def ms_cal_monthly_indicators(entity_type, indicator_type, monthly_returns) {
  934. if(find(['MF', 'HF', 'PF', 'FA'], entity_type) < 0) return null;
  935. if(monthly_returns.isVoid() || monthly_returns.size() < 1) return null;
  936. oldest_date = EXEC price_date.min() FROM monthly_returns;
  937. v_entity_ids = (SELECT DISTINCT entity_id FROM monthly_returns).entity_id;
  938. entity_info = get_entity_info(entity_type, v_entity_ids);
  939. if(entity_info.isVoid() || entity_info.size() == 0) { return null };
  940. end_day = today();
  941. // 取基金和基准的对照表
  942. if(indicator_type == 'BFI') {
  943. benchmark = SELECT entity_id, end_date.temporalParse('yyyy-MM') AS end_date, factor_id AS benchmark_id
  944. FROM get_entity_bfi_factors(entity_type, v_entity_ids, oldest_date.month(), end_day.month());
  945. } else if(indicator_type == 'CAI') {
  946. benchmark = SELECT fund_id AS entity_id, end_date.temporalParse('yyyy-MM') AS end_date, factor_id AS benchmark_id
  947. FROM ms_get_fund_category_average(v_entity_ids, oldest_date.temporalFormat('yyyy-MM'), end_day.temporalFormat('yyyy-MM'));
  948. } else {
  949. // 主基准, 对应 xxx_info 中的 primary_benchmark_id, TODO: 没有基准用沪深300顶,哪怕很多情况下不那么正确
  950. benchmark = SELECT entity_id, end_date, iif(benchmark_id.isNull(), 'IN00000008', benchmark_id) AS benchmark_id
  951. FROM ms_get_entity_primary_benchmark(entity_type, v_entity_ids, oldest_date.temporalFormat('yyyy-MM'), end_day.temporalFormat('yyyy-MM')) ;
  952. }
  953. // 取所有出现的基准月收益
  954. bmk_ret = get_benchmark_return(benchmark, end_day);
  955. //if(bmk_ret.isVoid() || bmk_ret.size() == 0) { return null; }
  956. // TODO: risk free指数月收益存在fund_performance表,所以先将就用 fund_id 表示。之后统一改为更准确的名字
  957. 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);
  958. if(risk_free_rate.isVoid() || risk_free_rate.size() == 0) { return null; }
  959. // 指标计算
  960. if(indicator_type == 'BFI') {
  961. t0 = cal_trailing_bfi_indicators(entity_info, benchmark, end_day, monthly_returns, bmk_ret, risk_free_rate);
  962. v_table_name = ['BFI-INCEP', 'BFI-YTD', 'BFI-3M', 'BFI-6M', 'BFI-1Y', 'BFI-2Y', 'BFI-3Y', 'BFI-4Y', 'BFI-5Y', 'BFI-10Y'];
  963. } else if(indicator_type == 'CAI') {
  964. t0 = cal_trailing_bfi_indicators(entity_info, benchmark, end_day, monthly_returns, bmk_ret, risk_free_rate);
  965. v_table_name = ['CAI-INCEP', 'CAI-YTD', 'CAI-3M', 'CAI-6M', 'CAI-1Y', 'CAI-2Y', 'CAI-3Y', 'CAI-4Y', 'CAI-5Y', 'CAI-10Y'];
  966. } else {
  967. t0 = cal_trailing_indicators(entity_info, benchmark, end_day, monthly_returns, bmk_ret, risk_free_rate);
  968. v_table_name = ['PBI-INCEP', 'PBI-YTD', 'PBI-3M', 'PBI-6M', 'PBI-1Y', 'PBI-2Y', 'PBI-3Y', 'PBI-4Y', 'PBI-5Y', 'PBI-10Y'];
  969. }
  970. return dict(v_table_name, t0);
  971. }