Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Trade gain code?

Does anyone have a trade gain % snippet that they could share?

When I tried to implement it I found it tricky to assess the 'cost basis' of closing trades.

2 responses

Tricky is right.

A few clues

https://www.quantopian.com/posts/track-orders

      pnl = ''  # for the trade only  
        if cb:  
          pnl  = -filled_amt * (prc - cb)

Would this do?

pos = context.portfolio.positions  
oos = get_open_orders()

for s in oos:  
    for o in oos[s]:  
        if o.status != 0:    # ignoring status 0, order not done yet  
            s = o.sid  
            pnl = o.amount * (data.current(s, 'price') - pos[s].cost_basis)  

Hopefully you won't have to resort to tracking a running balance.
In this area it can also be useful sometimes to know whether an order is opening, closing or crossover (long to short etc)

Thanks, I'll see if I can make it work.