python矢量化运算_使用python中的矢量化解决方案计算最大跌幅

Maximum Drawdown is a common risk metric used in quantitative finance to assess the largest negative return that has been experienced.

Recently, I became impatient with the time to calculate max drawdown using my looped approach.

def max_dd_loop(returns):

"""returns is assumed to be a pandas series"""

max_so_far = None

start, end = None, None

r = returns.add(1).cumprod()

for r_start in r.index:

for r_end in r.index:

if r_start < r_end:

current = r.ix[r_end] / r.ix[r_start] - 1

if (max_so_far is None) or (current < max_so_far):

max_so_far = current

start, end = r_start, r_end

return max_so_far, start, end

I'm familiar with the common perception that a vectorized solution would be better.

The questions are:

can I vectorize this problem?

What does this solution look like?

How beneficial is it?

Edit

I modified Alexander's answer into the following function:

def max_dd(returns):

"""Assumes returns is a pandas Series"""

r = returns.add(1).cumprod()

dd = r.div(r.cummax()).sub(1)

mdd = dd.min()

end = dd.argmin()

start = r.loc[:end].argmax()

return mdd, start, end

解决方案

df_returns is assumed to be a dataframe of returns, where each column is a seperate strategy/manager/security, and each row is a new date (e.g. monthly or daily).

cum_returns = (1 + df_returns).cumprod()

drawdown = 1 - cum_returns.div(cum_returns.cummax())

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值