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

last_sale_price is a part of portfolio object. One would think that would be the price at which the last trade for that security was placed. Similar to cost basis, but not averaged over past trades. For example if one bought IBM for 77 then for 79, the last sale price should be 79 regardless of the current price of the security.

As it turns out, the behavior of the object is as follows, at least according to my test:

  • Before any trade is executed last price is zero
  • After an order is placed, last price is still zero, presumably the order is not executed yet
  • After the order is executed, last price becomes equal to current trading price of the security.

That is, once we trade it, the last_sale_price of a security in portfolio becomes equal at any point to the security price. This in non-intuitive at best as one can simply get the price from data[].price. I believe the intent of the field was to record and keep the last price at which the security was traded in one's portfolio, not to duplicate the behavior of otherwise available current price of the security. If that indeed was the intention than this is a bug in last_sale_price method implementation.

4 responses

I think the intent was actually to record the last sale price of the security (hence the name). This is the flip side of the adjusted cost basis. Using these two values (and the number of shares) you can calculate the current PnL for the position.

It makes sense that last_sale_price (which is part of the portfolio object) would be undefined (or zero) prior to having a position in that security.

Also remember that the data object only reflects securities currently in the market. But as you know securities can be unlisted or halt trading. So there may not be a 'current price' for a security in every event. So conceptually last_sale_price is distinct from data.price

From a purely technical point of view it's sometimes nice not to have to pass both context and data as arguments to a helper function. So being able to get last_sale_price from context.portfolio is convenient (as opposed to needing the entire data object).

That explains it, thanks!

Does anyone know an easy way we can pull in the last price a security was sold at by the trading algorithm itself?

Thanks!

It is a mystery to me. I've included a backtest that tracks the orders, but the order object does not include the price. It seems like it should capture the price, no?