Комментарии пользователя mscinsider
# Calculate daily returns
df['Daily Returns'] = df['price'].pct_change()
# Shift the daily returns by one to apply them to the next day
df['Shifted Daily Returns'] = df['Daily Returns'].shift(-1)
# Strategy returns based on the signal and the shifted daily returns
# When Signal is 1 (buy), we use the shifted daily return as is (benefit from an increase in price next day).
# When Signal is -1 (sell), we invert the shifted daily return (benefit from a decrease in price next day).
# Neutral days have no impact (returns are 0).
df['Strategy Returns'] = np.where(df['Signal'] == 1, df['Shifted Daily Returns'],
np.where(df['Signal'] == -1, -df['Shifted Daily Returns'], 0))
# Calculate cumulative returns by compounding the strategy returns
df['Cumulative Returns'] = (1 + df['Strategy Returns']).cumprod() — 1
# Plot the cumulative returns
fig, ax = plt.subplots(figsize=(12, 8))
ax.plot(df['date'], df['Cumulative Returns'], color='blue')
ax.set_ylabel('Cumulative Returns')
ax.set_title('Strategy Cumulative Returns Over Time')
plt.show()