The Truth About MACD Trading | Algorithmic Strategy Backtest In Python

Поделиться
HTML-код
  • Опубликовано: 4 янв 2025

Комментарии • 114

  • @991.
    @991. 9 месяцев назад +8

    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  9 месяцев назад

      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?

  • @juanbernal8105
    @juanbernal8105 9 месяцев назад +2

    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  9 месяцев назад +1

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

    • @doge2themoon373
      @doge2themoon373 9 месяцев назад

      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 9 месяцев назад

      @@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.

  • @newenglandfamilyoutdoors
    @newenglandfamilyoutdoors 8 месяцев назад +1

    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  8 месяцев назад +1

      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.

    • @newenglandfamilyoutdoors
      @newenglandfamilyoutdoors 8 месяцев назад +1

      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  8 месяцев назад

      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.

  • @alfredquarx9147
    @alfredquarx9147 9 месяцев назад +2

    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  9 месяцев назад +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 9 месяцев назад

      @@CodeTradingCafe 🙏🏻 thx

  • @noimnotnice
    @noimnotnice 8 месяцев назад +2

    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  8 месяцев назад +1

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

  • @RobertWelles
    @RobertWelles Месяц назад

    How can you tell which signal is bullish or bearish when look at the chart? 13:14

    • @CodeTradingCafe
      @CodeTradingCafe  Месяц назад

      Hi, if the dot is below the candles the signal is bullish and the opposite is true.

  • @luisc777
    @luisc777 7 месяцев назад +2

    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  7 месяцев назад

      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 7 месяцев назад

      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()

  • @Divine.777
    @Divine.777 9 месяцев назад +2

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

    • @CodeTradingCafe
      @CodeTradingCafe  9 месяцев назад +1

      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 9 месяцев назад

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

    • @Divine.777
      @Divine.777 9 месяцев назад +1

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

    • @CodeTradingCafe
      @CodeTradingCafe  9 месяцев назад

      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.

  • @jroche1832
    @jroche1832 9 месяцев назад +5

    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  9 месяцев назад +1

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

  • @Iamnumber-01
    @Iamnumber-01 9 месяцев назад +1

    Another great video Zaid

  • @samfan179
    @samfan179 9 месяцев назад +2

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

    • @skullinor6058
      @skullinor6058 9 месяцев назад +2

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

    • @CodeTradingCafe
      @CodeTradingCafe  9 месяцев назад +1

      Thank you :)

  • @muhireinnocent2371
    @muhireinnocent2371 5 месяцев назад +1

    Hello @codetrading, instead of using the macd and signal line use the macd bullish and bearish divergence for trend reversal trades and hidden bullish/bearish divergence for trend continuation trades since they produce less wrong signals compared to the macd and signal line strategy, Eagerly waiting for such a video.Thanks

    • @CodeTradingCafe
      @CodeTradingCafe  4 месяца назад +1

      Thank you for the idea, I will check it out and come back if anything interesting comes up.

  • @mindminted1734
    @mindminted1734 3 месяца назад

    how do you make it so that the bot can check condition of the MACD on multiple time frame? I try to make it check at least 3 times frame at once

    • @CodeTradingCafe
      @CodeTradingCafe  3 месяца назад

      Hi, you can use multi-timeframe approach for the backtest, check this video ruclips.net/video/jObikg7gfpU/видео.html

  • @angelomarano8458
    @angelomarano8458 9 месяцев назад +3

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

  • @eduardomoura9586
    @eduardomoura9586 9 месяцев назад +1

    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  9 месяцев назад

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

  • @King_A_limited
    @King_A_limited 6 месяцев назад +1

    Hi can we test beat the market maker by Steve maro

    • @CodeTradingCafe
      @CodeTradingCafe  6 месяцев назад +1

      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
    @egnatjovanich7661 9 месяцев назад +1

    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  9 месяцев назад

      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.

  • @hyperionyt
    @hyperionyt 7 месяцев назад +1

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

    • @CodeTradingCafe
      @CodeTradingCafe  7 месяцев назад

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

  • @erikadanis1534
    @erikadanis1534 8 месяцев назад

    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  8 месяцев назад

      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 8 месяцев назад

      @@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  8 месяцев назад

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

    • @erikadanis1534
      @erikadanis1534 8 месяцев назад

      @@CodeTradingCafe yes that's right 😊

  • @talhakaracallik1352
    @talhakaracallik1352 9 месяцев назад +1

    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  9 месяцев назад

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

    • @talhakaracallik1352
      @talhakaracallik1352 9 месяцев назад +1

      @@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 9 месяцев назад +1

      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  9 месяцев назад

      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.

  • @DarmendrenRavindran
    @DarmendrenRavindran 9 месяцев назад +1

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

    • @CodeTradingCafe
      @CodeTradingCafe  9 месяцев назад

      Books, online, RUclips 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 9 месяцев назад +1

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

    • @CodeTradingCafe
      @CodeTradingCafe  9 месяцев назад

      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  9 месяцев назад

      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 9 месяцев назад +1

      @@CodeTradingCafe thank you so much!!

  • @piphunter
    @piphunter 9 месяцев назад +1

    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  9 месяцев назад +1

      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.

  • @ethan9936
    @ethan9936 9 месяцев назад +1

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

    • @CodeTradingCafe
      @CodeTradingCafe  9 месяцев назад

      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.

  • @moviesonlinesinema7929
    @moviesonlinesinema7929 9 месяцев назад +1

    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  9 месяцев назад

      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 9 месяцев назад

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

    • @moviesonlinesinema7929
      @moviesonlinesinema7929 9 месяцев назад

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

  • @dilansadeep
    @dilansadeep 9 месяцев назад

    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  9 месяцев назад

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

  • @ACN28
    @ACN28 9 месяцев назад +1

    how can i download the code??

    • @CodeTradingCafe
      @CodeTradingCafe  9 месяцев назад +1

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

  • @TheEcherriman
    @TheEcherriman 9 месяцев назад +2

    Thank you !

    • @CodeTradingCafe
      @CodeTradingCafe  9 месяцев назад +1

      Thank you for your support!

    • @TheEcherriman
      @TheEcherriman 9 месяцев назад

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

  • @DailyGameMoments7
    @DailyGameMoments7 9 месяцев назад +1

    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  9 месяцев назад

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

  • @TheChocolato
    @TheChocolato 9 месяцев назад +1

    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  9 месяцев назад

      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.

  • @jonathansands115
    @jonathansands115 9 месяцев назад +1

    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  9 месяцев назад

      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 8 месяцев назад +1

      @@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  8 месяцев назад

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

  • @lizard450
    @lizard450 9 месяцев назад +2

    Try a longer time period. 1 hour to daily.

    • @CodeTradingCafe
      @CodeTradingCafe  9 месяцев назад +1

      totally agree, low frames are difficult to handle.

  • @Zegik_Niet
    @Zegik_Niet 9 месяцев назад +3

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

    • @CodeTradingCafe
      @CodeTradingCafe  9 месяцев назад +1

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

    • @wrxrob2589
      @wrxrob2589 9 месяцев назад +1

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

  • @piphunter
    @piphunter 9 месяцев назад

    What about the MACD BB indicator? ruclips.net/video/f7R6El56M3c/видео.html It's something I am currently working with.

    • @a-m-vclips9653
      @a-m-vclips9653 9 месяцев назад

      What are your results?

    • @piphunter
      @piphunter 9 месяцев назад

      @@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  9 месяцев назад

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

  • @kenzamejhed4163
    @kenzamejhed4163 9 месяцев назад +1

    Sir why u don't reply on your email

    • @CodeTradingCafe
      @CodeTradingCafe  9 месяцев назад +1

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

    • @kenzamejhed4163
      @kenzamejhed4163 9 месяцев назад

      @@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_algo 6 месяцев назад +1

    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  6 месяцев назад +1

      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 6 месяцев назад +1

      @@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  6 месяцев назад +1

      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 6 месяцев назад +1

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