I've been playing around with set_universe and it's resulted in positions remaining open and orphaned when the universe changes. I'm monitoring len(data) to see when the list of stocks change. Is there a closeAllPositions() function that I can use to flatten my portfolio?
Also, does the data returned by the history() function change as the universe changes? Having some trouble debugging... I keep seeing my leverage number change to numbers it shouldn't be at. Wondering if it's a result of the universe changing and I'm getting more orphaned positions.
Is there a way to get a random universe of stocks, and then keep that universe the same for the duration of the test?
Update - after some more debugging, it looks like an orphaned order causes the "if get_op_orders() return" line to be stuck. The order never fills and no more trades are ever done for the backtest. All of my orders are market orders. This also explains the leverage numbers being off. Could it be that orders get stuck after a universe change no longer has the stock?
Update 2 - the orphaned order was caused by GDT, which was generated by set_universe, but stops trading after Jun 2006. Might need something which automatically cancels outstanding orders for stocks which have stopped trading.