How to build a trading strategy [Momentum] with Python?

แชร์
ฝัง
  • เผยแพร่เมื่อ 14 ธ.ค. 2024

ความคิดเห็น • 156

  • @Algovibes
    @Algovibes  3 ปีที่แล้ว +7

    Hi all,
    thanks alot for watching. Please note that the components table was being removed from yahoo finance.
    I am showing an alternative way in another video to get the ticker symbols in the very beginning:
    th-cam.com/video/5bUn-D4eL4k/w-d-xo.html
    Thank you very much to westcoast (dat name tho :D) for letting me know!

    • @westcoast7185
      @westcoast7185 3 ปีที่แล้ว +1

      Thanks a million for swift response. Cheers.

    • @realitychannel4770
      @realitychannel4770 3 ปีที่แล้ว

      Amazing skills, can I get this code for further enhancement

  • @xijinpingwinniethepooh9227
    @xijinpingwinniethepooh9227 2 ปีที่แล้ว +2

    Hey can you explain input 17 specially lambda function part , why did you subtracted 1 from it

    • @Algovibes
      @Algovibes  2 ปีที่แล้ว

      lol dat name :D this is cumulating the returns. You subtract a 1 to get a "raw" return. So as an example if you have stock price of 110 and on the next day it is 100. The stocks return is 100/110 = 0.90 but if you subtract a 1 now you will get -0.09 which is telling you the stock dropped by this amount. I have explained returns in the most granular detail here:
      th-cam.com/video/fWHQwqT3lNY/w-d-xo.html

    • @xijinpingwinniethepooh9227
      @xijinpingwinniethepooh9227 2 ปีที่แล้ว +2

      Thanks man love your work

  • @mayts9252
    @mayts9252 2 ปีที่แล้ว +4

    Great lesson! Easy to understand even for a newbie like me. A tutorial on long term backtests and stock recommendation systems based on this strategy would be very much appreciated.

  • @mainsg1838
    @mainsg1838 3 ปีที่แล้ว +1

    I have followed you from your python videos into this finance series. Great stuff! And the likes from me keep piling too!

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Thank you very much! You wouldn't believe the difference you are making with that :-)

  • @assafcohen3173
    @assafcohen3173 3 ปีที่แล้ว +1

    This is a great video and thanks for doing it. This might be super clear for some people but I feel like you ran through some steps here really fast. I've learned that adding some sort of visual aid to explain your point can really drive a point home by visualizing what's happening. For example, the whole 11 months part, the reason you substracted the means and the benchmarking you did. Again, super obvious to you but I felt a bit stomped :) Still, very good video.

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Hi buddy, thanks a lot for your feedback! This is kind of a problem: Some people say its too easy - some say its to hard. It really is kind of hard to find the balance here for me. But if you go through my videos step by step you should get a better idea. But I am always here for questions!

  • @bryan-9742
    @bryan-9742 2 ปีที่แล้ว +2

    this is great starter video. I think there needs to be a week or several days lack for rebalancing. The 4th would change every month (or day). One would want to buy t+1 month the top quintile and reassess t+4 weeks later, hold out for a week, and then rebalance into the next top decile correct? it looks here like you observed the top quintile after 1 year. Only now would one begin to hold the top decile no?

    • @Algovibes
      @Algovibes  2 ปีที่แล้ว

      Hi Bryan,
      quite some time since I published this video. Can you elaborate on your questions in the best case with some timestamps? Thx a lot in advance!

    • @bryan-9742
      @bryan-9742 2 ปีที่แล้ว

      @@Algovibes I can send you a code snippet of how I did this in a small project I was working if that's easier. (it's a bit nonsensical as I Was going to do a risk parity on the crypto with a garch(1,1) but then I couldn't get the circulating supply in time. That said I attempted to lag forward (shift(1) the returns pre binnning (to set up the resample) and I shifted the volatility (as i had to use the garch at t to forecast t+l to avoid contemporaneous affects). ANYWAY, it's a bit convoluted but I used your ideas for importation (i think anyway) fairly easy to read.

    • @bryan-9742
      @bryan-9742 2 ปีที่แล้ว

      In yours what seemed to stick out was how the strategy didn't seem implementable because there is no resample rollforward of your returns. Said differently I can't see where your new tickers are rebalanced into the top decile over time. It should roll forward through time to my understanding. Honestly, I haven't seen an equal weighted momentum outside of very old white papers so I may not know that it's occuring to be fair. It's certainly possibly I missed something, I'd suspect the latter :) )

  • @Anzeljaeg
    @Anzeljaeg 3 ปีที่แล้ว +1

    Im so happy i make it , and found your videos

  • @marcogelsomini7655
    @marcogelsomini7655 3 ปีที่แล้ว +1

    Nice!! I don't get the lambda function to obtain monthly returns

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Hi buddy, thanks for your comment.
      The lambda function is cumulating the returns.
      I am going more into details of cumulating stock returns here:
      th-cam.com/video/fWHQwqT3lNY/w-d-xo.html
      Let me know if anything is still unclear!

  • @cooltraderf
    @cooltraderf 3 ปีที่แล้ว +2

    I just ran your code on the updated DJI components as of April 4, 2021 which is slightly different the list in your code. This highlights the issue of "survivorship bias" that people need to be aware of. Ever considered combining momentum and mean reversion in one strategy? Your work is great, and very appreciated. Thank you.

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Thanks a lot for watching and your comment :-) I will release a vid on Mean reversion in the future. And yes I considered combining them. Might be another one on this channel. Also thanks for pointing out the survivorship bias!

  • @leof.8416
    @leof.8416 3 ปีที่แล้ว +3

    This is really good content, thanks a lot! I don't have a financial background, but you explained it really well

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Thanks a lot for your feedback. Really appreciate it! :-)

  • @kaminisolanki7780
    @kaminisolanki7780 3 ปีที่แล้ว +2

    Hello! This is so fantastic, thanks so much. Would it be possible to show how you would test for statistical significance of the momentum strategy? I am new to Python and Finance and Stats and your videos have been really helpful!

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Hey man, thanks a lot! I actually have some stuff like that in my Python for Finance playlist (e.g. Fama French regression - you could just add the MOM factor to this regression).

  • @joaovictorg.mattos7651
    @joaovictorg.mattos7651 2 ปีที่แล้ว +1

    i am trying to do this with bovespa index but on the first part of pdread_html its doing a HTTP Error

    • @Algovibes
      @Algovibes  2 ปีที่แล้ว

      I actually did that with Bovespa in my stock recommender playlist, maybe you will find some input there:
      th-cam.com/play/PL9ATnizYJ7f9sW_mdY3071dS8mMwBGu2S.html

  • @sheena7233
    @sheena7233 3 ปีที่แล้ว +1

    Great video! Sir, can you please also make a video using a bt package for backtesting?

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Thanks a lot buddy. Appreciate your comment :-)
      It is not in my top priority list but I wanted to go over the Backtrader library somewhen in the upcoming months.

    • @sheena7233
      @sheena7233 3 ปีที่แล้ว +1

      @@Algovibes okay sir. Looking forward to it and other more videos. :)

  • @alihobballah
    @alihobballah ปีที่แล้ว +1

    This is actually amazing quality content.. is there a course you are offering on creating momentum, mean reversion strategies, and backtesting them?

    • @Algovibes
      @Algovibes  ปีที่แล้ว +1

      Hey Ali, thank you very much. I am covering all of those things in both my Python for Finance and Cryptobot playlists. Be invited to check out my stuff :-)

  • @zixuanfang4967
    @zixuanfang4967 2 ปีที่แล้ว +1

    Hello! This is soooooo fantastic, and thanks so much. I got a question about t-test for momentum, how to conduct a t-test based on weekly momentum profits? For instance, holding is 2 weeks, and I got the mean profit for this strategy, how to verify momentum exist by t-test?

    • @Algovibes
      @Algovibes  2 ปีที่แล้ว

      Thank you man :-)
      The common libraries include a t-test (e.g. statsmodels).

  • @BinhKieu82
    @BinhKieu82 3 ปีที่แล้ว +1

    Thanks for such a great sharing Algovibes. Could you develop your code in the context of optimizing weights and sizing following volatility? Looking forward to your coming videos

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Hi man, thanks a lot for your kind words. Also thanks a lot for your suggestion. Sounds pretty interesting - noted!
      Anyhow I got a lot of topics which I want to cover first.
      Could you elaborate and "weights and sizing"? You just want to determine the weight of the asset depending on historical volatility right?

    • @BinhKieu82
      @BinhKieu82 3 ปีที่แล้ว

      @@Algovibes I saw you apply equal weight in most of your videos, just wonder if you play around with unequal weight scheme, one of them as you mentioned "weight regarding to volatility" or other fundamental factors: dividends, volume... or anything. By that your approach seems even more real, Cheers!

  • @cengizali1391
    @cengizali1391 2 ปีที่แล้ว +1

    How do you ignore where there is no prices? i.e. the stock wasnt listed during the period called?

    • @Algovibes
      @Algovibes  2 ปีที่แล้ว

      Can you elaborate? You mean NaN values or stocks which weren't in the DOW in this period?

    • @cengizali1391
      @cengizali1391 2 ปีที่แล้ว

      @@Algovibes I decided to do the ASX200 instead a few stocks werent in the composite - correct Nan values.

  • @Howard-bc7sl
    @Howard-bc7sl 2 ปีที่แล้ว +1

    Hi Algovibes,
    Can I ask why do we short sell the losers even if they generate positive returns?

    • @Algovibes
      @Algovibes  2 ปีที่แล้ว

      Hi Howard,
      can you elaborate on that question? E.g. with an example?

  • @anthonyjovceski
    @anthonyjovceski 3 ปีที่แล้ว +1

    Great video - Can you make a video on value investing and another one on small cap and growth investing?

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Thanks a lot for watching and your comment :-)
      Yes I can and will but it might take some time. Nevertheless thanks a lot for your suggestion!
      Until then you are very kindly invited to check out some videos in my Python for finance playlist. E.g. Fama French could be interesting for you:
      th-cam.com/video/pLyatGMTqzY/w-d-xo.html
      Thanks for your patience in advance.

  • @mumbai59
    @mumbai59 3 ปีที่แล้ว +1

    I was wondering if you can discuss dual momentum strategy in python

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Noted that! Interesting concept and surely interesting to test this strategy. Thanks for your contribution and also thanks a lot for watching.

    • @mumbai59
      @mumbai59 3 ปีที่แล้ว +1

      @@Algovibes Let me know how to contact you. I have some very specific questions about back testing. Which are probably not appropriate for posting here.

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      @@mumbai59 Setting up a mail soon. Will let you know in a community once I have done that.

  • @WarwickShoreAdvisors
    @WarwickShoreAdvisors 3 ปีที่แล้ว +1

    Very well explained. Thank you. On Yahoo Finance other indices do not have components. Is there a better place to get components for the S&P500, Russell 3000, etc. Also, can you show how to incorporate fundamental factors such as ROE, P/E. Thank you,

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Thank you very much! :-) I am showing how to get components e.g. for the S&P500 in my newest video and also in the momentum video on the S&P500. Be kindly invited to check that out! You can get the data for the Russel in the same way, at least for the Russel1000.
      Videos:
      Momentum S&P:
      th-cam.com/video/5W_Lpz1ZuTI/w-d-xo.html
      RSI trading:
      th-cam.com/video/pB8eJwg7LJU/w-d-xo.html
      Also thanks a lot for publicly subscribing. That is a huge help for me. Really appreciate it.
      Regarding fundamental factors: I have noted that on my list. Thanks a lot for the suggestion. I want to publish a strategy based on fundamental factors. But can't promise.

    • @WarwickShoreAdvisors
      @WarwickShoreAdvisors 3 ปีที่แล้ว +1

      @@Algovibes thank you so much

  • @clarence2c408
    @clarence2c408 3 ปีที่แล้ว +1

    This is great teaching. Thank you so much
    I would like to see you do a larger index, such as S&P500 soon.

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Hi mate,
      thank you so much for your comment. I really appreciate it.
      I already did that :-)
      Check it out:
      th-cam.com/video/5W_Lpz1ZuTI/w-d-xo.html
      Let me know what you think about it!

  • @Ekyls
    @Ekyls 3 ปีที่แล้ว +3

    Hi, nice video ! Quick question here, would you say that momentum strategy still works on volatile markets by lowering the observation timeframe and portfolio readjustment dates ? For instance a 7 days observation for a weekly readjustment ? Or would the return be too low to cover the fees to reallocate the portfolio ?
    Thanks !

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +2

      Hi and thanks a lot for watching :-) I can't tell ad hoc if this strategy would work (besides that it highly depends which market). But it would indeed be an interesting to test shorter term momentum on different markets. I am considering covering that in the future. Thank you very much for the suggestion!

  • @kaminisolanki7780
    @kaminisolanki7780 3 ปีที่แล้ว +1

    Hello! Would it be possible to do a playlist on Numpy as you did with Pandas? Thanks!

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      I am planning on covering more basics in the upcoming year. Numpy could be a part of that. Thanks a lot for the suggestion!

  • @dgdfgdfg34534
    @dgdfgdfg34534 3 ปีที่แล้ว +1

    Superb video. Nice tricks!)

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Thank you so much! :-)

  • @kevinkang5807
    @kevinkang5807 3 ปีที่แล้ว +1

    Why are you not evaluating the portfolio of end of December with rebalancing at the end of November? And i must say this is a fantastic video for beginners just like me

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Thanks a lot for your comment. Appreciate it!:)
      Regarding the rebalancing could you be more specific? What do you want to achieve? What exactly do you want to rebalance and when?
      Please note that I am buying every month again and the holding period is one month.
      I would be really thankful for an answer as I think you potentially have a very important and valid point here.

  • @nadonadia2521
    @nadonadia2521 2 ปีที่แล้ว +1

    Hi
    great video, informatiobns well explained, i'am learning python with you, but i do not agree wit you about starting date and ending date of the strategy, what about the components of the Dowjones in 2018 are they the same as now Ford Motors, General Electric were delisted from the Dowjonws and replaced with another company, can you made such a program wich include delisted and companies that have gone bankrupt for for any strategy staring year.

    • @Algovibes
      @Algovibes  2 ปีที่แล้ว

      Thanks a lot Nado,
      survivorship bias is an issue - agreed!

  • @shajankuriakose
    @shajankuriakose 4 ปีที่แล้ว +1

    Excellent presentation! Can this be done for daily trading?

    • @Algovibes
      @Algovibes  4 ปีที่แล้ว

      Hi and thank you very much for your kind comment :-)
      Good question - but my guess would rather be no as at least in my opinion it is not the best idea for daily trading as the daily volatility could diminish the momentum effect. But one has to backtest that.
      Nevertheless be kindly invited to check out my video on RSI strategies, that might be better for short term momentum trading:
      th-cam.com/video/JvfK4VBX75I/w-d-xo.html
      Also I am working on a video for momentum in the S&P500 including a backtest right now, so might be interesting for you as well :-)
      Best regards

  • @dgdfgdfg34534
    @dgdfgdfg34534 3 ปีที่แล้ว +1

    Is it possible to add commissions to the simulation?

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Absolute valid point. In reality commissions would play a big big role. You could take them into consideration by either calculating the absolute profit for every month (or rather every single security) and subtract them or take them into consideration in relative terms.
      Nevertheless in my opinion that doesn't make much sense in this particular strategy. We are buying and short selling every single month newly with the result of a massive turnover and a pain of transaction costs.
      But I noted on my list to optionally consider transaction costs in one of my further trading strategy videos. Thanks a lot for your contribution and thank you for watching :-)

  • @tlghnkck
    @tlghnkck 3 ปีที่แล้ว +1

    Hi, I'm a little confused about the dates. If I were to make an analysis as of now, how should I write the dates?

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Hi mate, you would just check the previous 12 months, skipping the most recent month and buy the top performers and short the worst performers and hold that portfolio for one month.

    • @tlghnkck
      @tlghnkck 3 ปีที่แล้ว

      @@Algovibes So, are these dates correct for January? 2020-12-01, 2021-12-01

  • @boohoo708
    @boohoo708 3 ปีที่แล้ว +1

    thx for this great lesson...i work with such a strategy using tradingview... 6 month ranking time and 3 month holding time with the top 5 or top10 of the first 200 stocks of Nasdaq...
    Problem is...i cant backtest this in tradingview...i can only make 5 ranking lists with 40 stocks...buy the top 5 stocks out of 200 and calculate the performance after 3 month in excel...that takes a lot of time, if you make a backtest over 24 years...beginning 1997 and have the big crashes included...
    my question is...is it possible to import tradingview datas to python, to make a complete backtest since 1997 or longer...

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Thanks a lot for watching and your comment. Yes that is why Python or R are my choices when working with any kind of data in general :-)
      I know that there is an API for tradingview, although I didn't check it out and I don't know if there is a demand for that:
      pypi.org/project/tradingview-ta/

  • @ihebbibani7122
    @ihebbibani7122 3 ปีที่แล้ว +1

    Hi , Thanks for the video. What do you mean by looking for quantiles ?

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Hello and thanks a lot for watching!
      I hope I got your question right: By using quintiles I am just sorting the stocks in 5 equal sized buckets and filter for the highest and lowest quintile (bucket) to find out what are the losers and winners stocks.
      Does this answer your question or did I got you wrong? In case I did please just tell me where I am talking about the mentioned stuff and tell me what exactly you want to know. I am happy to help out!

  • @srengodbersen1481
    @srengodbersen1481 3 ปีที่แล้ว +1

    Wouldn't it be possible to calculate the past 11 month return by following line instead?:
    mtl_ret = df.pct_change(periods=11)

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      In that particular case I would say no as you need to get the returns on a monthly base first. As far as I know the period shift (the periods=11 part in the function) is taking the particular index so it would take the returns over the last 11 days.
      Is this answering your question or did I got you wrong?

    • @srengodbersen1481
      @srengodbersen1481 3 ปีที่แล้ว

      @@Algovibes i guess that means that if I already have the returns on a monthly base stored, the period-argument should yield the same return as in your case? :-)

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      @@srengodbersen1481 Highly probably no as if you have stored them as monthly returns and take again the pct_change() function with the periods argument you wouldn't get what you want to as you are again taking the pct_change of those returns.
      But please correct me if I got you somehow wrong.

    • @srengodbersen1481
      @srengodbersen1481 3 ปีที่แล้ว

      @@Algovibes If df is a dataframe of monthly stock prices in the following line, wouldnt this line of code then calculate the return over the past three months?:
      past_ret = df.pct_change(periods=3)
      I have tried to look at the results that i get from this line and it looks porberly. But I am a bit afraid that I have missed something :-D

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      @@srengodbersen1481 if they are stock prices it should work. But as a disclaimer I have not yet used this function but understand it as it is just a row shift and then calculates the relative change. But if you are getting the same results and the function is working as I described I see no problem applying it.

  • @cjfeat.2631
    @cjfeat.2631 4 ปีที่แล้ว +1

    Really nice video! I have one request though.
    Can you show how to iterate this strategy over multiple periods rather?
    Maybe some kind of do-loop syntax is necessary.
    Any reference will be fine too.
    Thanks.

    • @Algovibes
      @Algovibes  4 ปีที่แล้ว +5

      Hi :)
      Thank you very much for watching and for your kind feedback.
      Your question is very reasonable and it would be the next step to backtest (which is nothing else than an iteration over multiple periods) such a strategy once we have defined it. I can provide a video on that as said in the end of the video.
      But let me give you an idea how I would do that in words, maybe this is helping you out for now.
      I would get some data over the last years. As the data scrape is pretty inefficient maybe store the request in a csv file or anything else.
      Then make the formation date flexible. So append the Momentumprofit in e.g. a list and just go one month forward with each iteration.
      To do so there are basically 3 ways (at least as far as I am concerned):
      - Use a for loop
      - Use functions where you are parameterizing information
      - Use classes where you initialize / inherit information (maybe the best way but you need to have an idea about Object oriented programming)
      I hope this is helping you out for now. I will see if I can add a video backtesting this strategy in the future.
      Best regards

    • @cjfeat.2631
      @cjfeat.2631 4 ปีที่แล้ว

      @@Algovibes ^^ Thanks a lot for your feedback. Keep my fingers crossed for your channel.

    • @Algovibes
      @Algovibes  4 ปีที่แล้ว +1

      @@cjfeat.2631 thank you very much. That’s very kind of you!

  • @michaelt9266
    @michaelt9266 4 ปีที่แล้ว +1

    Brilliant video, your style of building from the ground up with explanations of the underlying theory is top notch. One question though, if I wanted to vary the number of months for the holding period and formation period and create multiple strategies like Jegadeesh and Titman did in their paper, how would I go about this? Thanks

    • @Algovibes
      @Algovibes  4 ปีที่แล้ว +3

      First of all thank you so much for your appreciative comment.
      Secondly that is a great question but a satisfying answer would be a whole new video to be honest :-D
      Let me try it in a few sentences:
      Regarding the holding period you could create a second data frame containing the cumulative returns over e.g. 2 months (by the way if you are uncomfortable with cumulating returns you could just take the price change from e.g. t+2 - t0). Only take this data frame for the loc function when you are calculating winners/losers returns. Stick to the procedure shown for the past returns. Specify the relative delta as the e.g. 2 months in the locator.
      You can use loops for this approach to create 1-10 holding months.
      Regarding the formation period check out my code snippet as an example to implement more than one formation date. This is just looping over a specified range of months you want to check and is just an idea how to do it.
      Code:
      from pandas.tseries.offsets import MonthEnd
      array = []
      Dates = []
      realstart = start + MonthEnd(12)
      for i in range(...):
      formation = realstart + MonthEnd(i)
      end_measurement = formation - MonthEnd(1)
      ret_12 = past_11.loc[end_measurement]
      ret_12 = ret_12.reset_index()
      ret_12['quintile'] = pd.qcut(ret_12.iloc[:,1],5,labels=False)
      winners = ret_12[ret_12.quintile == 4]
      losers = ret_12[ret_12.quintile == 0]
      winnerret = mtl_ret.loc[formation + MonthEnd(1),df.columns.isin(winners.Symbols)]
      loserret = mtl_ret.loc[formation + MonthEnd(1),df.columns.isin(losers.Symbols)]
      WML = winnerret.mean() - loserret.mean()
      array.append(WML)
      Dates.append(formation)
      Please understand that It's kind of a challenge to answer your specific question via a comment and ofc you are kindly invited to ask further questions in case I got your question wrong or you are not satisfied with the answer.
      Best regards and I would love to hear if you found this helpful.

    • @michaelt9266
      @michaelt9266 4 ปีที่แล้ว +1

      @@Algovibes Thank you very much, I will continue to support the channel - you deserve a lot more views for this level of work and help for your subscribers.
      Following your steps in regards to the holding period, I created a new dataframe with two month rolling cumulative returns by simply altering the rolling function. I then call this cumulative data-frame when calculating the winner and loser returns and altered the relativedata to equal 2.
      This is equivalent to holding the formation portfolio and finding the returns of the strategy for 2 months. I can now proceed to create a loop which can vary the holding periods. Is this correct?

    • @Algovibes
      @Algovibes  4 ปีที่แล้ว +1

      Thank you so much for your support! Thats great to hear and people like you are very important to get literally "Momentum" on my channel someday :-P
      I would do it exactly like you described. To be very sure you could just take a look at the prices of the winners/losers and check how they developed after 2 months. If that's the same as with the rolling function you are fine.
      Then as you said you can loop through the different holding periods.
      I would be very interested in your results/progress so be kindly invited to drop me a comment anytime you need help or want to share something.
      One of the main objectives creating this channel is to connect with people sharing my interests and just have a nice time together.

    • @michaelt9266
      @michaelt9266 4 ปีที่แล้ว +1

      @@Algovibes Hey man hope you're well, I've managed to create a code based off this video and your replies to create a momentum portfolio. I just wanted to share what I've done with it and maybe get some feedback. How would I be able to share this with you?

    • @Algovibes
      @Algovibes  4 ปีที่แล้ว

      @@michaelt9266 Hi i am fine, hope you are doing great too. Can you share e.g. a jupyter notebook or do you maybe have a github link? If both not possible try pastie and provide me the link.
      Best regards

  • @srengodbersen1481
    @srengodbersen1481 4 ปีที่แล้ว +1

    nice video! I have a problem running the following program line: "ret_12["quintile"] = pd.qcut(ret_12.iloc[:,1],5, labels=False)". Any idea why this doesn't work?

    • @Algovibes
      @Algovibes  4 ปีที่แล้ว

      Thank you very much for your feedback! Happy that you liked it :-)
      Regarding your problem: Did you reset the index beforehand?
      ret_12 = ret_12.reset_index()
      Otherwise the integer locator (iloc) in your line of code wouldn't reference to the right colum.
      Please let me know if this has solved your problem and if not be kindly invited to send me your error message. I am happy to help!

    • @srengodbersen1481
      @srengodbersen1481 4 ปีที่แล้ว +1

      @@Algovibes thanks! I did not reset the index before hand, so now the code works. Thanks a lot for your response

    • @Algovibes
      @Algovibes  4 ปีที่แล้ว

      Perfect :-) Great to hear!
      BTW I am working on another trading strategy right now. I will release the video today or in the next couple of days. You are kindly invited to check that out!

  • @twtw785
    @twtw785 3 ปีที่แล้ว

    Amazing python skills - thank you so much. Can you please do a video on intraday strategies? Example, if the first hour trend is up buy at close, then hold until market close and vice versa.

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Love your name :-D Thanks a lot for your comment and even more for the suggestion. Intraday trading strategies are definitely on my plan for upcoming videos!
      Best regards :-)

  • @kartikaggarwal9023
    @kartikaggarwal9023 2 ปีที่แล้ว +1

    Can we get the source code?

    • @Algovibes
      @Algovibes  2 ปีที่แล้ว

      Hi Kartik, yes of course.
      Here is the link:
      th-cam.com/channels/87aeHqMrlR6ED0w2SVi5nw.htmljoin

    • @kartikaggarwal9023
      @kartikaggarwal9023 2 ปีที่แล้ว +1

      @@Algovibes I signed up and emailed you but haven't heard back. I kinda need it asap!!

    • @Algovibes
      @Algovibes  2 ปีที่แล้ว

      @@kartikaggarwal9023 ✅

  • @realitychannel4770
    @realitychannel4770 3 ปีที่แล้ว

    Can I get the code for my learning or I need to redo it again?

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      It's somewhere on my old laptop but besides that I am currently not uploading my code anywhere. Within this year I will provide a solution to that. Thanks for your patience!
      I am convinced you can rebuild that on your own! :-)

  • @TheFunvader
    @TheFunvader 3 ปีที่แล้ว +1

    Hey Algovibes, great video!
    I used some of your ideas for a project of mine. However, I ran into the problem of stocks being delisted during longer holding periods. I have a few solution ideas, would you maybe be willing to help out with your know-how?

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Hi and thanks a lot for watching and your comment :-)
      Please understand that I cannot provide code reviews or something like that due to limited time. But I am very happy to do my best providing qualitative answers to questions so be kindly invited to drop me your question. I will see what I can do. Thanks a lot for your understanding and best regards.

    • @TheFunvader
      @TheFunvader 3 ปีที่แล้ว +1

      No worries! Thanks for replying. The problem arises for the loser portfolio. I have tried to fix the issue by finding the last available return from formation period to end of holding period. If the stock is delisted before end of holding period i calculate the return up until that month and multiply it by -1 to receive the actual profit. I then multiply this return by the riskfree return for the remaining period to get the return of that one stock. Does this make sense or am I making a logical mistake along the way?
      Hope not to take too much time out of your day!

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Wow this is an interesting question and I actually stumbled over it during my thesis (some time ago) as well.
      The CRSP is suggesting how to deal with delisted stocks in general:
      leiq.bus.umich.edu/docs/crsp_calculations_splits.pdf
      on page 118. Maybe this is helpful for you.
      I am assuming you cumulated the return (you wrote: multiply) and then just cumulate them further from the delisting point on with the risk free rate right? I need to understand the background why you think it makes sense to take the risk free rate from this point on.
      I recalled my previous comments as I thought about it a second time. If you are shorting a stock which is being delisted you are making (close to) 100% in my understanding? Feel free to correct me ofc.

    • @TheFunvader
      @TheFunvader 3 ปีที่แล้ว +1

      @@Algovibes thanks for the hint! Yes that is what i meant :). Well, it depends at what price the stock was delisted. If for example the company didnt go bust but was simply taken off the market because in turned into private ownership the stocks dont necessarily go to 0 value, hence your return isnt 100%.
      Thanks again for the hint I will gladly be having a look through it! Also many thanks to you for this nice little conversation, I am looking forward to new content of yours
      Best
      Daniel

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      @@TheFunvader Totally makes sense. Didn't even think about that. In that case you are getting paid out and can invest in the riskless asset - reasonable. Thanks a lot for the chat :-)

  • @PMHijes
    @PMHijes 3 ปีที่แล้ว +1

    Thanks a lot for your videos, I am new in the topic and they are very helpful. I won't miss a single one, for sure.
    Regarding the "1-month reversal effect", have you tested the strategy with and without the skipping month? Do you think one could get valuable information from such comparison? Let's say we do it both ways and find a stock that is in winners_without_skipping but not in winners_with_skipping, could that suggest a reversal in such stock ? What if we short sell it, do you think it would be profitable? Thanks again!

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Hi :) Very cool to have you on board! Thank you very much. Nevertheless for someone new in the topic you are asking very specific and interesting questions. I actually never tested it which is kind of funny as I just accepted that as an academic proven fact. Shame on me!
      What I can tell you is that the 1 month reversal effect is way smaller then it was in the time when it was first observed.
      Regarding your second question: Well it depends. It could be on the one hand but on the other hand other stocks might have an effect on it as well.
      Imagine x(any number) stocks skyrocketing in the prior month superseding the winner which was in the winners without skipping but is only not in the with skipping because of the others stocks performance.
      Does this makes sense to you?

    • @PMHijes
      @PMHijes 3 ปีที่แล้ว +1

      @@Algovibes thanks a lot for answering and for finding interesting my question :)
      What you say makes sense to me. I think that the effect is smaller nowadays in part because everything happens/changes faster and many actors are involved. Thus, may we be looking at a too long time length here? Maybe at present one should be focused on weeks rather than months? Also, now I see that short selling something that has been performing well (although not in the winners Q) just because it did very well recently sounds like a bad idea x) (apart from the fact that, as you suggested, different effects might be involved).
      Anyway, I think that skipping 1 month could be a good approach back in time, but I have my doubts at present :) Also, momentum over shorter terms might be more suitable for current trends. The good thing is we can test it! Please, let me know your thoughts if possible.
      By the way, I have seen that in your second momentum video over SP500, you use a different function to go back/forward in time. Here is the relativedelta whereas in the second is MonthEnd. I was following this video but actually applying it to SP500 and I noticed an error when using relativedelta, I am not sure whether that is the reason you brought a different function...
      Cheers!

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Totally valid points!

  • @TheGermanenrique
    @TheGermanenrique 3 ปีที่แล้ว

    Do i have to instal dateutil with pip3 install dateutil right?

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      pip install python-dateutil

  • @batiste1158
    @batiste1158 ปีที่แล้ว +1

    Hey thanks for the video! I have just one question. How would you modify this code line :
    past_11 = (mtl_returns+1).rolling(11).apply(np.prod)-1
    if you dont want to use the prior 11 month (taking care of the reversal effect) as the ranking period but an intermediate horizon. For example the month 12 to 6 prior to Portfolio Formation. So that you skip the most recent 5 month.
    Thanks for your help!

    • @Algovibes
      @Algovibes  ปีที่แล้ว

      Hi mate, I have newer videos on momentum with flexible lookback videos. Your question should be answered there.

  • @ronnieelmore9066
    @ronnieelmore9066 3 ปีที่แล้ว +1

    Can a video be made using python that combines this one with the rsi video where you can automate the rsi result for each stock in the djia for the present day. It really sounds like a lot of work. lol

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      If I am getting you right you want to check if the RSI (and SMA) condition for a particular Dow Jones stock is fulfilled and then you are getting a recommendation whether you should buy or not?
      That shouldn't be a lot of work - sounds doable to me.
      I will highly probably release another video building a recommendation system out of the RSI strategy. But this is something I will cover in the upcoming months.

    • @ronnieelmore9066
      @ronnieelmore9066 3 ปีที่แล้ว +1

      Yes that is exactly correct. There are only 30 stocks and instead of checking the rsi one at a time on a rsi calculator you could automate and get all 30 at once. Or a true, false, to see if the rsi condition has been met.

  • @mataprasadagrawal5519
    @mataprasadagrawal5519 3 ปีที่แล้ว

    Can you pl share the code?

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Thanks a lot for your request. I didn't upload the code anywhere yet.

  • @Ks-oj6tc
    @Ks-oj6tc 3 ปีที่แล้ว

    Could you please give code access. Thanks a lot for your video.

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Thank you very much for watching and your comment. I am kindly asking for your patience regarding code access. I am planning on that in the second half of this year.
      Thanks a lot for understanding and best regards

  • @TheGermanenrique
    @TheGermanenrique 3 ปีที่แล้ว

    i have an issue, when i get thorugh the website to get the components there is like a disclaimer telling my that the information isn´t available...do i have to pay for a suscription, i mean is that content free?

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      No, it is free. When did you get this?

  • @mannyparmar
    @mannyparmar 3 ปีที่แล้ว +1

    Thanks so much for creating this very useful momentum strategy using python.
    I made as per your instructions and just have 1 question:
    Since you are using only 1 period (12 months), i changed that part and added 12 and 6 months. Everything works except i don't know how to take average of both.
    When i add ret_12+ret_6, the numerical data is correct but the ticker is shown as "MSFTMSFT", since text field is added from both the Arrays. Is there any way to just add numerical data and keep Ticker (text field) as it is?
    My result is: MSFTMSFT 0.52
    Also, i took weight of 50% to each strategy, i wanted to divide 0.52/2; Not sure how to achieve that. But it is not an big issue though. I can live with this.
    If and when you have time, do point me to some other videos or website showing how to handle addition of mixed type Arrays.
    thanks and Appreciate all your help.

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Hi buddy,
      thanks for your comment. I have a whole playlist on Pandas and Python for finance for further information. To be more specific: I would create a series of ret_12 and ret_6 and then just add them.

  • @ki5ngau
    @ki5ngau 4 ปีที่แล้ว +1

    Brilliant

    • @Algovibes
      @Algovibes  4 ปีที่แล้ว

      Hi,
      thank you for your appreciative comment. Very glad that you like it. Let me know if you made some bugs with it :-P

    • @cjfeat.2631
      @cjfeat.2631 4 ปีที่แล้ว

      @@Algovibes Speaking of which, I found some weird rules when using the 'get_data_yahoo' function. When I import multiple symbols (BTC, ETH, XRP), the start and end date matters for error msg.
      For example, the start dates of BTC, ETH, and XRP in Yahoo Finance are 9/16/2014, 8/6/2015, and 9/16/2014, respectively. I realized that the start date should be later than 8/6/2015 otherwise error msg. Your code seems free from this error.
      colab.research.google.com/drive/1RLHW_cHvjrd9jf4IXF83zXB9tZI3cGkt?usp=sharing

    • @Algovibes
      @Algovibes  4 ปีที่แล้ว

      Cool Notebook, thank you very much for the reference :-)
      Yea, I noticed that error as well when recording my Data Science with cryptocurrencies video.
      When it comes to cryptocurrencies there is a lack of data going more than 4 years back.
      Be kindly invited to suggest a database once you found one for cryptocurrencies. For stock prices the data reader is perfectly fine (although kind of a bit inefficient).
      Best regards

  • @evazhao01
    @evazhao01 3 ปีที่แล้ว +1

    what is the one month reversal effect? why would stocks winning for 11 month suddenly reverse and then next month perform? not making intuitive sense to me

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Hi and thank you very much for watching. The 1-month reversal effect is just a short term effect. Stocks which have risen a lot in the past month (only in the past 1 month) tend to drop in the subsequent month. Respectively stocks which have performed badly in the past month (only in the past 1 month) tend to perform good in the subsequent month.
      With excluding the prior month we just get rid of this effect. It is not like that stocks suddenly reverse but we want to avoid capturing this short term effect.
      We make our buying decision on the formation date and are interested how the particular stock has performed over the past 12 months but excluding the 1-month reversal effect. That is why we are skipping the most recent month.
      Does this help you getting a better intuition?

    • @evazhao01
      @evazhao01 3 ปีที่แล้ว +1

      @@Algovibes yes thanks for the quick reply!

  • @bobjazz2000
    @bobjazz2000 2 ปีที่แล้ว +1

    Yahoo not providing ^DJI components

    • @Algovibes
      @Algovibes  2 ปีที่แล้ว

      Hi Robert, just pull them directly from wikipedia. I have shown how to do that in newer videos. Let me know if you need anything!

  • @map18
    @map18 3 ปีที่แล้ว

    Am i the only one who cannot figure out how you are using this in real life?
    You are shows past 1 month (December's stock pick) by using November's performance and then showing with this strategy the future of stock returns for Jan 31. It does not calculate December 1st stock pick returns on Dec 31. And there is no calculation of what should be the stock pick on January 1st. However, you calculate Jan 31st performance without even picking stocks on Jan 1.
    Not sure how you jump to Jan 31 without knowing what you had picked on Jan 1.

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      You just buy(/sell) the top(/worst) performers over the last 12 month, skipping the most recent month and hold this portfolio for 1 month.
      In your example: Jan 31 I am picking the top/worst performers with the performance measurement period until End of December. I am ignoring the January returns as I am skipping the most recent month.
      How this can be handled in real life: You check out stocks from a certain index and see how they performed over the last 12 months, excluding the most recent month. So if you want to make a decision for say the formation date Sep 30 you check the performance of the stocks until End of August. You would hold this portfolio until the End of October and see how this 1 month performance is.
      If you want to understand why I am skipping the most recent month, please check this video here:
      th-cam.com/video/xpP048vfNrg/w-d-xo.html
      Is this answering your question?

    • @map18
      @map18 3 ปีที่แล้ว +1

      @@Algovibes Yes, got it. Thank you for your reply and explanation. This is perfect for generating future month list.

  • @stelios83
    @stelios83 3 ปีที่แล้ว

    Great video but i think your formula for the past_11 is wrong as if you change the start and end dates the past_11 only returns 8 months worth of data

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว +1

      Hi buddy, thanks for watching! I just double checked and I disagree on your statement.
      Please check the following video for applying a bunch of starting and ending dates:
      th-cam.com/video/5W_Lpz1ZuTI/w-d-xo.html

  • @eric752
    @eric752 2 ปีที่แล้ว +1

    So good 🤤

    • @Algovibes
      @Algovibes  2 ปีที่แล้ว

      Thanks my man :-)

  • @rverm1000
    @rverm1000 3 ปีที่แล้ว +1

    wow thats complicated

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      That was not the goal. I was trying to keep it as simple as possible.

  • @margarita1513
    @margarita1513 4 ปีที่แล้ว +2

    man this is so well explained! Thanks a lot!!

    • @Algovibes
      @Algovibes  4 ปีที่แล้ว

      Thank you very much for your kind words and thanks a lot for watching :-)

  • @pardhunani143
    @pardhunani143 3 ปีที่แล้ว

    I have modified this program for backtesting its not working
    def momentumprofit(formation):
    end_measurement = formation - relativedelta(months=1)
    ret_12 = past_11.loc[end_measurement].reset_index()
    ret_12['quintile'] = pd.qcut(ret_12.iloc[:,-1],5,labels=False)
    winners = ret_12[ret_12.quintile == 4]
    losers = ret_12[ret_12.quintile == 0]
    winnerret = mtl_ret.loc[formation + relativedelta(months=1),df.columns.isin(winners.Symbols)]
    loserret = mtl_ret.loc[formation + relativedelta(months=1),df.columns.isin(losers.Symbols)]
    Momentumprofit = winnerret.mean() - loserret.mean()
    return Momentumprofit
    profits = []
    dates = []
    for i in range(12*10):
    momentumprofit(formation + MonthEnd(i))
    dates.append(formation + MonthEnd(i))

    • @pardhunani143
      @pardhunani143 3 ปีที่แล้ว

      KeyError Traceback (most recent call last)
      in
      2 dates = []
      3 for i in range(12*10):
      ----> 4 momentumprofit(formation + MonthEnd(i))
      5 dates.append(formation + MonthEnd(i))
      6
      in momentumprofit(formation)
      1 def momentumprofit(formation):
      2 end_measurement = formation - relativedelta(months=1)
      ----> 3 ret_12 = past_11.loc[end_measurement].reset_index()
      4 ret_12['quintile'] = pd.qcut(ret_12.iloc[:,-1],5,labels=False)
      5 winners = ret_12[ret_12.quintile == 4]

    • @Algovibes
      @Algovibes  3 ปีที่แล้ว

      Hi mate,
      just stick to the procedure as described in this video:
      th-cam.com/video/5W_Lpz1ZuTI/w-d-xo.html
      I backtested the whole S&P there.
      Best regards