Back to Community
Dual momentum now goes to cash if everything is down

This is my latest version of Dual Momentum. Now I get out of everything if nothing has moved up over last 250 days.
Let me know what you think. Notice how it dodged the downturn in market in 2008 -9

Clone Algorithm
Backtest from to with initial capital
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):
    context.stocks = symbols('SPY','QQQ','EFA','IEV','GLD')
    context.formation = 250#30#250
    context.port_size = 1
    context.month_count = 0

def rebalance(context, data):
    #get daily historical prices
    h = history(context.formation, '1d', 'price')[context.stocks]
    #use dataframe resample to get monthly values
    h = h.resample('M', how='last')
    print h
    #first, get the pct_change() from the first date (0) in the dataframe and today (-1). Then splice the last row because the first row is all NaN. Drop all stocks with NaN then turn the dataframe into series. Series make it easier to sort.
    chg = h.iloc[[0,-1]].pct_change().tail(1).dropna(axis=1)
    mom = chg.squeeze()
    #order by return percentage, and take only the top N
    mom = mom.order().index[-context.port_size:]
    print mom
    #liquidate positions that are not in the buy list
    for s in context.portfolio.positions:
        if s not in mom or chg[s][0] < 0.0:
            order_target_percent(s, 0)
    #get weight based on how many stocks are selected
    weight = 0.95/len(mom)
    #purchase stocks in the buy list
    for s in mom:
        if s in data and chg[s][0] > 0.0:
            order_target_percent(s, weight)
# Will be called on every trade event for the securities you specify. 
def handle_data(context, data):
    record(leverage = context.account.leverage)
There was a runtime error.