Back to Community
Leverage and Sentiment Analysis

Hi All,

Could anyone help me adjust my algorithm to keep the leverage at 1 consistently? I've been working with get_open_orders() to prevent over ordering but for some reason the leverage is too low for the algorithm to make money. I think the issue is in the compute_weights function where I calculated the weights for longs and shorts. Additionally, can anyone also help me with adding sentiment analysis to my algorithm? I've looked through other posts but couldn't find out how to use the bullish and bearish intensity factors when importing stocktwits.

Thanks,

Rohit

Clone Algorithm
3
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 58fa8d479969e1618bcd9d46
There was a runtime error.
4 responses

Sentiment algos? Sorted by date Bollinger bands

Nothing dramatic, two algos, one in comments, merely a few ideas in case you might find anything useful

Clone Algorithm
2
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 58fb41daaffc256642b875fc
There was a runtime error.

Thanks Blue! However, in this algo the leverage still climbs past 2, is there a way to keep the leverage at 1 continuously throughout the backtest?

still past 2, that's funny, your leverage before was hardly above 0 with an all-time high of .15, I thought that was the problem that I started out wanting to solve. Notice long and short are stored and the weight applied to their counts. Your upper/lower filter was screening many out as it should. I think that's why your leverage was so low.

The second algo in that code (you can extricate it from the comments) has a maximum intraday leverage of 1.02 for that date range. So you can work on figuring the two out. (I use a tool that has maxlev built in by the way). In the second code I meant to set a maximum 10% allocation for times when there may be only one short or one long and now I see the short side should have been more like order_target_percent(s, max(-.1, -.30 / count)). I'll tell you a secret. For leverage 1.0, keep twice the short value in cash. A large number of stocks makes that easier. I don't know if you noticed, there's some lv math to automatically tailor multipliers to try to help target leverage of 1. Maybe give that a whirl on the second algo, as that 1.02 won't hold when you're making changes, it was luck, I didn't tweak. Bsst way to understand it is to set a watch in the debugger, which, I might add, is an unfortunate name in the industry, it leads us to think it is for when there are bugs. The debugger is really quite the educational tool.

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:  
    order_target_percent(stock, long_weight)  

for stock in shorts:  
    order_target_percent(stock, short_weight) 

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.

Clone Algorithm
6
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 58fb758e9c02e144b976eab9
There was a runtime error.