Back to Community
Why does my leverage go above 1 here?

What is causing the leverage to go above 1?

Clone Algorithm
2
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
def initialize(context):
    context.aapl = sid(24)
    
def handle_data(context, data):
    
    swag = data.history(context.aapl,'high',10,'1m')
    swaggy = swag[5:].sum() 
    swaggo = swag[:5].sum()
    
    cur_price = data.current(context.aapl,'price')
    print(cur_price)
    
    cur_pos = context.portfolio.positions_value
    print(cur_pos)
    
    cash = context.portfolio.cash
    print(cash)
    
    goo = get_open_orders()
    
    print(goo)
    
    if context.aapl not in goo and cur_pos>=0:
        if swaggy < swaggo:
            order_value(context.aapl,10000)
        
        if swaggy > swaggo and cur_pos>10000:
            order_value(context.aapl,-10000)
        
        
    record(leverage = context.account.leverage)
There was a runtime error.
2 responses
order_value(context.aapl,10000)  

This will order $10,000 worth of AAPL every time the condition is met, this builds up so if the condition is met two times, you'll hold $20,000 etc...

If you want to keep leverage at 1, use:

order_target_percent(context.aapl, 1)  

This should do the job, I removed the Handle Date method because it just stacked orders.

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
def initialize(context):
    context.aapl = sid(24)
    schedule_function(order_, date_rules.every_day(), time_rules.market_open())
    
def order_(context, data):
    
    swag = data.history(context.aapl,'high',10,'1m')
    swaggy = swag[5:].sum() 
    swaggo = swag[:5].sum()
    
    cur_price = data.current(context.aapl,'price')
    print(cur_price)
    
    cur_pos = context.portfolio.positions_value
    print(cur_pos)
    
    cash = context.portfolio.cash
    print(cash)
    
    if swaggy < swaggo:
        order_target_percent(context.aapl, 1.0)
        
    if swaggy > swaggo:
        order_target_percent(context.aapl, -1.0)
        
        
    record(leverage = context.account.leverage)
There was a runtime error.