def rebalance_A_to_B(A, B, target_relative_weight, transfer_fee):
    """
    Say you want to rebalance two investments A and B so that the relative weight of A to B is the
    target_relative_weight and transfering the money has a transfer fee proportional to the amount to transfer
    with fixed rate transfer_fee

    If transfer is the amount to move from A to B, we want to solve:
    (A - transfer) / (A - transfer + B + transfer * (1 - transfer_fee)) = target_relative_weight
    which can be algebraicely written into the equivalent:
    transfer = (A - target_relative_weight * (A + B)) / (1 - target_relative_weight * transfer_fee)

    :param A: float, value of A
    :param B: float, value of B
    :param target_relative_weight: what A / (A + B) should be after rebalancing
    :param transfer_fee: a percentage taken from the transfer of value from A to B
    :return: the amount to transfer from A to B to achieve the target_relative_weight


    A and B are already balanced, nothing must be taken from A

    >>> rebalance_A_to_B(10, 10, 0.5, 0)
    0.0

    For A to be 25% of the total, we need to move 5 unit from A to B (assuming no transfer fee)

    >>> rebalance_A_to_B(10, 10, 0.25, 0)
    5.0

    On the other hand, we need to GIVE to A to make A 0.75% of the total (still assuming no transfer fee)

    >>> rebalance_A_to_B(10, 10, 0.75, 0)
    -5.0

    Example including a transfer fee, here we need to transfer a little more to cover for the fee

    >>> a, b = 10, 10
    >>> target_ratio = 0.25
    >>> fee_percent = 0.01
    >>> transfer_amount = rebalance_A_to_B(a, b, target_ratio, fee_percent)
    >>> print(transfer_amount)
    5.012531328320802
    >>> new_a = a - transfer_amount
    >>> new_b = b + transfer_amount * (1 - fee_percent) # a portion of the transferred money is lost due to the fees
    >>> new_ratio = new_a / (new_a + new_b)
    >>> assert new_ratio == target_ratio
    >>> print(new_ratio)
    0.25

    """
    return (A - target_relative_weight * (A + B)) / (
        1 - target_relative_weight * transfer_fee
    )