def valuate_position(position, tdate):
    """Valuate the position for the given date.

    Parameters
    ----------
    position : alphapy.Position
        The position to be valued.
    tdate : timedate
        Date to value the position.

    Returns
    -------
    position : alphapy.Position
        New value of the position.

    Notes
    -----

    An Example of Cost Basis

    ======== ====== ====== ======
    Date     Shares Price  Amount
    ======== ====== ====== ======
    11/09/16  +100   10.0   1,000
    12/14/16  +200   15.0   3,000
    04/05/17  -500   20.0  10,000
    -------- ------ ------ ------
    All        800         14,000
    ======== ====== ====== ======

    The cost basis is calculated as the total value of all
    trades (14,000) divided by the total number of shares
    traded (800), so 14,000 / 800 = 17.5, and the net position
    is -200.

    """
    pdata = position.pdata
    if tdate in pdata.index:
        cp = float(pdata.loc[tdate]['close'])
        multiplier = position.multiplier
        netpos = 0
        tts = 0
        ttv = 0
        totalprofit = 0.0
        for trade in position.trades:
            tq = trade.quantity
            netpos = netpos + tq
            tts = tts + abs(tq)
            tp = trade.price
            pfactor = tq * multiplier
            cv = pfactor * cp
            cvabs = abs(cv)
            ttv = ttv + cvabs
            ev = pfactor * tp
            totalprofit = totalprofit + cv - ev
        position.quantity = netpos
        position.price = cp
        position.value = abs(netpos) * multiplier * cp
        position.profit = totalprofit
        position.costbasis = ttv / tts
        position.netreturn = totalprofit / cvabs - 1.0
    return position
