Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Using talib with USEquityPricing ? Is there any way?

Is there a way to use Talib with USQuitypricing? I am pretty new to Algo trading and Quantopian. Just learnt the basics of python but I am programmer for some time.

Please focus on this commented line LINE NUMBER 60-

fastk, fastd = talib.STOCHRSI(USEquityPricing.close, timeperiod=14, fastk_period=5, fastd_period=3, fastd_matype=0)

How can I make the Talib to work with USEquityPricing here specially while making pipeline?

Please be a little detailed if you can help?

4 responses

@Ray Trader,

How can I make the Talib to work with USEquityPricing here specially while making pipeline?

You can do this by creating a custom factor.
Something like this:

# Custom factor talib STOCH_RSI_FK  
from quantopian.pipeline import Pipeline, factors, filters, classifiers  
from quantopian.algorithm import attach_pipeline, pipeline_output  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.factors import CustomFactor  
import talib;  
# -------------------------------------------------------------------------------------------  
STK_SET = filters.StaticAssets(symbols('SPY', 'TLT')); PERIOD = 14; FK = 5; FD = 3; FDMA = 0;  
# -------------------------------------------------------------------------------------------  
class STOCH_RSI_FK(CustomFactor):  
    inputs = [USEquityPricing.close]  
    window_length = PERIOD + FK + FD + 1

    def compute(self, today, assets, out, close):  
        stoch_rsi_fk  = []  
        for C in close.T:  
            StochRsiFk = talib.STOCHRSI(C, PERIOD, FK, FD, FDMA)[0][-1]  
            stoch_rsi_fk.append(StochRsiFk) 

        out[:] = stoch_rsi_fk

def initialize(context):  
    fast_k = STOCH_RSI_FK(mask = STK_SET)  
    attach_pipeline(Pipeline({'fast_k': fast_k,}, screen = STK_SET), 'pipe')  

def before_trading_start(context, data):  
    output = pipeline_output('pipe')  
    fast_k = output.fast_k  
    record(fast_k = fast_k[0])  

If somebody can do it in a more elegant way please post it here.

This version uses pandas and applies the stochrsi as a lambda-expression. It seems to be a bit faster when traded with many symbols...

# Custom factor talib STOCH_RSI_FK  
from quantopian.pipeline import Pipeline, factors, filters, classifiers  
from quantopian.algorithm import attach_pipeline, pipeline_output  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.factors import CustomFactor  
import talib;  
import pandas as pd

# -------------------------------------------------------------------------------------------  
STK_SET = filters.StaticAssets(symbols('SPY', 'TLT')); PERIOD = 14; FK = 5; FD = 3; FDMA = 0;

# -------------------------------------------------------------------------------------------


class STOCH_RSI_FK(CustomFactor):  
    inputs = [USEquityPricing.close]  
    window_length = PERIOD + FK + FD + 1

    def compute(self, today, assets, out, C):  
        stoch_rsi_fk = pd.DataFrame(C).apply(lambda x: talib.STOCHRSI(x, PERIOD, FK, FD, FDMA)[0][-1], axis=0)  
        out[:] = stoch_rsi_fk


def initialize(context):  
    fast_k = STOCH_RSI_FK(mask=STK_SET)  
    attach_pipeline(Pipeline({'fast_k': fast_k, }, screen=STK_SET), 'pipe')


def before_trading_start(context, data):  
    output = pipeline_output('pipe')  
    fast_k = output.fast_k  
    record(fast_k=fast_k[0])  

P. S.:
Be aware that talib doesn't handle nans very well, so in order to avoid exceptions you need to get rid of them first. In my version I would do something like this:

class STOCH_RSI_FK(CustomFactor):  
    inputs = [USEquityPricing.close]  
    window_length = PERIOD + FK + FD + 1

    def compute(self, today, assets, out, C):  
        # Set all values for a symbol to zero if it has nans before passing them to talib:  
        C[np.isnan(C).any(),:] = 0

        stoch_rsi_fk = pd.DataFrame(C).apply(lambda x: talib.STOCHRSI(x, PERIOD, FK, FD, FDMA)[0][-1], axis=0)  
        out[:] = stoch_rsi_fk

In Vladimir's version you could do it that way:

class STOCH_RSI_FK(CustomFactor):  
    inputs = [USEquityPricing.close]  
    window_length = PERIOD + FK + FD + 1

    def compute(self, today, assets, out, close):  
        stoch_rsi_fk  = []  
        for C in close.T:  
            # If there are any nans, just append nan and don't pass them to talib  
            if np.isnan(C).any():  
                stoch_rsi_fk.append(np.nan)  
                continue  
            StochRsiFk = talib.STOCHRSI(C, PERIOD, FK, FD, FDMA)[0][-1]  
            stoch_rsi_fk.append(StochRsiFk)  
        out[:] = stoch_rsi_fk

And if you want both fastk and fastd as outputs of the same CustomFactor, you can that too

class STOCH_RSI(CustomFactor):  
    inputs = [USEquityPricing.close]  
    window_length = PERIOD + FK + FD + 1  
    # If you want 2 outputs, you need to add them here:  
    outputs = ['fastk', 'fastd']

    def compute(self, today, assets, out, C):  
        # Set all values for a symbol to zero if it has nans:  
        C[np.isnan(C).any(),:] = 0  
        df = pd.DataFrame(C)

        fastk = df.apply(lambda x: talib.STOCHRSI(x, PERIOD, FK, FD, FDMA)[0][-1], axis=0)  
        fastd = df.apply(lambda x: talib.STOCHRSI(x, PERIOD, FK, FD, FDMA)[1][-1], axis=0)

        out[:].fastk = fastk  
        out[:].fastd = fastd

fastk, slowk = STOCH_RSI()

Thank you all. I will take some time to go through this.