I want to compute the percentage change with the next n row. I’ve tried pct_change() but I don’t get the expected results
For example, with n=1
close return_n
0 100 1.00%
1 101 -0.99%
2 100 -1.00%
3 99 -4.04%
4 95 7.37%
5 102 NaN
With n=2
close return_n
0 100 0.00%
1 101 -1.98%
2 100 -5.00%
3 99 3.03%
4 95 NaN
5 102 NaN
>Solution :
Use pct_change and shift:
N = 2
df['return_n'] = df['close'].pct_change(N).mul(100).round(2).shift(-N)
print(df)
# Output:
close return_n
0 100 0.00
1 101 -1.98
2 100 -5.00
3 99 3.03
4 95 NaN
5 102 NaN