Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help with the MACD sample code

I am a recent college grad working in the financial/investment industry (so im familiar with the terminology), a novice to Quantipian.com, and I have a little experience in coding/using python. I was hoping I could ask the community to help me with the example algo for MACD to achieve what it is im looking for.

I'm having some issues reading trough the sample code. from what I gather its set to buy when the MACD "Signal" is > 0 and it sells when the MACD "Signal" is < 0. Its not quite clear what the "signal" is or how that number is calculated.

From my experience MACD is a graph that is made up of two lines, one black and one red. The red line represents the 9-day exponential moving average and the black line represents the differece between the 26-day and 12-day exponential moving average, I notice the sample algo mentions this info, but im still not sure what they are using as the "signal" when they compare it to 0 to trigger an order.

I am trying to build an algo that tracks the relationship between the black line and the red line (leaving out any relevance to values crossing over/under 0 like the sample algo focuses on).

I am specifically trying to figure this algo to the s&p 500, when the black line crosses over the red line I want that to trigger a buy signal and when it crosses under the red line I want that to trigger a sell signal.

Can anyone out there give me some guidance/explain what it is the sample algo is calculating?

Thanks guys, any help is appreciated.

4 responses

Ethan, what code are you referring to? It's always great when you run a backtest and "share" the backtest. Without that context, it's impossible to give good advice. Thanks.

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.

I was referencing the basic example that is in the help section of quantopian. I'll add the code to this post, I used the "code sample" input so idk why its not pretty looking like the other posts I have seen :/

# This example algorithm uses the Moving Average Crossover Divergence (MACD) indicator as a buy/sell signal.

# When the MACD signal less than 0, the stock price is trending down and it's time to sell.  
# When the MACD signal greater than 0, the stock price is trending up it's time to buy.

# Because this algorithm uses the history function, it will only run in minute mode.  
# We will constrain the trading to once per day at market open in this example.

import talib  
import numpy as np  
import pandas as pd

# Setup our variables  
def initialize(context):  
    context.stocks = symbols('MMM', 'SPY', 'GOOG_L', 'PG', 'DIA')  
    context.pct_per_stock = 1.0 / len(context.stocks)  
    # Create a variable to track the date change  
    context.date = None

def handle_data(context, data):  
    todays_date = get_datetime().date()  
    # Do nothing unless the date has changed and its a new day.  
    if todays_date == context.date:  
        return  
    # Set the new date  
    context.date = todays_date  
    # Load historical data for the stocks  
    prices = history(40, '1d', 'price')  
    # Create the MACD signal and pass in the three parameters: fast period, slow period, and the signal.  
    # This is a series that is indexed by sids.  
    macd = prices.apply(MACD, fastperiod=12, slowperiod=26, signalperiod=9)  
    # Iterate over the list of stocks  
    for stock in context.stocks:  
        current_position = context.portfolio.positions[stock].amount  
        # Close position for the stock when the MACD signal is negative and we own shares.  
        if macd[stock] < 0 and current_position > 0:  
            order_target(stock, 0)  
        # Enter the position for the stock when the MACD signal is positive and  
        # our portfolio shares are 0.  
        elif macd[stock] > 0 and current_position == 0:  
            order_target_percent(stock, context.pct_per_stock)  

    record(goog=macd[symbol('GOOG_L')],  
           spy=macd[symbol('SPY')],  
           mmm=macd[symbol('MMM')])  


# Define the MACD function  
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]  

I was confused by the MACD sample code too, but I realized that the "MACD" function is actually returning the difference between the two lines you mentioned. This is often visually displayed as the "MACD Histogram", which is what this example function should have been named.

If all you want to know is which line is on top, you can use the example function and test if the value is above zero or below zero. If you want direct access to the MACD and Signal values, you will have to adjust this function, or you can not use a function and simply use the "talib" command that exists inside the example function.

For more information on MACD and how it can be used, check this out:
http://stockcharts.com/school/doku.php?id=chart_school:technical_indicators:moving_average_convergence_divergence_macd