Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Tracking Intraday Leverage

Hello Q

I am trying to write an intraday algorithm that closes all positions by EOD. However, I cannot track the intraday leverage of the algorithm.

In this example, I have created a simple algorithm that buys and sells SPY 5 times the original cash. The EOD position is all cash.

Can someone please help me or point out the error?

Thanks
Shiv

3 responses

From the documentation of 'record' function: "Recording is done at day-level granularity". So I guess you have to log the information you look for inside 'handle_data' to have intra-day level information:

log.info("leverage %f exposure %f" % (context.account.leverage,context.account.net_leverage))

You'll want to store the maximum leverage seen each day and record it at the end of the day. Some code for that at this link although it is tough to work with.

An easier way that doesn't provide as much detail yet catches any new maximum is this from https://www.quantopian.com/posts/max-intraday-leverage:

def handle_data(context, data):  
    if 'mx_lvrg' not in context:             # Max leverage  
        context.mx_lvrg = 0                  # Init this instead in initialize() for better efficiency  
    if context.account.leverage > context.mx_lvrg:  
        context.mx_lvrg = context.account.leverage  
        record(mx_lvrg = context.mx_lvrg)    # Record maximum leverage encountered  

The common practice of doing record(leverage = context.account.leverage) misses 389 of 390 minutes of the trading day.
Look at every minute like above if you want to do well.

Blue Seahawk. Nothing short of genius. Thank you