edtechre / pybroker

Algorithmic Trading in Python with Machine Learning
https://www.pybroker.com
Other
2.09k stars 262 forks source link

enable_fractional_shares is not considered by calc_target_shares #65

Closed pennymax closed 11 months ago

pennymax commented 1 year ago

Hi, @edtechre,

I noticed that the "calc_target_shares" function consistently returns an integer value. It seems not to factor in the "enable_fractional_shares" option. Was this intentional? For context, higher-priced cryptocurrencies like BTC permit trading in fractional shares. When backtesting BTC with a limited initial cash amount, I always get a result of 0 shares from "calc_target_shares". While I can create my own function to determine shares, I'm wondering if I've correctly understood the purpose of the "enable_fractional_shares" option.

def calc_target_shares(
        self, target_size: float, price: float, cash: Optional[float] = None
    ) -> int:
        r"""Calculates the number of shares given a ``target_size`` allocation
        and share ``price``.

        Args:
            target_size: Proportion of cash used to calculate the number of
                shares, where the max ``target_size`` is ``1``. For example, a
                ``target_size`` of ``0.1`` would represent 10% of cash.
            price: Share price used to calculate the number of shares.
            cash: Cash used to calculate the number of number of shares. If
                ``None``, then the :class:`pybroker.portfolio.Portfolio` equity
                is used to calculate the number of shares.

        Returns:
            Number of shares given ``target_size`` and share ``price``.
        """
        shares = int(
            (to_decimal(cash) if cash is not None else self._portfolio.equity)
            * to_decimal(target_size)
            / to_decimal(price)
        )
        return max(shares, 0)
edtechre commented 1 year ago

Hi @pennymax,

The enable_fractional_shares option allows fractional shares to be used when placing orders. The calc_target_shares function is a utility function for computing shares, it does not have any effect on the order logic. But I can update the function to take into consideration the enable_fractional_shares config option.

pennymax commented 1 year ago

Hi, @edtechre,

I appreciate your detailed explanation. It'd be beneficial if the "enable_fractional_shares" option could be incorporated into the calc_target_shares function.

edtechre commented 11 months ago

Made this change in dev. This will be merged into the v1.1.30 release.