Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help Needed In Calculating Lower Partial Moments

I've previously written an algorithm that calculates equal-risk weights for a multi-asset portfolio, using standard deviation as a proxy for risk.  Now, I'm writing an algorithm that calculates these weights based solely on the downside deviations (lower partial moments).  Here's what I've got so far:

def make_pipeline():  
    base_universe = StaticAssets(symbols('IHI','XLY','TLT'))      
    Close = USEquityPricing.close.latest.fillna(0)      
    returns = DailyReturns(inputs=[USEquityPricing.close], window_length=2)      
    diff = 0 - returns    #simplied form for threshold=0      
    diff = np.clip(diff,a_min=0,a_max=None)    Vola = np.sum(diff**2) / len(returns)

    pipe = Pipeline(
        columns={
            'VolFactors' : Close / Vola,
            'Closes' : Close,
        },
        screen=base_universe
    )
    return pipe

The code works fine all the way through diff.clip operation, but as soon as I add the Vola-defining equation, the pipeline chokes, providing the following error message:

            TypeError: f() got an unexpected keyword argument 'out'  

I would appreciate any assistance in sorting out the problem in this last, crucial step.

1 response

I've worked through the problem by re-formulating the Lower Partial Moment calculation wholly as a Custom Factor with a fixed window, which was my originally intended approach until I was mis-directed by error messages.  After some more careful attention to parsing, I was able to get the algorithm working.  Here's the final result:

class Volatility(CustomFactor): 

    inputs = [USEquityPricing.close]  
    def compute(self, today, assets, out, close):  
        # [0:-1] is needed to remove last close since diff is one element shorter  
        daily_returns = np.diff(close, axis = 0) / close[0:-1]  
        diff = 0 - daily_returns  
        #a slight offset from 0 is required to avoid problems with long strings of positive daily_returns  
        diff = np.clip(diff,a_min=1.00E-07,a_max=None)  
        out[:] = (np.nansum(diff**2,axis=0) / len(daily_returns))

def make_pipeline():  
    base_universe = StaticAssets(symbols('IHI','XLY','TLT'))  
    Close = USEquityPricing.close.latest.fillna(0)  
    Vola = Volatility(window_length=period)

    pipe = Pipeline(  
        columns={  
            'VolFactors' : Close / Vola,  
            'Closes' : Close,  
        },  
        screen=base_universe  
    )  
    return pipe  

The algorithm is performing well in initial testing.