1. 程式人生 > >Oracle使用排列組合計算最大回撤幅度

Oracle使用排列組合計算最大回撤幅度

需要了解的知識點:

最大回撤率:在選定週期內任一歷史時點往後推,產品淨值走到最低點時的收益率回撤幅度的最大值。

最大回撤率計算公式:

最大回撤率=max[(Di−Dj)/ Di]

D為某一天的淨值,i為某一天,j為i後的某一天,Di為第i天的產品淨值,Dj則是Di後面某一天的淨值

準備工作:

假設有4條資料(1號-4號),如圖:

我把資料繪製成座標圖(微軟自帶的畫圖工具畫的,勿噴)

思路:

①使用sys_connect_by_path對這4條資料進行排列組合

select sys_connect_by_path(value, '#') combo
                  from (select *
                          from tmp
                         where bizdate <= 20110104
                         order by bizdate asc) t
                 where level = 2
                connect by prior bizdate < t.bizdate
                       and level <= 2

得到以下結果:

②擷取字串:

select substr(s.combo, 2, instr(s.combo, '#', -1) - 2) as num1,
               substr(s.combo, instr(s.combo, '#', -1) + 1) as num2
          from (select sys_connect_by_path(value, '#') combo
                  from (select *
                          from tmp
                         where bizdate <= 20110104
                         order by bizdate asc) t
                 where level = 2
                connect by prior bizdate < t.bizdate
                       and level <= 2) s

得到以下結果:

③最終計算出最大回撤幅度:

select max((a.num1 - a.num2) / a.num1)
  from (select substr(s.combo, 2, instr(s.combo, '#', -1) - 2) as num1,
               substr(s.combo, instr(s.combo, '#', -1) + 1) as num2
          from (select sys_connect_by_path(value, '#') combo
                  from (select *
                          from tmp
                         where bizdate <= 20110104
                         order by bizdate asc) t
                 where level = 2
                connect by prior bizdate < t.bizdate
                       and level <= 2) s) a

得到最終結果: