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.
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.
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.
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).
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.
@@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 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.
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)
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 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.
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
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 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!
@@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 !!!
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
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.
@@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.
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.
@@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
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
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.
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.
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
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
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.
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.
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
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.
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.
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?
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%.
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.
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👏
@@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?
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
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.
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 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'
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
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.
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})
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!
@@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
Very clear, Very usefull. As always, the best python finance content on RUclips. Thanks 👏👏👏
Thanks a bunch my friend! :-)
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.
Hi,
How can i prevet that from happenning then ?
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.
Thanks a lot. That's awesome to hear :-)
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.
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).
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.
@@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.
@@DontTrustMeImASc Interesting! Be invited to share the results :-)
@@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.
I’m having issues as a beginner because I didn’t install the packages like NumPy etc but now I’m getting them fixed
Issues are more than normal! Awesome that you are getting them fixed.
Hi thanks for video and very very good tha all contains
Please make more video like this.
Thanks for your feedback buddy :-) There will surely come more videos like this.
Thanks bro,...can u please one vedio on CPR pivot point for entry and exit
Please CPR
Thank you both for your suggestions! Appreciate it :-)
Yeah, CPR would be nice! Thanks!
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)
Thanks mate! Appreciate your comment and sharing your thoughts. Also the suggestion sounds pretty interesting!
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.
Hi Ayush,
was implementing SL and stuff like that e.g. here:
ruclips.net/video/4MnNft7Squk/видео.html
@@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?
@@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.
Amazinng work dude! Thanks for share!!! 💪👌👍🍺
Thanks for your appreciative comment :-)
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
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!
@@Algovibes that makes sense
Thank you
@@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!
@@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 !!!
Nicely explained, thank you for sharing
Thanks buddy :-)
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
Does the information or TA library take care of the look ahead bias?
Can you elaborate?
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 !
Thanks for watching and also for sharing your thoughts! :-)
I'm not a developer but caught myself looking your content! 😂
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.
@@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.
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.
I use Stochastic oscillator crossover for best confirmation. You should try it with rsi
Thanks for sharing! Anyhow can you elborate a bit? Thx in advance
@@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
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
Thanks for your feedback :-) I didn't play around with Volume indicators yet.
Money Flow Index is similar to RSI but weighted by volume
Very nice vids! How would you calculate the relative yearly returns of this strategy?
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.
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.
How can we find if there are any false signals for this strategy ?
What do you mean by false signals? Signals which end up in bad trades?
@@Algovibes yes sir
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 ?
Nope, slightly different.
@@Algovibes yeah thanks. same as what I observed.
Great video! Maybe we can plot a image to see buying and selling dates.
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
Really helpful... waiting for part 3... continuing.... also how to find current live signal? And store it
Thanks buddy, appreciate your comment :-)
I have covered getting signals in this playlist:
ruclips.net/p/PL9ATnizYJ7f9sW_mdY3071dS8mMwBGu2S
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
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.
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.
mathewdoman06@gmail.com)
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
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.
Can you backtest same for Nifty500 stocks universe??
Feel free to go for it!
Was playing around with Indian stocks here, might be interesting for you:
ruclips.net/video/YIsKSQh1xpY/видео.html
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.
Why do you think so?
@@Algovibes because when you by default pick the first trade, assuming that the second one overlaps with the first, you skip the second.
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?
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%.
@@Algovibes That's exactly what I was thinking of, thanks for illustrative example.
@@Algovibes is this the concept of positive expected value ?
Again Excelent video, thank you very much, much success
Thanks for watching, your feedback and the kind words my friend :-)
mathewdoman06@gmail.com)
I heard from Dr Ernest Chan that it's not practical to buy on open. Is that true?
s/o from South Africa
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.
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👏
@@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?
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
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.
Sure! What I would think of is just a simple break logic if x trades are executed.
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 ;)
just a typo, "momentum" is right.
Thanks for watching and nice trading setup there :D
Thanks for watching buddy!
@@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'
I have find, it was my virutal environnement ...
It's ok !
Thanks a lot for your video !
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
Thanks a lot for sharing!
This code is forward looking
Why do you think so?
nice stuff, THX!!
Thank YOU for watching and your comment mate! :-)
Super Videos danke!
Danke ♥️
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.
Thanks Thierry for sharing your thoughts! Appreciate it.
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})
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!
@@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
Rather than checking for conditions of next Buydate, use the while loop so you can modify the looping variable on the go.
Sounds reasonable. Anyhow: Can you elaborate?
Amazing work dude! Thanks for share!!! 💪👌👍🍺