使用cumprod()计算Python中的权益曲线

问题描述 投票:0回答:1

我很难用cumprod()计算复合回报。它从一开始就开始复合,但我只希望它在'Final_Order'等于买入时启动,当'Final_Order等于卖出时停止,然后在下一个买单再次重置。请参阅下面的示例。

下面的示例数据显示了我期望在“Backtest”列中看到的输出。

 Time  Adj_Price  Final_Order   Backtest
  0        7          nan          1000
  1        6          nan          1000
  2        5          Buy          1000
  3        7          Buy          1400
  4        8          Sell         1600
  5        6          Sell         1600
  6        4          Buy          1600
  7        5          Buy          2000
  8        7          Buy          2800
  9        9          Sell         3600
  10       7          Sell         3600
  11       7          Sell         3600
  12       6          Sell         3600

以下是'Backtest'的计算。

  • 时间1 = IF(Final_Order =“买(t0)”,(6/7)* 1000,Else 1000)= 1000
  • 时间2 = IF(Final_Order =“买(t1)”,(5/6)* 1000,Else 1000)= 1000
  • 时间3 = IF(Final_Order =“买(t2)”,(7/5)* 1000,Else 1000)= 1400
  • 时间4 = IF(Final_Order =“买(t3)”,(8/7)* 1400,Else 1400)= 1600
  • 时间5 = IF(Final_Order =“买(t4)”,(6/8)* 1600,其他1600)= 1600
  • 时间6 = IF(Final_Order =“买(t5)”,(4/6)* 1600,其他1600)= 1600
  • 时间7 = IF(Final_Order =“买(t6)”,(5/4)* 1600,其他1600)= 2000
  • 时间8 = IF(Final_Order =“买(t7)”,(7/5)* 2000,Else 2000)= 2800
  • 时间9 = IF(Final_Order =“Buy(t8)”,(9/7)* 2800,Else 2800)= 3600
  • 时间10 = IF(Final_Order =“买(t9)”,(7/9)* 3600,其他3600)= 3600

以下是我正在使用的代码。

data['Backtest'] = np.where(data['Final_Order'] == 'Buy',
                            ((1 + data['Adj 
Close'].pct_change(1)).cumprod())*1000,
                            data['Backtest'].ffill())
python python-3.x numpy return algorithmic-trading
1个回答
1
投票

创建一个初始值为1000且具有费率和最终订单的列表:

b = [1000]+list(zip(df.Adj_Price.shift(-1)/df.Adj_Price,df.Final_Order))

df['BACK']=list(itertools.accumulate(b,lambda x,y: round(y[0]*x) if y[1]=="Buy" else x))[:-1]

df

    Time  Adj_Price Final_Order  Backtest  BACK
0      0          7         NaN      1000  1000
1      1          6         NaN      1000  1000
2      2          5         Buy      1000  1000
3      3          7         Buy      1400  1400
4      4          8        Sell      1600  1600
5      5          6        Sell      1600  1600
6      6          4         Buy      1600  1600
7      7          5         Buy      2000  2000
8      8          7         Buy      2800  2800
9      9          9        Sell      3600  3600
10    10          7        Sell      3600  3600
11    11          7        Sell      3600  3600
12    12          6        Sell      3600  3600

将创建的列与已存在的列进行比较,它们是相同的

© www.soinside.com 2019 - 2024. All rights reserved.