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  
4 responses

Hi Seahawk, do you have any experience tracking/plotting PNL for futures? I'm having some trouble with it in my code. Its plotting the PNL per specific futures contract rather than the rolling PNL for the symbol.

thanks - js

The extent of my experience with futures is that I had it accidentally selected in the dropdown once and became remarkably confused for awhile. : )
If you post that bit of PnL code, surely someone can help there.

the last_sale_price isn't the real filled price of order in full backtest.
the real filled price is the closing price of next bar .
for example ,time of order is 9:35,the last_sale_price is closing price of 9:35,but the filled price of order is closing price of 9:36

That's right.
Really need to be monitoring all position changes each minute and this then comes closer to handling PnL for various conditions: