ClementPerroud / Gym-Trading-Env

A simple, easy, customizable Gymnasium environment for trading.
https://gym-trading-env.readthedocs.io/
MIT License
270 stars 56 forks source link

Interest settlement flaw #23

Open porta-logica opened 1 week ago

porta-logica commented 1 week ago

In each step, interest is charged on borrowed asset or borrowed fiat. Currently, the settlement is part of the function portfolio.trade_to_position. However, there are several flaws in the code and the approach.

Consider a current short (negative) position with some positive interest_asset. Assume that the next environment step position parameter is 0.5. In that case the interest settlement is skipped entirely because the "repay" conditions are not met. The portfolio.trade_to_position function will result in a portfolio with unmodified interest_asset and positive asset and fiat amounts. The subsequent call to portfolio.update_interest will reset the interest_asset to 0, loosing the interest_asset forever. This is an error.

A similar example can be constructed with a current position > 1 with some positive interest_fiat. In this case the interest_fiat amount will be lost.

Moreover, the function call to portfolio.trade_to_position, so the interest settlement itself, will be skipped entirely if the current and next positions are the same. This can span to several steps. During this step, or series of steps, the interest booking will be in error.

The interest settlement should be performed in each step, no matter what. The calculation should be refactored into a separate function and called unconditionally in each step prior to trade.

I think that the trading cost calculation is incorrect as well. I calculated the trade result manually when the position is increased from -0.5 to 0.5. In the current implementation the costs are too high and the resulting portfolio asset and fiat are too low. I can provide a simple calculation on request.