Algorithmic Trading in Python - MACD: Construction and Backtest

Поделиться
HTML-код
  • Опубликовано: 14 июн 2024
  • Thanks a lot for watching :-) Please subscribe to the channel if you enjoyed the video.
    Disclaimer: This is video is not an investment advice. It is for educational and entertainment purposes only.
    In this video we are constructing the MACD indicator, visualize trading signals and backtest the strategy with Python.
    If you have any questions or want to provide feedback be kindly invited to let me know in the comments below.
    Previous video on crossover moving averages:
    • Trading moving average...
    Regarding the adjust=False point:
    pandas.pydata.org/docs/refere...
    Video where I am going into more details about EMAs:
    • How to build a RSI Tra...
    The main point of using EMAs is to give more recent data points a larger weighting.
    Further reading (high level):
    www.investopedia.com/terms/e/...
    The 12/26/9 values are overall accepted standardized values but you can make amendments if you want.
    0:00 - 02:43 Explanation of the strategy
    02:43 - 03:20 Pulling online stock price data
    03:20 - 06:07 Adding the MACD indicators
    06:07 - 07:08 Plot MACD and signal line
    07:08 - 10:41 Get Buying and Selling signals
    10:41 - 14:15 Plot Buying and Selling signals
    14:15 - 21:22 Backtest
    21:22 - 24:27 Long term backtest

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

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

    This video is transformational! Thanks for your efforts to help your students. You're delivering insane value!

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

      Thanks buddy. Appreciate your comment and the positive attitude!

  • @mschuer100
    @mschuer100 3 года назад +1

    another amazing video. Looking forward to testing it out on my own stocks. Thanks for putting this together

    • @Algovibes
      @Algovibes  3 года назад

      Thanks a lot for watching and your kind comment. Appreciate it :-)

  • @sz8558
    @sz8558 2 года назад +1

    Excellent as usual! thank you

  • @web3beginners
    @web3beginners 2 года назад +2

    you're a great teacher!

    • @Algovibes
      @Algovibes  2 года назад

      Thanks for your kind words Zoe

  • @rverm1000
    @rverm1000 2 года назад +1

    great video. helped me learn some new methods to look at stocks in python.

    • @Algovibes
      @Algovibes  2 года назад

      Awesome! Thanks for watching and you feedback buddy!

  • @konturgestalter
    @konturgestalter 3 года назад +1

    excellent as always

    • @Algovibes
      @Algovibes  3 года назад

      Thank you very much for watching and your comment :) Appreciate it.

  • @unailopez1282
    @unailopez1282 2 года назад +1

    Great video!
    Have you try to compare this strategy with buy and hold?

  • @fx2gbg596
    @fx2gbg596 2 года назад +1

    thanks man extreemy simple to understand and good explained thank you bro

    • @Algovibes
      @Algovibes  2 года назад

      Thanks buddy. Happy to hear that :-)

  • @jitkadyan
    @jitkadyan 3 года назад +1

    Another Great Video

    • @Algovibes
      @Algovibes  3 года назад

      Thanks a lot mate. I really appreciate your support!

  • @snehapradeep3082
    @snehapradeep3082 Год назад +1

    Great content! Thank you so much xD

  • @FRANKWHITE1996
    @FRANKWHITE1996 3 года назад +1

    Well explained. Thanks.

    • @Algovibes
      @Algovibes  3 года назад

      Welcome :-) Thank you very much for watching and your support!

  • @anilmm2005
    @anilmm2005 Год назад +1

    Thanks a lot @algovibes. I would request many more such in depth content on India market preferably on NIFTY50 as the index.. Looking forward to it

    • @Algovibes
      @Algovibes  Год назад

      Thanks for watching mate. Noted your suggestion!

  • @ismaelconde8457
    @ismaelconde8457 Год назад +1

    excellent video . thanks a lot

  • @ivanuglanica1529
    @ivanuglanica1529 3 года назад +2

    Great explanation. Though, I’d add that you can use the first signal and calc back testing with it as well, as it may be calculated as short sell.

    • @Algovibes
      @Algovibes  3 года назад +1

      Absolutely awesome and right comment! Thanks a lot for your contribution. And also thanks for watching of course :-)

    • @ivanuglanica1529
      @ivanuglanica1529 3 года назад +1

      @@Algovibes thank you for great videos, course, absolutely enjoy it - plain and clear explanations and examples. Thanks a lot!

  • @user-pi9po1vi9j
    @user-pi9po1vi9j 2 года назад +2

    Thank you for sharing! The only thing I would mention if it wasn't already mentioned is that returns are not additive. The logreturns are additive, instead. This is about the cell where you do sum(prifitsrel) / len(profitsrel)

    • @Algovibes
      @Algovibes  2 года назад

      Hi man,
      thanks a lot for your comment. I am not calculating the cumulative but the average profit here.
      More background:
      ruclips.net/video/fWHQwqT3lNY/видео.html

    • @user-pi9po1vi9j
      @user-pi9po1vi9j 2 года назад

      @@Algovibes Definitely, worth to watch! Thank you for sharing! Thus, it was already mentioned)

  • @onurkoc6869
    @onurkoc6869 2 года назад +1

    You must be Professor! Thanks.

    • @Algovibes
      @Algovibes  2 года назад

      I am not but I appreciate your comment 😛

  • @rickymacharm9867
    @rickymacharm9867 3 года назад +1

    Hello @algovibes. Lovely video here. Do you have a video that backtests buy and sell signals...as I see this is a buy only strategy?
    Keep up the good work sire.

    • @Algovibes
      @Algovibes  3 года назад

      Thanks for your kind comment :-) I didn't backtest MACD yet but I have done some backtests on other strategies. Maybe you find some helpful stuff here and there on my channel.
      However I noted to cover MACD backtesting. Maybe it fits in when introducing a Backtesting library.

  • @vsalvato53
    @vsalvato53 Год назад +1

    Excellent! I am quite keen on exploring MACD; I am not able to program on Python but would like to run your script and run a series of back testing on various assets. Is the script available for C&P somewhere>

    • @Algovibes
      @Algovibes  Год назад

      Thanks! :-)
      As I wrote on one of your other comments. The code is available here:
      ruclips.net/channel/UC87aeHqMrlR6ED0w2SVi5nwjoin

  • @anatarek6022
    @anatarek6022 Год назад +1

    Bro your channel is awesome 👌 , in this strategy there's alot of fake signal how can i optimise this strategy and skip alot of fake signals

  • @thieshenningsen1070
    @thieshenningsen1070 3 года назад +1

    Sehr cooles Video,
    wäre interessant gewesen zu wissen, wie viel relativen Gewinn diese simple Strategie insgesamt gemacht hätte und nicht per Trade, um das ganze mit der Preisentwicklung der Tesla Aktie zu vergleichen

    • @Algovibes
      @Algovibes  3 года назад

      Vielen Dank für deinen Kommentar :-) Stimme dir zu, das hätte man auch machen können! Du kannst die returns aus der Strategie kumulieren (vorausgesetzt du hättest wirklich jeden einzelnen trade gemacht) und dann vergleichen. Am besten packst du die returns in einen dataframe wie ich am Ende und nutzt dann die cumprod Funktion. Ohne es gemacht zu haben: Ich denke, die Aktie wirst du unmöglich outperformen mit der Strategie. In den letzten 10 Jahren ist Tesla um mehr als 10.000% gestiegen :-D

  • @utopistsam3839
    @utopistsam3839 2 года назад +1

    Thank you for sharing! It's very helpful. Which IDE is this?

    • @Algovibes
      @Algovibes  2 года назад

      Welcome man, thanks for watching. That's Jupyter Notebook.

  • @Whiterabbitz42
    @Whiterabbitz42 10 месяцев назад +1

    Amazingly clear.. thanks Any chance of a IMACD example?

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

      Thanks mate! Interesting suggestion, thx!

  • @charlesmosongo
    @charlesmosongo 2 года назад +1

    Hi great video, just a confirmation, when at 23:28 you say average profit, do you mean average profit per trade?

    • @Algovibes
      @Algovibes  2 года назад

      Thanks mate. Just the average profit of all trades.

  • @sagarchoudhari9386
    @sagarchoudhari9386 3 года назад +1

    As Always Very Nice Content.... Can you please make a video on live server code python with strategy making trades and show trades on the broker terminal

    • @Algovibes
      @Algovibes  3 года назад

      First of all thank you very much for watching and your comment. Really appreciate it :-) Yes I am planning on doing live strategies with both cryptos and stocks roughly in mid of May or July as I am having some days off. Before that I have some other videos in the pipeline so I am kindly asking for your patience until then.

  • @Random_work822
    @Random_work822 11 дней назад +2

    can you make a complete video on backtesting with stop loss and take profit

    • @Algovibes
      @Algovibes  9 дней назад

      Already have some in place mate. Be invited to check out my other videos!

  • @franekaleksandrowicz33
    @franekaleksandrowicz33 2 года назад +1

    Hi,
    That's awesome explanation and I really love your film, but I have a slight problem. I was trying to do everything exeact as in video, but with data from binance, it gaves a timestamp so I changed it to time object, but whenever I call the .index() function on df I get:
    >>> RangeIndex(start=0, stop=180, step=1)
    Could you please help me?

    • @Algovibes
      @Algovibes  2 года назад

      Hi man, thanks a lot. That's happening because you have an integer index instead of a date time index. I have covered stuff like that in my cryptobot playlist. Please check that out, you will find your problem solved there!

  • @azizarslanhan1796
    @azizarslanhan1796 2 года назад +1

    hey, Algovibes, can you stream the data from binance and when some conditions met let python gives you alarm somehow?

    • @Algovibes
      @Algovibes  2 года назад +1

      Hi Aziz, quite funny: I did that in my most recent video :D Be kindly invited to check that out and let me know what you think.

  • @JavierVargas-ov2yq
    @JavierVargas-ov2yq 2 года назад +2

    As the EMA is calculated over the last 26 samples, could it be better if we ignore the first 26 samples to get a more reliable indicator?

    • @Algovibes
      @Algovibes  2 года назад

      Can you elaborate on that? Thanks in advance!

    • @ProSpase
      @ProSpase 2 года назад

      @@Algovibes The first 25 entries in the df do not show a true EMA26 as there was not enough data to compute EMA26. Same applies for the fist 11 entries for the EMA12.

  • @martiniyongo7576
    @martiniyongo7576 2 года назад +1

    @algovibes great content again! Just wanted to know I noticed a weird thing. My set up did not allowed me to sell after buying with the bot. So I changed the the paramters of my api then it worked. I sold and bot some eth, my last position was a buying position, but it desapeared, and the bnb bought to pay the fees also... I tried again and all my usd are gone and desapeared... could you give me some advices? Is it because of the fees when I'm selling? Thank you jave a great day

    • @Algovibes
      @Algovibes  2 года назад

      Thanks a lot for your kind words! I would need some more information. What do you mean it disappeared?

    • @martiniyongo7576
      @martiniyongo7576 2 года назад

      @@Algovibes no problem man you put some good work so it has to be told 😌! I mean I put an order to buy ethusdt and it has been executed (i checked it on my order history) then i saw it on my spot portfolio but few hours later it desapeared from my spot portfolio... and all my bnb also...🙄

  • @maddiehad
    @maddiehad Год назад +1

    Hi how can you prevent fake entries when for instance the candle is very volatile ?

    • @Algovibes
      @Algovibes  Год назад

      Enter the position as soon as the candle is closed. Other than that measure the volatility and set an entry threshold. Be invited to check out basically all my videos in the Python for Finance and cryptobot playlist. I have covered a ton of concepts there.

  • @hamad.learns
    @hamad.learns 3 года назад +3

    Hey! thanks a lot for the wonderful video. I think we need to see how we would have done in comparison to buy and hold or in comparison to SNP500. And I thinkg the 5 percent profit does not mean that I would make 5 dollars if I had invested 100 dollars, this will again be affected by the number of trades and the compounding affect. Would appreciate your comments / insights on this. Thanks!

    • @Algovibes
      @Algovibes  3 года назад +2

      Hi and thanks a lot for watching and your comment :-) Yes a benchmark test would be good but I would not use the S&P500 but rather the equity itself (Of course if you apply this strategy to the S&P500 - which is definitely possible - the benchmark would be the index). The 5% is the average return of the strategy without taking any fees into consideration. If you want to see how much you would have made out of 100 dollars you would need to cumulate the strategies return over the desired time period.

    • @hamad.learns
      @hamad.learns 3 года назад +1

      @Algovibes in this case 5% is pretty insane! I was wondering what are your thoughts on EMH and that everything is already priced ?

    • @Algovibes
      @Algovibes  3 года назад +3

      ​@@hamad.learns Well I am kind of supporting all three forms of the EMH (EMH = Efficient market hypothesis in case someone is reading along wondering) and there are great minds behind it and it totally makes sense. Anyhow: It is easy to say - and you will hear that from a lot of academia people: technical trading is coffee cup reading / everything is priced. But I personally don't believe that: Nearly ALL those established strategies are Momentum based. Momentum is widely discussed and 'proven' to be one of the main driver of excess returns (relative to the market).
      Besides that: The market has changed since EMH. Market access is a lot easier nowadays potentially increasing the share of naive actors in the market. Also automated trading systems are partly based on indicators and a lot of them are based on those momentum indicators. Besides that a lot of market actors are using technical indicators forming a kind of self fulfilling prophecy.
      I could add even more points but I don't want to bore you, so I hope this is giving you an idea how I see things.

    • @hamad.learns
      @hamad.learns 3 года назад +1

      @@Algovibes Definitely not boring AT ALL, could listen to this all day haha! Many thanks for the reply! Keep up the great work, I really dig your channel :)

    • @markk4203
      @markk4203 2 года назад

      @@Algovibes What would be the best way to factor in commission and slippage to relative profits? I'm guessing a couple lines of code would suffice?

  • @mychmose
    @mychmose 6 месяцев назад

    If nobody has mentioned this yet, the elif should be an if as they are mutually exclusive pieces of logic

  • @MexicanElmo
    @MexicanElmo 3 года назад

    Hello, I did this exactly as stated except with a csv file for crypto backtesting and I got a 'key error: 0'. Any solutions to this?

    • @Algovibes
      @Algovibes  3 года назад

      Need more details to help out. When did the key error occur? Thanks for your answer in advance!

  • @chapmansbg
    @chapmansbg 2 года назад +3

    can you take a few of these strategies and add in a stop loss of x amount of the average profit, eg. you calculated a average profit of 4.95% per trade so if you then add a stop loss of half of that and re-run to see if that makes any difference to the overall outcome.

    • @Algovibes
      @Algovibes  2 года назад

      That's a pretty nice idea!

    • @mako5708
      @mako5708 2 года назад +1

      Or open the trades with already predefined Take Profit and Stop Loss with Reward-to-Risk Ratio (RRR) e.g. 1,5 = 1,5 profit(reward) & 1 loss(risk). So the trades can be closed automatically.
      With RRR=1,5 the strategy can be theoretically profitable also with Win rate around 50% :)

    • @mako5708
      @mako5708 2 года назад +1

      Also some Money Management strategy implemented, not just buy all here, sell all here. Just simple risk max 2% of balance per trade.

    • @Algovibes
      @Algovibes  2 года назад

      @@mako5708 Thanks Matus for sharing your thoughts!

  • @KentokyG
    @KentokyG 2 года назад +1

    is relative profit, the amount you get for each buy and sell?

    • @Algovibes
      @Algovibes  2 года назад +1

      Relative profit is sell price - buyprice in relation the buyprice. So just the percentage profit you made. Makes sense to you?

  • @rshkmrpl10
    @rshkmrpl10 3 года назад +1

    Sir this calculation is on a daily close basis data. Sir, if I want to do these calculations on monthly Or weekly basis so to reduce noise(false signals). How to do that?

    • @Algovibes
      @Algovibes  3 года назад

      First of all thanks for your comment. Secondly I am not quite sure what you want to achieve as the MACD is defined as several EMA calculations over specified time horizons.
      So do you just want to have longer time horizons (months instead of days) or what? Appreciate your elaboration in advance!

    • @its_sharan54
      @its_sharan54 2 года назад

      Hey, I don't understand you correctly but if u r looking for data on weekly basis,not on daily basis u can use this
      import datetime as dt
      import yfinance as yf
      from pandas_datareader import data as pdr
      import pandas as pd
      yf.pdr_override()
      start = dt.datetime(2002,1,1)
      end = dt.datetime.now()
      stock = 'AAPL'
      df = pdr.get_data_yahoo(stock, start, end,interval='1wk')
      you can use these intervals : 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo

    • @josuecc7843
      @josuecc7843 2 года назад

      @@its_sharan54 You can also do the same that he did in the video and add " interval ='1m' " in the yf.download function
      Ex :
      df = yf.download(AAPL, period=1y, interval='1m')
      Valid intervals: [1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk, 1mo, 3mo]

  • @jitkadyan
    @jitkadyan 3 года назад +1

    Sir if we have to apply it in the live market how we can regularly update date from API and execute our trade, set buy/sell condition in live market data and take an entry, also set rules or condition that we will not buy or sell again if once buy or sell order executes and if place target and stop-loss order with buy or sell condition and if anyone order execute how to know through coding to cancel other order during the market hours, can you make a video of such type on a very popular strategy of Opening Range Breakout of 5 or 15 Minute candle High Low in a standard way that we can apply it in future in other types of strategy only changing buy or sell condition of entry in trade.

    • @Algovibes
      @Algovibes  3 года назад +2

      First of thank you very much for this suggestion. Happy to announce that I will cover live implementation of trading on both cryptos and stocks in the near future. I think I am covering that roughly in mid of May or July as I have some days off. Can't promise anything but this is my plan. Anyhow I will cover various topics beforehand so I am kindly asking for your patience.

  • @MrNabiwishes
    @MrNabiwishes 2 года назад +1

    Can we use normalize macd instead

    • @Algovibes
      @Algovibes  2 года назад

      Well, depends on what you want to achieve.

  • @DarrylHebbes
    @DarrylHebbes 3 года назад +5

    its called a "caret" character "^"

    • @Algovibes
      @Algovibes  3 года назад

      Haha :-D Thanks for the clarification and thanks a lot for watching :-)

  • @ullib3593
    @ullib3593 3 года назад +1

    Do you offer links to the program sources?

    • @Algovibes
      @Algovibes  3 года назад

      I am working on a solution for that. I am currently not sure if I made my own website or use a repo where Patreon members will have access. Will take some time until I figured it out but I will keep you updated (in the form of community posts) once I found a solution.

  • @msa888
    @msa888 Год назад +1

    Is that average per trade???

    • @Algovibes
      @Algovibes  Год назад +1

      Sorry, what are you referring to? quite some time since I recorded this video. Thanks!

    • @msa888
      @msa888 Год назад

      @@Algovibes I rewatched the video and clarified my doubt, thanks!

  • @teenspirit1
    @teenspirit1 2 года назад +1

    Why don't you streamline your videos to use some backtesting library instead of recreating the simulator every time? A backtester library will allow you to create your signalsl in a dataframe, simulate limit/market orders, calculate slippage and spread, you won't have problems like "I don't have a buy so I don't know how to account for this signal" you will just check if you have a position and enter if not.

    • @Algovibes
      @Algovibes  2 года назад

      Because these videos are meant to be educational videos on how you can use Python to transform a certain trading idea into code. Using Backtrader / vectorbt / or anything else is a whole different story, which will also be covered surely.

    • @teenspirit1
      @teenspirit1 2 года назад

      @@Algovibes Sorry got recommended this video again and realized I've got an additional comment. I think comparing your results to buy and hold of the underlying every time you make a video would be much appreciated so we can actually see if that strategy is worth anything.

  • @chapmansbg
    @chapmansbg 2 года назад +1

    carrot ^^^^^^^^^^

  • @chapmansbg
    @chapmansbg 2 года назад

    Can you provide the code in a file or repo?

  • @matthewrenegar6559
    @matthewrenegar6559 2 года назад

    Save some time with the MACD calculation.
    import pandas_ta as ta
    MACD = df.ta.macd(slow = 26, fast = 12)
    df = pd.concat([df, MACD], axis =1)
    This will create three columns in the dataframe to show the MACD, histogram, and signal values.

    • @Algovibes
      @Algovibes  2 года назад +1

      The point of this video is to code it from scratch (the whole series btw). I have covered technical analysis libraries in a lot of my other videos.

  • @prasannakumar5140
    @prasannakumar5140 2 года назад +1

    HI your videos are wonderful....how can i contact you, i would like to buy macd bot

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

    for i in range(2,len(df)):
    if df.MACD.iloc[i] >= df.signal.iloc[i] and df.MACD.iloc[i-1] < df.signal.iloc[i-1]:
    Buy.append(i)
    elif df.MACD.iloc[i] < df.signal.iloc[i] and df.MACD.iloc[i-1] >= df.signal.iloc[i-1]:
    Sell.append(i)
    # At Minute 12 in this video: I'm not sure because I'm noob, but can you avoid problems with exactly equal values for MACD and signal by changing code in the way above?
    Thanks for content!

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

      Welcome mate!