Back to Community
No of shares held in position and Pnl

Hi,

How to read number shares held in portfolio and PNL for each security which brought few days back?
1) Financial instrument name
2) Last price
3) Type of orders
4) Positions( Number of shares)
5) PnL
6) Traide price

I have following fields available in portfolio..

def initialize(context):
context.security = superSymbol(secType='FUT', symbol='XXXXX', exchange=XXX, currency='XXX',expiry='YYYYDD')

def handle_data(context,data):

for position in context.portfolio.positions:  
    cash_strt = context.portfolio.starting_cash  
    cash_now  = context.portfolio.cash  
    portfolio = context.portfolio.portfolio_value  
    pnl_per_security = context.portfolio.pnl  
    print('pnl_per_security', pnl_per_security)  
    drawdown  = cash_strt - cash_now  
    profit    = portfolio - cash_strt  
    print(cash_strt, cash_now, portfolio, drawdown, profit)  
    pos = context.portfolio.positions[context.security].position  
    print('pos', pos)  
    amt = context.portfolio.positions[context.security].amount  
    cash_ea = int( context.portfolio.cash / len(context.portfolio.positions.keys()) )  
3 responses

A start you can add to.

    pos = context.portfolio.positions  
    for s in pos:  
        cb  = pos[s].cost_basis  
        amt = pos[s].amount  
        prc = data.current(s, 'price')  
        pnl = amt * (pos[s].last_sale_price - cb)   # both long & short

        # prc & cb to 2 decimal places rounded  
        #log.info('{} {}  prc {}  cb {}  pnl {}'.format(amt, s.symbol, '%.2f' % prc, '%.2f' % cb, int(pnl)))

        # For vertical alignment  
        p = 7  # padding  
        log.info('{} {}   prc {}   cb {}   pnl  {}'.format(  
                str(amt)      .rjust(p),  
                s.symbol      .rjust(p),  
                ('%.2f' % prc).rjust(p),  
                ('%.2f' % cb) .rjust(p),  
                str(int(pnl)) .rjust(p),  
        ))

        '''  
        2018-03-15 05:45 before_trading_start:37 INFO       9    TSLA   prc  326.65   cb  313.54   pnl      118  
        2018-03-15 05:45 before_trading_start:37 INFO      18    AAPL   prc  178.49   cb  169.88   pnl      154  
        2018-03-15 05:45 before_trading_start:37 INFO       2    GOOG   prc 1149.22   cb 1047.31   pnl      203  
        '''  

PnL: https://www.google.com/search?q=pnl+site:quantopian.com
You could store info per stock by hacking track_orders, keeping some stats including partial fills.

Hi,
Thank for your reply.
How to find securities wise PnL in the loop?
Price is not coming from below, is there any way out?
prc = data.current(s, 'price')

Sorry I missed that over a year ago.
This is closer to handling PnL for various conditions:
https://www.quantopian.com/posts/per-ticker-pnl-attribution#5cc5ef5855bcf800492820e5