Backtesting Rayner Teos 3588% Stochastic Trading Strategy in Python

Поделиться
HTML-код
  • Опубликовано: 2 июн 2024
  • In this video we are testing the Stochastic Trading Strategy presented by Rayner Teo in Python applying it on different assets (Stocks, Cryptos, Forex)
    Get the Notebook/Source code by becoming a Tier-2 Channel member:
    / algovibes
    I already finished Backtesting all Russell 1000 stocks (over 1 million rows of data) and got some interesting results. Let me know if you want Part II by hitting the like button or leaving me a comment. What would also be quite interesting would be to test this in the live crypto market on different time intervals.
    Rayners video: • This Stochastic Tradin...
    Explaining stoch RSI K & D line here:
    • Highly Profitable Stoc...
    Be invited to check out more videos in my Python for Finance playlist and the cryptobot playlist and most importantly:
    Please subscribe if you want more of this content! Thx :-)
    Disclaimer: This video is not an investment advice and is for educational and entertainment purposes only!
    00:00 - 01:00 Introduction / Strategy / Disclaimer
    01:00 - 02:41 Libs/Pulling prices/ Indicators
    02:41 - 04:25 Buying conditions / Different scales!
    04:25 - 08:22 Step by step walkthrough Loop logic
    08:22 - 15:28 Code structure - Buying condition
    15:28 - 18:19 Code structure - Selling condition
    18:19 - 20:30 Checking output / Plotting the Strategy
    20:30 - 22:50 Profit calculation
    22:50 - 24:02 Did we win or lose (only HRB!)?
    24:02 - 25:50 Other assets (Cryptos, Forex) - quite surprising!
    25:50 - 26:50 Playaround with parameters
    26:50 - 18:59 Up next! 1000 stocks / Tradingbot?!
    #Python #Trading #Strategy #SMA #Stochastic

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

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

    Thanks for watching everyone!
    Yes, there are some simplifications regarding the buy limit order management. I was building this strategy with a more strict (and therefore more realistic approach) in another video. I was also avoiding looping using a vectorized approach. Check it out:
    ruclips.net/video/nAfnAuvRpqE/видео.html
    Cheers!

  • @bajnokkeresztes9549
    @bajnokkeresztes9549 Год назад +10

    Thank you for your videos. I started programming trading bots a year ago. In the last semester I made a 'simple' AI trading bot as my final thesis. I am happy that I had your videos along me on this long jouney.

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

      Thanks a lot Bajnok - that's awesome to read!
      Be invited to go more into details on your bot. Pretty sure a lot of people here would be interested in that as well (including me) :-)

  • @bryan-9742
    @bryan-9742 Год назад

    function logic /OOP version would be great to see. I spent two hours slowly working through this. Very helpful as usual!

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

    very excited for the next video coming up

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

      Awesome! Thanks for your support man.

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

    really interested in the implementation of this strategy for your next video! Looking forward to it!

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

      Just released. Excited what you think about it!

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

    Nice video, as always I have learn something new every video.

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

    You are the best man! Never stop these videos 🔥

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

      Never! :-) Thanks for your support man

  • @andycare
    @andycare Год назад +4

    Some thoughts, which might deterioate the performance:
    1. the survivorship bias should be considered, i.e. when backtesting a system like that on the current index constituents, it is usually rated too good, because the bad performing stocks had been removed from the index
    2. as a limit order already consumes margin, it is not possible to trade all 1000 of the Russell 1000 stocks. a sort of ranking will be needed (ATR works great on mean reversion systems)
    3. in live trading you do not know, which limit orders will be filled at the beginning of the day. In backtesting, when checking for Low

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

      Good points! Thx for sharing your thoughts Andreas.

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

    Love your videos. Keep them coming.
    From all the strategies that you tested until today what is the best (largest win rate and least drawdown)?
    May I suggest keeping a rank.

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

      It is not clear. This is the only video I have seen him get truly excited about the outcomes. I have tried many of the strategies and have not found one that is working yet. Will keep looking!

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

    Your code is more beautiful than the strat itself.

  • @sheps5656
    @sheps5656 Год назад +3

    This is great i'd love to see if this works on live markets like Crypto, FX, Indexes and on lower timeframes. Could be very interesting

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

      Thanks for your feedback man :-)

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

    Thank you for your code it is remarkable as usual. Looking forward for the bot version

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

      Thanks a lot Victor. Will surely come!

  • @polkobra5455
    @polkobra5455 Год назад +2

    Hey man, love the video. I have a question regarding one of you previous videos. For the python trading bot using sql it tells me that "" 'awai' outside function "". Do you know how I could fix that?

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

      Thanks a lot mate. Sure, I have shown it here:
      ruclips.net/video/nQkaJ207xYI/видео.html
      And in the pinned comment here:
      ruclips.net/video/rc_Y6rdBqXM/видео.html

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

      @@Algovibes Thanks!

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

    Wonderful content as always. Please run it on ran-time crypto market. I think we all want to see the result.

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

      Would be interested in that as well! Thanks for your feedback.

  • @TheBarneyG
    @TheBarneyG Год назад +2

    Hi dude, thank you for your work and expert tutorials. I have a small problem in that when i try to run the kernel i get the following error.
    NameError: name 'buydate' is not defined

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

      Very welcome man! Well you need to define the buydate somewhere. Where exactly are you running into this? (timestamp would be nice)

  • @peterfendrich9598
    @peterfendrich9598 Год назад +3

    I haven't run the code so maybe I missed something but I think there is a bug:
    When you break after k > 10 in the while loop, you have no buydate and
    the first thing that you test for after the the break is: if buydate > last_selldate without a buydate
    I'm not sure what you wan't to do in this case. Maybe skip buying?

    • @prashantdani8527
      @prashantdani8527 Год назад +2

      buydate local variable used before it is assigned error is there

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

      Yeah I didn't have time to cover that case anymore or it didn't come up during testing but this has to be covered indeed. That's happening because the Buy Limit order is not going through within the defined k. Just either stop the iteration or work with a try except here.

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

      Yes, I had this issue

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

    Great video ! I am wondering if instead of maximizing as backtesting.py does it is a way to minimize losses (tried pymoo but hell slow 😅)

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

      Thanks mate. Can you elaborate on what you tried or would be interested in? Didn't quite get it, sorry!

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

      @@Algovibes I was thinking about the broad concept of optimization. backtesting.py tries to maximize a given parameter, but sometimes (that's what I did with one of my bots) you have to clearly state that you want to maximize for example average profit while minimizing standard deviation, so a double objective optimization under constraint. I found pymoo package really useful.

  • @walduss7939
    @walduss7939 Год назад +3

    I am wondering if this could be implemented using backtesting.py library. Is it make sense to try? Or too much complicated?

    • @TheNotoriousPhD
      @TheNotoriousPhD Год назад +2

      I agree. But I am not sure if BT allows you to exit the position after 10 time periods in backtest.
      If we changed that condition to something like 'take_profit = 0.05', then BT would be a better choice.

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

      Interesting question and yes, that would be possible as well!

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

    please explain the code, how to code to reOrder_long when the price is bullish or trend up. I want first order 5% second order 20%, and so on

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

    Isn't there any python backtesting library out there that can handle more complex order types (buy limit, stop loss...) out of the box, other than the normal market order?

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

      There is. And I have covered a bunch of them both in introductory videos and in implementation of a more complex strategy. Just check out the Python for Finance playlist. Thanks :-)

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

      @@Algovibes so let's stay specific please, which libraries support these order types?

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

    I haven't watched everything yet, but what if the Buy conditions are met after the low price was set ? You place an order at a price that may never occur in the next candles.
    Usually when backtesting you avoid using conditions on data from the current candle, especially with the high / low that are impossible to time. In a live market you will probably have radically different results.
    On of the safest way to avoid this kind of information bias is to build an event driven backtester or use the existing open-source ones ;)

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

      The existing open source ones are VERY limiting. The fact that they are open source already says that there's also not a huge amount of money to be made with them either, or they would've never been put online for free. I looked through the top ones and pretty much came to the conclusing that the only way you can make a profitable one is to make one yourself tailored to your own strategies. If you can't trade profitable without a bot, chances are you're not gonna be profitable with one either.

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

      @@wickedgummybear3104 You're not wrong that open source means that you won't have the same level of control as you would have with a custom engine. I would also add that some of these project have a pretty steep learning curve and you might just as well start from scratch. But you'll need to put some hard work (and rework) on your backtesting engine to make it somewhat close to real market conditions (spread, fees, etc...).
      When you say that they wouldn't be put online for free if you could make money with it, it sounds weird to me because that's just the dynamic of open source. It's just a framework and weither you succeed or not is just a question of how you use it. There are thousands of open source projects which are allowing people and companies to save/make money, some of them even find a fair, stable business model

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

      First: I am your father!
      Second: The problem with the non filling Buy Limit Order is addressed in the video. Secondly please feel free to explore my channel. I have worked with a ton of Backtesting libraries already.
      These videos are made using as few libraries as possible and stay that way.

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

    Great video buddy!! Great content as ever. Just keep the good work going without any negativity affecting you. Request you to explain the .cumprod() with an example or give link of the video if ever you explained it. KUDOS 👍

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

      Thanks my friend! Sure. Explained return calculation here:
      ruclips.net/video/fWHQwqT3lNY/видео.html

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

    why do i get different output, when i use the same code and same symbol (eurusd, 2015-01-01) ?
    without adding buydate= pd.to_datetime("1900-01-01") if doesnt even work

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

    Thanks for your content.
    Could you give me an idea to make a bot for binance with dynamic stop loss? 😊

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

      Welcome mate,
      that could be helpful as I was playing around with trading stop loss here:
      ruclips.net/video/V6z1ME3-0_I/видео.html

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

    Thanks magister

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

      Thanks for watching mate

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

    Hey, can you upload the function version of the same code and upload it on the drive, and can you tell me how I can access the drive?

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

      Hi Aman,
      sorry did you already drop me a mail?

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

    hello, can you please tell me how to fix this error: " AttributeError: module 'ta' has no attribute 'tredn' "?

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

      I actually can: Just fix your typo :-)

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

    Have you made any videos for trading on pancake swap ? This would be very interesting

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

    so rainer use simple stoch? you use stochRSI?

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

    Sorry, even though I installed this package, it still gives this error
    ModuleNotFoundError: No module named 'yfinance', maybe I didn't install it correctly because I'm new, or I don't know how to install api, please help me

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

      If it doesn't find the module your current running python version is probably not added to your windows path..

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

      You need to install the module first :-) in Jupyter just type in: !pip install yfinance

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

    Hi Algovibes. Irgendwas stimmt mit den Loops nicht. Wenn ich folgendes eintrage: df = yf.download('HRB', start='2015-01-01') und den Python-Code mit einem frischen Kernel oder im Terminal ausführe erhalte ich die Fehlermeldung: NameError:"name 'buydate' is not defined. Did you mean: 'buydates'?". Woran kann das liegen?

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

      Ja, das musst du noch covern. Das passiert, wenn die Buy Limit order nicht durchgeht. Entweder du brichst den loop ab oder arbeitest mit try und except. Hatte ich keine Zeit mehr zu covern. Video war lang genug :D

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

    can you make videos on trading with leverage and Ichimoku indicator ?

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

      Hi Salem, thx for your suggestion. Will see what I can do!

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

      @@Algovibes Thank you so much my dear freind !!

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

    I do not understand the approach, why within the pandas data frame loop it is looked forward several times? I would take the orders and only look at whether the conditions are met or not and at most I would look backwards. This approach should be much simpler!?

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

      Hi Franky1, I have shown different approaches to match buying and selling signals and decided for a loop logic here. You can use vectorized methods, mapping methods,.... The sky is the limit. Be kindly invited to check out all my previous videos in both the Python for Finance and cryptobot playlist. You will find a lot of concepts there! Cheers

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

    For a second I thought that was you in the beginning of the video, a German/Asian, would have been surprising

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

      Will do face reveal at 100.000 subscribers (with a pinch of luck probably in the next 2-3 years)

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

    How Can I get such strategies or my strategy coded to trade automatically.

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

      I have a whole playlist on topics like that. Be invited to check that out! (Cryptobot playlist)

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

      Please let me know how can I buy this strategies from you to use for algo trading .

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

    Can I monitor live stocks using python ?

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

      Sure! Just need an API providing live stream of stock price data.

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

    Does it work by prediction or not?

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

      Can you elaborate on your question?

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

    How to apply this code in live market, pls make video on this...

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

      Just released the video. Looking forward to your thoughts on it!

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

      @@Algovibes Thanks bro 👍

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

    Thanks for your videos. I have sent the mail for the activation of the subscription code but I did not have an answer when you can see it, I would appreciate it.

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

      Added you! Thanks a ton for your support.

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

    lets run this on 1000

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

    Waiting for the bot

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

      Awesome. Will surely come!

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

    @algovibes you're not using the correct indicator as used by Rayner. He's using the "Stochastic" indicator, which is calculated based on the daily lows, highs and the most recent close. You're using the "Stochastic RSI' based on the close price only. These are NOT the same indicators.

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

      So it should be "ta.momentum.stoch" instead?

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

      @@franky12 yupp! And then first three parameters in order are high, low and close. Then window (set to 10).

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

      Thanks Andre, you are right! Played a bit around with that and ends up in better results. Will see that I update.
      Anyhow I also played a bit around with intraday crypto data and find this strategy (taking stoch_rsi) to be interesting to form into a Trading Bot (no investment advice).

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

    I haven't watched many of your videos but how do you and your community keep assessing strategies without using sharpe? Like for this video you have no idea what your risk adjusted returns vs buy and hold is. It's very, very naive to compare buy and hold to a strategy that gives 10 or even 5% of the returns. Do you take a strategy with 150% cagr but 90% drawdown vs a strategy that gives 50% cagr vs 11% drawdown? Of course not!

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

      You have everything what you need to calculate the risk adjusted returns - so what are you waiting for?
      If you want to have a Backtesting output solution containing all important metrics (SR, DD, ...) you can also use a Backtesting framework as I did in many of the previous videos. Be invited to check out all (don't skip a single one and don't skip a second in every video) videos in the Python for Finance playlist (and additionally the cryptobot playlist).

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

      @@Algovibes Thanks. I agree we have everything yes. Just surprised it wasn't part of your process here but as you say you have used Backtesting.py in your previous videos so it's not an issue. Thanks.

    • @bryan-9742
      @bryan-9742 Год назад

      @@Algovibes I'm painfully trying to makt this into a class and use the backtesting library lol.
      @xaknafein try this:
      profits = pd.DataFrame([(sell - buy)/buy for sell, buy in zip(sells,buys)])
      profit_vol = profits.std()
      profit_mean = profits.mean()
      sharpe = profit_mean/profit_vol
      # Vectors for cumulative Product and buy_Hold
      cumprod = (1 + profits).cumprod()
      buy_hold = (df.Close.pct_change() + 1).cumprod()
      #Cumulative Return Values
      cumprod.iloc[-1].values
      buy_hold[-1]
      algo_results = {"Results": "Reyner Teos Stochastic Model", 'Average Return': profit_mean,
      'Volatility' : profit_vol, "Sharpe": sharpe, "Cumulative Return": cumprod.iloc[-1].values,
      'Buy & Hold Return': buy_hold[-1]}
      results_RSI_BNB = pd.DataFrame(algo_results).T

  • @engenglish610
    @engenglish610 Год назад +2

    Please don't spend your time with these strategies, we all know that are bullish.
    The best idea is to detect liquidity (volume) in short time frame👍, please make us a video about this in Binance 🙏.
    Thank you for your channel 😎

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

      He's not wasting time. There are alot of concepts/knowlegde in these video's that are helpful to alot of people. If you clicked on any of these video's hoping to find a 'get rich quick bot' then you're in the wrong place anyway.

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

      Don't worry about my time guys. If you REALLY do consider becoming a channel member as time is money ;-)
      What I am doing on the channel is what I consider to be interesting.

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

    Bro accidentally found a billion dollar forex strategy

  • @freddurst4420
    @freddurst4420 Год назад +2

    you scroll and rush through the results too fast! i mean , its like the most important part of the video.

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

      Thanks for the feedback Fred. Just pause the video if anything is going to fast or play the video at a lower speed.

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

    3588% ? 😅 It seems absurd

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

      Was just quoting Rayner 😛 And to be fair it is over 22 years.

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

    cheater

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

    When I try to run the code on the line:
    if buyprice>=df.iloc[row+k].Low:
    I get an error:
    single positional indexer is out-of-bounds
    Is this a typo on my end somewhere?

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

      If I add some if's to prevent the Index Error the profits data at 23:22 looks the same, but if I change the ticker or the start date it differs from what you have. For example if I change the date like you did for the table at 24:02, the numbers become different. Did you change some additional settings in between these runs or is there a typo or something in the code that I use?

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

      i suppose he will not answer to an old video.
      here here. had the same indexer-errors. and when using BTC-USD from 2015-01-01 i get different results... strange