I'll add a few cents...
The way to keep leverage below 1 is to never hold more than 100% of the portfolio value. This might sound obvious but that's all there is. The first step is to figure out what percent of your portfolio your current holdings are 'consuming'. Then simply subtract that from 1. That will be the percent you have 'available' while still keeping your leverage below 1.
# determine percent of portfolio we have to invest
available_percent = max(1.0-context.account.leverage, 0.0)
Note the max function. There is the possibility that the current holdings went up or down in price so, even without doing anything, the leverage could be above 1 (similar to what happens when one gets a margin call). Won't go into how to handle that here. Basically will need to account for this situation and sell some current holdings to adjust the leverage.
Anyway... Once you determine what percentage of the portfolio is 'available' to trade, then divide that up between your longs and shorts. One issue with your current algorithm is that you will need to first figure out (ie count) how many of each you have. Don't order 'on the fly' since you don't know how many orders you will be placing. Determine the counts first.
# next distribute the available percent across the long and shorts
long_weight = (.70 * available_percent) / len(longs)
short_weight = (-.30 * available_percent) / len(shorts)
# finally, order the target percents
for stock in longs:
for stock in shorts:
Again, keeping the leverage below 1 is as simple as figuring out how much of your portfolio isn't invested yet, and then only placing orders for that amount. There's no magic just basic math. OK, a couple of caveats... as stated earlier, you will need to figure out what to sell in case the leverage does go above 1. Secondly, to get complete control over leverage you will need to place limit orders and not rely upon market prices. Otherwise you may end up paying more for a security than anticipated and therefore go over the 1 leverage. For similar reasons you should calculate the exact shares and price to order and use the simple order method and not rely upon the 'order_target_percent' method. For initial testing the above approach is fine. Only for live trading one would want to implement those details.
Attached is your backtest with a few modifications keeping leverage below 1.