How to Optimize & Rebalance a Stock Portfolio | R
Vložit
- čas přidán 1. 06. 2020
- I demonstrate how to rebalance & optimize a portfolio on a quarterly basis. You can rebalance on any time frame (monthly, quarterly, semi-annually, etc.) with the function we construct in this video.
#AlgorithmicTrading #Stocks #PortfolioOptimization - Věda a technologie
Great video! Thank you!
Glad you liked it!
Great video. I was getting a couple NULL moments at the end, but it turns out I needed to reinstall/update my DEoptim package. I actually ended up using the c("DEoptim", "random", "ROI") optimize method and itermax = 50 and yeah ... I can see why you wouldn't want to use that method inside a youtube structure. Takes so long. But it works!
Thanks Isaiah, I am sure your comment will be helpful for others wondering the same.
Excellent video sir, with example , Thanks for making this for us.
Thank you, I am glad it was helpful!
Great video! Is it possible to find/optimize a Long-Short portfolio using similar methodology?
Great video!!!!!!!!
Thank You!
Does the optimizer rebalance using the previously calculated weights? let's say for the first month I get certain weights and on the next rebalancing date, does it take into account (w-wp) or just a fixed number? Thanks!
Each rebalancing period is independent...it just grabs the data for each period and attempts to return the best weights without considering past results, only what is available.
Hi, first I would like to say what a great video, then I was wondering if there were any chances to see the for loop formula to avoid repeating: wts1,wts2 ecc.
Hello thank you! Thanks for bringing that up. In the PortfolioAnalytics package documentation there is a wrapper called *extractWeights()* that should pull all the weights from the portfolio object.
Thanks for the video. I tried to so the same thing but got an error in line 33
("Error in if (message) message("min not passed in as vector, replicating min to length of length(assets)") : argument is not interpretable as logical").
I also tried to find it in the stackoverflow but didn't get any solution for this. Can you help me with this?
Perhaps you didn't copy something correctly? The error stems from line 31... basically you have to pass in a vector of numeric weights for all the assets as min. If you have 4 stocks then min that has to pass into line 33 has to be *c(0.05, 0.05, 0.05, 0.05)* which is what line 31 is trying to accomplish. Check that line 31 is truly returning a vector of numeric weights.
It's a great video. Could you tell me the difference between portfolio re-balance and re-optimize? I am using 'portfolioBacktest' function in 'portfolioBacktest' package in R, and I am confused about the two parameters ('optimize_every' and 'rebalance_every').
You can lookup the documentation on the functions by running ?portfolioBacktest in RStudio. They usually list how the parameters are used.
Great video! I have a question though. With p1, p2 etc. you get the combined returns for each month. How would you get the returns separately for each asset for every month?
Thank you. At 13:16 I get the out-of-sample returns using the optimized weights in line 58, which gets you the returns for each asset by day. You can run something like: *colSums(RETS[,names(wts1)]["201807/201809"] )* this will give you each asset's return over the entire time-period. Hope that helped & apologize for the delay in responding.
Nice content!
Why did you choose DEoptim as your optimize method? I recall there are some other options like ROI
You are right, I just like this algorithm over the others. You can try to test using a different algo such as ROI and compare the results. They should hopefully yield very close results.
I´ve got a little problem in line 37-39 Error in UseMethod("extractObjectiveMeasures") :
no applicable method for 'extractObjectiveMeasures' applied to an object of class "c('simpleError', 'error', 'condition')"
Can you help me?
Is the function name optimize.portfolio.rebalancing() changed to optimize.portfolio.rebalancing2() ... I think that specific error comes from using the original function & trying to rebalance quarterly... see 6:42
@@ileo89 I got the same error message. were you able to figure it out?
Hey, do you know how to change the risk-free rate before optimizing?
Hello, you can try and read in the risk free rate via quantmod::getSymbols.FRED() ... I typically read in the "DGS10" (10 year treasury constant maturity). You can then subtract the risk-free rate from your stock returns, and use those adjusted returns for optimization.
@@quantroom Wouldn't that mess with the standard deviation?
This is truly brilliant. Your videos are always high-quality. How did you get so good at R? This is really awesome! Thanks a lot for your efforts!
Thank you! I have been using R for several years but still have more to learn.
@@quantroom Very interesting. Currently I'm struggling with in sample and out of sample performance based on business cycle phases. Any hints?
Hi Jason - your videos are really helpful !! I am a newbie at R but it's very helpful to see you walk through the code to help explain how it works. Quick question - I don't see a GitHub link for this video. Do you know where I could download the code ?
Thank you! If there is no GitHub I probably did not upload. This may have been in my old computer, If I find the script, I will provide a link.
@@quantroom Is this code still available ?
Thanks for the great video.
I've noticed that obviously the weightings will differ depending on the number of iterations and the optimization method.
Is there any way to get more consistent weightings?
Thank you very much in advance and keep up the great work.
Thanks Kanal, regarding the weights it differs each iteration as the optimization is testing/trying different combinations. If you set `itermax` to say 1000/2000 iterations you will notice a consistent weighing as it approached the itermax. Once you see this consistent weighing each iteration it may mean it has found the optimal weight for each stock given your constraints.
@@quantroom Thanks for your quick reply. Wouldn't it be more efficient to optimize on the test window (e.g. with optimize.portfolio) and use these weights for the next period instead of using this iterative approach. I don't understand 100% why the procedure is iterative?
Thanks a lot in advance.
Thanks for the video!! It was very helpful listening your explanation throughout the video! Quick question from a newbie: Is there any way to rebalance the portfolio randomly?
Once again, thank you for the video!
Thanks Pablo. I believe in the package documentation you can find how to add random portfolios, not entirely sure how it used in the optimization but I just remember seeing that somewhere.
How many iterations do you recommend being enough? I don't want to go overkill on it
I would say 100 iterations should suffice.
Hi, when i am trying to fill opt1 and later wts1 etc., wts1 and the other wts return NULL. I think optimize_method ="DEoptim", is not working. Did someone fix that issue?
Try installing and the requiring the DEoptim package.
Great video! Just wanted to check one thing. Are you optimizing the future of the portfolio based upon what was optimal in the past?
Thank you! Yes, it is!
help. I cant get the output then I run opt1
try searching the error it gives you in google, most can be answered from StackOverflow
I get this error message at the 10:41 time stamp - > optimizer was unable to find a solution for target. I have only two Etf funds in their could that be the problem ?
Hello Alex, you can cut and paste the error message into google and see if there are any solutions.
When I print opt1, its giving me "Error in UseMethod("extractObjectiveMeasures"): no applicable method for 'extractObjectiveMeasures' applied to an object of class "c('simpleError', 'error', 'condition')...
How do you solve this?
I don't know if this is an error from the package but see their CRAN. I just googled the error and took me to their CRAN PortfolioAnalytics issue 22.
What if I want to use my own data how do I supplement this info for an excel data set in a folder on my desktop ?
You can use your own data as long as you format it in R (ex. checking the column names, column classes, etc). From R you can output tables in CSV format to analyze in Excel.
Hi How can I check the out of sample performance of a maximized Sharpe Ratio portfolio?
I covered that in the later part of the video. I extracted the weights and applied those weights in the out of sample data. You can check out my video on Risk-Parity Portfolio Optimization, there is another package to run this type of portfolio optim.
@@quantroom Thanks Quant. I'm gonna do that tonight
there is a problem with python reading yahoo's URL, any help?
Not sure, I rarely use python & but I am sure you can find answers from someone who knows more python
Thank you, great tutorial !
Could have been every better with al little bit more explanation :)
Thanks for the feedback, I will try to be more thorough in future videos.
portfolio.spec function does not work on my end
Not sure, maybe look up the error on StackOverflow
Would be great if u could explain each function role before implementing it. Great job tho !
Thanks for the recommendation. I will be sure to explain functions thoroughly in future videos.
how can I use Risk Parity optim method?
I created a separate tutorial for risk parity portfolio. If you really want to use DEoptim you would have to create a function that optimizes for equal-risk.
Thank you, I saw your video about risk parity, I did everything but I have a problem with rebalance_every and optimize_every functions. I did the exact thing you did in the video, but when I plot weight allocation over time they’re steady, they never change. Why is that? And how I can solve this problem? Really thanks for your tutorials, very helpful.
@quantroom
dang I got to the very end only to get a error message. lol
:/ I hope you were able to debug