Notebook
In [29]:
# Import Pipeline class and datasets
import numpy as np
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.pipeline.data import USEquityPricing as USEP
from quantopian.pipeline.data.psychsignal import stocktwits
from quantopian.pipeline.factors import SimpleMovingAverage, BollingerBands
import talib


# Import built-in trading universe
from quantopian.pipeline.experimental import QTradableStocksUS

# Import run_pipeline method
from quantopian.research import run_pipeline
from datetime import datetime, timedelta

DELTA_TIME = 1


class GetMacDHistSlope(CustomFactor):
    inputs = [USEP.close]
    window_length = 220
        
    def compute(self, today, assets, out, close):
        
        hists = []
        
        for stock_close in close.T:
            try:
                #Compute only end of week equity prices!!
                macd, signal, hist = talib.MACD(stock_close, fastperiod=12,
                                                slowperiod=26, signalperiod=9)
                               
                if (hist[-3] > hist[-2]) and (hist[-2] > hist[-1]):
                    trend = -1
                elif (hist[-3] < hist[-2]) and (hist[-2] < hist[-1]):
                    trend = 1
                else:
                    trend = 0
                hists.append(trend)
            except:
                hists.append(np.nan)
        
        out[:] = hists

    
def make_pipeline():
    # Create a reference to our trading universe
    base_universe = QTradableStocksUS()

    # Get latest closing price
   
    close_price = USEP.close.latest
    wk_trend = GetMacDHistSlope()
    
    # Make some filters
    long_trade = True
    short_trade = True
    screen = (long_trade | short_trade) & base_universe
    
    # Return Pipeline containing close_price and
    # macd weekly trend
 
    pipe = Pipeline(
        columns={
            'close_price': close_price,
            'trend': wk_trend,
        },
        #screen=screen,
    )
    return pipe

# Generate date interval for pipeline computation
delta_time = timedelta(DELTA_TIME) # get the n previous days
start_date = datetime.strftime(datetime.today(), "%Y-%m-%d")
end_date = datetime.strftime(datetime.today(), "%Y-%m-%d")


pipeline_output = run_pipeline(
    make_pipeline(),
    start_date=start_date,
    end_date=end_date,
)

# Limit display to 10 rows
pipeline_output.head(10)
[[  25.39910696    3.67734925  174.42696767 ...,           nan
            nan           nan]
 [  25.42885992    3.67734925  172.54853861 ...,           nan
            nan           nan]
 [  25.92474252    3.42887971  172.37058218 ...,           nan
            nan           nan]
 ..., 
 [  19.215         2.71        212.51       ...,           nan
            nan           nan]
 [  19.69          3.          213.33       ...,           nan
            nan           nan]
 [  20.34          2.8         218.85       ...,           nan
            nan           nan]]
Out[29]:
close_price trend
2018-11-01 00:00:00+00:00 Equity(2 [ARNC]) 20.34 1.0
Equity(21 [AAME]) 2.80 0.0
Equity(24 [AAPL]) 218.85 0.0
Equity(25 [ARNC_PR]) 85.55 0.0
Equity(41 [ARCB]) 37.12 1.0
Equity(52 [ABM]) 30.76 1.0
Equity(53 [ABMD]) 342.38 1.0
Equity(62 [ABT]) 68.93 1.0
Equity(64 [ABX]) 12.54 -1.0
Equity(66 [AB]) 28.94 1.0
In [18]:
import numpy as np
import talib
import random


prices = [random.uniform(5,10) for price in range(50)]
prices = np.array(prices,dtype='f8') + 1
macd, signal, hist = talib.MACD(prices, fastperiod=12, slowperiod=26, signalperiod=9) 
In [25]:
    

NameErrorTraceback (most recent call last)
<ipython-input-25-e43250c12910> in <module>()
      1 close =  USEP.close.latest
----> 2 filters = StaticSids([24])
      3 

NameError: name 'StaticSids' is not defined
In [ ]: