Приведенный ниже код получит желаемый доход:
import pandas as pd
data = pd.DataFrame({
'Index':range(452, 464),
'close':[113.05,112.05,111.45,114.20,109.45,110.50,109.65,114.4,110.15,110.90,112.25,117.75],
'BUY':[1,1,0,0,0,0,0,0,0,0,0,0],
'SELL':[0,0,0,0,0,0,0,0,0,0,0,0]
})
def calculate_buy_returns(data, n):
returns = []
for i, row in data.iterrows():
if row.BUY == 1:
if (i + n) < len(data):
# get the close price at index + n
close_n = data[data.index == (i + n)].iloc[0].close
returns.append((close_n - row.close)/row.close)
else:
returns.append(0)
else:
returns.append(0)
return returns
data['returns'] = calculate_buy_returns(data, 10)
print(data)
Вывод:
Index close BUY SELL returns
0 452 113.05 1 0 -0.007077
1 453 112.05 1 0 0.050870
2 454 111.45 0 0 0.000000
3 455 114.20 0 0 0.000000
4 456 109.45 0 0 0.000000
5 457 110.50 0 0 0.000000
6 458 109.65 0 0 0.000000
7 459 114.40 0 0 0.000000
8 460 110.15 0 0 0.000000
9 461 110.90 0 0 0.000000
10 462 112.25 0 0 0.000000
11 463 117.75 0 0 0.000000