【问题标题】:Select first row that meets certain condition选择满足特定条件的第一行
【发布时间】:2015-05-19 00:17:26
【问题描述】:

我有以下数据框:

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

关于如何确定最大/最大回撤何时结束有什么建议吗? (即:如何判断第一次出现是runningtotal大于start_drawdown_ix,出现在max_drawdown_ix之后)

【问题讨论】:

  • 数据可能包含多个回撤?如果是,您是否只需要最大的一个?
  • 我只需要最大的一个。我发布的代码正确识别了最大回撤的开始,以及最大回撤位置。我需要知道的是最大的回撤何时结束。 (即:运行总额何时会大于缩编开始前。)谢谢。

标签: python pandas


【解决方案1】:

首先,让我们计算您的亏损。

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 在最大 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.

【讨论】:

  • 对不起,我认为选择这个作为正确答案就足够了。没问题,...赞成:)
猜你喜欢
  • 1970-01-01
  • 2011-12-28
  • 2014-02-18
  • 2013-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多