Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Problem with using MOM of TA-Lib

Hi everyone,

I'm a college student who just started my Quantopian journey. I was trying to implement a simple MOM strategy, but as shown in the log the output from the TA-Lib function doesn't seem to be a single number. This differs from the results I saw elsewhere. May I know what might be the reason ?

Below please find the code:

import quantopian.algorithm as algo  
import talib

def initialize(context):  
    """  
    Called once at the start of the algorithm.  
    """  
    context.future = continuous_future('CL', offset=0, roll='volume', adjustment=None)  
    # Rebalance every day, 1 hour after market open.  
    algo.schedule_function(  
        rebalance,  
        algo.date_rules.every_day(),  
        algo.time_rules.market_open(hours=1),  
    )

    # Record tracking variables at the end of each day.  
    algo.schedule_function(  
        record_vars,  
        algo.date_rules.every_day(),  
        algo.time_rules.market_close(),  
    )  
def rebalance(context, data):  
    """  
    Execute orders according to our schedule_function() timing.  
    """  
    spot = data.current(context.future, 'contract')  
    close = data.history(context.future, 'price', 30, '1d')  
    MOM1 = talib.MOM(close, timeperiod=25)  
    MOM2 = talib.MOM(close, timeperiod=20)  
    MOM3 = talib.MOM(close, timeperiod=15)  
    MOM4 = talib.MOM(close, timeperiod=10)  
    MOM5 = talib.MOM(close, timeperiod=5)  
    log.info(MOM1)  
    if MOM4 > MOM3 and MOM3 > MOM2 and MOM2 > MOM1:  
        if MOM5 < MOM4 and data.can_trade(spot):  
            order_target_percent(spot, 1.0)  
    elif MOM4 < MOM3 and MOM3 < MOM2 and MOM2 < MOM1:  
        if MOM5 > MOM4 and data.can_trade(spot):  
            order_target_percent(spot, -1.0)

def record_vars(context, data):  
    """  
    Plot variables at the end of each day.  
    """  
    pass  

Thank you all.

2 responses

An update - I just double checked and realized the MOM function actually returns a series instead of a single number. I thus replaced the code

MOM1 = talib.MOM(close, timeperiod=25) with

MOM1 = talib.MOM(close, timeperiod=25)[-1]

and the program runs.

Hopefully that solves the problem.

By the way, I find this page quite helpful: https://cryptotrader.org/talib

For your reference too.