i am working on a backtest and I had a problem with the fee calculation.
Supose the fee is 0.1%
And I have already the buy/sell prices so I can retrieve the percentage of profit:
where:
df['Profit'] = ((df['Sells'] - df['Buys']) / df['Buys']) + 1
Example:
Buys | Sells | Profit |
---|---|---|
3697.35 | 3698.69 | 1.000362 |
3698.24 | 3699.81 | 1.000425 |
3703.69 | 3706.23 | 1.000686 |
So the returns without the fees are
returns = df.Profit.cumprod()
How can I calculate the actual return (with the fees) ?
Let's take a look at your formula first:
Profit = (Sells - Buys) / Buys + 1
= Sells / Buys - Buys / Buys + 1
= Sells / Buys - 1 + 1
= Sells / Buys
Now due to the transaction fee, 0.1% is deducted from your Sells and also added to your Buys. We can thus rewrite the code as:
fee = 0.001
df['Profit'] = df['Sells'].mul(1 - fee) / df['Buys'].mul(1 + fee)