Back to Community
Meb Faber bug

Hey guys, I am struggling to figure out the bug in this pretty vanilla algorithm and was wondering if someone could lend some insight. Thank you for your help.

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
# http://papers.ssrn.com/sol3/papers.cfm?abstract_id=962461
# SPY EFA AGG VNQ GLD

def initialize(context):
    context.secs = [sid(8554),sid(12915),sid(19920),sid(27796),sid(23911)]
    set_commission(commission.PerShare(cost=.000))
    leverage = 2.0
    context.weight = leverage/len(context.secs)

def reweight(context,data,wt,min_pct_diff=0.1):
    liquidity = context.portfolio.positions_value+context.portfolio.cash
    orders = {}
    pct_diff = 0
    for sec in wt.keys():
        target = liquidity*wt[sec]/data[sec].price
        current = context.portfolio.positions[sec].amount
        orders[sec] = target-current
        pct_diff += abs(orders[sec]*data[sec].price/liquidity)
    if pct_diff > min_pct_diff:
        #log.info(("%s ordering %d" % (sec, target-current)))
        for sec in orders.keys(): order(sec, orders[sec])

def handle_data(context, data):
    wt = dict(((sec,(data[sec].mavg(20)>data[sec].mavg(200))*context.weight) for sec in context.secs))
    reweight(context,data,wt)
There was a runtime error.
2 responses

Try this:

def initialize(context):  
    schedule_function(trade, date_rules.month_start(), time_rules.market_close(minutes = 30))   

def trade(context,data):  
    assets = symbols('SPY', 'MDY', 'QQQ', 'SLV', 'TLT'); lev = 2.0  
    if get_open_orders(): return

    for sec in assets:  
        if data.can_trade(sec):  
            if data.current(sec, 'price') > data.history(sec, 'price', 200, '1d').mean():  
                order_target_percent(sec, lev/len(assets))  
            else:  
                order_target_percent(sec, 0)

    record(leverage = context.account.leverage)  

Much better. Thank you for your help.