选择满足特定条件的第一行

时间:2015-05-18 13:44:55

标签: python pandas

我有以下数据框:

Date         RunningTotal
01-05-2015   100
02-05-2015   150
03_05-2015   140
04-05-2015   130
05_05_2015   140
06-05-2015   170
07-05-2015   180

我需要确定运行总计的最大drawdown的开始和结束。到目前为止,我能够确定最大亏损的起始指数位置和最大亏损的指数位置,如下所示:

df.set_index(['RunningTotal'], inplace=True)
max_drawdown_ix = np.argmax(np.maximum.accumulate(df.index) - df.index)+1
start_drawdown_ix = np.argmax(df.index[:max_drawdown_ix])

我无法做的是确定下降结束时的指数位置(即:当运行总数高于下降开始时的时间)。在上面的例子中,结果如下:

max_drawdown_ix occurs on 04_05_2015 which is index position 3
start_drawdown_ix occurs on 02_05_2015 which is index position 1
end_drawdown_ix occurs on 06_05_2015 which is index position 5

有关如何确定最大/最大缩编何时结束的任何建议? (即:如何确定第一次出现的时间是runtotal是否超过start_drawdown_ix,这发生在max_drawdown_ix之后)

1 个答案:

答案 0 :(得分:2)

首先,让我们计算你的缩编。

df['drawdown'] = df.RunningTotal.cummax() - df.RunningTotal

接下来,找出最大跌幅发生的位置。

max_dd_idx = df.drawdown.idxmax()
max_dd_date = df.Date.iat[max_dd_idx]
>>> max_dd_date
'04-05-2015'

然后,我们需要在此索引位置之前搜索第一个零值,以找到缩编期的开始。

dd_start_idx = (df.drawdown.loc[:max_dd_idx]
                [df.drawdown.loc[:max_dd_idx] == 0].index[-1])
dd_start_date = df.Date.iat[dd_start_idx]
>>> dd_start_idx
'02-05-2015'

然后获取最大缩减周期结束时的索引位置(即最大DD在Max DD之后首先变为零)。

dd_end_idx = (df.drawdown.loc[max_dd_idx:]
              [df.drawdown.loc[max_dd_idx:] == 0].index[0])
dd_end_date = df.Date.iat[dd_end_idx]
>>> dd_end_date
'06-05-2015'

请注意,如果当前的缩编期正在进行,您将需要进行边界检查以避免索引错误。

if len(df.drawdown.loc[max_dd_idx:][df.drawdown.loc[max_dd_idx:] == 0]) == 0:
    pass  # Current drawdown period is ongoing.
相关问题