Portfolio Optimization in Python: Boost Your Financial Performance
Вставка
- Опубліковано 19 чер 2024
- Ryan O'Connell, CFA, FRM shows you how to perform portfolio optimization in Python. Have you ever wondered how to calculate the optimal portfolio from a group of risky stocks or securities? Find out here!
🎓 Tutor With Me: 1-On-1 Video Call Sessions Available
► Join me for personalized finance tutoring tailored to your goals: ryanoconnellfinance.com/finance-tutoring/
👨💼 My Freelance Financial Modeling Services:
► Custom financial modeling solutions tailored for your needs: ryanoconnellfinance.com/freelance-finance-services/
💻 Code Here: ryanoconnellfinance.com/portf...
Chapters:
0:00 - Intro to Portfolio Optimization in Python
0:36 - Import Required Libraries
1:52 - Define Securities and Time Range
3:57 - Import Adjusted Close Prices From yFinance
6:48 - Calculate Daily Returns (Lognormal)
8:36 - Calculate the Covariance Matrix
9:57 - Calculate Optimal Weights of the Portfolio
10:07 - Calculate Portfolio Expected Return and Standard Deviation
13:38 - Calculate the Sharpe Ratio
14:56 - Retrieve the Risk Free Rate from the FRED API
16:51 - Set the Initial Weights and Constraints
18:13 - Find the Weights in the Optimal Portfolio
20:44 - Display the Optimal Portfolio Results
Get Free FRED API Key: fred.stlouisfed.org/docs/api/...
*Disclosure: This is not financial advice and should not be taken as such. The information contained in this video is an opinion. Some of the information could be wrong. This channel is owned and operated by Portfolio Constructs LLC
Alternative Titles:
"Portfolio Optimization Mastery: Enhance Your Investments with Python"
"Python for Portfolio Optimization: Boost Your Financial Performance"
"Discover the Power of Python in Portfolio Optimization"
"Portfolio Optimization Techniques: Unleash Python's Potential"
"Optimal Investment Strategies: Portfolio Optimization with Python"
"Achieve Financial Success through Portfolio Optimization in Python"
"Mastering Portfolio Optimization: Python's Guide to Better Investments"
"Supercharge Your Investments: Portfolio Optimization using Python"
"The Python Advantage: Expert Portfolio Optimization Tips"
"Portfolio Optimization in the Digital Age: Python's Winning Formula"
👨💼 My Freelance Financial Modeling Services:
► Custom financial modeling solutions tailored for your needs: ryanoconnellfinance.com/freelance-finance-services/
💻 Code Here: ryanoconnellfinance.com/portfolio-optimization-using-python-and-modern-portfolio-theory/
this is amazing!! our professor just demoed at class but it was so quick that I couldn't even follow. but your video is clear and easy to understand!!! even i still found it a bit difficult to understand the covariance matrix part (my bad). thank you so much! can you share a bit on training and backtesting a model and rebalance pls?
Really great video, the explanation was to the point & crisp. You just earned a like :)
Glad you liked it!
This is so cool. We did this in our portfolio analysis class using excel solver
Thanks, you might recognize this then! I made a video about portfolio optimization in Excel 2 years ago: ua-cam.com/video/4zKipaNAnOM/v-deo.html
than you so much
these are very useful video
thank you so much
You are most welcome, it is my pleasure!
Dude, you are insane. Excellent video!
Thank you man! I appreciate it
Great video, Ryan. Thanks a lot! Just got a problem with my code when optimizing the weights to maximize my portfolio's sharpe ratio. When I execute the cell it returns this: ValueError: operands could not be broadcast together with shapes (4,) (3,). Any ideas why is this happening?
Hi Ryan, thanks for this great video i just went from total beginner (didnt have anything installed beforehand) to having a ready-model to optimize the portfolio. I tried this out with my personal portfolio which includes around 25 positions and when you use that much positions it just gives me 4 stocks to optimize the portfolio (40% COST, 20% DE, 10% DTEGF, 30% NVDA). This is nice and i guess correct but it goes against the Markowitz' assumption of diversification. How would you tackle that so you have good diversification and no overdivisification at the same time?
Really great video, how should one replicate this without the outlines?
First off, this is a top notch video. Excellent job.
I'm sure I'll find the problem as soon as I submit this comment but my Sharpe Ratio is coming up as 1756.8647....which would be phenomenal is possible.
My date inputs are End_date = 11/7/2023 and start date is End_date - (5*365)
The Expected returns = 10.9977
The Expect Volatility = 0.0062 which looks low to me
BND: 0.5 GLD 0.39 QQQ 0.11
To me, it looks like your expected return is far too high and your expected volatility is far too low. You probably did something wrong when determining the daily returns or rolling returns. Did you figure out your problem yet?
Sir I have proceeded as you said but on Jupyter notebook , making changes in console.log() but my covariance matrix values is coming different from your values after 1st decimal places. And my sharp ratio is differing a lot . Can you tell me why this is happening and where I can show u my code
So much quicker than Excel, thanks.
Its my pleasure!
Tbh I would Never go back to Excel if non-data stakeholders didnt require products in Excel 😪
Thanks for sharing!
I'm wondering why we dont use current risk free rate instead of 5 year average risk free rate?
I think it is best to use the current risk free rate due to the decision being what to invest in right now and into the future
Why do you not annualize the standard deviation?
thank you! in practise, to use this model effectively how large a portfolio should be, and how long a time horizon should be? does it make sense to use it for just 3 types of assets for, like, 3 years? And I'm not quite clear on the interpretation of the Sharpe ratio of 0.48. They say that SR less than 1 is bad, but here we have gold and nasdaq ETFs with a low SR, but that does not necessarily mean that we have to invest elsewhere? Oh and also, could you please make a vid on how to optimize a bond porfolio by means of python?
Hello! I'm glad you found the video helpful. Let me address your questions one by one.
Portfolio size and time horizon: The effectiveness of this model does not rely solely on the number of assets or the length of the time horizon. However, including a diverse set of assets can improve the risk-reward balance in the portfolio. While you can use this model for a portfolio with just three types of assets over a three-year time horizon, it might be more effective with a broader set of assets and a longer time horizon. This will allow you to capture more varied market dynamics and potentially improve the overall optimization results.
Sharpe Ratio interpretation: A Sharpe Ratio of 0.48 indicates that the risk-adjusted return of the portfolio is lower compared to a portfolio with a higher Sharpe Ratio. While it's true that a Sharpe Ratio below 1 is considered suboptimal, it doesn't mean you must necessarily invest elsewhere. Instead, consider optimizing the portfolio further or re-evaluating the constraints to achieve a better risk-return balance. Also, keep in mind that the Sharpe Ratio is just one of many performance metrics to consider when evaluating a portfolio.
Bond portfolio optimization video: This is definitely something I can look into in the future but it may not happen for a while
@@RyanOConnellCFA you might as well become a professor at MIT or something) thank you for this detailed explanation!
@victoricus1 Hahah I appreciate it! I definitely don't have the education required for that. Also, I stubbornly want to be an entrepreneur even if it is less prestigious and more work than some other career routes
@@RyanOConnellCFA if you have the spirit and the smarts, you should definitely follow your dreams!
Much appreciated!
Could you use scatter plot? So, you can show sharpe ratio in the bar.
Hey Aaron, to create a scatter plot I'd have needed to done an implementation where i ran lets say 10,000 simulations then stored all the results. This implementation just uses an iterative process to find the highest sharpe ratio so we cannot use it to create a scatter plot
I will however be releasing an Excel based implementation of portfolio optimization similar to what you just described in about 1 month
Excellent. Could you plot Efficient Frontier?
This is a video I have on my future to-do list Aaron!
Hi, how do you make sure that the dates are the exact same for each? when I download manually, I always have to clean the data myself first before starting to analyze it. Otherwise, some companies will have some extra date and price that others do not have.
In the script, after downloading the adjusted close prices for each asset using the yfinance library, one effective approach to ensure consistency across dates for all assets is to use the pandas DataFrame's .dropna() method, which can be applied to the DataFrame storing the adjusted close prices. This step will remove any rows where at least one asset does not have data, ensuring that only dates where all assets have a price are included in the analysis
Hi Ryan, I'm having an issue in running the optimized _results function, the error is being traced back to to the standard_deviation function. The error message itself is saying AttributeError: 'function' object has no attribute 'T', which I believe is referring to where we transpose weights using weights.T . Would love some help in figuring this out. Thanks!
It is really hard for me to say without seeing the rest of your code, the error is likely stemming from an earlier mistake. Try running your code through ChatGPT to see if it can catch your bug. Its a great debugging tool
@@RyanOConnellCFA will do, thanks so much.
@@gordiemarshall1336 My pleasure!
What if I wanted to do this with monthly adjusted closing prices? Where would I add that in the code?
If you're looking to switch from daily to monthly adjusted closing prices, several areas of the provided code would need alterations:
(Define Tickers and Time Range): Adjust the time range calculation to ensure you're downloading sufficient data points. You could either keep the 5-year window but remember that when resampling to monthly data, you'll end up with a smaller dataset (roughly 60 data points). Depending on the breadth and depth of your analysis, you might want to adjust the range to capture more years of data.
(Download Adjusted Close Prices): After downloading the daily data, resample the data to capture the monthly adjusted close prices. After the line adj_close_df[ticker] = data['Adj Close'], insert the code: adj_close_df = adj_close_df.resample('M').last(). This will convert your dataset to show the adjusted close prices on the last trading day of each month.
(Calculate Lognormal Returns): The calculation here remains the same, but do remember that the frequency of returns is now monthly, not daily.
(Calculate Covariance Matrix): Adjust the annualization factor. Since you're working with monthly data, replace the * 252 with * 12 to reflect 12 months in a year. So the covariance matrix calculation should be: cov_matrix = log_returns.cov() * 12.
NameError: name 'neg_sharpe_ratio' is not defined. Any idea what this is about, Ryan? (sharpe_ratio is already defined)
Just realized part of the code where you define "neg_sharpe_ratio" is missing in the video. It's in the code in the link in the description of the video for anyone looking for it.
I believe you forgot to define objective function for the optimization fuction which is negative sharpe ratio. So I don't get it how your optimization function worked out.
The objective function for the optimization process is defined as the negative Sharpe ratio through the neg_sharpe_ratio function. This function is passed as the first argument to the minimize method from the Scipy library, effectively guiding the optimization to maximize the Sharpe ratio by minimizing its negative value. Therefore, the optimization function operates as intended by directly using the negative of the Sharpe ratio as its objective to be minimized.
I don't understand, you are multiplying with 252 which is weekend in a year, but don't you americans have diffirent holidays, isn't stocks closes on holidays? because we can't trade on extra holidays on Turkey also they are changing in every year, sometimes they are match up with weekend sometimes not, I couldn't figure out this problem
Hello, 252 is often used as the default assumption for number of trading days in a year. This # accounts for holidays. There are 365 days in the year for most years (leap years excluded). 5/7 of those are weekdays. So (5/7)*365 = 261. Then assuming there are 9 holidays each year where stock exchanges arent open, we get 261 -9 = 252 trading days per year
@@RyanOConnellCFA yes, unfortunatly in turkey each year holdays are in diffirent days, that complicated things for me
hello i get an error TypeError: unsupported format string passed to Series.__format__