Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Limiting Leverage When I Have Multiple Signals on Same Day

Hi Everyone,

I'm just getting started here at Quantopian, and with Python in general. I've created a simple mean-reversion algorithm for learning purposes. It uses a few of the indicators included in the talib library. My question relates to how I can limit leverage correctly. the algorithm doesn't currently limit leverage at all. It simply takes new positions in all stocks that have an entry signal and creates a log if context.long_leverage is exceeded.

I'd like to keep taking new signals in each stock that meets the entry criteria, up until I've reached my desired leverage threshold(1.5 in this example). Once the leverage threshold is reached, no new positions will be opened until existing positions are closed. I think it'd be pretty easy to use a true/false statement to check where the leverage is at before taking any positions. For example:

context.account.leverage < context.long_leverage  

But this doesn't account for the instances where I'm getting signals in a bunch of stocks at the same time. In those cases, the leverage is fine before I take any new positions, but it might go through the roof once all the new positions are opened. Does that make sense?

I think it'll take some kind of loop that first determines which stocks have new signals, then checks available leverage and keeps adding new positions until the leverage threshold is reached, then disregards the remaining new signals. I'm just not sure how to make that work and can't seem to figure it out.

The other examples I've found regarding leverage limits didn't seem to apply in this case, so I'm sorry if I'm asking a question that's already been answered in the past.

Thanks in advance for any and all help! And I'd be really happy to hear any other suggestions/criticisms regarding the code. Like I said, I'm just starting out so I'll take all the help I can get.

Graham