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"

КОМЕНТАРІ • 49

  • @RyanOConnellCFA
    @RyanOConnellCFA  Рік тому +2

    👨‍💼 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/

  • @brittoneden9667
    @brittoneden9667 2 місяці тому

    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?

  • @sciwizShreyasKulkarni
    @sciwizShreyasKulkarni 8 місяців тому +2

    Really great video, the explanation was to the point & crisp. You just earned a like :)

  • @heshanpalliyaguruge6333
    @heshanpalliyaguruge6333 Рік тому +1

    This is so cool. We did this in our portfolio analysis class using excel solver

    • @RyanOConnellCFA
      @RyanOConnellCFA  Рік тому +3

      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

  • @user-nz2tp8co6q
    @user-nz2tp8co6q 11 місяців тому +1

    than you so much
    these are very useful video
    thank you so much

    • @RyanOConnellCFA
      @RyanOConnellCFA  11 місяців тому

      You are most welcome, it is my pleasure!

  • @misterr2359
    @misterr2359 Місяць тому +1

    Dude, you are insane. Excellent video!

  • @diegobleinrothrodriguez2585
    @diegobleinrothrodriguez2585 Місяць тому

    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?

  • @oliverweldner8704
    @oliverweldner8704 14 днів тому

    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?

  • @dalenjournigan6957
    @dalenjournigan6957 14 днів тому

    Really great video, how should one replicate this without the outlines?

  • @ericg8461
    @ericg8461 7 місяців тому +1

    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

    • @RyanOConnellCFA
      @RyanOConnellCFA  7 місяців тому

      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?

  • @pranavkumar1734
    @pranavkumar1734 13 днів тому

    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

  • @andrespoire1854
    @andrespoire1854 7 місяців тому +2

    So much quicker than Excel, thanks.

    • @RyanOConnellCFA
      @RyanOConnellCFA  7 місяців тому

      Its my pleasure!

    • @lionzion5382
      @lionzion5382 6 місяців тому

      Tbh I would Never go back to Excel if non-data stakeholders didnt require products in Excel 😪

  • @tracywang1
    @tracywang1 4 місяці тому +1

    Thanks for sharing!
    I'm wondering why we dont use current risk free rate instead of 5 year average risk free rate?

    • @RyanOConnellCFA
      @RyanOConnellCFA  4 місяці тому

      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

  • @mohamedassili2678
    @mohamedassili2678 3 місяці тому

    Why do you not annualize the standard deviation?

  • @victoricus1
    @victoricus1 Рік тому +2

    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?

    • @RyanOConnellCFA
      @RyanOConnellCFA  Рік тому +1

      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

    • @victoricus1
      @victoricus1 Рік тому +1

      @@RyanOConnellCFA you might as well become a professor at MIT or something) thank you for this detailed explanation!

    • @RyanOConnellCFA
      @RyanOConnellCFA  Рік тому

      @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

    • @victoricus1
      @victoricus1 Рік тому +1

      @@RyanOConnellCFA if you have the spirit and the smarts, you should definitely follow your dreams!

    • @RyanOConnellCFA
      @RyanOConnellCFA  Рік тому

      Much appreciated!

  • @aarondelarosa3146
    @aarondelarosa3146 Рік тому

    Could you use scatter plot? So, you can show sharpe ratio in the bar.

    • @RyanOConnellCFA
      @RyanOConnellCFA  Рік тому +1

      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

  • @aarondelarosa3146
    @aarondelarosa3146 Рік тому +1

    Excellent. Could you plot Efficient Frontier?

    • @RyanOConnellCFA
      @RyanOConnellCFA  Рік тому +2

      This is a video I have on my future to-do list Aaron!

  • @JL-hq4sg
    @JL-hq4sg 3 місяці тому +1

    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.

    • @RyanOConnellCFA
      @RyanOConnellCFA  3 місяці тому

      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

  • @gordiemarshall1336
    @gordiemarshall1336 6 місяців тому +1

    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!

    • @RyanOConnellCFA
      @RyanOConnellCFA  6 місяців тому

      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

    • @gordiemarshall1336
      @gordiemarshall1336 6 місяців тому +1

      @@RyanOConnellCFA will do, thanks so much.

    • @RyanOConnellCFA
      @RyanOConnellCFA  6 місяців тому

      @@gordiemarshall1336 My pleasure!

  • @pranithadeverachetty240
    @pranithadeverachetty240 8 місяців тому +1

    What if I wanted to do this with monthly adjusted closing prices? Where would I add that in the code?

    • @RyanOConnellCFA
      @RyanOConnellCFA  8 місяців тому +1

      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.

  • @DeepVoiced
    @DeepVoiced 4 дні тому

    NameError: name 'neg_sharpe_ratio' is not defined. Any idea what this is about, Ryan? (sharpe_ratio is already defined)

    • @DeepVoiced
      @DeepVoiced 4 дні тому

      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.

  • @forzakule
    @forzakule 3 місяці тому +1

    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.

    • @RyanOConnellCFA
      @RyanOConnellCFA  3 місяці тому

      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.

  • @hakankosebas2085
    @hakankosebas2085 10 місяців тому +1

    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

    • @RyanOConnellCFA
      @RyanOConnellCFA  10 місяців тому +1

      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

    • @hakankosebas2085
      @hakankosebas2085 10 місяців тому +1

      @@RyanOConnellCFA yes, unfortunatly in turkey each year holdays are in diffirent days, that complicated things for me

  • @AdoptedPoo
    @AdoptedPoo 2 місяці тому

    hello i get an error TypeError: unsupported format string passed to Series.__format__