Following along with E.P. Chan's book, I'm attempting to calculate the maximum drawdown and the longest drawdown duration from cumulative portfolio returns. He codes it in MATLAB, but I wanted to try my hand at the same code in Python.
import pandas as pd def drawdownCalculator(data): highwatermark = data.copy() highwatermark[:] = 0 drawdown = data.copy() drawdown[:] = 0 drawdownduration = data.copy() drawdownduration[:]=0 t = 1 while t <= len(data): highwatermark[t] = max(highwatermark[t-1], data[t]) drawdown[t] = (1 + highwatermark[t])/(1 + data[t]) - 1 if drawdown[t] == 0: drawdownduration[t] = 0 else: drawdownduration[t] = drawdownduration[t-1] + 1 t += 1 return drawdown.max(), drawdownduration.max() max_drawdown, max_drawdown_time = drawdownCalculator(cumulative_returns) #cumulative_returns is a Pandas series
I thought I had it figured out, but I'm getting the following error:
return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None)) File "pandas/_libs/index.pyx", line 80, in pandas._libs.index.IndexEngine.get_value File "pandas/_libs/index.pyx", line 88, in pandas._libs.index.IndexEngine.get_value File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc File "pandas/_libs/hashtable_class_helper.pxi", line 992, in pandas._libs.hashtable.Int64HashTable.get_item File "pandas/_libs/hashtable_class_helper.pxi", line 998, in pandas._libs.hashtable.Int64HashTable.get_item KeyError: 0
Thank you in advance