程式

Python中的全域最大回撤和最大回撤持續時間實現

  • January 4, 2021

跟隨 EP Chan 的書,我試圖從累積的投資組合回報中計算最大回撤和最長回撤持續時間。他在 MATLAB 中編寫程式碼,但我想嘗試在 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

我以為我已經弄清楚了,但我收到以下錯誤:

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

先感謝您

我猜你的系列是由時間戳索引的,這可以解釋為什麼通過整數訪問不起作用。但我無法確定,因為您沒有向我們展示任何數據。

好消息是無論如何我都不需要它。這是計算所需內容的更慣用方法:

highwatermarks = cumulative_returns.cummax()

drawdowns = (1 + highwatermarks)/(1 + cumulative_returns) - 1

max_drawdown = max(drawdowns)

沒有簡單的方法可以用數組表示法計算持續時間。幸運的是,這個問題展示瞭如何在您的場景中使用累加器:

from itertools import accumulate

drawdown_times = (drawdowns > 0).astype(np.int64)

max_drawdown_time = max(accumulate(drawdown_times, lambda x,y: (x+y)*y))

或者,您可以將連續的持續時間組合在一起。我不推薦這種方法,但我會為後代包括它:

max_drawdown_time = drawdown_times.groupby((drawdown_times != drawdown_times.shift()).cumsum()).cumsum().max()

引用自:https://quant.stackexchange.com/questions/55130