Backtesting Rayner Teos RSI SMA Trading Strategy in Python [Part II]

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

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

  • @rraul
    @rraul 3 года назад +13

    Very clear, Very usefull. As always, the best python finance content on RUclips. Thanks 👏👏👏

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

      Thanks a bunch my friend! :-)

  • @bosco6771
    @bosco6771 3 года назад +6

    One more scenario to handle when removing overlapping trades: imagine there are multiple consecutive trades generated with same sell date, then the logic shown in the video will not be able to remove all invalid trades since the logic only covers shift(1). This is exactly what I encountered when conducting testing with a bigger dataset.

  • @r.sp.378
    @r.sp.378 3 года назад +3

    Awesome video. Iam learning a lot from your videos and explanation. This really ignited my interest in data science and trading. Thank you for you effort.

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

      Thanks a lot. That's awesome to hear :-)

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

    Thank you so much for the additional content on this topic. I feel like any amount more you'd be willing to go into this topic would be helpful to me and worth a watch.

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

      Thanks for the feedback buddy! Thats really helpful for me :-)
      Yea I am personally interested in how the Net profit could be improved as well. I am probably working on another one here implementing another exit strategy (instead of the 10 days).

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

      I absolutely recommend Mr Mathew Doman to new traders who are struggling to make profit out of their crypto investment I was once in that situation until I met Mr Mathew who in fact changed my life I began making good profits out of my traders till date best trader I know.

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

      @@Algovibes I've been charting the distribution of the mean profits (per S&P500 constituent), plus the StDevs. Matplotlib/Seaborn boxplots with jitter, distplots/histograms etc. Not terribly exciting. Am currently aiming to create an alternative exit condition, such as for example close < 200 day SMA, i.e. not dependent upon a fixed forward-looking window of time, to see if profitability improves.

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

      ​@@DontTrustMeImASc Interesting! Be invited to share the results :-)

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

      @@Algovibes I keep encountering NaT values if the strategy is long at the end of the dataframe. Not clear how to ensure that any final long position is exited at the end of the time span without a distinct exit condition.

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

    I’m having issues as a beginner because I didn’t install the packages like NumPy etc but now I’m getting them fixed

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

      Issues are more than normal! Awesome that you are getting them fixed.

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

    Hi thanks for video and very very good tha all contains
    Please make more video like this.

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

      Thanks for your feedback buddy :-) There will surely come more videos like this.

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

    Thanks bro,...can u please one vedio on CPR pivot point for entry and exit

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

    this video is great for educational purposes but the thing is had you invested in s&p500 in 1996 instead of trading with rayner's strategy, your investment would've grown ~7x. Whereas, rayner's strategy gives about ~1.6x and that is excluding transaction costs, short term capital gains etc.
    It would be wonderful if you can make a video of algo trading v.s algo investing(buy and hold)

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

      Thanks mate! Appreciate your comment and sharing your thoughts. Also the suggestion sounds pretty interesting!

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

    Can you please make a video on how I can implement trailing SL by %( for example, start SL at -1% but if price moves up by 1% bring sl to cost, if by 2% then at 1%+)? Have been racking my head over this trying to implement it in the structure you gave above.

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

      Hi Ayush,
      was implementing SL and stuff like that e.g. here:
      ruclips.net/video/4MnNft7Squk/видео.html

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

      @@Algovibes This is just the basic one SL and one Target right, as I saw in the video. I was wondering if there was a way to do trailing SL?

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

      @@Algovibes A video on specifically for setting target and SL in different variations will be very helpful :)
      Like a case study of types on which type of take profit method works best.

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

    Amazinng work dude! Thanks for share!!! 💪👌👍🍺

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

      Thanks for your appreciative comment :-)

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

    hello I've tried to follow your code exactly and I am encountering an Indexing error for the Selling dates "single positional indexer is out of bounds"
    Which made sense for me since the range of "i" is the whole length of df
    So if i == len(df) where would the dataframe get the "i+j"th term
    My question is how did it work for you without the "-11" for the first case of this loop
    Sorry kinda new to programming
    Anyways thanks for the great video

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

      Hi man, thanks a lot for watching. It's just because I probably don't get a Selling signal (j) shooting over the loop range. It is exactly like you said: Limit the loop for the forward looking period. Hope that helps!

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

      @@Algovibes that makes sense
      Thank you

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

      @@wyatt09277487073 Im new with Python and also english is not my native language. I keep getting the same error. Could you please tell me, how to edit the code exactly? Thank you very much!

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

      @@Algovibes Limiting the loop is ridiculous if you're using this to drive an automated bot, as you wouldn't get a buy signal until the day's trade is already closed !!!

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

    Nicely explained, thank you for sharing

  • @connorf.8555
    @connorf.8555 3 года назад +1

    An sich so wie ich auch trade, nur halt ohne bot halt an Hand der Indikatoren und währungspaar Vergleich ob die andere Paare den weiteren Verlauf ergenzen halt im forex Bereich

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

    Does the information or TA library take care of the look ahead bias?

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

    You should try to apply split on buying and selling price, or transactions fees, in order to make it realistic. Thanks for the educative content !

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

      Thanks for watching and also for sharing your thoughts! :-)

  • @HK-yo4se
    @HK-yo4se 3 года назад +1

    I'm not a developer but caught myself looking your content! 😂

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

      How dare you? jokes aside my goal would be to make this kind of stuff both appealing for devs but also people who are just curious about it. So I am more than happy to read that.

    • @HK-yo4se
      @HK-yo4se 3 года назад

      @@Algovibes
      I really like that you explain clearly what and why you do things. So yes Jupyter will be started and I will repeat what you did to learn something.

    • @HK-yo4se
      @HK-yo4se 3 года назад

      Btw. Is there somewhere a good overview on the libraries you're using and which formulas they cover. I look for Excel alternatives and Python seems to do the trick.

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

    I use Stochastic oscillator crossover for best confirmation. You should try it with rsi

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

      Thanks for sharing! Anyhow can you elborate a bit? Thx in advance

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

      @@Algovibes try Stochastic oscillator crossovers with settings 14 3 3. Use only crossovers at the extreme levels (above lvl 80 and under lvl 20). Also check rsi 14 at extreme levels that re enter towards the centre. 1 minute timeframe and max 3-5 minutes expiry. This strategy is for fast positions

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

    Would love to see more of these coding ideas. Do you have any suggestions on volumn indicator? rsi alone seems like all about the price as far as I know

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

      Thanks for your feedback :-) I didn't play around with Volume indicators yet.

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

      Money Flow Index is similar to RSI but weighted by volume

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

    Very nice vids! How would you calculate the relative yearly returns of this strategy?

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

      Hi buddy, thanks a lot for your kind comment.
      Good question. I probably won't compare that to e.g. a buy & hold S&P strategy as the amount if time within a position is not comparable.

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

    My simulated winrate using a small dataset (1-day minute price) is only around 56%. Will try to use a bigger dataset tonight for a more accurate result.

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

    How can we find if there are any false signals for this strategy ?

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

      What do you mean by false signals? Signals which end up in bad trades?

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

      @@Algovibes yes sir

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

    The new method of calculating RSI in the Part 2 video, is it giving the same result as Part 1, at which you used Wilder's Smoothing Method ?

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

      Nope, slightly different.

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

      @@Algovibes yeah thanks. same as what I observed.

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

    Great video! Maybe we can plot a image to see buying and selling dates.

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

      Thanks a lot mate! :-)
      Yep, that's definitely possible. I covered plotting signals among other in this video:
      ruclips.net/video/pB8eJwg7LJU/видео.html
      Or this one:
      ruclips.net/video/cwEORaERl2o/видео.html

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

    Really helpful... waiting for part 3... continuing.... also how to find current live signal? And store it

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

      Thanks buddy, appreciate your comment :-)
      I have covered getting signals in this playlist:
      ruclips.net/p/PL9ATnizYJ7f9sW_mdY3071dS8mMwBGu2S

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

    You are a legend man , I 'm big fan , please always use functions , it's easier and clean , would like these type of videos , You Rocks > would be nice if you provide source code , as it would help us learn

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

      Thanks for your kind words mate. Really appreciate it :-) Trying to slice it up before wrapping it in functions or classes for a better understanding of the code.

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

      I absolutely recommend Mr Mathew Doman to new traders who are struggling to make profit out of their crypto investment I was once in that situation until I met Mr Mathew who in fact changed my life I began making good profits out of my traders till date best trader I know.

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

      mathewdoman06@gmail.com)

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

    Thanks for the video bro....I am novice .Can you please explain how to get tomorrow stock name based on above strategy if i run the code today.assuming that when running for all 500 stocks

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

      Welcome mate. Well you need to check using this code where the condition is fulfilled. I did something like that here:
      ruclips.net/video/pB8eJwg7LJU/видео.html
      Also check out the stock recommendation playlist. I have covered your question exactly there.

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

    Can you backtest same for Nifty500 stocks universe??

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

      Feel free to go for it!
      Was playing around with Indian stocks here, might be interesting for you:
      ruclips.net/video/YIsKSQh1xpY/видео.html

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

    Is there any chance that choosing the very FIRST trade may affect subsequent trades? There is the possibilities that if we skip the first trade and enter the second trade (which we are likely to skip if we stick to the first trade), we'll get better result.

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

      Why do you think so?

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

      ​@@Algovibes because when you by default pick the first trade, assuming that the second one overlaps with the first, you skip the second.

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

    I really enjoy your videos, thanks. Does a high winning rate percentage necessarily equate to a high profit factor? Could it be the case that of two potential strategies, a strategy with a lower winning rate percentage actually makes more money when compared to a similar strategy that has a much higher winning rate percentage? Can you explore this question in a future video please?

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

      Great to hear. Thanks for watching :-)
      No it doesn't. A very low winning rate could even outperform an extremely high winning rate. The Net Profit (but also the other mentioned metrics) is decisive that's why I am covering them in this video as well.
      As a simple example:
      Imagine you made 10 trades and won 1 Dollar on 9 of them. On the 10th you made a loss of 10 Dollar. Overall you made losses but the winning rate is 90%.
      The other extreme:
      You made 10 trades and lost 1 Dollar on 9 of them.
      On the 10th you made a win of 10 Dollar.
      Overall you won but the winning rate is 10%.

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

      @@Algovibes That's exactly what I was thinking of, thanks for illustrative example.

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

      @@Algovibes is this the concept of positive expected value ?

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

    Again Excelent video, thank you very much, much success

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

      Thanks for watching, your feedback and the kind words my friend :-)

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

      mathewdoman06@gmail.com)

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

    I heard from Dr Ernest Chan that it's not practical to buy on open. Is that true?
    s/o from South Africa

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

      It depends. The market tends to be more volatile on open, so some day traders prefer things to settle down later in the day before they make any trading decisions. Other day traders might specifically want to trade on market open for that volatility and various other reasons. But if you're a longer term trader, like a swing trader, then what time of day you trade usually doesn't matter.

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

      Hi both,
      first of all greetings back to 🇿🇦 :-)
      I have nothing more to add to SwingTraders comment. Thanks a lot for supporting others - awesome mentality👏

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

      @@Algovibes If you wanted to incorporate slippage and commissions, would you use a function to adjust the buy/sell prices and how/where would that fit in?

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

    Intersting content! Any ways to get the script to C&P on Python? I do not know Programming language but would love to play around with this and do some analysis and screening

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

    Is there a way to limit the amount of trade in addition to preventing overlapping? Like, entering into 1 trade per month only on the first time the signal hit.

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

      Sure! What I would think of is just a simple break logic if x trades are executed.

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

    Hi,
    I have installed 'ta'
    But i have this error with Pycharm :
    df['RSI'] = ta.momentun.rsi(df.Close, window=10)
    AttributeError: module 'ta' has no attribute 'momentun'
    Thanks for the stuf ;)

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

      just a typo, "momentum" is right.
      Thanks for watching and nice trading setup there :D
      Thanks for watching buddy!

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

      @@Algovibes Yes "momentum" sorry.
      I have the same problem with :
      df['MA200'] = ta.trend.sma_indicator(df.Close, window=200)
      trend & momentum are in yellow background
      At the moment i have this error :
      df['MA200'] = ta.trend.sma_indicator(df.Close, window=200)
      TypeError: sma_indicator() got an unexpected keyword argument 'window'

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

      I have find, it was my virutal environnement ...
      It's ok !
      Thanks a lot for your video !

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

    I got a SSL error while reading html from wikipedia, then I added these two lines to fix it:
    import ssl
    ssl._create_default_https_context = ssl._create_unverified_context

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

      Thanks a lot for sharing!

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

    This code is forward looking

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

    nice stuff, THX!!

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

      Thank YOU for watching and your comment mate! :-)

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

    Super Videos danke!

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

    not a very good strategy. lack of trade over a 20 ish years period. - Not even taking into account the bullish bias of the index over an extended period of time.
    THe holly grail period with zero IR and "your best friend" the FED printing money like there was no tomorrow. That was the "over" perfect market for such a strategy. I guess with this new paradigm shift -> inflation and raising rate. The accuracy of such a strategy might go south. The idea to buy the correction into a trend is a good idea but in this case this strategy is far too simplistic to be effective.

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

      Thanks Thierry for sharing your thoughts! Appreciate it.

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

    I am trying to implement what I learned from your videos, I am trying to RSI and EMA strat but I get "arrays must all same length" error. Where do I wrong?
    Code is:
    Buying_dates = []
    Selling_dates = []
    for i in range(len(df)):
    if df.Signal.iloc[i]:
    Buying_dates.append(df.iloc[i].name)
    elif df['Close'].iloc[i] >= df['EMA144'].iloc[i]:
    Selling_dates.append(df.iloc[i].name)
    frame = pd.DataFrame({'Buying_dates':Buying_dates, 'Selling_dates':Selling_dates})

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

      The error is occurring because Buying and Selling dates are not of the same length. On first sight the loop logic doesn't make much sense to me since you are adding a Buying date when there is a signal but if there isn't a signal you are checking for the close higher than the EMA. But I would rather think you want to check that from the date on you bought. I solved that with a nested loop in my video. Can you double check the approach in the video again?
      Let me know if that has helped you out!

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

      @@Algovibes Thank you for your response, I watched your video. I am trying to implement strategy similar to mean reversion strategy. My actual buying strategy is: df['Signal'] = np.where((df.Close < df.EMA144) & (df.RSI < 25), True, False)
      Main selling strategy is: while Close price < EMA144, sell when the Close price equals or larger than EMA144 but the problem is selling strategy overlaping(selling signals are bigger than buying signals) and I do not know how to implement while loop. How can I avoid overlaping signals? I tried this but the problem is overlaping:
      Buying_dates = []
      Selling_dates = []
      for i in range(len(df)):
      if df.Signal.iloc[i]:
      Buying_dates.append(df.iloc[i].name)
      for j in range(len(df)):
      if df['Close'].iloc[i] >= df['EMA144'].iloc[i]:
      Selling_dates.append(df.iloc[i].name)
      break

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

    Rather than checking for conditions of next Buydate, use the while loop so you can modify the looping variable on the go.

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

      Sounds reasonable. Anyhow: Can you elaborate?

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

    Amazing work dude! Thanks for share!!! 💪👌👍🍺