Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Can someone help me understand where I'm going wrong with pipeline?

Hey guys, new to pipeline and python, mind helping me out?

Here's my code and the error I get is saying that I have an invalid syntax on the "pipe =" line


from quantopian.pipeline import Pipeline  
from quantopian.algorithm import attach_pipeline, pipeline_output  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.filters.morningstar import Q1500US  
from quantopian.pipeline.factors import MovingAverageConvergenceDivergenceSignal  
from quantopian.pipeline.data import morningstar  
import talib  
import numpy as np  
import pandas as pd

def initialize(context):  
    # The algo will go long on the number of stocks set here  
    context.num_stocks_to_buy = 15  
    # Rebalance every day at market open  
    schedule_function(rebalance,  
                      date_rule=date_rules.every_day(),  
                      time_rule=time_rules.market_open())  



def before_trading_start(context):  
    """  
    Called before the start of each trading day.  
    """  



def create_weights(context, stocks):  
    """  
    Takes in a list of securities and calculates  
    the portfolio weighting percentage used for each stock in the portfolio  
    """  
    if len(stocks) == 0:  
        return 0  
    else:  
        # Buy only 0.95 of portfolio value to avoid borrowing  
        weight = .95/len(stocks)  
        return weight  
def handle_data(context, data):  
    """  
    Code logic to run during the trading day.  
    handle_data() gets called every price bar. In this algorithm,  
    rather than running through our trading logic every price bar, every day,  
    we use scheduled_function() in initialize() to execute trades 1x per day  
    """  
    prices = data.current(context.stocks, fields = "price", bar_count = 1, frequency = "1d"  
    pipe = Pipeline()  
    attach_pipeline(pipe, 'my_pipeline')  
    pipe.add(prices, 'Prices')  
    pipe.add(pe_ratio, "PE Ratio")  
    pipe.add(eps_growth, "EPS Growth")  
    eps_growth = morningstar.fundamentals.earnings_ratios.diluted_eps_growth.latest  
    pe_ratio = morningstar.fundamentals.valuation_ratios.pe_ratio.latest  
    net_margin = morningstar.fundamentals.operation_ratios.net_margin.latest  
    current_ratio = morningstar.fundamentals.operation_ratios.current_ratio.latest  
    rev_growth = morningstar.fundamentals.operation_ratios.revenue_growth.latest  
    pipe.set_screen(fundamentals.valuation.market_cap > 100000000)  
    pipe.set_screen(fundamentals.valuation_ratios.pe_ratio < 15)  
    pipe.set_screen(fundamentals.valuation_ratios.pe_ratio > 0)  
    pipe.set_screen(fundamentals.earnings_ratios.diluted_eps_growth > 20)  
    pipe.set_screen(fundamentals.operation_ratios.current_ratio > 1.5)  
    pipe.set_screen(fundamentals.operation_ratios.net_margin > 5)  
    pipe.set_screen(fundamentals.operation_ratios.revenue_growth > 20)  
    output = pipeline_output('my_pipeline')  
    context.my_universe = output.sort('EPS Growth', ascending=False).iloc[:300]  
    update_universe(context.my_universe.index)

def MACD(prices, fastperiod=12, slowperiod=26, signalperiod=9):  
    '''  
    Function to return the difference between the most recent  
    MACD value and MACD signal. Positive values are long  
    position entry signals 

    optional args:  
        fastperiod = 12  
        slowperiod = 26  
        signalperiod = 9

    Returns: macd - signal  
    '''  
    macd, signal, hist = talib.MACD(prices,  
                                    fastperiod=fastperiod,  
                                    slowperiod=slowperiod,  
                                    signalperiod=signalperiod)  
    return macd[-1] - signal[-1]  
def rebalance(context, data):  
    # Track cash to avoid leverage  
    cash = context.portfolio.cash  
    pricess = data.history(context.portfolio.positions, fields="price", bar_count=40, frequency="1d")  
    macd = pricess.apply(MACD, fastperiod=12, slowperiod=26, signalperiod=9)  
    # Exit all positions that have fallen out of the top rankings  
    for stock in context.portfolio.positions:  
        if stock not in context.my_universe.index or macd[stock] < 0:  
            if stock in data:  
                order_target(stock, 0)  
                cash += context.portfolio.positions[stock].amount  
                log.info("Exiting security: %s" % stock)  
    # Create weights for each stock  
    weight = create_weights(context, context.my_universe.index)

    # Rebalance all stocks to target weight of overall portfolio  
    for stock in context.my_universe.index:  
        if weight != 0 and stock in data and macd[stock] > 0:  
            notional = context.portfolio.portfolio_value * weight  
            price = data[stock].price  
            numshares = int(notional / price)  
            # Growth companies could be trading thin: avoid them  
            if cash > price * numshares and numshares < data[stock].volume * 0.2:  
                if stock in data:  
                    order_target_percent(stock, weight)  
                    cash -= notional - context.portfolio.positions[stock].amount  
                    log.info("Placing order: %s" % stock)  
1 response

The problem is on the line before.

prices = data.current(context.stocks, fields = "price", bar_count = 1, frequency = "1d"

You're missing a closing ')' on that line, and the error isn't very helpful unfortunately.

As soon as you fix that, it's going to complain that you haven't defined context.stocks, but I'll let you worry about that =)

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.