Back to Community
Any reason my data frame is coming back empty and orders aren't being placed???

Any help would be much appreciated, pretty new to python and quantopian

Clone Algorithm
6
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
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
from quantopian.pipeline.data import Fundamentals
import talib
import numpy as np
import pandas as pd

def initialize(context):
    global pipe
    pipe = Pipeline()
    attach_pipeline(pipe, 'my_pipeline')
    
    # 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 my_pipeline():
    
    global eps_growth
    global pe_ratio
    global net_margin
    global current_ratio
    global rev_growth


    
    eps_growth = fundamentals.earnings_ratios.diluted_eps_growth.latest
    pe_ratio = fundamentals.valuation_ratios.pe_ratio.latest
    net_margin = fundamentals.operation_ratios.net_margin.latest
    current_ratio = fundamentals.operation_ratios.current_ratio.latest
    rev_growth = fundamentals.operation_ratios.revenue_growth
    mkt_cap = fundamentals.valuation.market_cap

    pipe.add(pe_ratio, "pe_ratio")
    pipe.add(eps_growth, "eps_growth")
    
    pipe.set_screen(mkt_cap > 100000000 & pe_ratio < 15 & pe_ratio > 0 & eps_growth > 20 & current_ratio > 1.5 & net_margin > 5 & rev_growth > 20)
    
    
  
    
def before_trading_start(context, data): 
    """
    Called before the start of each trading day. 
    
    """
    global output
    
    securities = pipeline_output('my_pipeline')
    context.output = securities
    print context.output.head(5)
    
    
    

    
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
    """


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.output 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.output)

    # Rebalance all stocks to target weight of overall portfolio
    for stock in context.output:
        if weight != 0 and stock in data:
            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 and macd[stock] > 0:
                    order_target_percent(stock, weight)
                    cash -= notional - context.portfolio.positions[stock].amount
                    log.info("Placing order: %s" % stock)
                
There was a runtime error.
5 responses

Hi Mathew,

I took a look at your algo and corrected a few issues. I attached a modified version of your algo which addresses the following issues:

  1. The pipeline being attached to the algo was just an empty pipeline, it wasn't the one defined in my_pipeline (line 15). The new version attaches the output of my_pipeline to the algo.
  2. Lines 39-44 are using the wrong namespace for fundamental data. The notation should look something like Fundamentals.market_cap.latest if you want to use the latest market cap. I fixed the calls in the attached algo.
  3. The use of global variables in not necessary, and actually discouraged. I removed these.
  4. There were also some deprecated functions being used, so I changed those to newer versions.

The algo still isn't ordering anything, but it's at least getting a non-empty pipeline. My suggestion as a next step would be to try debugging by printing out the state of different variables before orders are placed to make sure everything is behaving as you expect it to. I'd also recommend going through the tutorials to get a better understanding of the current API.

I hope this helps.

Clone Algorithm
1
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
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
from quantopian.pipeline.data import Fundamentals
import talib
import numpy as np
import pandas as pd

def initialize(context):
    
    # Our pipeline is defined in my_pipeline()
    pipe = my_pipeline()
    attach_pipeline(pipe, 'my_pipeline')
    
    # 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 my_pipeline():
    
    eps_growth = Fundamentals.diluted_eps_growth.latest
    pe_ratio = Fundamentals.pe_ratio.latest
    net_margin = Fundamentals.net_margin.latest
    current_ratio = Fundamentals.current_ratio.latest
    rev_growth = Fundamentals.revenue_growth.latest
    mkt_cap = Fundamentals.market_cap.latest
    
    my_screen = (
        (mkt_cap > 100000000)
        & (pe_ratio < 15)
        & (pe_ratio > 0)
        & (eps_growth > 20)
        & (current_ratio > 1.5)
        & (net_margin > 5)
        & (rev_growth > 20)
    )

    pipe = Pipeline(
        columns={
            'pe_ratio': pe_ratio,
            'eps_growth': eps_growth,
        },
        screen=my_screen
    )
    
    return pipe
    
  
    
def before_trading_start(context, data): 
    """
    Called before the start of each trading day. 
    
    """
    
    securities = pipeline_output('my_pipeline')
    context.output = securities.index.tolist()    

    
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 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.output or macd[stock] < 0:
            if data.can_trade(stock):
                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.output)

    # Rebalance all stocks to target weight of overall portfolio
    for stock in context.output:
        if weight != 0 and data.can_trade(stock):
            notional = context.portfolio.portfolio_value * weight
            price = data.current(stock, 'price')
            numshares = int(notional / price)
            
            # Growth companies could be trading thin: avoid them
            if cash > price * numshares and numshares < data.current(stock, 'volume') * 0.2:
                if data.can_trade(stock) and macd[stock] > 0:
                    order_target_percent(stock, weight)
                    cash -= notional - context.portfolio.positions[stock].amount
                    log.info("Placing order: %s" % stock)
                
There was a runtime error.
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.

Hey there Jamie! Thank you very much for your help! After seeing how you fixed my algorithm, I was able to tweak the pipeline into returning a data frame. However, now I've encountered a new problem: None of my orders are going through. I will attach the back test and some code that I think is influencing this error, but I can't seem to figure out why my python code is not executing my purchases. Any help would be much appreciated.

Creates my weights for the stocks:

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  

Next Code has to do with MACD:

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]  

Next code defines my rebalance:

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)  

and finally, here is the purchase code I have:

    # Create weights for each stock  
    weight = create_weights(context, context.output)

    # Rebalance all stocks to target weight of overall portfolio  
for stock in context.output:  
        if weight != 0 and data.can_trade(stock):  
            notional = context.portfolio.portfolio_value * weight  
            price = data.current(stock, 'price')  
            numshares = int(notional / price)  
            # Growth companies could be trading thin: avoid them  
            if cash > price * numshares and numshares < data.current(stock, 'volume') * 0.2:  
                if data.can_trade(stock) and macd[stock] > 0:  
                    order_target_percent(stock, weight)  
                    cash -= notional - context.portfolio.positions[stock].amount  
                    log.info("Placing order: %s" % stock)  
Clone Algorithm
2
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
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
from quantopian.pipeline.data import Fundamentals
import talib
import numpy as np
import pandas as pd

def initialize(context):
    
    # Our pipeline is defined in my_pipeline()
    pipe = my_pipeline()
    attach_pipeline(pipe, 'my_pipeline')
    
    # 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 my_pipeline():
    
    eps_growth = Fundamentals.diluted_eps_growth.latest
    pe_ratio = Fundamentals.pe_ratio.latest
    net_margin = Fundamentals.net_margin.latest
    current_ratio = Fundamentals.current_ratio.latest
    rev_growth = Fundamentals.revenue_growth.latest
    mkt_cap = Fundamentals.market_cap.latest
    
    my_screen = (
        (mkt_cap > 100000000)
        & (pe_ratio < 20)
        & (pe_ratio > 0)
        & (eps_growth > 10)
        & (current_ratio > 1.5)
        & (net_margin > 0.04)
        & (rev_growth > 0.04)
    )

    pipe = Pipeline(
        columns={
            'pe_ratio': pe_ratio,
            'eps_growth': eps_growth,
            'net_margin': net_margin
        },
        screen=my_screen
    )
    
    return pipe
    
  
    
def before_trading_start(context, data): 
    """
    Called before the start of each trading day. 
    
    """
    
    securities = pipeline_output('my_pipeline')
    context.output = securities.index.tolist()
    print securities.head(5)
    
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 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.output or macd[stock] < 0:
            if data.can_trade(stock):
                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.output)

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

Hi Matthew,

The last algo you shared is running into an issue because you are indexing macd with securities from context.output (line 129), but macd is only calculated/ only contains securities that were already in your portfolio (lines 106, 107).

To fix this, you could create a set that contains securities in your portfolio and securities from context.output, and use it to calculate macd.

I hope this helps.

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.

Hey Ernesto, that actually did help and it made complete sense. When creating a new set for securities in context.ouput, I ran into a new error:

"Exception: inputs are all NaN There was a runtime error on line 109."

Any Idea why this is showing up??

Thank you for your help by the way, this has been a great learning experience

Clone Algorithm
2
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
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
from quantopian.pipeline.data import Fundamentals
import talib
import numpy as np
import pandas as pd

def initialize(context):
    
    # Our pipeline is defined in my_pipeline()
    pipe = my_pipeline()
    attach_pipeline(pipe, 'my_pipeline')
    
    # 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 my_pipeline():
    
    eps_growth = Fundamentals.diluted_eps_growth.latest
    pe_ratio = Fundamentals.pe_ratio.latest
    net_margin = Fundamentals.net_margin.latest
    current_ratio = Fundamentals.current_ratio.latest
    rev_growth = Fundamentals.revenue_growth.latest
    mkt_cap = Fundamentals.market_cap.latest
    
    my_screen = (
        (mkt_cap > 50000000)
        & (pe_ratio < 25)
        & (pe_ratio > 0)
        & (eps_growth > 3)
        & (current_ratio > 1.5)
        & (net_margin > 0.02)
        & (rev_growth > 0.02)
    )

    pipe = Pipeline(
        columns={
            'pe_ratio': pe_ratio,
            'eps_growth': eps_growth,
            'net_margin': net_margin
        },
        screen=my_screen
    )
    
    return pipe
    
  
    
def before_trading_start(context, data): 
    """
    Called before the start of each trading day. 
    
    """
    
    securities = pipeline_output('my_pipeline')
    context.output = securities.index.tolist()
    print securities
    
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 MACD(prices, fastperiod=8, slowperiod=19, signalperiod=5):  
    '''  
    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")
    pricesss = data.history(context.output, fields="price", bar_count=40, frequency="1d")
    macd1 = pricess.apply(MACD, fastperiod=8, slowperiod=19, signalperiod=5) 
    macd2 = pricesss.apply(MACD, fastperiod=8, slowperiod=19, signalperiod=5)
    # Exit all positions that have fallen out of the top rankings
    for stock in context.portfolio.positions:
        if stock not in context.output or macd1[stock] < 0:
            if data.can_trade(stock):
                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.output)

    # Rebalance all stocks to target weight of overall portfolio
    for stock in context.output:
        if weight != 0 and data.can_trade(stock):
            notional = context.portfolio.portfolio_value * weight
            price = data.current(stock, 'price')
            numshares = int(notional / price)
            
            # Growth companies could be trading thin: avoid them
            if cash > price * numshares and numshares < data.current(stock, 'volume') * 0.2:
                if data.can_trade(stock) and macd2[stock] > 0:
                    order_target_percent(stock, weight)
                    cash -= notional - context.portfolio.positions[stock].amount
                    log.info("Placing order: %s" % stock)
                
There was a runtime error.

Hi Mathew,

Talib's functions raise that error when you pass a vector consisting entirely of NaN values as input.

The underlying issue is that HNNA has a start date of Sep, 2005, but pricing data is not available until May, 2014 (when it was listed on NASDAQ). So this asset makes it through your pipeline filters into your tradable universe before there is any pricing data for it, and data.history returns a vector of NaNs for this asset. I have made a reported of this particular issue, and I'll share it with our data team for review.

In the meantime, you can easily avoid this type of issues by adding a price filter to your pipeline screen. See the backtest attached for an example in line 46.

I hope this helps.

Clone Algorithm
1
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
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
from quantopian.pipeline.data import Fundamentals
import talib
import numpy as np
import pandas as pd

def initialize(context):
    
    # Our pipeline is defined in my_pipeline()
    pipe = my_pipeline()
    attach_pipeline(pipe, 'my_pipeline')
    
    # 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 my_pipeline():
    
    eps_growth = Fundamentals.diluted_eps_growth.latest
    pe_ratio = Fundamentals.pe_ratio.latest
    net_margin = Fundamentals.net_margin.latest
    current_ratio = Fundamentals.current_ratio.latest
    rev_growth = Fundamentals.revenue_growth.latest
    mkt_cap = Fundamentals.market_cap.latest
    
    my_screen = (
        (mkt_cap > 50000000)
        & (pe_ratio < 25)
        & (pe_ratio > 0)
        & (eps_growth > 3)
        & (current_ratio > 1.5)
        & (net_margin > 0.02)
        & (rev_growth > 0.02)
        & (USEquityPricing.close.latest > 5)
    )

    pipe = Pipeline(
        columns={
            'pe_ratio': pe_ratio,
            'eps_growth': eps_growth,
            'net_margin': net_margin
        },
        screen=my_screen
    )
    
    return pipe
    
  
    
def before_trading_start(context, data): 
    """
    Called before the start of each trading day. 
    
    """
    
    securities = pipeline_output('my_pipeline')
    context.output = securities.index.tolist()
    print securities
    
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 MACD(prices, fastperiod=8, slowperiod=19, signalperiod=5):  
    '''  
    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.keys(), fields="price", bar_count=40, frequency="1d")
    pricesss = data.history(context.output, fields="price", bar_count=40, frequency="1d")
    macd1 = pricess.apply(MACD, fastperiod=8, slowperiod=19, signalperiod=5) 
    macd2 = pricesss.apply(MACD, fastperiod=8, slowperiod=19, signalperiod=5)
    # Exit all positions that have fallen out of the top rankings
    for stock in context.portfolio.positions:
        if stock not in context.output or macd1[stock] < 0:
            if data.can_trade(stock):
                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.output)

    # Rebalance all stocks to target weight of overall portfolio
    for stock in context.output:
        if weight != 0 and data.can_trade(stock):
            notional = context.portfolio.portfolio_value * weight
            price = data.current(stock, 'price')
            numshares = int(notional / price)
            
            # Growth companies could be trading thin: avoid them
            if cash > price * numshares and numshares < data.current(stock, 'volume') * 0.2:
                if data.can_trade(stock) and macd2[stock] > 0:
                    order_target_percent(stock, weight)
                    cash -= notional - context.portfolio.positions[stock].amount
                    log.info("Placing order: %s" % stock)
                
There was a runtime error.