Back to Community
How to multiply a custom factor slice by an integer?


This is (hopefully) a simple python, pandas, or numpy question. I built a custom factor that returns some macroeconomic data. When I try to use it in pipeline I attempt to do some simple math on it (multiply it by 2) but I get an error:

TypeError: unsupported operand type(s) for *: 'int' and 'Slice'  

The offending line is this:

valid_price = price >= 2 * my_custom_factor_slice  

Can someone please point out what I'm doing wrong and how to do this math correctly?


Here's the custom factor and pipeline code:

class custom_factor_data(CustomFactor):  
    Custom factor to generate which looks like a self serve data factor  
    Just return a different number depending on the year  
    window_length = 1  
    # The factor needs an input but this is ignored.  
    inputs = [USEquityPricing.close]  
    # Associate this factor with the SPY asset  
    mask = StaticAssets(symbols(['SPY']))  
    def compute(self, today, assets, out, value):  
        # Make a dictionary with year as the key, and some macro data as the value  
        custom_factor_data_dict = {2018:100.0, 2019:150.0}  
        # Returns a different number depending on the year  
        out[:] = custom_factor_data_dict[today.year]

def make_pipeline():  
    # However, for testing and speed one may want to limit to a much smaller set  
    universe = Q500US()  
    # Create the custom factor and get its slice  
    my_custom_factor_data = custom_factor_data()  
    my_custom_factor_slice = my_custom_factor_data[symbols('SPY')]

    price = USEquityPricing.close.latest

    # This works but the one below generates an error  
    #valid_price = price >= my_custom_factor_slice  
    # This generates an error: TypeError: unsupported operand type(s) for *: 'int' and 'Slice'  
    # How do I multiply the value of the slice by an integer?  
    valid_price = price >= 2 * my_custom_factor_slice

    # Create the pipeline with columns for all our factors  
    pipe = pipe = Pipeline(  
        columns = {  
        'price' : price,  
        'valid_price': valid_price  
        screen = universe  
    return pipe  
Loading notebook preview...
4 responses

Slices in many ways are second class citizens to their factor counterparts. Not all methods, and in this case operators, work with them. One workaround is to first broadcast the slice values across all assets effectively turning the slice into a factor. This new factor can then be manipulated with the usual operators. Since slices can be used as inputs to factors, one can use the 'hack' below to broadcast the slice values and get our desired factor. The above calculation will then work with this new factor.

price_slice_broadcasted = SimpleMovingAverage(inputs=[my_custom_factor_slice], window_length=1)  
valid_price = price >= 2 * price_slice_broadcasted

However, factors and slices can be combined in operations just fine. (ie factors broadcast the slice before performing the operation). The result will be a factor. So, one can simply re-arrange the calculation above and it works too.

# instead of  
valid_price = price >= 2 * my_custom_factor_slice

# move the factor and the slice together  
valid_price = (price / my_custom_factor_slice) >= 2

For more info on slices for those of you who aren't too familiar, check out these links in the docs


The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Thanks Dan! Broadcasting works! I guess I have a follow up question.... I don't think yy custom factor uses the the input but I can't figure out how to write one that doesn't take an input. I was wondering if there was a way to write it so that it doesn't? Meaning, how can I get rid of this (seemingly useless) line?

inputs = [USEquityPricing.close]

The inputs must be defined for a custom factor (otherwise you will get an error). However, the inputs can be an empty list. So, the following will work too

inputs = []

# If there are no inputs then the parameters to the compute function must reflect that  
def compute(self, today, assets, out):

If not using inputs then remember to not include any inputs in the compute parameter list. This maybe does make it a bit cleaner. Good catch.

Ah, that makes sense now. Thanks Dan!