In investing, portfolio optimization is the task of selecting assets such that the return on investment is maximized while the risk is minimized. For example, an investor may be interested in selecting five stocks from a list of 20 to ensure they make the most money possible. Portfolio optimization methods, applied to private equity, can also help manage and diversify investments in private companies. More recently, with the rise in cryptocurrency, portfolio optimization techniques have been applied to investments in Bitcoin and Ethereum, among others.
In each of these cases, the task of optimizing assets involves balancing the trade-offs between risk and return, where return on a stock is the profits realized after a period of time and risk is the standard deviation in an asset's value.Many of the available methods of portfolio optimization are essentially extensions of diversification methods for assets in investing. The idea here is that having a portfolio of different types of assets is less risky than having ones that are similar.
Finding the right methods for portfolio optimization is an important part of the work done by investment banks and asset management firms. One of the early methods is called mean variance optimization, which was developed by Harry Markowitz and, consequently, is also called the Markowitz Method or the HM method. The method works by assuming investors are risk-averse. Specifically, it selects a set of assets that are least correlated (i.e., different from each other) and that generate the highest returns. This approach means that, given a set of portfolios with the same returns, you will select the portfolio with assets that have the least statistical relationship to one another.
For example, instead of selecting a portfolio of tech company stocks, you should pick a portfolio with stocks across disparate industries. In practice, the mean variance optimization algorithm may select a portfolio containing assets in tech, retail, healthcare and real estate instead of a single industry like tech.Althoughthis is a fundamental approach in modern portfolio theory, it has many limitations such as assuming that historical returns completely reflect future returns.
Additional methods like hierarchical risk parity (HRP) and mean conditional value at risk (mCVAR) address some of the limitations of the mean variance optimization method. Specifically, HRP does not require inverting of a covariance matrix, which is a measure of how stock returns move in the same direction. The mean variance optimization method requires finding the inverse of the covariance matrix, however, which is not always computationally feasible.
Further, the mCVAR method does not make the assumption that mean variance optimization makes, which happens when returns are normally distributed. Since mCVAR doesnt assume normally distributed returns, it is not as sensitive to extreme values like mean variance optimization. This means that if a stock has an anomalous increase in price, mCVAR will be more robust than mean variance optimization and will be better suited for asset allocation. Conversely, mean variance optimization may naively suggest we disproportionately invest most of our resources in an asset that has an anomalous increase in price.
The Python package PyPortfolioOpt provides a wide variety of features that make implementing all these methods straightforward.Here, we will look at how to apply these methods to construct a portfolio of stocks across industries.
More From Sadrach PierreNeed to Perform Financial Data Analysis? Why Python Is Your Best Tool.
We will pull stock price data using the Pandas-Datareader library. You can easily install the library using pip in a terminal command line:
Next, lets import the data reading in a new Python script:
We should pull stocks from a few different industries, so well gather price data in healthcare, tech, retail and finance. We will pull three stocks for each industry.Lets start by pulling a few stocks in healthcare. We will pull two years of stock price data for Moderna, Pfizer and Johnson & Johnson.
First, lets import Pandas and relax the display limits on rows and columns:
Next, lets import the datetime module and define start and end dates:
Now we have everything we need to pull stock prices. Lets get data for Moderna (MRNA):
Lets wrap this logic in a function that we can easily reuse since we will be pulling several stocks:
Now, lets pull for Pfizer (PFE) and Johnson & Johnson (JNJ):
Lets define another function that takes a list of stocks and generate a single data frame of stock prices for each stock:
Now, lets pull stocks for the remaining industries:
Healthcare: Moderna (MRNA), Pfizer (PFE), Johnson & Johnson (JNJ)
Tech: Google (GOOGL), Facebook (FB), Apple (AAPL)
Retail: Costco (COST), Walmart (WMT), Kroger Co (KR)
Finance: JPMorgan Chase & Co (JPM), Bank of America (BAC), HSBC Holding (HSBC)
We now have a single dataframe of returns for our stocks. Lets write this dataframe to a csv so we can easily read in the data without repeatedly having to pull it using the Pandas-Datareader.
Now, lets read in our csv:
Now we are ready to implement the mean variance optimization method to construct our portfolio. Lets start by installing the PyPortfolioOpt library:
Now, lets calculate the covariance matrix and store the calculated returns in variables S and mu, respectively:
Next, lets import the EfficientFrontier module and calculate the weights. Here, we will use the max Sharpe statistic. The Sharpe ratio is the ratio between returns and risk. The lower the risk and the higher the returns, the higher the Sharpe ratio. The algorithm looks for the maximum Sharpe ratio, which translates to the portfolio with the highest return and lowest risk. Ultimately, the higher the Sharpe ratio, the better the performance of the portfolio.
We can also display portfolio performance:
Finally, lets convert the weights into actual allocations values (i.e., how many of each stock to buy). For our allocation, lets consider an investment amount of $100,000:
Our algorithm says we should invest in 112 shares of MRNA, 10 shares of GOOGL, 113 shares of AAPL and 114 shares of KR.
We see that our portfolio performs with an expected annual return of 225 percent. This performance is due to the rapid growth of Moderna during the pandemic. Further, the Sharpe ratio value of 5.02 indicates that the portfolio optimization algorithm performs well with our current data. Of course, this return is inflated and is not likely to hold up in the future.
Mean variance optimization doesnt perform very well since it makes many simplifying assumptions, such as returns being normally distributed and the need for an invertible covariance matrix. Fortunately, methods like HRP and mCVAR address these limitations.
The HRP method works by finding subclusters of similar assets based on returns and constructing a hierarchy from these clusters to generate weights for each asset.
Lets start by importing the HRPOpt method from Pypfopt:
We then need to calculate the returns:
Then run the optimization algorithm to get the weights:
We can now print the performance of the portfolio and the weights:
We see that we have an expected annual return of 24.5 percent, which is significantly less than the inflated 225 percent we achieved with mean variance optimization. We also see a diminished Sharpe ratio of 1.12. This result is much more reasonable and more likely to hold up in the future since HRP is not as sensitive to outliers as mean variance optimization is.
Finally, lets calculate the discrete allocation using our weights:
We see that our algorithm suggests we invest heavily into Kroger (KR), HSBC, Johnson & Johnson (JNJ) and Pfizer (PFE) and not, as the previous model did, so much into Moderna (MRNA). Further, while the performance decreased, we can be more confident that this model will perform just as well when we refresh our data. This is because HRP is more robust to theanomalous increase in Moderna stock prices.
The mCVAR is another popular alternative to mean variance optimization. It works by measuring the worst-case scenarios for each asset in the portfolio, which is represented here by losing the most money. The worst-case loss for each asset is then used to calculate weights to be used for allocation for each asset.
Lets import the EEfficicientCVAR method:
Calculate the weights and get the performance:
Next, get the discrete allocation:
We see that this algorithm suggests we invest heavily into JP Morgan Chase (JPM) and also buy a single share each of Moderna (MRNA) and Johnson & Johnson (JNJ). Also we see that the expected return is 15.5 percent. As with HRP, this result is much more reasonable than the inflated 225 percentreturns given by mean variance optimizationsince it is not as sensitive to the anomalous behaviour of the Moderna stock price.
The code from this post is available on GitHub.
More in FinanceIs Your Startup Fundraising in 2021? This Is Your Time.
Although we only considered healthcare, tech, retail and finance, the methods we discussed can easily be modified to consider additional industries. For example, maybe you are more interested in constructing a portfolio of companies in the energy, real estate and materials industry. An example of this sort of portfolio could be made up of stocks such as Exxonmobil (XOM), DuPont (DD), and American Tower (AMT). I encourage you to play around with different sectors in constructing your portfolio.
What we discussed provides a solid foundation for those interested in portfolio optimization methods in Python. Having a knowledge of both the methods and the tools available for portfolio optimization can allow quants and data scientists to run quicker experiments for optimizing investment portfolio.
View post:
An Introduction to Portfolio Optimization in Python - Built In
- Global Data Science Platform Market Report 2020 Industry Trends, Share and Size, Complete Data Analysis across the Region and Globe, Opportunities and... [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Data Science and Machine-Learning Platforms Market Size, Drivers, Potential Growth Opportunities, Competitive Landscape, Trends And Forecast To 2027 -... [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Industrial Access Control Market 2020-28 use of data science in agriculture to maximize yields and efficiency with top key players - TechnoWeekly [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- IPG Unveils New-And-Improved Copy For Data: It's Not Your Father's 'Targeting' 11/11/2020 - MediaPost Communications [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Risks and benefits of an AI revolution in medicine - Harvard Gazette [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- UTSA to break ground on $90 million School of Data Science and National Security Collaboration Center - Construction Review [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Addressing the skills shortage in data science and analytics - IT-Online [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Data Science Platform Market Research Growth by Manufacturers, Regions, Type and Application, Forecast Analysis to 2026 - Eurowire [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- 2020 AI and Data Science in Retail Industry Ongoing Market Situation with Manufacturing Opportunities: Amazon Web Services, Baidu Inc., BloomReach... [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Endowed Chair of Data Science job with Baylor University | 299439 - The Chronicle of Higher Education [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- Data scientists gather 'chaos into something organized' - University of Miami [Last Updated On: November 11th, 2020] [Originally Added On: November 11th, 2020]
- AI Update: Provisions in the National Defense Authorization Act Signal the Importance of AI to American Competitiveness - Lexology [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Healthcare Innovations: Predictions for 2021 Based on the Viewpoints of Analytics Thought Leaders and Industry Experts | Quantzig - Business Wire [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Poor data flows hampered governments Covid-19 response, says the Science and Technology Committee - ComputerWeekly.com [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Ilia Dub and Jasper Yip join Oliver Wyman's Asia partnership - Consultancy.asia [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Save 98% off the Complete Excel, VBA, and Data Science Certification Training Bundle - Neowin [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Data Science for Social Good Programme helps Ofsted and World Bank - India Education Diary [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Associate Professor of Fisheries Oceanography named a Cooperative Institute for the North Atlantic Region (CINAR) Fellow - UMass Dartmouth [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Rapid Insight To Host Free Webinar, Building on Data: From Raw Piles to Data Science - PR Web [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- This Is the Best Place to Buy Groceries, New Data Finds | Eat This Not That - Eat This, Not That [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Which Technology Jobs Will Require AI and Machine Learning Skills? - Dice Insights [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Companies hiring data scientists in NYC and how much they pay - Business Insider [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Calling all rock stars: hire the right data scientist talent for your business - IDG Connect [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- How Professors Can Use AI to Improve Their Teaching In Real Time - EdSurge [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- BCG GAMMA, in Collaboration with Scikit-Learn, Launches FACET, Its New Open-Source Library for Human-Explainable Artificial Intelligence - PRNewswire [Last Updated On: January 12th, 2021] [Originally Added On: January 12th, 2021]
- Data Science Platform Market Insights, Industry Outlook, Growing Trends and Demands 2020 to 2025 The Courier - The Courier [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- UBIX and ORS GROUP announce partnership to democratize advanced analytics and AI for small and midmarket organizations - PR Web [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Praxis Business School is launching its Post Graduate Program in Data Engineering in association with Knowledge Partners - Genpact and LatentView... [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- What's So Trendy about Knowledge Management Solutions Market That Everyone Went Crazy over It? | Bloomfire, CSC (American Productivity & Quality... [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Want to work in data? Here are 6 skills you'll need Just now - Siliconrepublic.com [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Data, AI and babies - BusinessLine [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Here's how much Amazon pays its Boston-based employees - Business Insider [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Datavant and Kythera Increase the Value Of Healthcare Data Through Expanded Data Science Platform Partnership - GlobeNewswire [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- O'Reilly Analysis Unveils Python's Growing Demand as Searches for Data Science, Cloud, and ITOps Topics Accelerate - Business Wire [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Book Review: Hands-On Exploratory Data Analysis with Python - insideBIGDATA [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- The 12 Best R Courses and Online Training to Consider for 2021 - Solutions Review [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Software AG's TrendMiner 2021.R1 Release Puts Data Science in the Hands of Operational Experts - Yahoo Finance [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- The chief data scientist: Who they are and what they do - Siliconrepublic.com [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Berkeley's data science leader dedicated to advancing diversity in computing - UC Berkeley [Last Updated On: January 31st, 2021] [Originally Added On: January 31st, 2021]
- Awful Earnings Aside, the Dip in Alteryx Stock Is Worth Buying - InvestorPlace [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Why Artificial Intelligence May Not Offer The Business Value You Think - CMSWire [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Getting Prices Right in 2021 - Progressive Grocer [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Labelbox raises $40 million for its data labeling and annotation tools - VentureBeat [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- How researchers are using data science to map wage theft - SmartCompany.com.au [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Ready to start coding? What you need to know about Python - TechRepublic [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Women changing the face of science in the Middle East and North Africa - The Jerusalem Post [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Mapping wage theft with data science - The Mandarin [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Data Science Platform Market 2021 Analysis Report with Highest CAGR and Major Players like || Dataiku, Bridgei2i Analytics, Feature Labs and More KSU... [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Data Science Impacting the Pharmaceutical Industry, 2020 Report: Focus on Clinical Trials - Data Science-driven Patient Selection & FDA... [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- App Annie Sets New Bar for Mobile Analytics with Data Science Innovations - PRNewswire [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- Data Science and Analytics Market 2021 to Showing Impressive Growth by 2028 | Industry Trends, Share, Size, Top Key Players Analysis and Forecast... [Last Updated On: February 12th, 2021] [Originally Added On: February 12th, 2021]
- How Can We Fix the Data Science Talent Shortage? Machine Learning Times - The Predictive Analytics Times [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Opinion: How to secure the best tech talent | Human Capital - Business Chief [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Following the COVID science: what the data say about the vaccine, social gatherings and travel - Chicago Sun-Times [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Automated Data Science and Machine Learning Platforms Market Technological Growth and Precise Outlook 2021- Microsoft, MathWorks, SAS, Databricks,... [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- 9 investors discuss hurdles, opportunities and the impact of cloud vendors in enterprise data lakes - TechCrunch [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Rapid Insight to Present at Data Science Salon's Healthcare, Finance, and Technology Virtual Event - PR Web [Last Updated On: February 14th, 2021] [Originally Added On: February 14th, 2021]
- Aunalytics Acquires Naveego to Expand Capabilities of its End-to-End Cloud-Native Data Platform to Enable True Digital Transformation for Customers -... [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Tech Careers: In-demand Courses to watch out for a Lucrative Future - Big Easy Magazine [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Willis Towers Watson enhances its human capital data science capabilities globally with the addition of the Jobable team - GlobeNewswire [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Global Data Science Platform Market 2021 Industry Insights, Drivers, Top Trends, Global Analysis And Forecast to 2027 KSU | The Sentinel Newspaper -... [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- A Comprehensive Guide to Scikit-Learn - Built In [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Industry VoicesBuilding ethical algorithms to confront biases: Lessons from Aotearoa New Zealand - FierceHealthcare [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- How Intel Employees Volunteered Their Data Science Expertise To Help Costa Rica Save Lives During the Pandemic - CSRwire.com [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Learn About Innovations in Data Science and Analytic Automation on an Upcoming Episode of the Advancements Series - Yahoo Finance [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Symposium aimed at leveraging the power of data science for promoting diversity - Penn State News [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Rochester to advance research in biological imaging through new grant - University of Rochester [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- SoftBank Joins Initiative to Train Diverse Talent in Data Science and AI - Entrepreneur [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Participating in SoftBank/ Correlation One Initiative - Miami - City of Miami [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Increasing Access to Care with the Help of Big Data | Research Blog - Duke Today [Last Updated On: February 22nd, 2021] [Originally Added On: February 22nd, 2021]
- Heres how Data Science & Business Analytics expertise can put you on the career expressway - Times of India [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Yelp data shows almost half a million new businesses opened during the pandemic - CNBC [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Postdoctoral Position in Transient and Multi-messenger Astronomy Data Science in Greenbelt, MD for University of MD Baltimore County/CRESST II -... [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- DefinedCrowd CEO Daniela Braga on the future of AI, training data, and women in tech - GeekWire [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Gartner: AI and data science to drive investment decisions rather than "gut feel" by mid-decade - TechRepublic [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Jupyter has revolutionized data science, and it started with a chance meeting between two students - TechRepublic [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- Working at the intersection of data science and public policy | Penn Today - Penn Today [Last Updated On: March 14th, 2021] [Originally Added On: March 14th, 2021]
- The Future of AI: Careers in Machine Learning - Southern New Hampshire University [Last Updated On: April 4th, 2021] [Originally Added On: April 4th, 2021]
- SMU meets the opportunities of the data-driven world with cutting-edge research and data science programs - The Dallas Morning News [Last Updated On: April 4th, 2021] [Originally Added On: April 4th, 2021]
- Data, Science, and Journalism in the Age of COVID - Pulitzer Center on Crisis Reporting [Last Updated On: April 4th, 2021] [Originally Added On: April 4th, 2021]