Back to Community

Portfolio profit-and-loss is context.portfolio.pnl. (Accurate even with margin)

For any individual stock, long or short, this returns profit-and-loss .

def pnl(context, data, s):  
    pos = context.portfolio.positions[s]  
    return pos.amount * (pos.last_sale_price - pos.cost_basis)  

('s' stands for security or stock)

This returns a dictionary with PnL as keys for accessing high and low, and stocks as values. Optionally specify just 'long' or 'shrt' stocks. 'c' stands for context.

def pnls(c, data, long_shrt=None):  
    pnl_per_sid = {}  
    pos = c.portfolio.positions  
    for s in pos:  
        amt = pos[s].amount  
        if long_shrt:  
            if   long_shrt is 'long' and amt <= 0: continue  
            elif long_shrt is 'shrt' and amt >= 0: continue  
        pnl = amt * (pos[s].last_sale_price - pos[s].cost_basis)  
        pnl_per_sid[pnl] = s '{} {}'.format(s.symbol, pnl))  
    return pnl_per_sid