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

Hi Everybody,

I'm hoping someone can guide me i the right direction, I'm looking to set up my algo so the entry happens when the MACD crosses the signal line as opposed to the zero line. I see several examples that show: if MACD > 0, however this would be after my desired time. I'm very new to python, so I'm not sure how to set up the code so the MACD line and Signal line and independent and can be referenced as such. Thank you!

10 responses

talib.MACD has 3 outputs: macd, signal, hist
hist = macd-signal,
so hist zero crossover is actually the same as macd signal crossover.

if hist[-2]<0 and hist[-1]>0:  
    macd_ sinal_crossover= True  

Hey S. Chapel, I joined Quantopian about 6 months ago in order to try and do something very similar to what you are trying to do. Thankfully I had a background in C++ so learning Python wasn't that difficult, but here are a few things you should know since you're headed down the same path as me.
1. You'll need to expand your stock universe... Just picking AAPL or XOM and building a trading program that trades on the MACD histogram of the stock may not work very well at all, and here is the first reason why. You need to expand that range of stocks that your program searches through in order to have consistent orders. For example, for AAPL, there may only be a MACD crossover once every 2 months. So your program will more than likely not be doing much trading. To fix this, I would suggest looking into how to use the PIPELINE in Quantopian. It'll also help you screen stocks.
2. Quantopian's TALIB MACD is complete trash. If you're trying to get the program to day-trade... or week-trade... anything besides investing in a single stock for 2-3 months at a time, you'll find that the built in MACD method will not work for you AT ALL! As you may know, MACD has a few calibrations... a first, second and third EMA or WMA. TALIB does let you calibrate these, but it does not let you calibrate the data set frequency. Basically, if you sample data for the MACD once a day, it's only good for a buy/sell outlook of 1-3 months. If it samples every hour, you get a buy/sell outlook for 5-10 days and every 5 min gets you 1-4 hours. Unfortunately, TALIB doesn't allow you to do modify the data sampling. I was forced to build my own MACD function.
3. It will prolly only work 50% of the time. As you know, MACD is not always accurate. Sometimes, you need to check the MACD yourself because it falls when the price rises or vice versa. You'll need to build a function that compares the general MACD trend with the price trend or use another study/characteristic to iron out the misfits.

Hey James,

What do you suggest as an alternative to TALIB for technical indicators and chart patterns?

Thanks !

As far as TALIB goes, I've found that the larger the sample size, the more accurate the TA jives with chart software (thinkorswim by tdameritrade)... for example, the formula to calculate EMA references the EMA of the prior day... this would make calculating an EMA infinite, but it has to start somewhere, typically with an SMA... but if calculating a 20 day EMA, there is a big difference whether you start calculating 20 days ago with the SMA, versus say 250 days ago with the SMA... I've found that using 250 data points (days) with TALIB will give me an EMA = the EMA in thinkorswim... I've found the 250 to work the same for TALIBs MACD and RSI

@ Addison - Yes, that's absolutely right. Correct me if I'm wrong, but what you're saying is that TALIB seems to use about a 250 day look-back with it's data set. I believe that is true as well, but our issue lies with another aspect of TALIB. TALIB's results will align perfectly with the results of TDAmeritrade and ThinkorSwim, but only if the TDAmer charts that you're using are based on daily sample data. I believe when I first got TDAmer, it defaulted all charts to a length of 3Months and a daily tick frequency. If you simply print the results of any of TALIB's moving average functions, their results will match perfectly with any TDAmer chart studies on the daily frequency. I think this also agrees with your statement above, because TDAmer uses a 252 tick look-back on it's studies. However, my ThinkorSwim is set up with multiple different chart lengths and frequencies (2Day:5m,20Day:1h,3Mon:1Day,1Year:1Week). What I have found is that, by varying the tick frequency in ThinkorSwim, it sends a different data set into the moving average formula, usually changing a 9 day ema (with 252 day look-back) for example, into a 9 hour ema (with 252 hour look-back). If your trading strategy relies more on going long/short on a security for months at a time, you may never have run into any issues with TALIB. My trading strategy, however, is much more short term and the results of TDAmer/ThinkorSwim data from charts with hourly or 5 min tick frequencies are MUCH more helpful. So I guess, if your outlook is longterm, TALIB is fine, but if your outlook is short term... You're kinda backed into a corner.

@ Leigham - As of now, I haven't found any built-in methods in Quantopian that provide you the same moving average formulas as TALIB with more control over it's input data. I've resorted to programing my own functions into the Algo in order to clear up these issues. For the most part, you should be able to make your own functions fairly easily because most of them are pretty simple. Unfortunately I needed MACD which is one of the most complicated averages in TALIB. If you want to make your own, I'd suggest getting a data set of daily ticks and trying out the formula in Excel. Then, once you have a better idea of how the formula works, program it in Quantopian. Here's an instruction page on building the MACD formula in EXCEL : InvestExcel - MACD
If you want me to post my MACD function, just let me know.

@James,

Thank you for the input! My response was of ignorance, when it comes to different frequencies. I am used to thinkorswim using 'ticks' when calculating TA, which is exactly what you described above when you change the length and freq (or I think it is)... Since we are limited to using daily data history, it may be necessary to build an algo that 'records' data as it occurs and builds its own history... unfortunately, that means it may take a few days of running an algorithm before enough data is collected to generate necessary, and wouldn't work within Pipeline.

Also, I think its possible to get minute data history? (I'm on mobile right now, so my ability to research the answer is limited)
If so, perhaps we can use pandas resample method, as I learned about on this thread. See Nathan Wolf on August 5th, 2016
https://www.quantopian.com/posts/ma-crossover-on-weekly-price-data#57d1458123577e685300010e

You can actually build an numpy array of past prices in 1m or 1d frequency using the following code:

    historical_prices = data.history(stock, 'price', 252, '1d')

That ^ would build an array of prices dynamically so you wouldn't have let a historical prices list aggregate together over time. The resample method is a good idea! It would certainly make things easier.

Have you ever try to use this talib.MACDEXT - MACD with controllable MA type function?
It is working for me.

   stk = symbol('SPY')  
    fast=12  
    slow=26  
    sig=9  
    period = fast+slow+sig  
    prices = data.history(stk, 'price', period, '1d')  
    macd, signal, hist = talib.MACDEXT(prices, fastperiod=fast, fastmatype=0, slowperiod=slow, slowmatype=0, signalperiod=sig, signalmatype=0)  
    MACD = macd[-1]  
    SIGNAL = signal[-1]  
    HIST = hist[-1]  
    record(macd = MACD, signal = SIGNAL, hist = HIST)  
    # SMA = 0; EMA = 1; WMA = 2; DEMA = 3; TEMA = 4; TRIMA = 5; KAMA = 6; MAMA = 7; T3 = 8    


check here

Wow! Thanks Vladimir! This looks very useful! Do you know if Quantopian has any documentation on this method? I can't find it on their help page.

@ Vladimir Yevtushenko
Thanks for the formula

@James Kerfoot
Thanks for the excel link.

Btw I'm currently reading
1.python for dummies more than half way finished
2. Then I'm going to be reading automate the boring stuff.
3.Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython

What other books should I read. (I've been trading for 4 years, just I've never programmed so still learning and trying to get tips from everyone I can. Thanks !)