Erm, your "optimized" portfolio has a Sharpe ratio of 1.35. The unoptimized one had 32%/23% = 1.391. Most likely this is because you use arithmetic annual returns instead of compounded returns: for each stock product(1 + daily returns) - 1.
This was an awesome video. Thank you so much for the instructions. I am just starting Python and love the support. I hope you will do more! You are very good. Thanks again.
Are you able to assist with an optimization model for liability driven investments. Technically, I want to rebalance the portfolio and keep 100% hedge ratio across various tenors. I already have PV01 and IE01 for the bonds. 🙏🏽
I'm wondering if there is a function that lets you optimize for short selling. Is there for example a Monte Carlo method that allows you to do it, maybe with some constraints? That would help a lot because it would give back a market-neutral portfolio, which is always a plus.
Hi Am getting this error "string indices must be integers" when I do the same code " df[stock]=web.DataReader(stock,data_source='yahoo',start=stockStartDate, end=today)['Adj Close'] what am i doing wrong ?
This is awesome! My only comment would be past performance doesn't always dictate future profits. Is it possible to force Python to include all the stocks would removing. And provide a best case with all stocks. Or only remove those which just aren't required.
Sorry I've answered my own question :-) Just needed this ef = EfficientFrontier(mu, S) ef.add_objective(objective_functions.L2_reg, gamma=0.2) ef.min_volatility() w = ef.max_sharpe() print(ef.clean_weights()) ef.portfolio_performance(verbose=True) Along with the from pypfopt import objective_functions Had to increase gamma to larger portfolios as wanted to included as many stocks as possible
At 23:02, you are printing the "Simple Annual Return" as "Expected Annual Return". They are different isn't it? For computing Expected Annual return, you should use historical returns, with a model such as Black-Scholes model? I am confused.
Thank you! this was a great video. I had some problems installing PyPortfolioOpt into my working jupyter notebook. Using pip seemed to work fine but when I tried to import the modules, I kept getting an error, module not found. To fix this, run the following code in a cell in your Jupyter Notebook import sys !{sys.executable} -m pip install PyPortfolioOpt Everything worked after that.
I seem to have the same problem...where the code appears to be loading infinitely and I get no error message, but the package also doesnt install. Did you have this problem too?
@Computer Science. Kindly help me out in installing pyPortfolioOpt. I won't be able to do so as it showing error for the same. Is there any other method for doing the same?? Quick response is highly appreciated.
I am having troubles with the last part on "Get the discrete allocation of each share per stock". When I run the code I get "NameError: Solver GLPK_MI is not installed". How do I go about installing this?
I am getting error "Solver GLPK_MI is not installed"...and m not even able install it while running code for #Get the discrete allocation. Can u guide ?
Love the content: Can you do one on neural networks python price optimizaition, or just more examples of neural networks and python ... Thank you for this content
Thanks for sharing this education , i have try to practice the video but i have got a problem with this line of code is giving me an remotedata error:. can you please help
Very nice video... One question that I have been struggling with on my own is how to calculate/extract the YTD, 1yr, 5yrs, 10yrs, and Life return rate for a number of stocks. Any pointers on how to get these will be appreciated.
Hi !! Awesome content !! Being a Windows user I am unable to use PyPortfolioOptimizer while working on Jupyter .. Do you have any way to go about it? Thanks again !! I usually use R and am new to Python, helped me a lot !! Please post more covering concepts like Mean-Variance Optimization, Risk Parity weighting etc.
Hi Dhruv, I have just seen your comment and I am currently in need of help with using MV, Risk Parity etc on Python. Is it possible you could go over some of your findings?
He calculated the portfolio variance which is an equation consisting of weights of the individuals parts multiplied by their covariances in order to get a single number. This is the basis of portfolio optimization, combining securities in order to diversify away portfolio risk by netting out covariances as best you can
This tutorial is incredible. The only issue I'm having is calculating the portfolio variance. ValueError: shapes (15,15) and (16,) not aligned: 15 (dim 1) != 16 (dim 0).
hey, can you visualize the data? i mean the sharpe ratio, the efficient frontier and all the probable portfolios from different combinations of this 5 stocks.
When should i use log returns instead of simple returns? I always create my portfolio using log returs since they are additive in time but u use simple returns. In short windows of time they are pretty similar but for larger periods of observation that doesn't hold.
Very good video. I personally learned a lot however want to validate if this approach to optimize portfolio is really gonna work i.e. we are looking only at historical data/return to decide our portfolio split, is it ok to only look at the past performance of stocks to decide our portfolio?
You could implement constraints for your stock weights. We know the sums of all of them have to be 1. But you could do something like no stock holds less than 5% weight or no stock has more than 20% weight allocation. It’s very rare that all stocks would be equally weighted especially if you have multiple stocks and a more complex covariance matrix. And then you have to consider long positions (positive weights) and short positions (negative weights). Part of the optimization is figuring out how to assign these weights optimally. That’s fine using an optimizer function in python or R or even SOLVER in excel if you don’t want to code it. Hope that helps :) (financial engineer here)
Thanks for this , extremely easy to follow, great tutorial. I have a question : if I wanted to add a cryptocurrency such as bitcoin as part of the portfolio , how would I do that ?
This doesn't work on mac or am I doing something wrong? I'm getting an error message on the very first word on the code, "from". This is so frustrating, I've been sitting here for 3 hours trying to properly install python and these packages
Does your code still run on colab? I was trying to run a pandas and pandas-datareader example on colab, code from another tutorial, and it appears colab has outdated versions in its runtime environment. I was about to file a report, but others did so in 2020, and no updates are applied. Cudos to you for sharing the content, but I'd rather not get fixated on Colab if they aren't supporting it
make this change to get datareader to work from pandas_datareader import data as pdr import yfinance as yfin yfin.pdr_override() # Get the Stock Symbols in the portfolio assets = ['BND', 'VTI', 'SPY', 'WSM', 'WIRE'] weights = np.array([0.2, 0.2, 0.2, 0.2, 0.2]) df=pd.DataFrame() for stock in assets: df[stock] = pdr.DataReader(stock, data_source='yahoo', start = stockStartDate, end = today)['Adj Close'] df
It's unfortunate this is a great video up until you reach the pyportfolioopt where one tries to get the discrete allocation and as one can see from several comments that the error 'Solver GLPK_MI is not installed' surfaces and no one seems to have a solution for it. So the whole goal after watching 38 minutes and running the code to optimize your portfolio fails. Can anyone resolve? Someone said just to reboot the IDE but that fails too. I have both cvxopt and cvxpy installed. But it needs this GLPK_MI which searching the internet I see no fix for an amateur programmer like myself!
While executing pip install PyPortfolioOpt code in Jupiter it remains unexecuted for infinite time and when done using Anaconda Prompt getting error as "Building wheel for cvxpy (PEP 517) ... error". Hopes u can help me in resolving it.
nice video really helpful. but for me >> pip install pyportfolioopt is not working, it says could not find a version. is it because i am using python 2?
Hi, great content! Could you tell how can I do it to brazilian stocks? I tried it, but in the command "port_variance = np.dot(weights.T, np.dot(cov_matrix_annual, weights)) port_variance" appear an error. Can you help me?
Hi, First of all, I want to thank you for putting such great work for me to learn. looking forward to your other work/tutorial. I am new to the python data science stuff and colaboratory notebook. And I was hoping if you could help me here, I kept running to issue when I code along your video, where " df[stock] = web.DataReader(stock, data_source='yahoo', start =stockStartDate, end=today)['Adj Close']" return error such as "KeyError Traceback (most recent call last) /usr/local/lib/python3.6/dist-packages/pandas/core/indexes/base.py in get_loc(self, key, method, tolerance) 2645 try: -> 2646 return self._engine.get_loc(key) 2647 except KeyError: pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item() KeyError: 'Date' " Do you have any idea what this happened? Thanks
Nice, but dude, you don’t have to read out EVERY single digit in a number. It’s not necessary at all and is pretty annoying. We can see them but more importantly, they’re not significant after a few digits. In other words, it doesn’t matter!
Computer Science because it’s allot easier to follow and meany of my friends would like you to make a bot what predicts the stock market in a text editor that is what would be great
@@ComputerSciencecompsci112358 no disprespect is intended , material is excellent but it's moving in a very low pace, if presentation will be quicker, I think this will be phenomenal :) Again my apologies, did not mean anything personal, just the pace of presentation is slow
Hi there, I'm trying to recreate the Python For Finance Portfolio Optimization code in your RU-vid video, and I think it may have been written for an older version of pandas and datareader because I'm getting some errors. First I had a problem pulling data from Yahoo Finance, and stack overflow said I needed to upgrade pandas, so I did. But now I'm getting another error creating the stock dataframe (and there might be subsequent errors, but I can't get past this step). Here is the error: ValueError Traceback (most recent call last) in () 1 df = pd.DataFrame() 2 for stock in assets: ----> 3 df[stock] = web.DataReader(stock, data_source='yahoo', start = stockStartDate, end = today)['Adj Close'] 10 frames /usr/local/lib/python3.7/dist-packages/pandas/core/indexes/base.py in _validate_can_reindex(self, indexer) 3783 # trying to reindex on an axis with duplicates 3784 if not self._index_as_unique and len(indexer): -> 3785 raise ValueError("cannot reindex from a duplicate axis") 3786 3787 def reindex( ValueError: cannot reindex from a duplicate axis I read a tip to set ignore_index=True, but that didn't work. Do you have any ideas, please? I'm doing this as a school assignment, so your help would be great! Thanks.
I may be too late, but the problem relies on the fact there is an extra space somewhere after "assets:". I fixed the problem by simply deleting all the lines after the colon, then press enter
make this change to get datareader to work from pandas_datareader import data as pdr import yfinance as yfin yfin.pdr_override() # Get the Stock Symbols in the portfolio assets = ['BND', 'VTI', 'SPY', 'WSM', 'WIRE'] weights = np.array([0.2, 0.2, 0.2, 0.2, 0.2]) df=pd.DataFrame() for stock in assets: df[stock] = pdr.DataReader(stock, data_source='yahoo', start = stockStartDate, end = today)['Adj Close'] df