Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
How to write an algo to keep leverage under three?

Good day Everyone

Appreciate some kind help to advise how write algo to keep leverage under three?
If my cash is $100,000 do i change the max position size to 300000 and min position size to -300000?

Does it work this way?

# Setting our maximum position size, like previous example
context.max_notional = 100000.1
context.min_notional = -100000.0

Thank you so much

This example runs the same momentum play as the first sample

(https://www.quantopian.com/help#sample-basic), but this time it uses more

securities during the backtest.

Important note: All securities in an algorithm must be traded for the

entire length of the backtest. For instance, if you try to backtest both

Google and Facebook against 2011 data you will get an error; Facebook

wasn't traded until 2012.

First step is importing any needed libraries.

import datetime
import pytz

def initialize(context):
# Here we initialize each stock.
# By calling symbols('AAPL', 'IBM', 'CSCO') we're storing the Security objects.
context.stocks = symbols('AAPL', 'IBM', 'CSCO')
context.vwap = {}
context.price = {}

# Setting our maximum position size, like previous example  
context.max_notional = 1000000.1  
context.min_notional = -1000000.0

# Initializing the time variables we use for logging  
# Convert timezone to US EST to avoid confusion  
est = pytz.timezone('EST')  
context.d=datetime.datetime(2000, 1, 1, 0, 0, 0, tzinfo=est)  

def handle_data(context, data):
# Initializing the position as zero at the start of each frame
notional=0

# This runs through each stock.  It computes  
# our position at the start of each frame.  
for stock in context.stocks:  
    price = data[stock].price  
    notional = notional + context.portfolio.positions[stock].amount * price  
    tradeday = data[stock].datetime  

# This runs through each stock again.  It finds the price and calculates  
# the volume-weighted average price.  If the price is moving quickly, and  
# we have not exceeded our position limits, it executes the order and  
# updates our position.  
for stock in context.stocks:  
    vwap = data[stock].vwap(3)  
    price = data[stock].price  

    if price < vwap * 0.995 and notional > context.min_notional:  
        order(stock,-100)  
        notional = notional - price*100  
    elif price > vwap * 1.005 and notional < context.max_notional:  
        order(stock,+100)  
        notional = notional + price*100

# If this is the first trade of the day, it logs the notional.  
if (context.d + datetime.timedelta(days=1)) < tradeday:  
    log.debug(str(notional) + ' - notional start ' + tradeday.strftime('%m/%d/%y'))  
    context.d = tradeday  
5 responses

Chen,

Here's an example. Basically, if you convert your allocations to percentages that sum to one (taking the absolute value of any short positions), you can then use order_target_percent with a multiplier to adjust your leverage.

One thing to watch out for is that order_target_percent does not take open orders into account, so you can end up exceeding your intended leverage, if there is slippage. This code is a guard against that problem:

if get_open_orders():  
        return  

Grant

Grant gave a great example, the family of order_target() functions will automatically seek to their target positions and avoid leverage. The documentation is available here: https://www.quantopian.com/help#api-order-methods

And here's an example to use context.account.leverage to control the algo's leverage: https://www.quantopian.com/posts/quantopian-open-example-algorithm-to-control-leverage

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Thks alot Grant and Alisa.

Hi Alisa
The example to use context.account.leverage is coded in days and months. If my algo trade based on per min bar does it still work or do I have to modify the code?
Thk u

The example to use context.account.leverage is coded in days and months

Hmm... I'm not sure where you're getting this info. In the example, leverage is calculated in handle_data(), which runs every bar. So in minute-mode backtests this check will run every minute. In live trading, where algos receive minutely data, the check will also be performed every minute.

You can take the code straight from the example and plug into your strategy :)

Thk u so much