我很难用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'的计算。
以下是我正在使用的代码。
data['Backtest'] = np.where(data['Final_Order'] == 'Buy',
((1 + data['Adj
Close'].pct_change(1)).cumprod())*1000,
data['Backtest'].ffill())
创建一个初始值为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
将创建的列与已存在的列进行比较,它们是相同的