Momentum Trading Strategy implemented in Python on a 500 Stocks universe [Beginner friendly]
HTML-код
- Опубликовано: 14 июн 2024
- In this video we are constructing a momentum trading strategy in Python.
First we are pulling ticker symbols which are currently in the S&P 500 and also take care of added and removed stocks diminishing survivorship bias.
Then we are pulling prices for those ticker symbols and calculate monthly returns (I am also recapping how cumulating returns are working). We are then cumulating returns over the last n months (12 in the first place) and check for the top performing stocks over this time horizon. The top performers performance is the performance over the upcoming month so we are screen the monthly returns for the winning stocks and do that for every single month in our observation period.
Get the Notebook/Source code by becoming a Tier-2 Channel member:
/ @algovibes
Want more trading strategies? Please let me know but liking this video and subscribing to the channel.
Video on how (stock) returns are calculated:
• How To Calculate Stock...
Previous Momentum videos:
• Trading strategy and B...
Momentum on Dow:
• How to build a trading...
Momentum on Cryptocurrencies:
• Momentum Trading Strat...
wiki link:
en.wikipedia.org/wiki/List_of...
Further reading:
mba.tuck.dartmouth.edu/pages/f...
www.jstor.org/stable/2328882?...
Momentum is a hot topic in academics as there is empirical evidence that this strategy is working but there is a discussion about WHY this strategy is working.
Disclaimer: This video is not an investment advice and is for educational and entertainment purposes only!
00:00 - 00:49 Introduction / Strategy
00:49 - 08:34 Getting bias free S&P500 ticker symbols
08:34 - 10:18 Pulling stock price data for the symbols
10:18 - 11:20 Sharing some thoughts (skippable)
11:20 - 12:52 Data manipulations (merging/renaming)
12:52 - 16:53 RECAP: How to cumulate returns (step by step)
16:53 - 18:05 Calculate monthly returns
18:05 - 19:03 Raw price monthly return calculation (just to make it clear)
19:03 - 20:42 Calculating past 12 month returns
20:42 - 22:15 Understand the logic calculating the winner portfolio
22:15 - 25:39 Winner portfolio calculation on a single row
25:39 - 30:45 Wrapping everything into a function
30:45 - 32:32 Discussing the outcome / some amendments
32:32 - 33:20 Benchmark comparison
33:20 - 35:21 Some chatting /shorting losers / Thx for watching :-)
#Python #Trading #Momentum #Backtest
I can't get enough of your videos... Extremely useful and very well explained... Please keep making them...
Thanks a ton for your support Marc. Really appreciate it!
Loved the video, TYTY man!
Thanks Alex, appreciate you leaving a comment!
Hello Brother. Your videos keep improving and the ideas you come up with is just so interesting. You definitely give a coding outlook with your fluent coding. YOU ARE THE BEST.
Thank you very much for your support Rajeev!
Fantastic video you did there, thanks, brilliant for getting familiar with Pandas!
Thanks my man!
Great video, thank you kindly
Most welcome! Thanks a lot for watching :-)
Thanks for the wonderful video! I am a slow learner but I got it eventually.
It's perfectly fine. Every has his individual digestion time. As long as you want to learn something new you are absolutely fine.
excellent! would be great to add a sector constraint, considering a representative stock for each of the 11 sectors to diminish risk. Volume and market cap are also important as you are possibly not getting your price for low volumes and low market caps. These values can be scraped with Beautiful Soup and request. This is one of your best videos.
Yes, please! can you add the additional metrics (Vol, DD, etc) to measure this strategy and if you can, a way to export this in a report format as you would in excel. Thank you 10^6.
You are the best, mate, you cant imagine how much i learned with your videos. At the moment im working a lot on one project, seems to be a good idea and day by day im improving the code. The only thing is driving me mad is that, after all this time coding your bots and coding my own, i still get LOT_SIZE error with some coins.. but im working on it. Anyway , amazing content mate.
Thank you so much Esteban. Please check the previous video. You won't have problems with the Lotsize anymore if you follow the approach.
@@Algovibes thanks a lot , i just implemented that limit order system to my bot and im running the previous version and the new one to compare if it works properly :)
@@Algovibes I dont have LOT_SIZE exceptions any more! and the bot is doing well, 84.5% profit by the last 6 trades.. , thanks a lot again!
nice idea, really like your videos! However the comparison of the different lookback periods is not really fair because - depanding on the lookback period - you times in the market are different. Eg. for 1 you drop only one month with missing values, but for 12 you drop first 12 months -> results are not comparable.
One way to fix this would be to return (in the mom function) the whole time series of montly returns (with monthly time index) and then, outside of the function to select only the months for evaluation which are for all periods available
Love job
Thanks a lot mate :-) Didn't cover order book yet.
How would code a momentum strategies when I want a 1 month time gap between the formation and holding period?
Hi, Thank you so much for posting the wonderful and extremely useful tutorials. Could you please post a tutorial on calculating drawdown and volatility of the strategy? If you have already covered this in any other video, please redirect me to that video. Thanks
Hi buddy, thanks a ton :-)
Please make a video with different buy and sell rule ie buy top 10 but sell only below top 20 like some room to increase hold period.thank you 🙏🙏🙏.
Thanks a lot for your suggestion RAM! 🐏
Great vid! Can you do one with a database and show us how to store it and update it? All the best!
Got a lot of videos like that. Be invited to check out my Python for Finance playlist or also my course :-)
@@Algovibes I love your stuff. I will have to buy your course at some point. :)
Hello Algo,
How can I reach you to talk about Python and trading bot? I have to build my own trading bot with the help of your videos and backtested it. Results are pretty nice in my honest opinion. I would like to hear your ideas and opinions on the results and strategy. I wish we can meet and talk about ;)
Keep it up!
Hi Murat,
thanks a bunch for your comment. Go ahead: what's your strategy? Happy to exchange!
Hello everyone, can someone tell me which jupyter is he using and which theme?
Sure man! I am using Jupyter Notebook here and the theme is Monokai.
24:48 - is anyone else getting "AttributeError: 'str' object has no attribute 'name'" at this point?
EDIT: This was because I attached _to_string()_ to _"win_ = curr_.nlargest(10)"_ so that I could see the full, non-truncated output.
Once I removed it, it worked.
Thanks for sharing the solution. Very good and rare attitude!
Please , one video for binance futures websocket connection. I try 50 time but no response. Please one video.
Thanks a lot for your suggestion!
👏👏👏🙏🙏💪
Thanks a lot Kipkosgei, appreciate your support!
@@Algovibes I don't know what you have planned.. kindly add any of these frameworks in your list ...ccxt ,freqtrade and Jesse ..
And there the like goes.
Man of honor!
OPTION PRICING???
Do you want to know how to do option trading using python?
You mean like designing a model (Black-Scholes/...) which is calculating an option price in Python or what would you be interested in?
Hi, when I run the code below to download the symbols I get an error: Anyone know what to do here?
prices, symbols = [] , [] # for mapping mechanism
for symbol in tickers:
df = yf.download(symbol, start=start)['Adj Close']
if not df.empty:
prices.append(df)
symbols.append(symbol)
AttributeError: 'Series' object has no attribute 'split'
Hi AlgoVibes - I'm using the russell 3000 to run this strategy and i'm getting 2678 columns, but the ticker count is 2697. This creates an error mismatch when I try to set the columns to their corresponding ticker name. In your loop: shouldn't all missing tickers not be appended? Why would there be a mismatch? Thank you!!!
prices, symbols = [],[]
for symbol in tickers:
df = yf.download(symbol, start=start)['Adj Close']
if not df.empty:
prices.append(df)
symbols.append(symbol)
I hope you see this message.
Hi Javier,
sorry, didn't got a notification for that. Just do it as you did and you won't run into problems. You just need to make sure that the tickers list and the dataframes list is in alignment.
Cheers
@@Algovibes thanks algo! How can I make sure the tickers are in alignment?