2009-09-30 56 views
0

我有以下的列的表的表最大的「虧損」:SQL查詢來查找金融交易

id int(10) 
winner int(10) 
profit double 
created datetime 

我試圖創建一個查詢,返回最大的縮編,或「峯低谷「在利潤欄方面。 (更多info on drawdown here。)

理想情況下,它將返回爲縮進的開始和結束創建的值以及從開始到結束的利潤深度。

編輯:利潤列不是累積的,但查詢需要查找累計折減。降價可能會有所上升,但一旦累計利潤達到新高,降幅就會結束。這是一個顯示它的line graph。紅色點和綠色點之間的X距離是最大壓差。

+0

你如何定義「高」?你能舉出一些示例數據並顯示哪些數據點包含在Drawdown中? – RedFilter

+0

我添加了一個鏈接到一個圖像,顯示一個線條圖,應該更易於追蹤。 – Dave

回答

0

我不是一個mySQL嚮導,所以請原諒我,如果我犯了一個錯誤。但是,如果沒有其他連接標準,它是整個表的話,我認爲這可能爲你工作:

select a.created as starttime 
    , b.created as endtime 
    , a.profit as startprofit 
    , b.profit as endprofit 
    , b.profit - a.profit as depth 
    from your_table a 
    join your_table b 
    on a.created < b.created 
order by b.profit - a.profit 
limit 1 

如果有其他連接標準,期待與您的ID或贏家幾個結果,或者通過別的東西加入,然後我會嘗試如下所示。但是,不要忘記,您必須關聯where子句中的子查詢。所以,如果你是用id做的,你需要在子查詢中使用where x.is = a.id

select a.created as starttime 
    , b.created as endtime 
    , a.profit as startprofit 
    , b.profit as endprofit 
    , b.profit - a.profit as depth 
    from your_table a 
    join your_table b 
    on a.created < b.created 
     ...other join criteria... 
where b.profit - a.profit = (select min(y.profit - x.profit) 
           from your_table x 
           join your_table y 
            on x.created < y.created 
            ...other join criteria... 
            ...where clause to correlate subquery...) 
0

在閱讀該鏈接後,我並不真正瞭解縮進的要求。如果這意味着,「顯示值最大uninterruped下降」,那裏有不間斷的手段是垮臺過程中沒有暫時的反彈,那麼像這樣可以工作:

select top 1 p1.Created as Created1, p2.Created as Created2, p1.profit as p1, p2.profit as p2, p1.profit - p2.profit as Downfall 
from profit p1 
inner join profit p2 on p1.profit > p2.profit 
    and p2.Created > p1.Created 
    and not exists (
     select 1 
     from profit p1a 
     inner join profit p2a on p1a.Created < p2a.Created 
      and p1a.profit < p2a.profit 
     where p1a.Created >= p1.Created 
      and p2a.Created <= p2.Created 
    ) 
order by Downfall desc 
1

如果你的目標是獲得最大的不間斷在連續下降,你只需要做到以下幾點:

set @max_drawdown = 0; select MIN(if(profit < 0, @max_drawdown:[email protected]_drawdown + (profit), @max_drawdown:=0)) as max_drawdown from your_table order by date;

所以,如果你有這樣的例子:

 
date, profit 
1, -1 
2, -13 
3, 3 
4, -7 
5, -2 
6, -2 
7, -9 
8, 0 
9, -15 

你會得到-20。