Toward the most efficient universal function that can always be counted on to pull a floating point price and never a nan no matter what state the stock is in, thought I might as well share the code I was using to look into it, since it might be useful for other things too. It takes a look at any differences between these:
data.current(stock, 'price')
data.history(stock, 'price', 1, '1m')[-1] # Minute resolution
data.history(stock, 'price', 1, '1d')[-1] # Daily resolution
context.portfolio.positions[stock].last_sale_price
Basically turns out to be pretty simple (except the last point):
- data.current(stock, 'price') Always best as long as data.can_trade(stock)
- context.portfolio.positions[stock].last_sale_price Always populated even when delisted.
- As soon as delisted, everything except last_sale_price are nan.
- At any time of day, latest history '1m' and '1d' are often the same, yet not always.
This was a level of detail I needed, to be certain.
Easier than I thought, looks like this ought to be fine:
def price(context, data, s): # Always return latest known price, avoiding nan
if data.can_trade(s): return data.current(s, 'price')
else: return context.portfolio.positions[s].last_sale_price
Can turn on Q1500US() among other options ...