Back to Community
Record PnL per stock

This code records Profit and Loss (PnL) values per day per stock (up to five of them) in the custom chart.
It also does logging of all stocks periodically (the 126 setting is twice a year).

It allows you to see which stocks are doing well. And when.

Screenshot using this ...

First, in your existing algorithm, temporarily comment out any current record() lines you are using because the custom chart can only accept five total and this is set to use them all.
Then paste this all at once at the end of initialize().

    schedule_function(record_pnl, date_rules.every_day(), time_rules.market_close())  
    context.day_count = 0  
    context.pnl_sids  = [ ]  
    context.pnl_sids_exclude  = [ ]  

def record_pnl(context, data):  
    def _pnl_value(sec, context, data):  
        pos = context.portfolio.positions[sec]  
        return pos.amount * (data.current(sec, 'price') - pos.cost_basis)

    context.day_count += 1

    for s in context.portfolio.positions:  
        if not data.can_trade(s): continue  
        if s in context.pnl_sids_exclude: continue

        # periodically log all  
        if context.day_count % 126 == 0:  
            log.info('{} {}'.format(s.symbol, int(_pnl_value(s, context, data))))

        # add up to 5 securities for record  
        if len(context.pnl_sids) < 5 and s not in context.pnl_sids:  
            context.pnl_sids.append(s)  
        if s not in context.pnl_sids: continue     # limit to only them

        # record their profit and loss  
        who  = s.symbol  
        what = _pnl_value(s, context, data)  
        record( **{ who: what } )  

If you want to insure that one or more stocks are included in the recording, you can add them like this:
context.pnl_sids = [sid(8554), sid(24)] or just context.pnl_sids = [sid(24)]

If you want to exclude any stocks from recording, you can exclude them like this:
context.pnl_sids_exclude = [sid(39840), sid(2)]

Click chart legend items to toggle some off/on.

2 responses

Thank you for this!
But I am a bit confused - if i have exactly 5 assets that i'm trading and tracking, shouldn't the sum of all recorded pnls equal the sum of my profits?
I only ask since the numbers don't seem to come along that way.

5 assets that i'm trading and tracking, shouldn't the sum of all recorded pnls equal the sum of my profits?

Well, context.portfolio.pnl should match the sum of those assets (during that minute) only up to the point where one position is closed. Except for commissions.