2009-09-30 79 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。