No video

Backtesting Rayner Teos 88.89% winning rate Trading strategy in Python

  Рет қаралды 50,354

Algovibes

Algovibes

Күн бұрын

Пікірлер: 183
@Algovibes
@Algovibes 3 жыл бұрын
PLEASE READ THIS (Edited 26.07.2021): I made an updated version amending and complementing some stuff here: kzbin.info/www/bejne/qIrJlmx4nJd6mbs Also: There is a mistake in the for loop at around 24:10. Thank you so much to Lewis Wong for letting me know! The corrected syntax would be: PnL = [] for i in range(len(df) - 12): if "Yes" in df['Buy'].iloc[i]: for j in range(1,11): if df['RSI'].iloc[i + j] > 40: PnL.append(df['Open'].iloc[i+j+1] - df['Open'].iloc[i+1]) break elif j == 10: PnL.append(df['Open'].iloc[i+j+1] - df['Open'].iloc[i+1]) I apologize for any inconvenience arising due to that!
@StevenWernerCS
@StevenWernerCS 3 жыл бұрын
with this change, i get a win ratio of 0.9594594594594594 and a total sum of PnL as 1414.8587036132812 buying at the first Buy and selling on the last would get you nearly double that: df['Open'].iloc[len(df) - 12] - df['Open'].iloc[1] 2751.1499633789062 (buying every 2 weeks also outperforms bucketing and buying at the 'Buy') edit: thanks for the video, it was very informative, great job
@QuanttradingVega
@QuanttradingVega 3 жыл бұрын
@@StevenWernerCS hello mate , after backtesting did you take this strategy in live markets.?
@toprandomvideos2123
@toprandomvideos2123 2 жыл бұрын
I watched your other video and this worked now. I really appreciate these videos. Depending on the overreliance on that pull type from wikipedia, I just want to let you know that you will have extreme upwards skew in your results if you are including companies using a start date prior to their incorporation into the S&P 500 due to how the index components are selected. In effect you have not just a survivorship sampling bias but an outperformance sampling bias. This is because you are selecting samples from when they were smaller and higher risk companies but the outcome of the data selected is inherently slanted to guarantee that they will be *at least* good enough to become S&P 500 companies. That is a level that the vast majority of traded companies never reach the status of and it isnt really practically possible to know which companies will grow to that level early. To avoid this sampling issue you would at a minimum need to pull from an origination date accurate to each components incorporation date. That likely wouldnt be a perfect normalization of the sample depending on what is being tested, just a significant component. If you were to try to do much more statistically significant long term data sets it could get fairly complicated because the exact time series of adding/removing components throughout the S&P 500 history arent uniformly available complete with start/end dates in an easy to use format at the moment (at least that I'm aware of). It would be cool to see how you would address that problem efficiently or apply this sort of process to futures contracts or options because the way to pull those databases is significantly more complicated itself than getting the current S&P 500 components too. Btw is there a simple way to export something as a CSV from Jupyter (cloud binder)? It would also be cool to learn about more data visualization methods with these tools because it can be difficult to really examine the data in direct text matrixes especially as the size increases. Keep up the videos!
@FireFly969
@FireFly969 2 жыл бұрын
I love the way that you understand and know how to put the ideas into code I really want to get your level Thanks for this great content
@Algovibes
@Algovibes 2 жыл бұрын
Thank you for your kind words my friend. BTW I got a more updated video on this topic: kzbin.info/www/bejne/qIrJlmx4nJd6mbs
@ThinAirElon
@ThinAirElon Жыл бұрын
even i feel the same ...became fan from last 24 hrs
@beachbumis
@beachbumis 2 жыл бұрын
Fantastic Python content. No idea why this came up while searching for Bayes Theorem but glad it did. Something to note is that assuming a single share is traded the profit would be 490.54 but if you bought on 10/15/96 (your first day) and sold on 10/30/20 (your last day) profit would be 2567.38 (not including dividends). Just reporting a win ratio without summing the transactions and comparing it to a benchmark isn't helpful in measuring success. Going to watch your updated video now. Thank you for the great content!
@Algovibes
@Algovibes 2 жыл бұрын
Thanks a lot for your comment! :-) Also good point!
@DarrylHebbes
@DarrylHebbes 3 жыл бұрын
This is just what I needed, busy learning to backtest strategies and this helps me to sketch out ideas with Python. Thanks so much.
@DarrylHebbes
@DarrylHebbes 3 жыл бұрын
I hear an accent, if German then Dankeschön
@Algovibes
@Algovibes 3 жыл бұрын
Thank you very much for watching and your kind words. I really appreciate it. Yes it is a german accent. Working on it :-P
@DarrylHebbes
@DarrylHebbes 3 жыл бұрын
@@Algovibes Ahh, dein Englisch ist sehr gut... Dankeschön trotzdem
@NZspearoCJ
@NZspearoCJ 2 жыл бұрын
Thats a very interesting perspective, bear in mind though that your losses could be much higher in value, therefore, if you win 10 trades at an average of 50pips, but lost 5 with an average of 100pips, while this strategy may seem awesome, in actual fact, it will draw your account massively since there is no risk management applied. Just a thought to consider :) Thanks for sharing.:)
@Algovibes
@Algovibes 2 жыл бұрын
Hi mate, thanks a lot for your comment and there is nothing I don't agree on! I was going a bit more into details on how this strategy is actually performing when cancelling out trades etc. Be kindly invited to let me know what you think: kzbin.info/www/bejne/qIrJlmx4nJd6mbs
@domorewithsage
@domorewithsage 2 жыл бұрын
Win rate is irrelevant if the risk to reward is off. Your example shows the last two losses totally eclipsing all the previous wins. You need to plot the equity curve.
@Algovibes
@Algovibes 2 жыл бұрын
Good comment! But anyhow this is just a technical implementation of backtesting the claimed winning rate. BTW I made Part II here - would be interested in your thoughts: kzbin.info/www/bejne/qIrJlmx4nJd6mbs
@riccardoronco627
@riccardoronco627 2 жыл бұрын
indeed - what is required is a "catastrophic loss" rule: go flat if CLOSE < 200-day sma
@sherlock27
@sherlock27 3 жыл бұрын
Your explanation is superb! Thanks a lot mate
@Algovibes
@Algovibes 3 жыл бұрын
Thank YOU for watching :-) I have a lot of other stuff regarding programming and trading on my channel. Be kindly invited to have a look.
@TheRons200
@TheRons200 3 жыл бұрын
You've explained it splendidly .
@Algovibes
@Algovibes 3 жыл бұрын
Thanks for watching and thank you very much for your appreciative words :-)
@russnagel1
@russnagel1 3 жыл бұрын
I have watched a few of your videos this morning. ABSOLUTELY FANTASTIC content! I will begin studying your videos today because this is exactly what I want to learn. Writing a program to backtest a strategy is, in my opinion, the only reliable way to determine trading results. Thank You. Keep up the good work. Like and subscribed.
@Algovibes
@Algovibes 3 жыл бұрын
Thank you so much ☺️ Really appreciate it and that is a huge help for me.
@smitkumarsuryawanshi3608
@smitkumarsuryawanshi3608 3 жыл бұрын
Awesome, I am working on Indian market. Your videos are very helpful to me. Thank you so much
@Algovibes
@Algovibes 3 жыл бұрын
Nice, appreciate your comment :-) Let me know what you think about the momentum video in the Indian stock market: kzbin.info/www/bejne/j3rWfIaHnZarprs
@nsaikrishna
@nsaikrishna 2 жыл бұрын
In your PnL calc, you use a for loop with j in 1:10. Under it, there is an if for RSI > 40 and another one for RSI < 40. I believe the second one should be j=10 as right now your code will go through the first iteration of j and execute one of the if conditions
@Algovibes
@Algovibes 2 жыл бұрын
Did you check the pinned comment?
@riccardoronco627
@riccardoronco627 2 жыл бұрын
you can write the RSI as (avg up / (avg up + avg down)) *100 .... to simplify
@Algovibes
@Algovibes Жыл бұрын
Thanks for sharing Riccardo!
@cihanulas5438
@cihanulas5438 2 жыл бұрын
Thanks for sharing this but you should calculate the average profit as Cj Natan said. Also it would be best to add sharpe ratio and maximum drawdown measurements. Also the commisions needs to be added as well.
@Algovibes
@Algovibes 2 жыл бұрын
Hi buddy, thanks a lot for your comment! Please check out the newer version of this and let me know what you think: kzbin.info/www/bejne/qIrJlmx4nJd6mbs
@akshitvashishth5481
@akshitvashishth5481 3 жыл бұрын
Amazing work! You are really fluent while explaining the code and your videos have given the right framework to backtest more complex strategies as well. I see how humbly you reach out to every comment. All the best man!
@Algovibes
@Algovibes 3 жыл бұрын
Thanks a lot for your kind comment. Appreciate your feedback! Yes I am trying to react to every comment - even to the not so nice ones 😛
@FRANKWHITE1996
@FRANKWHITE1996 3 жыл бұрын
Great! Thanks for this video. Appreciated!!!
@Algovibes
@Algovibes 3 жыл бұрын
Appreciate your comment. Thanks a lot :-)
@jeevankumarreddyravuru3346
@jeevankumarreddyravuru3346 2 жыл бұрын
Great Content✌
@Algovibes
@Algovibes Жыл бұрын
Thanks buddy :-)
@okculartepesi31
@okculartepesi31 3 жыл бұрын
you have %88 winrate but your net profit is negative :) cool story mate
@Algovibes
@Algovibes 3 жыл бұрын
Thank you very much for watching and your comment. Main objective of this video is to backtest the claimed winning rate with Python. Net Profit might be negative - I trust your claim, didn't check that. I didn't mean to tell a story but I can understand that you are disappointed with the net profit. My videos are meant to give some ideas for potential trading strategies and construct them in Python. In reality it is a lot more about e.g. in which market phases these strategies can be applied and a lot more factors which can be relevant. Nevertheless: The RSI in combination with SMA can be a very good choice! Or in other words: Momentum strategies are still working out well. I extended the RSI strategy to all S&P stocks. Might be interesting for you as well. Be kindly invited to check that out and let me know what you think! Your feedback is highly appreciated! kzbin.info/www/bejne/pnObln2tnJx_gLc
@Algovibes
@Algovibes 3 жыл бұрын
@Ramzataz Very valuable and true comment. This video is not presenting an end-to-end trading strategy but is just showing the technical implementation of a backtest and how I would handle it with Python. Of course there are several adjustments to be made e.g. risk management.
@Day1kingfx
@Day1kingfx Жыл бұрын
That’s true also vibes, I’m guessing you should do a video on that, putting risk management into consideration. May a 2 to 1 and see how it goes.
@TheChievovr
@TheChievovr 2 жыл бұрын
You will gain only if the probability to choose the winning buy is > sl / (tp + sl)
@Algovibes
@Algovibes 2 жыл бұрын
DIdn't test that but that would be indeed interesting to check out. Thanks for sharing!
@TheChievovr
@TheChievovr 2 жыл бұрын
@@Algovibes the gain is pw x tp - (1 - pw) x sl where pw is probability to win. So if you put that expression > 0 (gain positive) you get that you win if pw > sl / (tp + sl).
@RafeedChowdhury
@RafeedChowdhury 3 жыл бұрын
this strategy is great to look at but when you see that out of 6000 trading days only 75 calls were made in this strategy out of 24 years. so each year you would expect only 3 trade signals. Anyway good video, I would be happy if you could make some backtesting of other strategies as well with more frequency of trading opportunity.
@Algovibes
@Algovibes 3 жыл бұрын
Thanks for your feedback mate. I totally agree with you. That is a disadvantage of this strategy at least considering the S&P500. I will release a video in the upcoming weeks where I am testing that strategy on a large amount of assets and let's see how many signals we are getting (have not tested it yet tho). Best regards and thanks for watching.
@RafeedChowdhury
@RafeedChowdhury 3 жыл бұрын
@@Algovibes waiting for the next one then! ;)
@hijack80
@hijack80 3 жыл бұрын
Tried this method from 1997 january to today and I got 95.6% (i may have done something wrong here haha) Cheers for the really well explained video! I was wondering could the same strategy be applied to a portfolio consisting of stocks?
@Algovibes
@Algovibes 3 жыл бұрын
Hi mate, thanks for watching :-) Yes the winning rate is incredible but also the number of trades is just way too small. Yes you can do that! I just released a video doing exactly that on all 500 S&P stocks. Be kindly invited to check that out. kzbin.info/www/bejne/pnObln2tnJx_gLc
@stefanoroveda6581
@stefanoroveda6581 2 жыл бұрын
I wanted to calculate the wilder method directly instead of using that escamotage of changin N. That would be N = 10 alpha = (1/N) df['avg Up'] = df['Upmove'].apply(lambda x: alpha * x) #this line is only for initializing the column df['avg Up'] = df['Upmove']*(alpha) + df['avg Up'].shift() * (1 - alpha) I chose to write it like this because in applying a lambda function it would not like x.shify(). It gives me that x is a float that does not support shift and I could not solve. Anyways, using this calculation lead me to different values of avg Up and Avg Down. Can anybody explain this to me?
@Skandawin78
@Skandawin78 2 жыл бұрын
Brilliant explanation
@Algovibes
@Algovibes 2 жыл бұрын
Thank you mate. Be kindly invited to check out the second part and let me know what you think. I made some amendments here and there: kzbin.info/www/bejne/qIrJlmx4nJd6mbs
@Skandawin78
@Skandawin78 2 жыл бұрын
@@Algovibes sure
@DarrylHebbes
@DarrylHebbes 3 жыл бұрын
perfect explanation of the Wilders formula alpha
@Algovibes
@Algovibes 3 жыл бұрын
Glad it was helpful. I appreciate your comment. Thanks a lot :-)
@DanielLeachTen
@DanielLeachTen 3 жыл бұрын
Great video, thank you!
@Algovibes
@Algovibes 3 жыл бұрын
Thanks a lot for watching and your kind comment. Appreciate it :)
@YoMoodiefoodie
@YoMoodiefoodie 3 жыл бұрын
All of your video are very awesome and amazing However if you start putting your complete raw code also in description to download would be helpful
@Algovibes
@Algovibes 3 жыл бұрын
Hi buddy, thanks a lot for your kind words :-) Will provide code access probably within this year.
@tirtha9
@tirtha9 3 жыл бұрын
this is gold. great content, I wish you great suceess.
@Algovibes
@Algovibes 3 жыл бұрын
Phenomenal to hear! :-) Thanks a lot for your kind words my friend.
@tirtha9
@tirtha9 3 жыл бұрын
@@Algovibes I just came to write another comment. First of all this video is a superb basic approach without much effort to find the win rate, after our idea generation phase. But can you also create tutorial on Backtrader, this framework looks good. need help on the OOPs way of creating the strategy classes in backtrader
@Algovibes
@Algovibes 3 жыл бұрын
Hi :-) Backtrader sounds very interesting. I will definitely have a look. Thanks for sharing! I have some other videos planned on my schedule, but I will keep it in mind :-)
@mr.gk5
@mr.gk5 2 жыл бұрын
Very helpful video, sub!
@Algovibes
@Algovibes 2 жыл бұрын
Awesome man, thanks a lot for your sub :-) Be invited to check out the 2nd part: kzbin.info/www/bejne/qIrJlmx4nJd6mbs
@markk4203
@markk4203 3 жыл бұрын
Thanks for doing the video! I'm trying to learn Python and apply it to my trading so this was very educational. I have one question to ask. I've heard it said that loops in Python are slow. Is there a more array-based way of coding this that could replace the loop(s)?
@Algovibes
@Algovibes 3 жыл бұрын
Thanks for your comment! :-) You heard it right! The solution to that is vectorization. I am using that as well in my videos but in some cases I am keeping a loop structure (e.g. if there are a lot of side conditions).
@markk4203
@markk4203 3 жыл бұрын
@@Algovibes I'm going to watch more of your videos, but can you give me an example of how vectorization can replace a loop?
@markk4203
@markk4203 3 жыл бұрын
@Algovibes *bump*
@Algovibes
@Algovibes 3 жыл бұрын
@@markk4203 Haha :D it's impossible to react to every comment that fast and I am not getting notifications on comments of comments. Just check out the newest on SMAs. I already did one on SMA and didn't use a vectorized approach but in the newest one I did. Instead of checking every single row I am multiplying the whole column/vector with another or a scalar.
@HitAndMissLab
@HitAndMissLab 2 жыл бұрын
You have to apply stops. Video is completely meaningless with losses -406 pips etc. In real life one would put a stop on that. If you were less mathematical guy you would understand after watching just one video that Rayner Teo is a just a salesman selling trading courses and that he doesn't have a clue about trading and he doesn't care if his viewers make or loose money. Anyway, good video, keep doing it.
@Algovibes
@Algovibes 2 жыл бұрын
First one is a really good point! I like the sentence "if you were less mathematical guy" :D It's quite funny: I was accused of many things below this video but this one is something where I feel appreciated. BTW thanks for your kind words :-)
@Aservy
@Aservy 2 жыл бұрын
Wrong implementation of the exit condition, all the trades are exited right away; either 1st following day has a RSI > 40, which is intended behaviour, or the trade gets exited by the +10 day condition. Also, first trade entry is incorrect, since it comes from unsanitized data (the first few rows will either have the avg Up or avg Down being 0, in this case only the first row with avg Up; this triggers an unintended entry signal) Redoing the exact same implementation but with the corrected mistakes yields 73 trades with a winrate of 95.89% over that same time period. (3 losses, 70 wins)
@Algovibes
@Algovibes 2 жыл бұрын
Hi man, thanks for your comment. Did you check the pinned comment? Also please check the updated version here: kzbin.info/www/bejne/qIrJlmx4nJd6mbs
@Aservy
@Aservy 2 жыл бұрын
@@Algovibes I did not, and the next day YT suggested your updated version to me 😂 Beside that it was a great video tho!
@emilfischer1990
@emilfischer1990 2 жыл бұрын
The piece I find is missing (please let me know if it is in the video): The strategy really needs to be benchmarked against another strategy to prove whether it is good or not. I would benchmark to a completely random strategy. The market has a general up-trend so I would expect a random strategy to actually also have >50% winning rate. The question is: would it have the same winning rate or much lower or just little lower?
@Algovibes
@Algovibes 2 жыл бұрын
Good point! Nope I didn't do that here. I have a second part (but didn't benchmark here as well) if you are interested: kzbin.info/www/bejne/qIrJlmx4nJd6mbs
@gondalaprasad
@gondalaprasad 3 жыл бұрын
Can u please suggest how to add exit column that, when the exit was came.? And highly appreciated for such a superb video...
@Algovibes
@Algovibes 3 жыл бұрын
Thank you very much for your kind comment :-) You can use a loc function in the loop assigning a new column containing the Sell signal. Btw the loop is not 100% correct as I have noted in the comments. You can also check out this one: kzbin.info/www/bejne/pnObln2tnJx_gLc Please let me know if you need any more support with that. Some people where already asking for this. I will cover that at least in one of my upcoming vids or in a pinned comment on the other video. Best regards
@gondalaprasad
@gondalaprasad 3 жыл бұрын
@@Algovibes Thanks for the RSI video, I have seen the vid. Just I have a query. I have modified little bit to this code as this will save df to a xl file. I want to give a list of stocks so that, for all stocks the xl files should be saved.. Preseent I hv kept symbol as input. I hv seen in RSI video it is implimented by you, but no luck in my case.. If there is any mail ID, I can send my code. Thx.
@BoazPlants
@BoazPlants 2 жыл бұрын
But what is the risk to reward?, you can have a high win rate but the risk to reward is low that you still losing money
@Algovibes
@Algovibes 2 жыл бұрын
Good point!
@leosiemens9202
@leosiemens9202 2 жыл бұрын
Nice work backtesting, but the strategy is trash, it won't work in bearish market, it's a 100% drawdown in a long term. S&P500 was bullish for more than 20 years now. Try backtesting some stock or something that has different long term market conditions and you'll see how bad it is
@Algovibes
@Algovibes 2 жыл бұрын
I love that you got that this strategy is not mine but I just backtested it. Thanks :D BTW: I tested a bunch of stocks here: kzbin.info/www/bejne/pnObln2tnJx_gLc and also I made a second part here where I am getting rid of overlaying positions: kzbin.info/www/bejne/qIrJlmx4nJd6mbs Would love to hear your thoughts!
@KONDORPA
@KONDORPA 3 жыл бұрын
Problem here is average loss is way more than profit. No matter what, if RR is 3:1, you need around 80% winning rate just to break even.
@Algovibes
@Algovibes 3 жыл бұрын
Hi buddy, thanks for watching. Please watch the updated version: kzbin.info/www/bejne/qIrJlmx4nJd6mbs
@marouceril6352
@marouceril6352 2 жыл бұрын
Very interesting
@Algovibes
@Algovibes 2 жыл бұрын
Thank you mate. Be kindly invited to check out the second part: kzbin.info/www/bejne/qIrJlmx4nJd6mbs and let me know what you think :-)
@khtan5531
@khtan5531 2 жыл бұрын
So the Rayner Teo’s strategy is legit since you managed to backtest with some decent results ? What is your take ?
@Algovibes
@Algovibes 2 жыл бұрын
Getting more into details in this one here: kzbin.info/www/bejne/qIrJlmx4nJd6mbs If you are cancelling out the overlapping trades it seems to be a decent strategy. My take on this is: I think it is a good orientation but I would probably not trade this indicator pair.
@pakmediareaction3451
@pakmediareaction3451 2 жыл бұрын
I have no concept of python and in data science,can you suggest me what shall i do to take my self to this type of coding. By the way i have complete knowledge of market
@Algovibes
@Algovibes 2 жыл бұрын
Sure. I talked about how I learned Python here: kzbin.info/www/bejne/p3S9mniEi51mqKc Also I have two playlists which might be helpful for you: Python Introduction Python for Finance
@pakmediareaction3451
@pakmediareaction3451 2 жыл бұрын
@@Algovibes thanks a lot my friend
@TurboDank420
@TurboDank420 3 жыл бұрын
If the day after buying, the RSI is below 40 then won't mark the sale as after 10 trading days no matter what the RSI is on any of the consequent days? That is to say that the inner for loop will mostly break early?
@Algovibes
@Algovibes 3 жыл бұрын
Good observation! I already corrected that in the pinned comment. Be invited to check out Part II btw. I made some more improvements here and there.
@TurboDank420
@TurboDank420 3 жыл бұрын
@@Algovibes Oh I didn’t spot the pinned comment, my bad! Thanks for the great video. I’ll be checking out part II for sure!
@alessandroramalli5355
@alessandroramalli5355 3 жыл бұрын
Would you backtest this strategy on other markets? I think it's pointless to backtest it on a market that has been mostly in an uptrend.
@Algovibes
@Algovibes 3 жыл бұрын
Sure. Would be very interesting! But let me add that we are covering a time horizon where the S&P had very bad times. I also tested this strategy on single stocks. Be kindly invited to check that out and let me know what you think! kzbin.info/www/bejne/pnObln2tnJx_gLc Nevertheless I somehow disagree with your statement that this strategy is pointless in a mostly uptrend market. Maybe I am getting your wrong, so can you explain that in more detail please? I am always happy to discuss!
@alessandroramalli5355
@alessandroramalli5355 3 жыл бұрын
@@Algovibes I said it was pointless to backtest it that way. Try it on the FTSE MIB for example. It was meeting the uptrend requirements back in 1996.
@ritobrotoseth7828
@ritobrotoseth7828 3 жыл бұрын
Rayner's algo says: "You should sell after 10 trading days if the RSI does not move above 40 within those next 10 days". But you are not doing that, when the first condition is false that is when RSI is below 40 on the (i+1) day, you are appending the value to the PnL list and exiting the jth inner loop. So technically you are always existing the jth loop after the first iteration which shouldn't be the case you need to check for the next 10 days. Correct me my understanding is wrong.
@Algovibes
@Algovibes 3 жыл бұрын
Thank you very much for your comment. Did you check my pinned comment? :-P
@ritobrotoseth7828
@ritobrotoseth7828 3 жыл бұрын
@@Algovibes LOL!! I missed that one, thanks for clearing my doubt. Cheers!!!
@tohando
@tohando 3 жыл бұрын
Is it correct, to set the buy flag on the same day the condition is met? I think the "yes" flag must be set on the following day, since you use the close price of the same day in your technical indicators.
@Algovibes
@Algovibes 3 жыл бұрын
Thank you very much for watching and your comment. Let me explain why I would disagree with your suggestion: As I am buying on the next days Open (I am doing that in the for loop at around minute 23:00 by setting df[Open].iloc[i+1] with the +1 indicating that I want to buy on the next days date) I or my trading algorithm knows on the subsequent day if the close price on the prior day was above or below the 200 day MA. In general I definitely agree with you that if I would need to make a same day decision it wouldn't make sense to take the same day's close price. Also: If the same day flag is not intuitive for you, you could set the flag on the next day. I am just using that as a reference point to get the price where I am buying and selling in the loop. But if you do that you have to consider that the loop structure would be slightly different (e.g. not adding +1 to your loop). Does this make sense to you or did I get your wrong? Best regards
@tohando
@tohando 3 жыл бұрын
@@Algovibes Thanks! yes make sense now!
@ericanderson7570
@ericanderson7570 3 жыл бұрын
I watched this and saw the sell bug (that's been addressed in comments) immediately. What bothered me the most is the lack of intellectual curiosity about why the discrepancy occurred. OP was just like "oh well". But the bug in the sell logic isn't the only bug. I duplicated this test and fixed BOTH bugs. I thought it would be a good exercise for my first Python code ever. 1) As addressed, sell logic selling on day 11 IF the first hold day was below 30. 2) NOT ADDRESSED: If we buy then we can't buy again for the duration of the hold. The algorithm as written "overlaps" holding periods. If the criteria are met, it buys on DAY 1 and then projects a sell X days later, but then buys again on DAY 2, which would be inside the first holding period, when no more capital is available. The solution is to jump ahead in the i loop to the day after the sell. I addressed both of these, and used data from 1996 (not 1969 as mentioned incorrectly in the vid) through June 2021. The win rate jumps to 96% with both bugs fixed and the added months of data. Great, right? Not really. The return? 262% Or ~3.93% Annualized. Buying and holding the S&P500 in 1996 would have resulted in 7+% annualized. Win rates are high but win returns are low. Not surprising as this approach only resulted in 75 opportunities over 25 years (3 / yr).
@Algovibes
@Algovibes 3 жыл бұрын
oh well... jokes aside: Thanks for your comment! Appreciate sharing your thoughts. I am accounting for open positions in most of my videos where I am applying strategies in real trading. In this case I am keeping them in which is also a possible approach btw but I definitely agree to exclude them making for sense! Anyhow I didn't mean to bother you with my lack of intellectual curiosity😄
@PRADEEPKUMAR2772
@PRADEEPKUMAR2772 2 жыл бұрын
Hi , I'm getting error on "line 64, in PnL.append(data['Open'].iloc[i+12] - data('Open').iloc[i+1])" TypeError: 'DataFrame' object is not callable
@Algovibes
@Algovibes 2 жыл бұрын
Most probably because of the wrong parantheses. Should be ['Open'] instead of ('Open').
@PRADEEPKUMAR2772
@PRADEEPKUMAR2772 2 жыл бұрын
@@Algovibes i figured it out , btw thanks a lot for your help 🙂
@davidrwolkoff
@davidrwolkoff 3 жыл бұрын
How do you add the PnL [] loop to your df as a column? I keep getting an error that the length of values does not match the index length when I try....any tips?
@Algovibes
@Algovibes 3 жыл бұрын
Hi David, thank you very much for watching. Please check out the video 'How to build a RSI strategy'. Link: kzbin.info/www/bejne/pnObln2tnJx_gLc Then do the following: Use the .loc function and screen for the buying dates as the row and create a PnL column with that. Check out this video for conditional column creation using .loc in the very end of the video: kzbin.info/www/bejne/npfZn2xvn7lkY7s With that you can add rows with the PnL out of every trade. Every other rows will have NaN values. This would be my approach to do so. Is that helpful for you? In case you need any support with that please let me know!
@9713QPMZ
@9713QPMZ 3 жыл бұрын
In the for loop section - for j in range(1,11) the loop seems to me that will break very soon when j = 1 anyway, the only exception is when rsi =40, which is very unlikely to happen. Am i wrong about how the for loop is going?
@Algovibes
@Algovibes 3 жыл бұрын
Hi mate, first of all great to have you on my channel :-) The inner loop (for j in range(1,11) has to break once the RSI is above 40 in the first condition, as we want to immediately sell on the next days open if this is happening. So after we have appended that profit we are breaking the loop. If the RSI is never above 40 within the next 10 days (which are the 10 iterations 1-11 in the loop) the loop has to break in the second if statement once the profit from after 10 days is appended (otherwise it would be appended multiple times). If it is more comfortable for you, instead of using the second (within the inner loop) if statement you could also just use an else statement to cover the case when the RSI is exactly 40. But as you already mentioned this is such an unlikely case that I disregarded that. Syntax: PnL = [] for i in range(len(df) - 12): if "Yes" in df['Buy'].iloc[i]: for j in range(1,11): if df['RSI'].iloc[i + j] > 40: PnL.append(df['Open'].iloc[i+j+1] - df['Open'].iloc[i+1]) break else: PnL.append(df['Open'].iloc[i+12] - df['Open'].iloc[i+1]) break I hope I could help you out with this comment. In case you have any additional questions or suggestions please let me know!
@9713QPMZ
@9713QPMZ 3 жыл бұрын
Thank you for your reply. But i do think you are not looping through the next 10days. As your condition is fulfilled when i =1 no matter what, I believe you should have something like: PnL = [] for i in range(len(df) - 12): if "Yes" in df['Buy'].iloc[i]: for j in range(1,11): if df['RSI'].iloc[i + j] > 40: PnL.append(df['Open'].iloc[i+j+1] - df['Open'].iloc[i+1]) break if j==11: PnL.append(df['Open'].iloc[i+12] - df['Open'].iloc[i+1]) break Which i changed the second condition to "if j==11".
@Algovibes
@Algovibes 3 жыл бұрын
I just invested some time reviewing my code and yes! You are absolutely right. Thank you so much for the incredible valuable remark. I will leave a comment for other viewers with the corrected code or might even reupload the corrected version (I am also not satisfied with the sound quality so this might be the best solution). Nevertheless I made some final amendments to your suggested code. The correct code would be: PnL = [] for i in range(len(df) - 12): if "Yes" in df['Buy'].iloc[i]: for j in range(1,11): if df['RSI'].iloc[i + j] > 40: PnL.append(df['Open'].iloc[i+j+1] - df['Open'].iloc[i+1]) break elif j == 10: PnL.append(df['Open'].iloc[i+j+1] - df['Open'].iloc[i+1]) Be kindly invited to check it out. Again thank you very much for your contribution! Best regards
@chapmansbg
@chapmansbg 2 жыл бұрын
Good work! But what is a walyoo?
@Algovibes
@Algovibes 2 жыл бұрын
:D :D great comment! Had a good laugh. Be invited to give me feedback if I improved my pronunciation in the newer videos please! I am actually really interested in that.
@chapmansbg
@chapmansbg 2 жыл бұрын
@@Algovibes of course I was just teasing you about your pronunciation, great vids. I have subscribed and hit the alert button.
@chapmansbg
@chapmansbg 2 жыл бұрын
@@Algovibes I am guessing that you are German?
@koz.b1741
@koz.b1741 3 жыл бұрын
if this can scan for signals in a bunch of assets, would be just great
@Algovibes
@Algovibes 3 жыл бұрын
Yes mate, that will be one of my next videos by the way :-P Thanks for watching! :-)
@koz.b1741
@koz.b1741 3 жыл бұрын
@@Algovibes great news! Thank you for the reply and the great content.
@varioustopics
@varioustopics 3 жыл бұрын
Nice work
@Algovibes
@Algovibes 3 жыл бұрын
Thanks 😊 very happy you like it.
@matthewrenegar6559
@matthewrenegar6559 3 жыл бұрын
Try installing pandas ta as ta. You can do a lot of the analysis a lot quicker df['SMA 200] = df.ta.sma(200) df['rsi'] = df.ta.rsi()
@Algovibes
@Algovibes 2 жыл бұрын
Please check the newest version of the video: kzbin.info/www/bejne/qIrJlmx4nJd6mbs
@SarthakGarg
@SarthakGarg 3 жыл бұрын
Hii brother - How can I connect with you? I am interested in learning ML and AI for finance but I am confused how to go about it. Need some career guidance as well. Thanks in advance
@Algovibes
@Algovibes 3 жыл бұрын
Hi mate, thanks a lot for watching and your request. Unfortunately I don't have any contact information publicly available. I will refresh the information in the upcoming weeks. Until then I am kindly asking for your patience. In general I would try to get practical experience. I did a lot of internships in various finance fields during my graduation. Additionally you need some projects. In the best case you are not just taking a suggested project but a project which is individual and what you are really passionate about. You can check out my video on how to learn Data Science / Math required for Data Science. These skills are also in high demand in finance. Time series analysis might be by far the most important skill. Understanding different volatility topics (e.g. ARCH, GARCH) would be helpful as well. Could this help you out any further? Best regards
@SarthakGarg
@SarthakGarg 3 жыл бұрын
@@Algovibes Yes.. I have also started to build some momentum strategy as suggested by you in the earlier video.. I have done some courses on Udemy with did covered Time series analysis. But I wanted to know more. Let's see if I can get some sort of internship.
@iamtheonewhoknocks4288
@iamtheonewhoknocks4288 2 жыл бұрын
Why don't you use backtrader??
@Algovibes
@Algovibes 2 жыл бұрын
Because I am the one who knocks. On a serious note: I wouldn't know how to implement the rather "complicated" selling logic in Backtrader. At least with my current knowledge of the lib.
@8ksmiff502
@8ksmiff502 3 жыл бұрын
Hello ! I have parse data with my python file and getting the result in python console, now I want to export this data to google sheet. Can you help me to do that ?
@yuvalbra
@yuvalbra 3 жыл бұрын
i can help you if you need
@kentverge
@kentverge 2 жыл бұрын
Wouldn't the second condition (RSI < 40) potentially fire prior to the 10 day window vs waiting the dull ten days before editing? It's inside of the 'j' loop, but you're not checking j. That would change your results from Rayner's.
@kentverge
@kentverge 2 жыл бұрын
Just saw your note in the description but can't find your pinned comment. In any case looks like you already found this.
@Algovibes
@Algovibes 2 жыл бұрын
Yessir, good catch! BTW made a second one on this here: kzbin.info/www/bejne/qIrJlmx4nJd6mbs Let me know what you think about it!
@silentknight8732
@silentknight8732 3 жыл бұрын
What's the point of just showing winrate. Even with a winrate of 90%, if your avg loss is 10 times yours profits , you are losing in the end. This video will be complete if you show avg profits and avg losses. Or just show CAGR
@Algovibes
@Algovibes 3 жыл бұрын
First of all thanks a lot for watching and your feedback! You have some great points and overall I agree with you. But let me share some thoughts with you: The point of this video is to show a technical perspective of implementing a backtest of the presented strategy via Python. Anyhow a general rule for for all my presented trading strategies: Feel free to implement your own ideas and add your requirements. It is nearly impossible to show a complete and perfect trading strategy. That is: Some people want to see the average return, some people will want to see the alpha and so on and so on. I am trying to account for a lot of suggestions in my trading strategy videos so be kindly invited to check out my other videos and let me know what you think! I am always grateful for suggestions and input.
@silentknight8732
@silentknight8732 3 жыл бұрын
@@Algovibes Thank you replying. Is there a link to the full code.
@Algovibes
@Algovibes 3 жыл бұрын
@@silentknight8732 Not yet but there will be a possibility of code access in the future. Thanks for your patience.
@elata1991
@elata1991 2 жыл бұрын
How yo search companies that Apply now to this strategy?
@Algovibes
@Algovibes 2 жыл бұрын
In a nutshell: By reading in all price data for a particular universe (S&P, DAX, or whatsoever) and checking which company is crossing the technicals. I did something similar here, where I am screening 3 different markets for "technical indicator signals": kzbin.info/www/bejne/p3ikhqpsaNWSq80
@cudanakiju0
@cudanakiju0 3 жыл бұрын
It appears that this trading strategy allows multiple positions to be opened at the same time, right?
@Algovibes
@Algovibes 3 жыл бұрын
That's absolutely right but it is kind of a perspective if that is desired or not. I would probably exclude the possibility or at least limit the number of open positions.
@vinu-zu9qg
@vinu-zu9qg 3 жыл бұрын
can you use fxcm and implement your strategy on demo account it will be very useful. fxcm is available in Maxim no of country. and provides data continuesly.
@Algovibes
@Algovibes 3 жыл бұрын
Hey mate, thanks a bunch for the suggestion! Noted that.
@vinu-zu9qg
@vinu-zu9qg 3 жыл бұрын
But FXCM is illegal to use another option is Angle Broking
@Algovibes
@Algovibes 3 жыл бұрын
@@vinu-zu9qg I like how you request a video on an illegal to use platform :D But jokes asides I wanted to cover some FX trading as well within this year.
@vinu-zu9qg
@vinu-zu9qg 3 жыл бұрын
I recommend FXCM, because they provide tick data for free, even in demo account. I have tried it . I works very well. If u want it i can share the code to you. by mail or Whatsapp. Im stuck only in converting ask and bid price to Open high low close
@ray_zhung
@ray_zhung 3 жыл бұрын
If you have consecutive days when RSI is below 40, wouldn't this loop count 2 trades? First trade starts at i ends at i+j, second trade starts at i+1 and ends at i+j too, and both trades' pnls are appended which inflates the result?
@ray_zhung
@ray_zhung 3 жыл бұрын
Adding df.loc[(df['Buy'].shift(1) == 'Yes'), 'Buy'] = 'No' seems to have solved the problem
@Algovibes
@Algovibes 3 жыл бұрын
@@ray_zhung First of all thanks a lot for watching but did you read the pinned comment? :-P No worries if you didn't but I think that is addressing your point. Please correct me if it doesn't.
@ray_zhung
@ray_zhung 3 жыл бұрын
@@Algovibes Thanks for your reply, appreciate the content! Yea that's the code I used, albeit I was calculating a different oscillator that's functionally similar to RSI. I noticed it generated way more trades than I anticipated and that's how I realized. I think since this code loops over every element i, so if i-1 and i both trigger it will calculate 2 trades. This isn't necessarily an error though if the trading setup is to double down on the position whenever it triggers again after the initial entry.
@LowkeeLT
@LowkeeLT 3 жыл бұрын
Oddly, I get the exact same results when limited the # of RSI
@Algovibes
@Algovibes 3 жыл бұрын
Probably because all threshold breaks were happening before day 10. But thanks a lot for sharing your observation!
@Skandawin78
@Skandawin78 2 жыл бұрын
Could you pls share the python code?
@chapmansbg
@chapmansbg 2 жыл бұрын
Percentage wins look good but amount of money won vs lost doesn't appear to look very good.
@Algovibes
@Algovibes 2 жыл бұрын
Please check the newest version of this. I have covered taking a closer look at the strategy performance. kzbin.info/www/bejne/qIrJlmx4nJd6mbs Let me know what you think!
@yuvalbra
@yuvalbra 3 жыл бұрын
great job, can i get the source code?
@davidrod2865
@davidrod2865 3 жыл бұрын
have you published the code somewhere like github?
@Algovibes
@Algovibes 3 жыл бұрын
Didn't publish anything yet but will do probably in the course of this year. Thanks for your patience!
@LowkeeLT
@LowkeeLT 3 жыл бұрын
@@Algovibes can you please link the code used in this video?
@k2icc
@k2icc 3 жыл бұрын
Lets plot it on a chart.
@Algovibes
@Algovibes 3 жыл бұрын
Could have covered that. Would be interesting indeed! Thanks for the suggestion.
@shbit
@shbit 2 жыл бұрын
Getting this error: TypeError Traceback (most recent call last) C:\Users\SHIVAM~1\AppData\Local\Temp/ipykernel_4924/2397107027.py in 1 PnL = [] 2 for i in range(len(df) - 12): ----> 3 if 'Yes' in df['Buy'].iloc[i]: 4 for j in range(1,11): 5 if df['RSI'].iloc[i + j] > 40: TypeError: argument of type 'float' is not iterable
@Algovibes
@Algovibes 2 жыл бұрын
How does your df.Buy series look like? Is it really containing "Yes" values? Seems like it is containing floats. BTW I have an updated video on this one, be kindly invited to check that out: kzbin.info/www/bejne/qIrJlmx4nJd6mbs
Blue Food VS Red Food Emoji Mukbang
00:33
MOOMOO STUDIO [무무 스튜디오]
Рет қаралды 21 МЛН
Секрет фокусника! #shorts
00:15
Роман Magic
Рет қаралды 45 МЛН
Option Basics and How To Price Options with Python
17:18
Algovibes
Рет қаралды 6 М.
CRYPTO Live Trading Bot with Python [Stoch, RSI, MACD]
24:04
Algovibes
Рет қаралды 125 М.
Best and Worst Trading Strategies: Tier List
8:13
Algovibes
Рет қаралды 3,5 М.
Simple Trading Strategy on Bitcoin with Python FULL walkthrough
37:03
Blue Food VS Red Food Emoji Mukbang
00:33
MOOMOO STUDIO [무무 스튜디오]
Рет қаралды 21 МЛН