Back to Community
Can't figure out why my Pipeline-Algo isn't working

Hello Everyone,
I built an algorithm to find only stocks hitting new 52-Week Highs using the pipeline and then the built in TALIB to get MACD information on each stock and trade them accordingly. For some reason, it's not trading, but I'm getting data out of the pipeline perfectly and the MACD part of the program works perfectly well with other pipelines that I've created. I can't figure out why it's now working, but I think it has to do with my rebalance() function not interpreting the pipeline data correctly. Any help would be greatly appreciated!
Thank You All!

Clone Algorithm
15
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
from quantopian.pipeline import Pipeline, CustomFactor
from quantopian.algorithm import attach_pipeline, pipeline_output
from quantopian.pipeline.data.builtin import USEquityPricing
from quantopian.pipeline.factors import SimpleMovingAverage, AverageDollarVolume, Latest
import talib
import numpy as np

class MaxHigh(CustomFactor):  
    inputs = [USEquityPricing.high]
    window_length = 252

    def compute(self, today, assets, out, high):
        out[:] = np.nanmax(high, axis=0)
        
def initialize(context):
    context.LOW_RSI =50
    
    pennyStocksMask = (USEquityPricing.close.latest) > 1.0
    overPricedMask = (USEquityPricing.close.latest) < 20.0

    longHigh = MaxHigh(mask = pennyStocksMask and overPricedMask) 
    shortHigh = MaxHigh(window_length = 5, mask = pennyStocksMask and overPricedMask)

    volume = Latest(inputs=[USEquityPricing.volume])
    price = Latest(inputs=[USEquityPricing.close],window_length=1)
    pipe_screen = ((price > 1.0) & (price < 20.0))

    pipe_columns = {'volume':volume, 'price':price, 'longHigh':longHigh, 'shortHigh':shortHigh}

    pipe = Pipeline(columns=pipe_columns,screen=pipe_screen)
    attach_pipeline(pipe, 'example')


def before_trading_start(context, data):
    output = pipeline_output('example')

    
    newHighs = output[output.shortHigh >= output.longHigh]
    context.my_securities = newHighs.sort('volume', ascending=False).iloc[:50]
    print len(context.my_securities)

    context.security_list = context.my_securities.index
    
    log.info("\n" + str(context.my_securities.head(5)))
    
    
def rebalance(context, data):
    
    # Load historical data for the stocks
    prices = data.history(context.security_list.index, 'price', 40, '1d')
    
    macds = {}
    rsis = {}
    macdRaws = {}
    
    
    # Iterate over the list of stocks
    for stock in context.security_list.index:
        macd_raw, signal, hist = talib.MACD(prices[stock], fastperiod=12, slowperiod=26, signalperiod=9)
        macdHist = macd_raw[-1] - signal[-1]
        macdRaw = macd_raw[-1]
        macdRaws[stock] = macdRaw
        macds[stock] = macdHist
        rsi = talib.RSI(prices[stock], timeperiod=14)[-1]
        rsis[stock] = rsi
        current_position = context.portfolio.positions[stock].amount
        
        if macdHist < 0 and current_position > 0 and data.can_trade(stock):
            order_target(stock, 0)
            
        elif macdHist > 0 and macdRaw < 0 and current_position == 0 and data.can_trade(stock):
            order_target_percent(stock, 1)
There was a runtime error.
2 responses

You need to schedule the rebalance() function. Add something like schedule_function(rebalance, date_rules.week_start(),time_rules.market_open()) somewhere in the initialize(). In rebalance() remove .index i.e. context.security_list.index -> context.security_list

Thank You VERY MUCH! That worked perfectly, but I decided to go with a executing my orders under a handle_data() function instead of in the rebalance() function because I wanted to check the MACD data every trade minute. But again, thank you very much!