From a19f7e7b21723695e9d87f2a713d855eb5c9af13 Mon Sep 17 00:00:00 2001 From: Gourav Kumar Date: Mon, 14 Mar 2022 23:54:54 +0530 Subject: [PATCH] added max_drawdown function --- fincal/fincal.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/fincal/fincal.py b/fincal/fincal.py index a9759da..da830e6 100644 --- a/fincal/fincal.py +++ b/fincal/fincal.py @@ -517,6 +517,24 @@ class TimeSeries(TimeSeriesCore): rr = self.calculate_rolling_returns(**kwargs) return statistics.mean(rr.values) + def max_drawdown(self): + max_val_dict = {} + + prev_val = 0 + prev_date = list(self.data)[0] + + for dt, val in self.data.items(): + if val > prev_val: + max_val_dict[dt] = (dt, val, 0) + prev_date, prev_val = dt, val + else: + max_val_dict[dt] = (prev_date, prev_val, val / prev_val - 1) + + max_drawdown = min(max_val_dict.items(), key=lambda x: x[1][2]) + max_drawdown = dict(start_date=max_drawdown[1][0], end_date=max_drawdown[0], drawdown=max_drawdown[1][2]) + + return max_drawdown + if __name__ == "__main__": date_series = [