Back to Community
Momentum Strategy, how to pull stock from result?

Hello Q,

How can I get the stock that is in 'picks' on line 14 to be in data.history on line 22?
It says that it isn't iterable , but when I print it out it is actually a stock.

If someone could help me with that, thanks.

def initialize(context):
schedule_function(trade, date_rules.month_start(), time_rules.market_open(minutes = 65))

def trade(context, data):
context.tlt = sid(23921)
mom, n, lev = 60, 1, 1.0
stocks = symbols('DIA', 'SPY', 'QQQ', 'MDY', 'IWM')
if get_open_orders(): return

C = data.history(stocks, 'price', mom + 1, '1d')  
M = C.iloc[-1] / C.iloc[0]  
M = M.dropna()  
M.sort_values(ascending = False, inplace = True)  
picks = M.head(n)  
print picks  
wt = lev / len(picks) if len(picks) != 0 else 0  

D = data.history(context.tlt, 'price', mom + 1, '1d')  
N = D.iloc[-1] / D.iloc[0]  

for asset in stocks:  
    D = data.history(, 'price', mom + 1, '1d')  
    N = D.iloc[-1] / D.iloc[0]  

    E = data.history(context.tlt, 'price', mom + 1, '1d')  
    L = E.iloc[-1] / E.iloc[0]  

    if N > L:  
        if data.can_trade(asset):  
            if asset in picks:  
                order_target_percent(asset, wt)  
            else:  
                order_target(asset, 0)  
    else:  
        order_target_percent(context.tlt, 1.0)  

def before_trading_start(context, data):
record(leverage = context.account.leverage)
record(num_positions=len(context.portfolio.positions))

1 response

"Picks" looks to be a string, when it needs to be a list to be iterable

Try adding the line below in Initialize so that picks is declared as a list

picks = []