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.
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 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
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
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?
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 ?
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?
@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.
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.
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. 🙏🏽
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).
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?
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
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
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.
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?
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 ?
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)
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.
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
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?
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 ?
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!
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
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
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?
@@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 RUclips 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
Aye bro deadass this saved me!! took out all the fluff and just gave the essential things to do, cheeers
Great work, but why have your viewer type up the source over again instead of posting the source in Github?
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.
the best py tutorial i ve found on youtube, thanks for the rich content
Wow, thanks!
@@ComputerSciencecompsci112358 Bro how do you even get started? How do I actually make the code work and run properly?
very well narrated. and loved working on colab. thanks mate
Thanks, glad you enjoyed it!
This guy sounds like Naval. Insightful video, thank you.
Really didactic! Greetings from Brazil
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.
I never noticed this, thank you !
@@ComputerSciencecompsci112358 You're welcome, and thanks for the video.
How would you fix this? Where in the code?
@@ComputerSciencecompsci112358 you could at least "ping" his comment for other people as the video will mislead many people. Don't you think ?
This is a 10/10 tutorial
please make more
Great content, I was able to follow along easily and clearly!
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.
Thanks and yes that is possible!
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
WHere can we find your colab? Amazing video btw
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
伸手党就是牛批嗷
Neural network doesn't work my friend
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?
use !pip install PyPortfolioOpt
Dude you´re a pro
Thank you, I wouldn't consider myself a pro, but thanks again for the kind words.
Excellent. You forgot to plot Efficient Frontier.
Can you make a discord group or telegram ?
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.
dude your a legend
Haha thank you!
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 ?
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?
Try "conda install -c conda-forge cvxopt" in anaconda or "pip install cvxopt". restart you ide if necessary. Happend the same thing to me
@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 have the same problem, may be library doesn't work correctly
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.
Nice video. How would you deal with weekly rebalanced stocks from a universe?
Great video! could you please show us how to rebalance the portfolio
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. 🙏🏽
Really well explained sir. Can you please share the link to the article related to this video.
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).
make your # of weights the same # as the # of stocks you have so 15 stocks you need 15 weights
You are fab!!
Thanks Priya !!! 😊
While installing PyPortfolioOpt ..getting error - The filename, directory name, or volume label syntax is incorrect
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.
Hey, you should download C++. As a Mac user I also had to download Xcode and Command Line Developer tools for Xcode
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?
good job
Thanks !
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
how do I plot the efficient frontier graph?
Awesome video! But I'd like to ask why the port_variance in 17:34 is a single number?
Isn't the result a 1x5 matrix instead of a single number?
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
Awesomeness!
Thanks !
God bless you man
good program , simple explanation
Thanks you!
How would you add constraints such as min and max weights for each stock
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.
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?
it´s not sufficient. In the end of the day this is not telling you much except what would have worked
So how effective is this program do you think?
What does DCP error mean and why does it happen whan I expand the number of stocks to 16 and have 16 weight values of 0.0625?
is the code shared on github ?
Great video!
Love the channel
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 ?
Amazing job!!!
are you sure it's the right way to calculate annual returns?
Hi, is there a better way of assigning the weights to the stocks? Assuming that there could be more stocks in a portfolio. Cheers.
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)
Very good job
i am not getting the point why we eliminate the google stocks can someone please explain me
Great session 👍
you tried with indian NSE data?
Dear Admin, can you make a tutorial session for predicting Raininfall/ Weather forecast.
Regards
Kazim
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.
I love you man
GREAT VIDEO !
I have an error reading the data from yahoo, does anyone else have the same ptoblem?
TypeError: string indices must be integers
can you buy stocks not in rounded numbers, like not 6 shares of Facebook, but 5.666?
Hello can you share the data you used in this video
Thank you
why did you calculate the simple return (in 13:55) instead of log return
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
how did you try to install the 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
you should use f strings f'sometext{variable}'
can we have negative weights from this program? like shorting the market at risk free rate.
i think the best way to implement that would be just multiplying the returns of the shorted stock by -1 or what ever leverage u got
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.
I got the same error message. Did you solve the problem?
@@Felixgarb Not Yet...
Same problem here, could you find the solution?
I have no idea how to solve this. Same problem here.
Hi can you share how otot add a constraint for the optimization using pyportfolioopt?
what was the profit of that portafolio? 200%?
is it possible to do the same from a local source?
how would you add different colours to the chart at 13:21 ? For when there are more than 5 stocks.
32:21 shows df as not defined for me (((
Shouldn’t the returns be multiplied together to get annual return?
I have 1245 CSV files how can I use them for python?
Can the colors be painted with an if condition such as if one stock is over or greater than the other, then color.green else color.red?
the unit for variance is % squared, not %
where can i get the datset?
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?
It's not working here as well. And my version is Python 3
@@pedrocampos-tg2ne same story here, and I've tried different ways. I'm using python 3 in Anaconda
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 ?
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!
have u found the solution yet ? :D
How can I use this codes for Indian stocks?
Awesome video!
On my channel I make python tutorial videos too and I am always inspired by your content
Variance should be in %^2
Anybody knows how to solve the problem of install pyPortfolioOpt?
I couldn't install here too
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!
Can you make your videos in a text editor
Yes but why ?
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
@@ademottoman962 I think this is lot better
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
see if u typed the stock symbol correctly
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?
ERIK RODRIGUES what kind of error.
@@lividpudding8565 I am getting the same error. ValueError: shapes (15,15) and (16,) not aligned: 15 (dim 1) != 16 (dim 0)
@@cervmeup assuming you have 15 assets in your portfolio, the weight vector will be (15,) and the covariance matrix will be a square matrix of (15,15)
please show it for indian data once... please.... please... please...!!
I am trying but not working..!!!
Without optimization:
Expected annual return: 168.0%
Annual volatility/risk: 28.999999999999996%
Annual variance: 9.0%
After optimization:
Expected annual return: 10721.0%
Annual volatility: 113.7%
Sharpe Ratio: 94.24
Not exactly a fan of 113.7% risk factor... lol
With that sharpe you could reduce volatility by holding cash.
someone have the codes in somewhere?
🤯
u didnt import yinnace duuuumas
guide to install pyPortFolioOpt i have tried many ways but unsuccesfull all the time help me
sound is horrible and can bearishly be heard without pumping volume to the fullest ....
than visit fewer parties... wtf
boring
Sorry you think so, thanks for your opinion!
@@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
@@ahmedqassem4326 If you click the settings icon on the video, you can set the speed to 1.5. I do this on many videos.
Hi there,
I'm trying to recreate the Python For Finance Portfolio Optimization code in your RUclips 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
@hayesfj1 Thank you so much for this solution, I was struggling with this. It helped a lot.
what risk measure are you implementing