【问题标题】:How to create a rolling difference between two different conditions?如何在两种不同的条件之间创建滚动差异?
【发布时间】:2021-12-20 21:10:05
【问题描述】:

我必须在 Pandas DataFrame 中创建一个新列,其中包含买入和卖出之间的滚动利润(持有期)。buy=1 是买入 卖出=1 是卖出 .. 买入和卖出之间是持有期。

因此,滚动利润应该是当日价格(收盘列)和最后买入价(买入的收盘价=1条件)之间的差异,直到平仓为止。

trading_df = pd.DataFrame({'Date': ['10/1/2020', '10/2/2020', '10/3/2020', '10/4/2020', '10/5/2020', '10/6/2020', '10/7/2020', '10/8/2020', '10/9/2020'],
 'Close': [90, 91, 89, 92, 93, 92, 94, 91, 89],
 'Buy': [0, 1, 0, 0, 0, 0, 1, 0, 0],
 'Sell': [0, 0, 0, 1, 0, 0, 0, 0, 1],
 'Rolling Profit': [None, 0.0, -2.0, 1.0, None, None, 0.0, -3.0, -5.0]})

【问题讨论】:

    标签: pandas


    【解决方案1】:

    你可以使用:

    df['no_trading'] = df['Sell'].replace({0:np.nan, 1:'no_trade'}).fillna(df['Buy'].replace({1:'bought'})).astype(str).replace('0', np.nan).ffill()
    df['no_trading'] = df['no_trading'].mask(((df['no_trading'] == 'no_trade') & (df['Sell'] == 1)), 'sold')
    
    
    df['unique_buys'] = df['Buy'].replace(0, np.nan).cumsum().ffill()
    df['profit'] = df.groupby('unique_buys')[['Close']].apply(lambda x: x-x.iloc[0])
    df['profit'] = df['profit'].mask(df['no_trading'] == 'no_trade', np.nan)
    df.drop(columns=['no_trading', 'unique_buys'], inplace=True)
    print(df)
    

    OUTPUT

            date  Close  Buy  Sell  profit
    0 2020-10-01     90    0     0     NaN
    1 2020-10-02     91    1     0     0.0
    2 2020-10-03     89    0     0    -2.0
    3 2020-10-04     92    0     1     1.0
    4 2020-10-05     93    0     0     NaN
    5 2020-10-06     92    0     0     NaN
    6 2020-10-07     94    1     0     0.0
    7 2020-10-08     91    0     0    -3.0
    8 2020-10-09     89    0     1    -5.0
    

    【讨论】:

      猜你喜欢
      • 2014-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-04-06
      • 1970-01-01
      • 2018-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多