Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Can Custom Factor return dates?

Hello there

Here is a stripped down version of a custom factor my Algo uses. This gets the max and the min from two series (daily High and daily low) for each stock and returns the difference found in that time window.

The "days" argument is used to lag the window backwards.

def Difference(days,  **kwargs):  
    kwargs['window_length'] += days  

    class diff_calc(CustomFactor):  
        def compute(self, today, assets, out, high,low):  
            out[:] = np.nanmax(high[:self.window_length-days], axis=0)) - np.nanmin(low[:self.window_length-days], axis=0))  
    return diff_calc(**kwargs)  

Would it also be possible to also return the dates of the max value and the date of the min value which are returned?

My use case for this is to classify whether the max came before the min, or vice versa.

Any hints tips appreciated!

4 responses

I guess I could do it in excel.

Something like = match(max(range),range,0)
(taken from the below source) https://exceljet.net/formula/position-of-max-value-in-list

Can anybody think of a good way to do this with a custom factor?

Factors by definition return real numbers, so, returning dates is a bit tricky. However, not sure actual dates are helpful. Probably simply the number of days (actually trading days) between a high and a low may be more useful?

Take a look at the numpy methods 'argmin' and 'argmax' (https://docs.scipy.org/doc/numpy-1.11.0/reference/generated/numpy.argmax.html and https://docs.scipy.org/doc/numpy-1.11.0/reference/generated/numpy.argmin.html#numpy.argmin)

Maybe use something similar to your original method but have it return multiple outputs -one for the delta value and one for the delta days? Something like this

class Delta_High_Low(CustomFactor):  
    inputs = [USEquityPricing.high, USEquityPricing.low]  
    outputs = ['delta_value', 'delta_days']  

    def compute(self, today, assets, out, high,low):  
        # Sometimes the data can be all NaNs which doesn't work even if using the nanargmax method.  
        # Replace any NaNs with -inf (a low number) or inf ( a high number)  
        high[np.isnan(high)] = -np.inf  
        low[np.isnan(low)] = np.inf  
        # find the difference between the highest high and the lowest low  
        out.delta_value[:] = np.nanmax(high, axis=0) - np.nanmin(low, axis=0)  
        # Now  use the 'argmin' and 'argmax' methods to find the indexes of those values  
        # A positive value means the high occured after the low (sloping up)  
        # A negative value means the low occurred after the high (sloping down)  
        # Note these functions will find the FIRST occurance of each value  
        # May want to think through if this is desirable or not?  
        out.delta_days[:] = np.argmax(high, axis=0) - np.argmin(low, axis=0)  



See attached notebook.

@Ben & @Dan:

In order to make a CustomFactor produce datetime values instead of floats, you need to change the dtype. Factors can be expressions that produce either float or datetime values so either option is valid. You can see an example of a CustomFactor that produces datetime values here (the PreviousAsOf custom factor).

Sorry for the confusion, the dtype override isn't in our documentation. We will look to add it in.

Disclaimer

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! Appreciate the notebook!

Thanks Jamie - Good to now know about the potential for factors to return dates.