kernc / backtesting.py

:mag_right: :chart_with_upwards_trend: :snake: :moneybag: Backtest trading strategies in Python.
https://kernc.github.io/backtesting.py/
GNU Affero General Public License v3.0
5.39k stars 1.05k forks source link

When closing a trade, can the size be specified as larger than an integer? #954

Open IMYin opened 1 year ago

IMYin commented 1 year ago

Discussed in https://github.com/kernc/backtesting.py/discussions/953

Originally posted by **IMYin** March 31, 2023 My trading target is futures, with a minimum trading size of 1 lot and a minimum unit of 300 per lot. When I trigger a certain signal, I only want to reduce my position instead of closing it completely. However, the parameter in the close function is a proportion value. So, if I hold a position of 7 lots and my size is 2100, the parameter set for `self.position.close(portion=6/7)`, which is not wrong. But the result is that my position is 301, which is incorrect and causes a chain reaction of position errors later on. ![image](https://user-images.githubusercontent.com/11770037/229113040-2db7e809-4730-40b9-a966-4cfa0fa53366.png) The sample shown in the picture is incorrect. The correct one should look like the following. ![image](https://user-images.githubusercontent.com/11770037/229113414-077f751c-ece4-4abd-99a6-738856d6ab56.png) So I am wondering if it is possible to adjust the setting of the `portion` parameter?
kernc commented 1 year ago

https://github.com/kernc/backtesting.py/blob/0ce24d80b1bcb8120d95d31dc3bb351b1052a27d/backtesting/backtesting.py#L555-L560

>>> (1 - 6/7) * 2100
300.0000000000001

>>> from math import copysign
>>> copysign(max(1, round(abs(2100) * (6/7))), -2100)
-1800.0

Looks like a rounding error on your platform. 32-bit OS by chance?