Understanding Leverage - Python for Finance 18

Algorithmic trading with Python Tutorial




Leverage is a heck of a drug. In the previous tutorial, we covered successfully applying leverage to our machine learning trading algorithm. What exactly is leverage? Leverage, in finance, is a way to multiply your investment size, risk, and returns. That said, the multiples are not always as predictable as people expect.

The other problem with leverage is it can allow you to lose more money than you even have. For this reason, another problem comes up: Your broker almost certainly has a sort of "stop-loss" in place where they will stop your trading and take away the leverage.

Leverage is almost always seen as a loan. You usually have to apply for leverage from your broker. First, you're highly likely to have to pay an interest rate on the leverage, since it acts as a loan to you. Because of this, you also need to consider that you need to earn back the interest. From there, should you begin losing money, your broker can come to collect their money at any time, leaving you stuck in a hole.

For example, let's say you have $100,000, and 3X leverage, so your broker is lending you $200,000, giving you a total of $300,000 to invest with. Should you experience 33.33% drawdown, your $300,000 becomes $200,000. Then what do you have? You have nothing. You're now broke, because that $200,000 belongs to your broker.

Oh, also, you owe 9% interest.

Before you took on leverage, you were able to experience 100% drawdown before being broke. With your 3X leverage, not anymore. After that 33% drawdown, your broker will collect their funds and you'll be dead in the water, rather than being able to possibly recover from a 33.33% drawdown.

Using the following starting code, we will try a few samples of leverage testing:


def initialize(context):
    context.stocks = symbols('XLY',  # XLY Consumer Discrectionary SPDR Fund   
                           'XLF',  # XLF Financial SPDR Fund  
                           'XLK',  # XLK Technology SPDR Fund  
                           'XLE',  # XLE Energy SPDR Fund  
                           'XLV',  # XLV Health Care SPRD Fund  
                           'XLI',  # XLI Industrial SPDR Fund  
                           'XLP',  # XLP Consumer Staples SPDR Fund   
                           'XLB',  # XLB Materials SPDR Fund  
                           'XLU')  # XLU Utilities SPRD Fund

def handle_data(context, data):
    for stock in context.stocks:   
        ma1 = data[stock].mavg(50)
        ma2 = data[stock].mavg(200)
        if ma1 > ma2:
            order_target_percent(stock,0.11)
        elif ma1 < ma2:
            order_target_percent(stock,-0.11)
    record('ma1',ma1)
    record('ma2',ma2)
    record('Leverage',context.account.leverage)

This is just a simple moving average crossover strategy. Since we use a moving average of 200, which equates to 200 days, we'll start this with at least 200 days prior, so we'll start with 5/30/2002. Feel free to choose the current date to end on, but we'll be going to June 15th 2015 (6/15/2015). You can either just run the build, or run a full back-test. I will just show the build images here. For this starting strategy, we build without any leverage, and the return is:

Now, we invested with $1,000,000, so then our next question is what if we apply leverage? Let's try 2X leverage. Your senses might suggest that you will double the return, and double drawdown. So you are hoping for 173% return and a drawdown likely that is 66.2%


def initialize(context):
    context.stocks = symbols('XLY',  # XLY Consumer Discrectionary SPDR Fund   
                           'XLF',  # XLF Financial SPDR Fund  
                           'XLK',  # XLK Technology SPDR Fund  
                           'XLE',  # XLE Energy SPDR Fund  
                           'XLV',  # XLV Health Care SPRD Fund  
                           'XLI',  # XLI Industrial SPDR Fund  
                           'XLP',  # XLP Consumer Staples SPDR Fund   
                           'XLB',  # XLB Materials SPDR Fund  
                           'XLU')  # XLU Utilities SPRD Fund

def handle_data(context, data):
    for stock in context.stocks:   
        ma1 = data[stock].mavg(50)
        ma2 = data[stock].mavg(200)
        if ma1 > ma2:
            order_target_percent(stock,0.22)
        elif ma1 < ma2:
            order_target_percent(stock,-0.22)
    record('ma1',ma1)
    record('ma2',ma2)
    record('Leverage',context.account.leverage)

The return is not quite what we were possibly thinking. Less return than expected, but also less drawdown. Okay, so if we're getting a diminishing drawdown here, why not 3X leverage? What could go wrong!?


def initialize(context):
    context.stocks = symbols('XLY',  # XLY Consumer Discrectionary SPDR Fund   
                           'XLF',  # XLF Financial SPDR Fund  
                           'XLK',  # XLK Technology SPDR Fund  
                           'XLE',  # XLE Energy SPDR Fund  
                           'XLV',  # XLV Health Care SPRD Fund  
                           'XLI',  # XLI Industrial SPDR Fund  
                           'XLP',  # XLP Consumer Staples SPDR Fund   
                           'XLB',  # XLB Materials SPDR Fund  
                           'XLU')  # XLU Utilities SPRD Fund

def handle_data(context, data):
    for stock in context.stocks:   
        ma1 = data[stock].mavg(50)
        ma2 = data[stock].mavg(200)
        if ma1 > ma2:
            order_target_percent(stock,0.33)
        elif ma1 < ma2:
            order_target_percent(stock,-0.33)
    record('ma1',ma1)
    record('ma2',ma2)
    record('Leverage',context.account.leverage)

Even though we ended "up," since this was allowed to play out, this would have never gotten this far. Notice the first spike in leverage? Let's zoom into that spot.

It was at that point where you lost 100%, and would have been stopped. This strategy was also, at one point, -1,731,393%. I don't think anyone is going to lend you enough money to get out of that hole!

As you can see hopefully by now, leverage is not just a magical "multiply" button. It can help, but it can also hurt, a lot.

Generally, conventional wisdom for leverage says that you should never buy and hold leverage. A leverage strategy is meant for quick trades. The idea is that you trade as close to a "sure thing" as possible. Set tight trailing stop loss maybe, but definitely don't plan to stay exposed for long.

You simply cannot predict market movements, and flash crashes are common in a lifetime. You will almost certainly see one or two in your lifetime. If you're leveraged enough, these very quick market moves can make you bust, especially if things are currently in bad shape for you. Even though they only occur once or twice in a lifetime in theory, one is still one too many times to go bust.

In small, calculated, doses, leverage can be a good thing, and can actually be the smart choice, but you need to be extremely careful with, and respectful towards, leverage.



In the next tutorial, we'll be talking about the Quantopian Pipeline API:





  • Programming for Finance with Python, Zipline and Quantopian
  • Programming for Finance Part 2 - Creating an automated trading strategy
  • Programming for Finance Part 3 - Back Testing Strategy
  • Accessing Fundamental company Data - Programming for Finance with Python - Part 4
  • Back-testing our strategy - Programming for Finance with Python - part 5
  • Strategy Sell Logic with Schedule Function with Quantopian - Python for Finance 6
  • Stop-Loss in our trading strategy - Python for Finance with Quantopian and Zipline 7
  • Achieving Targets - Python for Finance with Zipline and Quantopian 8
  • Quantopian Fetcher - Python for Finance with Zipline and Quantopian 9
  • Trading Logic with Sentiment Analysis Signals - Python for Finance 10
  • Shorting based on Sentiment Analysis signals - Python for Finance 11
  • Paper Trading a Strategy on Quantopian - Python for Finance 12
  • Understanding Hedgefund and other financial Objectives - Python for Finance 13
  • Building Machine Learning Framework - Python for Finance 14
  • Creating Machine Learning Classifier Feature Sets - Python for Finance 15
  • Creating our Machine Learning Classifiers - Python for Finance 16
  • Testing our Machine Learning Strategy - Python for Finance 17
  • Understanding Leverage - Python for Finance 18
  • Quantopian Pipeline Tutorial Introduction
  • Simple Quantopian Pipeline Strategy