Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
On the stock market, nobody knows I'm a dog. How am I going into debt?

So admittedly, I have no idea what I'm doing, but I'm messing around with stuff I don't understand and ran into this. Sure I didn't intend for the algo to snowball it's investments into ever increasing order sizes. Sure I didn't intend for it to go almost a billion in debt either, but it ends above 4B in the green!

All that aside, I'm not sure how this is going into debt. Each order it places, it uses order_target_percent and the sum of the orders should never be greater than 1. It also sells of any positions that are not a part of the order. With an initial investment of 100k, how does it go almost a billion in debt?!?

6 responses

You always need to check if there are open orders if you are using order_target_percent. That function doesn't check outstanding orders and as a result often ends up in a positive feedback loop run wild like the one you show.

I am not sure how to total value is calculated for order_target_percent. Docs say current "position + cash", but what would happen if that sum is negative?
Another thing that might have to do with it is update_universe. if a stock fall out of universe, does its position get liquidated? if not you will keep adding more money / loan over time

Thank you Kevin, Canceling old orders got rid of 99% of my problem. I still slowly slip into debt over time, but it's not a billion dollars! I am currently placing a sell order for all positions that are not a part of the universe anymore, I think. I'm selling any open positions that are not a part of the handle_data data obj. I'm hoping that the extra capital_used slippage at this point is just the algo reinvesting profits, but I'm not sure of any way to check this.

You can check context.account.leverage, if it passes 1 you are using more money then you have. Basically ordering 100% stocks might raise the leverage to something like 1.01, because transaction fees.

I've tried eveything I can think of to prevent leverage from going over 1. Is there any setting I can use to just not allow my algo to go into debt? I mean, what would happen if it was live trading? It would just continue to try and execute orders without funds?

If you did not have a Margin T account, you would never go over 1 in leverage, as the order would just be denied. Before doing any order, you must either cancel all open orders, or substract their value from your new orders. One common code to use is:

for stock in context.portfolio.positions:  
     if get_open_orders(stock):  
        return # Can't procced, open orders!  

or:
for stock in context.portfolio.positions: for order in get_open_orders(stock): cancel_order(order)