The Truth About MACD Trading | Algorithmic Strategy Backtest In Python

Discover the Truth About MACD Trading as we dive deep into an Algorithmic Strategy Backtest in Python. Ever stumbled upon trading strategies promising high win rates? We put one of the most talked-about strategies, the MACD trading strategy, under the microscope to verify its claims of an 80% win rate. This video is your ultimate guide to understanding, applying, and backtesting the MACD trading strategy using Python.
🔍 What You Will Learn:
The basics of MACD Trading and how it can revolutionize your trading approach... or not!
Step-by-step guide to implementing an Algorithmic Trading Strategy in Python.
Backtesting the MACD strategy on historical data to uncover the truth about its efficiency.
Applying a 200 exponential moving average to detect trading trends.
How to interpret MACD signals for long and short entry signals.
Optimizing trading strategies with forward testing on unseen data.
📈 Why MACD Trading?
The MACD, or Moving Average Convergence Divergence, is a potent tool in the arsenal of traders seeking to identify trend direction and reversals. By focusing on the MACD line's cross over the signal line, traders can discern potential buy or sell opportunities, making it a cornerstone of algorithmic trading strategies.
🐍 Python and Trading:
Leverage the power of Python to automate and backtest your trading strategies. In this video, we provide a downloadable Python script to help you experiment with the MACD trading strategy on your own. Whether you're a seasoned trader or new to the world of algorithmic trading, our step-by-step tutorial ensures you can follow along and apply these strategies to your trading toolkit.
🕒 Choosing the Right Timeframe:
We explore the impact of different timeframes on the MACD strategy's performance, with a focus on the 15-minute timeframe. Learn how adjusting the timeframe can affect your trading outcomes and how to find the sweet spot for your trading style.
🔄 Forward Testing for Optimization:
Discover how forward testing can enhance your strategy's reliability. By optimizing parameters on a slice of data and testing on future, unseen data, you can refine your strategy to better predict market movements.
Subscribe for more insights into trading strategies and how to leverage Python for financial analysis. Join us as we uncover the Truth About MACD Trading and push the boundaries of what's possible with Algorithmic Strategy Backtest in Python.
°°° Discount Vouchers for my Algorithmic Trading and Python courses:
💲 Algorithmic Trading: bit.ly/CouponAlgorithmicTrading
💲 Data Analysis with Numpy and Pandas: bit.ly/CouponDataAnalysis
💲 Machine Learning Methods In Algorithmic Trading: bit.ly/CouponMachineLearningT...
The code download link:
drive.google.com/file/d/1q9qS...
And the Data file:
drive.google.com/file/d/1AsOq...

Пікірлер: 108

  • @jroche1832
    @jroche18323 ай бұрын

    Great video as always. Appreciate your work. You obviously like to trade currency pairs. Is it possible to get your tests against say SPY or QQQ for those who haven't leveled up to Currency Trading?

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    Thank you for your support, definitely yes SP and other stocks have the advantage of centralized volume values, so we can leverage this as well, I will figure out something for stocks trading...

  • @991.
    @991.3 ай бұрын

    Can you create this strategy Purchase Conditions: Buy : Price Above the ema 200. Exiting the Bollinger lower band with a close, then returning inside the Bollinger with another close. It's not a requirement for it to be a single candle, meaning the price can break below the Bollinger lower band with more than one candle, but once the price enters the range and the candle closes, it's a signal to enter. Sell : (Opposite of Purchase): Price: Below the ema200. Exiting the Bollinger upper band with a close, then returning inside the Bollinger with another close. It's not a requirement for it to be a single candle, meaning the price can break above the Bollinger upper band with more than one candle, but once the price enters the range and the candle closes, it's a sell signal.

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    Hi, it's very close to the strategy we tested live and backtested in the previous videos lately, I am not sure it will give better results though. did you check these vids recently?

  • @noimnotnice
    @noimnotniceАй бұрын

    I have had similar experiences while examining a strategy built on only MACD. However... this indicator's performance is drastically dependent on the timeframe as well as window sizes for the MACD components. This means, that once the timeframe is chosen, one first has to optimize for the MACD parameters. It doesn't work out of the box. This is not surprising because this indicator set contains smoothing (moving averages) as well as semi-derivatives (differences of moving averages), which are windowed and thus behave differently between changing timescales. My general experience is that any trend indicator such as MACD needs to be paired with (at least) an entry confirmation signal to work properly.

  • @CodeTradingCafe

    @CodeTradingCafe

    Ай бұрын

    I agree, I also think it has to follow the trader's discretion.

  • @juanbernal8105
    @juanbernal81053 ай бұрын

    Excellent work. It's a common, basic strategy, and it works well in trend. You can consider the ADX above a minimum level and also eliminate certain market hours. Only open orders in European and/or American trading hours depending on the asset.

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    Hi, thank you for the tips, I will check it out again at some point within NY session and add ADX...

  • @doge2themoon373

    @doge2themoon373

    2 ай бұрын

    I always hear about this adx and wonder if it is true or not. I've run into an issue when my trading strategy failed due to market range/chop.

  • @juanbernal8105

    @juanbernal8105

    2 ай бұрын

    @@doge2themoon373 All the information is in the price movement, and cannot be predicted. Indicators help us to see what the price has done, and we assume that it will continue to do so, this is very often the case in trends, the momentum of the price, and the price movement. A very detailed description of the use and interpretation of the indicators can be found in investopedia.

  • @piphunter
    @piphunter3 ай бұрын

    Thank you for creating this video. As a discretionary trader wanting to move towards systematic models and wanting to learn python. What are a few books / online resources would you recommend?

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    For Python, it's all available for free online here on youtube you have plenty of courses, as introductory, at some point when you feel confident and information starts to be repetitive to you, you can move on to paid courses on Udemy, probably choosing one course advanced enough. But what I am trying to say, you're good for around 3 months of learning python for free here on YT.

  • @hyperionyt
    @hyperionytАй бұрын

    Thanks for this info! Where do you get your candlestick data that you use in these videos?

  • @CodeTradingCafe

    @CodeTradingCafe

    Ай бұрын

    Hi, thank you for your support, I get the data from yfinance, my broker and dukascopy

  • @ethan9936
    @ethan99362 ай бұрын

    Hey there, just out of curiosity, how come you use Jupiter Notebook? Why not a normal python file? Loved the video, Ethan

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Hey Ethan, thank you for your support. In my day job and research I use Python, but for presentations it's a bit easier with Jupyter notebook, also with notebooks you don't have to rerun the whole code every time so sometimes it's faster.

  • @TheEcherriman
    @TheEcherriman3 ай бұрын

    Thank you !

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    Thank you for your support!

  • @TheEcherriman

    @TheEcherriman

    3 ай бұрын

    Thank you@@CodeTradingCafe . I won't forget you once when I'm a successful trader. (Don't hold your breath !!!).

  • @Random.Videos.007
    @Random.Videos.0072 ай бұрын

    Another great video Zaid

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Thank you so much for your support.

  • @alfredquarx9147
    @alfredquarx91472 ай бұрын

    Maybe a stupid question, but: how you manage in vs Code, that you can run the Code Celle separately below your Code line? You typing in interactive window?

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Hi, if you create a new file with the extension .ipynb so it's a notebook file, then you can run each cell on its own, try it out and let me know.

  • @alfredquarx9147

    @alfredquarx9147

    2 ай бұрын

    @@CodeTradingCafe 🙏🏻 thx

  • @samfan179
    @samfan1793 ай бұрын

    is it possible to apply testing with python on order flow data in futures markets?

  • @skullinor6058

    @skullinor6058

    3 ай бұрын

    yes, you just need to format the order flow data into an readable datatype. You could use lists as an example

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    Thank you :)

  • @newenglandfamilyoutdoors9252
    @newenglandfamilyoutdoors92522 ай бұрын

    Thanks for this video, I appreciate the work. I believe I know of the video you are reacting to, but without a link in the description or specific reference I am assuming that point. In that video one part of the strategy is a bounce off of a support/resistance, price/over under 200 EMA to a verified trend, MACD crosses (above/below zero as indicated by trend) for entry. I didn't notice the support/resistance in the code and that would have some impact. Your point is taken that this is testing the indicator not the full strategy, but trade management is a major component to the strategy. I use this strategy and hit closer to 60-70 percent accuracy but my losses are capped very tight and my wins exponentially over losses trading futures on the 1min but using a 5min for supplement trend evaluations and support/resistance levels. While I value the testing and information, the conclusion of not really being able to use the indicator for profit is not entirely accurate as your testing also indicated 40-60% accuracy which is profitable with a 2:1 p/l I traded 3 of these today by the book so if you are getting zero hits on 18k periods, something is wrong. This was an interesting video with valuable information, thank you.

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Hey, thanks a lot for your input, true there is part that was skipped, I was testing the indicator mainly. But it's good to know your trading experience with this system, now I would reconsider implementing the whole strategy all together and backtesting again, I didn't expect much of a difference, but looks like you have a different point of you, good to know, thanks again.

  • @newenglandfamilyoutdoors9252

    @newenglandfamilyoutdoors9252

    2 ай бұрын

    Thanks for the reply. One thing I am curious of is if time of day has impact on accuracy of the indicator (I expect there is correlation). Also, I was a bit unclear on the time period you ultimately tested, but I would not use this technique on anything longer than the 1min. At 15 minutes the price action would already have resolved in what I have experienced.

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    You have a point regarding the timeframe, I have to try it again on 1 or 5 min, but at these frames the spread is high compared to price movement, it kind of becomes a scalping strategy.

  • @talhakaracallik1352
    @talhakaracallik13523 ай бұрын

    Hi, Thank you for sharing. Can you to create strategy which includes psar, stoch and rsi. I think psar indicator works pretty well for scalping strategy. Maybe you can combine with psar and macd.

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    Hi yes it's possible, if you have a specific strategy in mind or a reference just let me know.

  • @talhakaracallik1352

    @talhakaracallik1352

    3 ай бұрын

    @@CodeTradingCafe I'm sharing strategy that ı used. You should use 30 min candle, 1. Candles are above the 200 ema 2. Macd line is above trigger line 3. When it comes to psar point from top to bottom we enter position. Take profit 1.6 atr(14) Sl 1.4 atr This strategy works high winrate.

  • @talhakaracallik1352

    @talhakaracallik1352

    3 ай бұрын

    This strategy not useful for lower time frame than 30min. If you like this strategy maybe we create strategy that works in lower time with add to new indicator like obv, rsi.

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Hi Thank you for the details, I can test it (not immediately though I have made other promises:) ). But I agree with you low timeframes are very challenging, I usually trade above 4H much simpler.

  • @luisc777
    @luisc777Ай бұрын

    Not sure if is just me, but when trying to replicate the results, the function for MACD outputs [macd, hist, signal] while you're code is set up assuming different outputs, [macd, signal, hist].

  • @CodeTradingCafe

    @CodeTradingCafe

    Ай бұрын

    it depends on the library version you have, or also I might be mistaken and have an error myself. Let me know if it's not solved I can recheck my code.

  • @mhbracewell

    @mhbracewell

    Ай бұрын

    I am seeing the same issue where the signal and histogram are reversed. Add a validation column using # Calculate the 9-period EMA of MACD (Signal Line) data['Validate_Signal_Line'] = data['MACD'].ewm(span=9, adjust=False).mean()

  • @angelomarano8458
    @angelomarano84583 ай бұрын

    sorry for my question, from where do you get all the data?

  • @wesselbeer8041

    @wesselbeer8041

    3 ай бұрын

    Yfinance library

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    Hi, Yfinance and Dukascopy.

  • @jonathansands115
    @jonathansands1152 ай бұрын

    have you considered using a random Forrest ML algorithm that determines the probability of a stock or crypto having positive returns in the next period? and then you long the assets with the highest probability of having positive returns over the next period and short the assets with the highest probability of underperforming or having negative returns for the next period

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Hi, short answer yes, but any ML model depends on the input, we need to input indicators that are really correlated with the future, and since these are usually one or 2 then ML will only add noise here, it's better to use such indicators the classic way like we are doing in the videos. (By indicators I mean advanced custom built not the classic ones these for sure will not work with ML. I have couple of videos (old videos) showing this.

  • @jonathansands115

    @jonathansands115

    2 ай бұрын

    @@CodeTradingCafe thank you for this answer, helped a lot. will look for those videos. but do you think you could expand further on which indicators might be useful for a random forest if the time frame is monthly. as in the model is only trying o determine at what percentage the relevant asset is likely to have a positive next month or negative next month.

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Actually this is a great idea, I never tried the monthly timeframe yet, maybe it's a good way to start. In general, out of experience, slow timeframes are easier to deal with (daily, weekly... maybe also 4H).

  • @dilansadeep
    @dilansadeep3 ай бұрын

    I need a help I want to find out what is the maximum amount of parallel trades class rsibuy(Strategy): def init(self): pass def next(self): signal= self.data.RSI_Cross[-1] atr= self.data.ATR[-1] price=self.data.Close[-1] size=round(10/price) if signal: self.buy(size=size,tp=price+(atr_mlt* atr))

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    create a counter of number of current opened trades that executes at the beginning of "next" method and score the maximum there. Something like mymax= max(mymax, len(_trades))

  • @Divine.777
    @Divine.7772 ай бұрын

    Do you think it’s possible to incorporate level 2 into the algorithm to give signals?

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Definitely yes, and for stocks it would be a great approach but Level 2 APIs are paid I need to find a not very costly provider to play around for a while.

  • @Divine.777

    @Divine.777

    2 ай бұрын

    @@CodeTradingCafe I see. Thanks. I think that would be an interesting video if you are able to do it.

  • @Divine.777

    @Divine.777

    2 ай бұрын

    @@CodeTradingCafe maybe you could scrape the data with a python bot instead of using an api?

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    I will see if there is a democratic way of doing it without too many memberships or expensive memberships so everyone can do the same.

  • @eduardomoura9586
    @eduardomoura95862 ай бұрын

    Where did you gather this data? I'm currently at university and would like to study this area further with my colleague. I'm from Brazil, tks!

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Hi, data is available from yfinance and dukascopy, both provide data samples for analysis.

  • @boamahmarcus4002
    @boamahmarcus40023 күн бұрын

    Hi can we test beat the market maker by Steve maro

  • @CodeTradingCafe

    @CodeTradingCafe

    3 күн бұрын

    I will check it out and see if anything interesting come up, I will come back with a video only if the results are showable.

  • @egnatjovanich7661
    @egnatjovanich76612 ай бұрын

    do not understand what parameters for MACD calculation do you use? Also MACD signal line should be the EMA of the MACD bars (Difference Slow and Fast EMA).

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Hi, the parameters are in the code with all the details, you can modify these if necessary the code is available for download in the description.

  • @lizard450
    @lizard4502 ай бұрын

    Try a longer time period. 1 hour to daily.

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    totally agree, low frames are difficult to handle.

  • @DarmendrenRavindran
    @DarmendrenRavindran2 ай бұрын

    Hi, How to find strategy like this online, so I can backtest by my own

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Books, online, KZread Channels (just be careful most are not working properly), but I believe a selection of books have good information to get inspired and build your own strategy from there.

  • @DarmendrenRavindran

    @DarmendrenRavindran

    2 ай бұрын

    @@CodeTradingCafe can you suggest good book to read, maybe do a video collection of books can read to get creative ideas

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    There are plenty, or so I say because I like books, the first few that came to my mind are: *Trading Systems and Methods - Kaufman *Systematic Trading - Carver *Automated Day Trading Strategies - Blake Buttler *Machine Learning for Algorithmic Trading: Predictive models to extract signals from market and alternative data for systematic trading strategies with Python - Jensen And a book that everyone likes, but not really related to strategies: *Trading in the Zone - Douglas These books are a good start to brainstorm, as for videos some of Rayner Theo's strategies are good (on his YT channel) some are harder to make profit in a very systematic approach.

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Brainstorming books: * Trading Systems and Methods - Kaufman * Systematic Trading - Carver * Automated Day Trading Strategies - Blake Butler A book that everyone likes but not really related to strategies: * Trading in the Zone - Douglas For Machine Learning: * Machine Learning for Algorithmic Trading: Predictive models to extract signals from market and alternative data for systematic trading strategies with Python - Stefan Jansen There are a lot of other books that might be useful (I like books) but these came to my mind now, for videos Rayner Theo on YT channel sometimes publishes interesting ideas, but at some point everything will get repetitive for you which is a good sign, this is where you know you are starting to build your own experience. ... And of course CodeTrading the best ;)

  • @DarmendrenRavindran

    @DarmendrenRavindran

    2 ай бұрын

    @@CodeTradingCafe thank you so much!!

  • @erikadanis1534
    @erikadanis15342 ай бұрын

    Could you please create the python logic for this strategy? It works alright on the 30min timeframe after some manual back testing but would like to test it on multiple timeframes and instruments programmatically. If RSI(length=14) > 75 then at some point after the SMA (length=14, StdDev=2) crosses the RSI that's a SHORT entry If RSI(length=14) < 25 then at some point after the SMA (length=14, StdDev=2) crosses the RSI that's a LONG entry

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Hi, the SMA is for the price or the RSI (I assume the RSI)? and when you say the SMA crosses the RSI in which direction? when you use standard deviation in which direction above or below the SMA?

  • @erikadanis1534

    @erikadanis1534

    2 ай бұрын

    @@CodeTradingCafe Yes the SMA is for the RSI. It doesnt matter it which direction it crosses the RSI. If the RSI hit the less than 25 mark, we're waiting for the next time the SMA crosses the RSI for a LONG entry. If the RSI hits the more than 75 mark, we're waiting for the next time the SMA crosses the RSI for a SHORT entry.

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    What is the RSI is above 75 and the SMA crosses the RSI in the long direction we still go short?

  • @erikadanis1534

    @erikadanis1534

    2 ай бұрын

    @@CodeTradingCafe yes that's right 😊

  • @moviesonlinesinema7929
    @moviesonlinesinema79292 ай бұрын

    I want bot will work i will buy short when price increase from this position will closed when coin price return down position will active we can use this program when a crypto rich high price can you write this

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    It's a relatively simple idea, not sure it has potential but you can write it starting from a sample code on this channel.

  • @moviesonlinesinema7929

    @moviesonlinesinema7929

    2 ай бұрын

    thank you dear but i am not understanding write a code but i try activate a code on market @@CodeTradingCafe

  • @moviesonlinesinema7929

    @moviesonlinesinema7929

    2 ай бұрын

    simple thing will let you earn complex things will make us poor @@CodeTradingCafe

  • @TheChocolato
    @TheChocolato3 ай бұрын

    why just changing into another asset like stocks and futures where you can use orderflow and volume , in order to improve your model? you can't have a longterm profitable strategy, based on price only, and therefore I think that the FX market is the wrong market...

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    You are right, just saw this tested on Forex somewhere else and wanted to do the same. I agree volume is crucial and using stocks is much easier.

  • @ACN28
    @ACN282 ай бұрын

    how can i download the code??

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Same here check the description there is a link to download the code.

  • @DGM-DailyGameMoments
    @DGM-DailyGameMoments2 ай бұрын

    Would like to share with the process of using MACD and you can modify your codes accordingly. Keep in touch in the emails. Cheers!

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Sounds great! I will check my emails, might be slow to reply though.

  • @zegikniet9999
    @zegikniet99992 ай бұрын

    the statement fundamentally is flawed. Not everyone can winrate 80 and if so the strategy would fail.

  • @CodeTradingCafe

    @CodeTradingCafe

    2 ай бұрын

    Actually the way the backtest is shown, no one will win anything :)

  • @wrxrob2589

    @wrxrob2589

    2 ай бұрын

    Zero sum game bro, only thing that separates good and bad trades is discretion, and that can’t be taught.

  • @piphunter
    @piphunter3 ай бұрын

    What about the MACD BB indicator? kzread.info/dash/bejne/mGuGmKelZZmzY8Y.html It's something I am currently working with.

  • @a-m-vclips9653

    @a-m-vclips9653

    3 ай бұрын

    What are your results?

  • @piphunter

    @piphunter

    3 ай бұрын

    @@a-m-vclips9653 It just came to me this morning. I was meditating when the the bollinger bands flashed on a mental image of my chart. I added VWAP to and it's looking nicer.

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    Hey, I haven't tried it this way, let us know if you see any potential.

  • @kenzamejhed4163
    @kenzamejhed41633 ай бұрын

    Sir why u don't reply on your email

  • @CodeTradingCafe

    @CodeTradingCafe

    3 ай бұрын

    I really apologize, my email is stacking in the meantime life is happening, work and travel... trying my best.

  • @kenzamejhed4163

    @kenzamejhed4163

    2 ай бұрын

    @@CodeTradingCafe Sir You Are the Best...Please keep posting everyday....i watch all your video since october 2023 until now

  • @machines_go_algo
    @machines_go_algo8 күн бұрын

    I think there is a small but important mistake with MACD here. ============= help(ta.macd) gives us this: Returns: pd.DataFrame: macd, histogram, signal columns. ============= but the way way you append the columns is MACD, SIGNAL, HISTOGRAM am I missing something here?

  • @CodeTradingCafe

    @CodeTradingCafe

    8 күн бұрын

    Now I am perplexed I will have to go back and verify the code! but thank you for pointing this out, I guess this can be easily verified also on the plot

  • @machines_go_algo

    @machines_go_algo

    8 күн бұрын

    @@CodeTradingCafe i think i know what is wrong, the code you use is based on talib's output. You thought that ta and talib are consistent in their output signature since so much of ta is based on talib. Unfortunately they are not :( just swap ta with talib and you are good. ========================= help(talib.MACD): Outputs: macd macdsignal macdhist =========================

  • @CodeTradingCafe

    @CodeTradingCafe

    7 күн бұрын

    Makes sense, thank you for getting back, so I assume talib is being called in the background I wasn't aware of the differences!

  • @machines_go_algo

    @machines_go_algo

    7 күн бұрын

    @@CodeTradingCafe glad to help you. Love your content.