Back to Community
Leverage shoots up on the Minute data mode

Hi everyone,

My algo works fine on the daily mode, but not in the minute mode. the minute mode uses too much leverage.

Any help would be appreciated. Thanks!

Clone Algorithm
4
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
import pandas

def initialize(context):  
    set_universe(universe.DollarVolumeUniverse(95, 97))  
    context.size = float(context.portfolio.cash / 15)
 
    context.shorts = []
    context.shorting= True
    
def handle_data(context, data):
    
    
    high = history(251, "1d", "high")  
    low = history(251, "1d", "low")
    rolling_max = pandas.stats.moments.rolling_max(high,250)
    rolling_min = pandas.stats.moments.rolling_min(low,250)
    
    prices_200 = history(200, '1d', 'price')   # gets the trailing 200 EOD prices for all stocks in algo  
    prices_100 = prices_200[-114:]   # grab the last 100 prices  
    prices_30 = prices_200[-35:]   # grab the last 30 prices  
    prices_14= prices_200[-12:]   # grab the last 14 prices
        
    for s in data:  
        price = data[s].price  
        pmin = rolling_min[s][-2]
        pmax = rolling_max[s][-2]
 
          
        ma5 = prices_14[s].mean()  
        ma10 = prices_30[s].mean()  
        ma50 = prices_100[s].mean()  
        ma200 = prices_200[s].mean()  

        current_position = context.portfolio.positions[s].amount
        price = data[s].price
        
        if  (price > pmax) and (current_position == 0) and (ma10 > ma50) and (ma50 > ma200)  :
             if not get_open_orders():
                 order_target_value(s, context.size )  
                 log.info("LONG " + str(s.symbol)) 
                
                
        elif (price < ma5) and (current_position != 0) and s not in context.shorts :  
            order_target_value(s, 0)  
            log.info("sell " + str(s.symbol))  
         
            
        if context.shorting:
    
            if (price < pmin) and (current_position == 0) and (ma10 < ma50) and (ma50 < ma200) :
                if not get_open_orders() :
                    order_target_value(s, -context.size )
                    context.shorts.append(s)
                    log.info("short " + str(s.symbol)) 
                
            elif (price > ma5) and (current_position != 0) and s in context.shorts :  
                order_target_value(s, 0)  
                log.info("recover " + str(s.symbol)) 
                context.shorts.remove(s)
        
    record('Leverage',context.account.leverage)
There was a runtime error.
5 responses

It looks like there were some orders going through when there were still pending orders. I added a check for open orders and it seems to fix your issue.

Clone Algorithm
1
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
import pandas

def initialize(context):  
    set_universe(universe.DollarVolumeUniverse(95, 97))  
    context.size = float(context.portfolio.cash / 15)
 
    context.shorts = []
    context.shorting= True
    
def handle_data(context, data):
    
    
    high = history(251, "1d", "high")  
    low = history(251, "1d", "low")
    rolling_max = pandas.stats.moments.rolling_max(high,250)
    rolling_min = pandas.stats.moments.rolling_min(low,250)
    
    prices_200 = history(200, '1d', 'price')   # gets the trailing 200 EOD prices for all stocks in algo  
    prices_100 = prices_200[-114:]   # grab the last 100 prices  
    prices_30 = prices_200[-35:]   # grab the last 30 prices  
    prices_14= prices_200[-12:]   # grab the last 14 prices
    
    open_orders = get_open_orders()
    
    
    for s in data:  
        if s in open_orders:
            continue
        price = data[s].price  
        pmin = rolling_min[s][-2]
        pmax = rolling_max[s][-2]
 
          
        ma5 = prices_14[s].mean()  
        ma10 = prices_30[s].mean()  
        ma50 = prices_100[s].mean()  
        ma200 = prices_200[s].mean()  

        current_position = context.portfolio.positions[s].amount
        price = data[s].price
        
        if  (price > pmax) and (current_position == 0) and (ma10 > ma50) and (ma50 > ma200):
            
             order_target_value(s, context.size )  
             log.info("LONG " + str(s.symbol)) 
                
                
        elif (price < ma5) and (current_position != 0) and s not in context.shorts :  
            order_target_value(s, 0)  
            log.info("sell " + str(s.symbol))  
         
            
        if context.shorting:
            if (price < pmin) and (current_position == 0) and (ma10 < ma50) and (ma50 < ma200):
                order_target_value(s, -context.size)
                context.shorts.append(s)
                log.info("short " + str(s.symbol)) 
                
            elif (price > ma5) and (current_position != 0) and s in context.shorts :  
                order_target_value(s, 0)  
                log.info("recover " + str(s.symbol)) 
                context.shorts.remove(s)
        
    record('Leverage',context.account.leverage)
There was a runtime error.

Thank you David, but the problem still unsolved.

Clone Algorithm
4
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
import pandas

def initialize(context):  
    set_universe(universe.DollarVolumeUniverse(90, 94))  
    context.size = float(context.portfolio.cash / 20)
 
    context.shorts = []
    context.shorting= True
    
def handle_data(context, data):
    
    
    high = history(251, "1d", "high")  
    low = history(251, "1d", "low")
    rolling_max = pandas.stats.moments.rolling_max(high,250)
    rolling_min = pandas.stats.moments.rolling_min(low,250)
    
    prices_200 = history(200, '1d', 'price')   # gets the trailing 200 EOD prices for all stocks in algo  
    prices_100 = prices_200[-114:]   # grab the last 100 prices  
    prices_30 = prices_200[-35:]   # grab the last 30 prices  
    prices_14= prices_200[-12:]   # grab the last 14 prices
    open_orders = get_open_orders()    
    for s in data: 
        if s in open_orders:
            continue
        price = data[s].price  
        pmin = rolling_min[s][-2]
        pmax = rolling_max[s][-2]
 
          
        ma5 = prices_14[s].mean()  
        ma10 = prices_30[s].mean()  
        ma50 = prices_100[s].mean()  
        ma200 = prices_200[s].mean()  

        current_position = context.portfolio.positions[s].amount
        price = data[s].price
        
        if  (price > pmax) and (current_position == 0) and (ma10 > ma50) and (ma50 > ma200)  :
             if not get_open_orders():
                 order_target_value(s, context.size )  
                 log.info("LONG " + str(s.symbol)) 
                
                
        elif (price < ma5) and (current_position != 0) and s not in context.shorts :  
            order_target_value(s, 0)  
            log.info("sell " + str(s.symbol))  
         
            
        if context.shorting:
    
            if (price < pmin) and (current_position == 0) and (ma10 < ma50) and (ma50 < ma200) :
                if not get_open_orders() :
                    order_target_value(s, -context.size )
                    context.shorts.append(s)
                    log.info("short " + str(s.symbol)) 
                
            elif (price > ma5) and (current_position != 0) and s in context.shorts :  
                order_target_value(s, 0)  
                log.info("recover " + str(s.symbol)) 
                context.shorts.remove(s)
        
    record('Leverage',context.account.leverage)
There was a runtime error.

In order to keep your leverage from creeping up you will have to limit the number of positions you have open since you are using a fixed allocation for each trade. It looks like you need to limit to 20 positions to keep leverage under 1. Also, you might want to adjust the position sizes as the portfolio value fluctuates.

David. my Algo works fine on the daily data mode.

Here is the algo on the daily mode with the the check you added. the leverage reaches 106.

Thanks!

Clone Algorithm
4
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
import pandas

def initialize(context):  
    set_universe(universe.DollarVolumeUniverse(90, 95))  
    context.size = float(context.portfolio.cash / 20)
 
    context.shorts = []
    context.shorting= True
    
def handle_data(context, data):
    
    
    high = history(251, "1d", "high")  
    low = history(251, "1d", "low")
    rolling_max = pandas.stats.moments.rolling_max(high,250)
    rolling_min = pandas.stats.moments.rolling_min(low,250)
    
    prices_200 = history(200, '1d', 'price')   # gets the trailing 200 EOD prices for all stocks in algo  
    prices_100 = prices_200[-114:]   # grab the last 100 prices  
    prices_30 = prices_200[-35:]   # grab the last 30 prices  
    prices_14= prices_200[-20:]   # grab the last 14 prices
    open_orders = get_open_orders()    
    for s in data: 
        if s in open_orders:
            continue
        price = data[s].price  
        pmin = rolling_min[s][-2]
        pmax = rolling_max[s][-2]
 
          
        ma5 = prices_14[s].mean()  
        ma10 = prices_30[s].mean()  
        ma50 = prices_100[s].mean()  
        ma200 = prices_200[s].mean()  

        current_position = context.portfolio.positions[s].amount
        price = data[s].price
        
        if  (price > pmax) and (current_position == 0) and (ma10 > ma50) and (ma50 > ma200)  :
                 order_target_value(s, context.size )  
                 log.info("LONG " + str(s.symbol)) 
                
                
        elif (price < ma5) and (current_position != 0) and s not in context.shorts :  
            order_target_value(s, 0)  
            log.info("sell " + str(s.symbol))  
         
            
        if context.shorting:
    
            if (price < pmin) and (current_position == 0) and (ma10 < ma50) and (ma50 < ma200) :
                    order_target_value(s, -context.size )
                    context.shorts.append(s)
                    log.info("short " + str(s.symbol)) 
                
            elif (price > ma5) and (current_position != 0) and s in context.shorts :  
                order_target_value(s, 0)  
                log.info("recover " + str(s.symbol)) 
                context.shorts.remove(s)
        
    record('Leverage',context.account.leverage)
There was a runtime error.

I took a quick stab at limiting your leverage. You either have to reduce position sizes or limit the number of positions you can have open at a given time. I went with the latter and keep the allocation at a 20th of the portfolio value and limited you to 30 open positions (1.5x leverage). You will have to do some work to add/drop stocks when you are at your maximum position count. Hope this helps.

Clone Algorithm
1
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
import pandas


def initialize(context):
    set_universe(universe.DollarVolumeUniverse(90, 95))
    context.size = float(context.portfolio.cash / 20)

    context.shorts = []
    context.max_positions = 30
    context.shorting = True


def handle_data(context, data):
    context.size = abs(float(context.portfolio.portfolio_value/ 20))

    high = history(251, "1d", "high")
    low = history(251, "1d", "low")
    rolling_max = pandas.stats.moments.rolling_max(high, 250)
    rolling_min = pandas.stats.moments.rolling_min(low, 250)

    prices_200 = history(200, '1d', 'price')  # gets the trailing 200 EOD prices for all stocks in algo  
    prices_100 = prices_200[-114:]  # grab the last 100 prices  
    prices_30 = prices_200[-35:]  # grab the last 30 prices  
    prices_14 = prices_200[-20:]  # grab the last 14 prices
    open_orders = get_open_orders()
    
    position_count = get_position_count(context)
    
    for s in data:
        if s in open_orders:
            continue
        price = data[s].price
        pmin = rolling_min[s][-2]
        pmax = rolling_max[s][-2]

        ma5 = prices_14[s].mean()
        ma10 = prices_30[s].mean()
        ma50 = prices_100[s].mean()
        ma200 = prices_200[s].mean()

        current_position = context.portfolio.positions[s].amount
        price = data[s].price

        if (price > pmax) and (current_position == 0) and (ma10 > ma50) and (ma50 > ma200):
            if position_count < context.max_positions:
                order_target_value(s, context.size)
                log.info("LONG " + str(s.symbol))
                position_count += 1


        elif (price < ma5) and (current_position != 0) and s not in context.shorts:
            order_target_value(s, 0)
            log.info("sell " + str(s.symbol))
            position_count -=1

        if context.shorting:
            if (price < pmin) and (current_position == 0) and (ma10 < ma50) and (ma50 < ma200):
                if position_count < context.max_positions:
                    order_target_value(s, -context.size)
                    context.shorts.append(s)
                    log.info("short " + str(s.symbol))
                    position_count += 1

            elif (price > ma5) and (current_position != 0) and s in context.shorts:
                order_target_value(s, 0)
                log.info("recover " + str(s.symbol))
                context.shorts.remove(s)
                position_count -= 1


    record('Leverage', context.account.leverage,
           'position_count', position_count)


def get_position_count(context):
    n = 0
    for position in context.portfolio.positions.itervalues():
        if position.amount != 0:
            n += 1
    return n
There was a runtime error.