最小窗口长度的最大亏损

时间:2016-07-27 02:47:29

标签: python algorithm

对于给定的浮点数时间序列,很容易在O(n)时间内计算无约束的最大值,其中max drawdown定义为

\min_{i,j, i<j}(x_j - x_i)

在python中,我们的计算是min(x - numpy.expanding_max(x)),但要获得O(n)算法明确写出来:

def max_drawdown(s):
    drawdn = 0
    m,M = s[0],s[0]
    t1,t2 = 0,0
    T1,T2 = 0,0
    for i,v in enumerate(s):
        if (v < m):
            if (v-m) < drawdn:
                drawdn = v-m
                t2 = i
                T1,T2 = t1,t2
        else:
            m = v
            t1 = i
    return T1,T2,drawdn

是否存在针对max_drawdown的O(n)算法,该算法被限制为具有窗口持续时间&gt; MIN_LENGTH?在这种情况下,我想\ min_ {i,j,(j-i)&gt; min_length}(x_j - x_i)。

请注意,这不是Compute *rolling* maximum drawdown of pandas Series中的“滚动缩编”计算。

1 个答案:

答案 0 :(得分:1)

与您的max_drawdown功能相比,修改非常少。当前算法可以用伪代码

编写
Iterate over list
  if (current_element > maximum)
    maximum = current_element
  if (current element - maximum < drawdn)
    drawdn = current_element-maximum

现在,我们不是在同一索引处搜索max_drawdown,而是搜索距离min_length与这些索引之间所需的最大值。在Python中,这变为:

def max_drawdown_min_lenght(s,min_length):
    min_length += 1 #this is for i-j > l (not i-j >= l)
    drawdn = 0
    m = s[0]
    t1 = 0
    T1,T2 = 0,0
    for i in range(len(s)-min_length):
        if (s[i] >= m): #do we have new maximum?
            m = s[i]
            t1 = i
        if (s[i+min_length]-m) < drawdn:#do we have new max drawdown?
            drawdn = s[i+min_length]-m
            T1,T2 = t1,i+min_length
    return T1,T2,drawdn