Back to Community
A Simple ETF Algo

SPY - 40%, TLT - 30%, rest cash. Re-balance on a threshold.

Clone Algorithm
41
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 math

def initialize(context):
    """
    Called once at the start of the algorithm.
    """   
    # Rebalance every day, 5 minutes before market close.
    schedule_function(rebalance, date_rules.every_day(), time_rules.market_close(minutes=5))
   
    context.spy = symbol('SPY')
    context.tlt = symbol('TLT')
    
    context.spy_weight = 0.4
    context.tlt_weight = 0.3
    
    context.spy_threshold = 0.02 # Position size threshold to trigger rebalancing
    context.tlt_threshold = 0.02
 
def my_assign_weights(context, data):
    """
    Assign weights to securities that we want to order.
    """
    pass
 
def rebalance(context,data):
    """
    Execute orders according to our schedule_function() timing. 
    """
    
    if math.isnan(data.current(context.spy, 'price')):
        return
    
    if math.isnan(data.current(context.tlt, 'price')):
        return
    
    spy_target = math.ceil(context.spy_weight*context.portfolio.portfolio_value / data.current(context.spy, 'price'))
    spy_pos = context.portfolio.positions[context.spy].amount
    
    tlt_target = math.ceil(context.tlt_weight*context.portfolio.portfolio_value / data.current(context.tlt, 'price'))
    tlt_pos = context.portfolio.positions[context.tlt].amount
    
    if spy_pos == 0:
        spy_delta = 100 # something large
    else:
        spy_delta = math.fabs(spy_target/spy_pos - 1.0)
        
    if spy_delta > context.spy_threshold:
        order_target(context.spy, int(spy_target))
        
    if tlt_pos == 0:
        tlt_delta = 100 # something large
    else:
        tlt_delta = math.fabs(tlt_target/tlt_pos - 1.0)
        
    if tlt_delta > context.tlt_threshold:
        order_target(context.tlt, int(tlt_target))
 
def handle_data(context,data):
    """
    Called every minute.
    """
    pass
There was a runtime error.