Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Sorting Error

Hi! I'm fairly new to Quantopian and am slowly getting the hang of things. In my attached algorithm everything is working fine EXCEPT even though I'm resorting my list of ETFs before trading starts every time, my trades aren't being launched according to that list. Is there any way I could make it so it trades the top 3 momentum ETFs every time? Also does anyone know any way to attach the risk management pipeline to this algorithm?

Thanks!

2 responses

Something very similar and may help you:

from quantopian.algorithm import attach_pipeline, pipeline_output  
from quantopian.pipeline.filters import  StaticAssets  
from quantopian.pipeline import Pipeline  
import quantopian.pipeline.factors as Factors  
# --------------------------------------------------------------------  
ASSETS, MOM, N, LEV = symbols('SPY', 'XLV', 'TLT', 'IEF'), 80, 2, 1.0  
# --------------------------------------------------------------------  
def initialize(context):  
    schedule_function(trade, date_rules.month_start(), time_rules.market_open(minutes = 65))  
    m = StaticAssets(ASSETS)  
    momentum = Factors.Returns(window_length = MOM + 1, mask = m)  
    pipe = Pipeline(columns = {'Momentum': momentum}, screen = m)  
    attach_pipeline(pipe, 'pipeline')

def before_trading_start(context, data):  
    output = pipeline_output('pipeline')  
    output.sort_values(['Momentum'], ascending = False, inplace = True)  
    context.etfs = output.head(N).index  
    record(leverage = context.account.leverage, num_positions = len(context.portfolio.positions))     

def trade(context, data):  
    if get_open_orders(): return  
    weight = LEV/len(context.etfs) 

    for etf in context.portfolio.positions:  
        if data.can_trade(etf):  
            if etf not in context.etfs:  
                order_target(etf, 0) 

    for etf in context.etfs:  
        if data.can_trade(etf):  
            order_target_percent(etf, weight)  

Thank you Vladimir, that did help guide me on the right path.