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 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.
{"extraction_info": {"found_math": true, "script_math_tex": 0, "script_math_asciimath": 0, "math_annotations": 0, "math_alttext": 0, "mathml": 0, "mathjax_tag": 0, "mathjax_inline_tex": 0, "mathjax_display_tex": 0, "mathjax_asciimath": 1, "img_math": 0, "codecogs_latex": 0, "wp_latex": 0, "mimetex.cgi": 0, "/images/math/codecogs": 0, "mathtex.cgi": 0, "katex": 0, "math-container": 0, "wp-katex-eq": 0, "align": 0, "equation": 0, "x-ck12": 0, "texerror": 0, "math_score": 0.2904079556465149, "perplexity": 7024.589353802107}, "config": {"markdown_headings": true, "markdown_code": true, "boilerplate_config": {"ratio_threshold": 0.18, "absolute_threshold": 20, "end_threshold": 15, "enable": true}, "remove_buttons": true, "remove_image_figures": true, "remove_link_clusters": true, "table_config": {"min_rows": 2, "min_cols": 3, "format": "plain"}, "remove_chinese": true, "remove_edit_buttons": true, "extract_latex": true}, "warc_path": "s3://commoncrawl/crawl-data/CC-MAIN-2018-43/segments/1539583512499.22/warc/CC-MAIN-20181019232929-20181020014429-00538.warc.gz"}