There's context.portfolio.pnl built-in, and then for individual securities you might be able to extract the relevant elements out of this where I added a few lines:
who = 'pnl_' + sym
what = int(context.books[sym]['balance'])
record( **{ who: what } )
It is from here, could use some work, and also doesn't handle shorting yet. In my ponderings over modifying it to do so, I figure maybe a starting point would be to think of both buying and shorting in terms of their risk, exchange money for stock or stock for money, negative shares are like money spent, sort of. Anyway, some idea basics, even if not perfect yet.