numpy - Start, End and Duration of Maximum Drawdown in Python -
given time series, want calculate maximum drawdown, , want locate beginning , end points of maximum drawdown can calculate duration. want mark beginning , end of drawdown on plot of timeseries this:
a busy cat http://oi61.tinypic.com/r9h4er.jpg
so far i've got code generate random time series, , i've got code calculate max drawdown. if knows how identify places drawdown begins , ends, i'd appreciate it!
import pandas pd import matplotlib.pyplot plt import numpy np # create random walk want calculate maximum drawdown for: t = 50 mu = 0.05 sigma = 0.2 s0 = 20 dt = 0.01 n = round(t/dt) t = np.linspace(0, t, n) w = np.random.standard_normal(size = n) w = np.cumsum(w)*np.sqrt(dt) ### standard brownian motion ### x = (mu-0.5*sigma**2)*t + sigma*w s = s0*np.exp(x) ### geometric brownian motion ### plt.plot(s) # max drawdown function def max_drawdown(x): mdd = 0 peak = x[0] x in x: if x > peak: peak = x dd = (peak - x) / peak if dd > mdd: mdd = dd return mdd drawseries = max_drawdown(s) maxdd = abs(drawseries.min()*100) print maxdd plt.show()
just find out running maximum minus current value largest:
n = 1000 xs = np.random.randn(n).cumsum() = np.argmax(np.maximum.accumulate(xs) - xs) # end of period j = np.argmax(xs[:i]) # start of period plt.plot(xs) plt.plot([i, j], [xs[i], xs[j]], 'o', color='red', markersize=10)
Comments
Post a Comment