1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
|
def drawdown(pnl): """ calculate max drawdown and duration Returns: drawdown : vector of drawdwon values duration : vector of drawdown duration """ cumret = pnl highwatermark = [ 0 ] idx = pnl.index drawdown = pd.Series(index = idx) drawdowndur = pd.Series(index = idx) for t in range ( 1 , len (idx)) : highwatermark.append( max (highwatermark[t - 1 ], cumret[t])) drawdown[t] = (highwatermark[t] - cumret[t]) drawdowndur[t] = ( 0 if drawdown[t] = = 0 else drawdowndur[t - 1 ] + 1 ) return drawdown, drawdowndur % timeit drawdown(spy) 1 loops, best of 3 : 1.21 s per loop |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
def dd(s): # ‘‘‘ simple drawdown function ‘‘‘ highwatermark = np.zeros( len (s)) drawdown = np.zeros( len (s)) drawdowndur = np.zeros( len (s)) for t in range ( 1 , len (s)): highwatermark[t] = max (highwatermark[t - 1 ], s[t]) drawdown[t] = (highwatermark[t] - s[t]) drawdowndur[t] = ( 0 if drawdown[t] = = 0 else drawdowndur[t - 1 ] + 1 ) return drawdown , drawdowndur % timeit dd(spy.values) 10 loops, best of 3 : 27.9 ms per loop |