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?


Clone Algorithm
Total Returns
Max Drawdown
Benchmark Returns
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
# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
                      time_rule = time_rules.market_open(minutes = 30)
                      time_rule = time_rules.market_close(minutes = 30)

def buySPY(context, data):
    order_target_percent(symbol('SPY'), 5)
def sellSPY(context, data):
    order_target_percent(symbol('SPY'), 0)

# Will be called on every trade event for the securities you specify. 
def handle_data(context, data):
    record(Leverage = context.account.leverage)
    record(Exposure = context.account.net_leverage)
There was a runtime error.
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:"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

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