Risk and Return
In financial terms, risk is characterized as the probability that an investment's actual gains or results will deviate from the anticipated outcome or return. From a measurable standpoint, risk is typically evaluated by examining past behaviors and results. In finance, a widely used metric linked to risk is standard deviation.
On the other hand, financial return(often referred to as just return) can be succinctly defined as the profit or loss generated from an investment during a specific duration. A portfolio’s return is mathematically represented by the expectation formula. This formula is a generalization of the weighted average of the portfolio’s value.
Risk-free return is the theoretical return of an investment that has no risks involved. A commonly used approximation of this value is the return provided by sovereign bonds.
Sharpe ratio assesses risk-adjusted returns by comparing a fund's performance and volatility to a benchmark. It’s calculated as the portfolio's excess return divided by standard deviation.
Striking a balance between minimizing risk to safeguard capital and maximizing returns for wealth growth is crucial for optimizing the overall risk-return trade-off, ensuring long-term financial stability.
The Compound Annual Growth Rate(CAGR) provides a smoothed-out measure of an investment's average annual return. To calculate it, you find the nth root of the ratio between the final value of the investment after n periods and the initial value. Then, subtract one from this result and convert it into a percentage. Essentially, CAGR assumes that the investment grows at a constant rate over the specified time frame, with returns reinvested and compounded. This makes it a handy tool for comparing investment performance over different periods. Nevertheless, it's important to note that CAGR doesn't account for the volatility or fluctuations experienced along the way.
The risk aversion parameter represents an investor's willingness to take on risk in pursuit of higher returns. It is multiplied by the portfolio variance and subtracted from the portfolio return within the optimization framework to maximize the risk-adjusted return. An optimal risk aversion parameter typically falls within a range of 0.2 to 10, with values closer to 0 indicating lower aversion to risk and values closer to 10 reflecting higher aversion to risk.
Modern Portfolio Thoery
Modern portfolio theory suggests that risk and return must be balanced to generate greater returns without a higher level of risk. The theory helps investors to construct portfolios that can maximize returns for a given acceptable risk.
The return of the portfolio is the profit or loss generated in a specific time period. The portfolio's return can be calculated by the expectation formula, which is the weighted sum of the expected returns of its constituent stocks.
Where:
E(Rp) is the expected return of the portfolio.
E(Ri) is the expected return of asset i.
wi is the weight of asset i in the portfolio.
Risk, according to MPT, is the deviation from the average return of a stock. The risk of a portfolio is a function of the variance of each stock and the correlation between them. Because of the correlation between each stock, the total risk is less than the risk calculated by the weighted sum.
Portfolio creation is essential for diversification. Diversification helps in risk mitigation as different stocks react differently in the same conditions. Mathematically, if the correlation between 2 stocks is negative, it reduces the total risk, while a positive correlation between stocks increases the standard deviation or risk of the portfolio. The formula of the correlation coefficient is given as:
We define an iso-mean curve to be the set of all points with a given expected return. An increase in expected return does not change the slope of an iso-mean curve’s line, but only its intercept. This means that the iso-mean curve in a Markowitz portfolio is a system of parallel lines. Each point represents a separate portfolio.
An iso-variance curve is defined to be the set of all points with a given variance of return. Since variance is the squared form of the standard deviation, the curve is used to depict the risk levels graphically. The iso-variance curve in this theory takes the shape of a system of concentric ellipses. The center of this system is the point where we minimize the variance and, thereby, the risk. The point of the iso-mean line at which the variance takes on its least value is the point at which the iso-mean line is tangent to an iso-variance curve.

If a portfolio is well diversified, then the idiosyncratic risk is lower or negligible because the loss in a stock is likely to be covered by the gain in another stock. However, diversification cannot lower systematic risk as it is common to the entire market. A well-constructed portfolio not only decreases risk but also helps in the optimization of returns.
The purpose of MPT is optimization, which refers to selecting the optimal portfolio from all the possible portfolio combinations. An optimal portfolio is one that provides the maximum return for a given level of risk or the minimum risk for a given level of return. This requires mathematical calculations to determine the weights of each asset in the portfolio.
Applying Modern Portfolio Theory
The optimization strategy used in the provided code is based on the principles of mathematical optimization and is employed to find the optimal weights for constructing investment portfolios. Specifically, when coding the same in Python, it utilizes the scipy.optimize module to maximize an objective function representing the trade-off between portfolio returns and risks.
The math behind Markowitz Optimization Theory
The breakdown of the Optimization strategy can be given as follows:
Objective function: the goal of the objective function is to either risk minimization for a specified return or maximization of returns for a given risk.
Mathematically, it can be represented as:
\(f(x) = {\mu^Tx - {\delta \sqrt{x^T\Sigma x}}} \)Here, the Expected Return is a weighted sum of the expected returns of individual assets, and the Portfolio Variance is a measure of the overall risk of the portfolio. The Risk Aversion parameter reflects the investor's willingness to trade-off between risk and return. Variance is substituted by the standard deviation in such a manner as not to affect the risk-aversion parameter. This form is favorable because then the standard deviation penalty term will be of the same scale as the portfolio return. Moreover, if we assume portfolio return to be normally distributed, then δ has a more tangible meaning.
We can see that for δ = 0, we maximize the expected portfolio return. Then, by increasing, we put more and more weight on tail risk, i.e., we maximize a lower and lower quantile of portfolio return. This makes the selection of δ more intuitive in practice. Note that computing quantiles is more complicated for other distributions because, in general, they are not determined by only mean and standard deviation.
Constraint: For the purpose of optimization, some constraints are imposed. Here, to ensure that the entire investment is fully utilized, the sum of all the weights assigned to all assets in the portfolio must be equal to 1. This can be written as:
\(1^Tx = 1\)
Sectors used for analysis
The following sectors were analyzed from May 2019 to May 2022 to subject the portfolio to a macroeconomic event, COVID-19:
E-Commerce: Amazon [AMZN], Alibaba [BABA], EBay [EBAY], MercadoLibre [MELI], Pinduoduo [PDD], Rakuten [RKUNF], Shopify [SHOP]
Banks: State Bank of India [SBIN], HDFC Bank [HDFCBANK], ICICI Bank [ICICIBANK], Axis Bank [AXISBANK], Kotak Mahindra Bank [KOTAKBANK], Punjab National Bank [PNB], Bank of Baroda [BANKBARODA]
Automobiles: Tesla [TSLA], Toyota [TM], General Motors [GM], Ford [F], Stellantis [STLA], Honda [HMC], Ferrari [RACE]
Aviation: Honeywell International [HON], Elbit Systems [ESLT], Boeing [BA], Raytheon Technologies [RTX], Lockhead Martin [LMT], Northrop Grumman [NOC], TransDigm [TDG]
Oil: Schlumberger [SLB], Chevron [CVX], Occidental Petroleum [OXY], Exxon Mobil [XOM], ConocoPhillips [COP], Halliburton Co. [HAL], BP [BP]
Python libraries required
The datetime and timedelta functions from datetime make it convenient to work with dates and date arithmetic.
The minimize function from SciPy(scipy.optimize to be exact) is used to minimize the objective function i.e. the negative of the portfolio return minus the risk aversion parameter times the portfolio variance. This yields the optimal weights of each stock in the desired sector.
Numpy is used to work mathematical operations upon arrays and matrices.
Pandas makes it efficient to work on data frames.
MatPlotLib is used to plot the efficient frontier and the monthly stock-wise distribution.
Finally, yfinance aids in importing stock data from Yahoo Finance.
Exponentially Moving Averages
The ema function returns the exponential moving average of the closing price on a particular day. The exponential moving average is the weighted mean of the closing price, wherein a higher weight is assigned to recent data. This is then used in the select_portfolio function, where the 9-day EMA is compared to the 21-day EMA. If the EMA of the shorter duration is greater than the longer, it indicates a bullish trend, thus appending the corresponding stocks to the portfolio at the start of the month. In our project, we have used EMA as an indicator to create portfolios.
Optimization Algorithm
Data Retrieval and Preprocessing:
The get_stock_data function fetches historical stock price data from Yahoo Finance for a given symbol and time range.
The ema function calculates the Exponential Moving Average (EMA) of the closing prices of a stock over a specified duration.
Objective Function and Optimization:
The objective_function function defines the objective function for portfolio optimization. It maximizes the risk-adjusted return (Sharpe ratio) of the portfolio by considering both portfolio return and risk (portfolio variance).
The maximize_objective function utilizes the Sequential Least Squares Programming (SLSQP) optimization algorithm to find the optimal portfolio weights that maximize the objective function subject to constraints.
Constraints ensure that the weights sum up to 1, indicating that the entire investment is allocated among the assets.
Portfolio Selection:
The select_portfolio function selects stocks for the portfolio based on the Exponential Moving Average (EMA) crossover strategy. If the EMA with a shorter duration is higher than the EMA with a longer duration, the stock is included in the portfolio.
Optimal Portfolio Weights Calculation:
The get_optimal_weights function calculates the optimal weights for each selected portfolio using historical stock data. It computes expected returns and the covariance matrix of returns for each portfolio period and uses the maximize_objective function to find optimal weights.
Performance Evaluation:
The calculate_cagr function calculates the Compound Annual Growth Rate (CAGR) of the portfolio over the entire duration. It computes the cumulative returns of each portfolio period and derives the net CAGR using the geometric mean.
Visualization:
The plot_pie_chart function visualizes the portfolio weightage for a given date using a pie chart.
Overall, the code performs portfolio optimization by dynamically selecting portfolios based on the EMA crossover strategy and finding the optimal allocation of assets to maximize the risk-adjusted return. It evaluates the performance of the optimized portfolios in terms of CAGR and visualizes the weightage of assets in the portfolio.
Example
When running the code for e-commerce companies for the month of June 2019 and taking the risk aversion parameter to be 3, the following portfolio is being generated with the CAGR value being 6.77%.
Analysis
Overall, one significant analysis of the entire project is low growth rate values for portfolios which was caused by the decline in stock prices in the aftermath of COVID-19. In a situation where the prices of many stocks were declining, this project helps us understand the performances of various portfolios.
Code
The link to the Python notebook wherein the code of the above project is provided: