FMP
Sep 11, 2023 5:42 PM - Rajnish Katharotiya
Would you like to know how your portfolio is performing and how much risk you are taking? In this post, you will learn how to measure portfolio risk and calculate portfolio returns using Python. We will see step by step how to calculate the risk and returns of a portfolio containing four stocks Apple, Novartis, Microsoft and Google.
Photo by ready made on Pexels
Portfolio return indicates how much loss or gain an investment portfolio has achieved during a period of time. An investment portfolio may include many stocks from different classes.
The investor risk profile will determine how the portfolio is configured. For example, a risk lover investor will have fast (and more) risky growing companies in its portfolio. On the other side, a risk averse investor will probably tend to have a higher number of risk free securities such as Treasury Bond and more mature companies.
By looking into the returns and standard deviations from a few assets, we could easily see that there is a trade off between returns and risk. Take T-bills as an example. Treasury bills have low returns but they also have a very low risk (null risk actually).
But… how can we measure risk?!
To measure the risk of a security, we can use standard deviation. By using the standard deviation we will measure the variability of a stock return distribution over the mean.
A way to reduce risk is to invest in s stocks that do not have a relationship between them. So if one of the stocks would go down in price, the other stock will not follow a similar trend. Therefore, portfolio risks will decrease as the correlation between assets fall. The lower the correlation between the stocks, the lower the risk. We can measure the relationship of two assets in a portfolio using the covariance:
A positive covariance indicates that the return of two selected stocks move in the same direction
A negative covariance means that the return of stocks move in opposite directions.
Having a well diversified portfolio help investors to reduce risk. It is beneficial to invest in stocks which have low correlation between them. There is certain risk that can be eliminated through diversification. That kind of risk is call unsystematic risk.
Unfortunately, not all risk can be removed through diversification. The risk that cannot be diversified is called systematic risk. This type of risk goes beyond a company control. For example, economy recessions.
Total risk = Systematic risk + unsystematic risk
Now that we know a bit more about portfolio returns and risk, we can move on to calculate portfolio risk and portfolio returns using Python.
Lets suppose that we have a portfolio with the following four stocks: Novartis (20%), Apple (30%), Microsoft (30%) and Google (20%).
First, we retrieve closing prices from each of the stocks in our portfolio and add them to a Pandas DataFrame. We will assume that the stocks were bought in the same day for simplicity. The stock prices can be easily retrieved using a financialmodelingprep API.
Note that we loop through each of the stocks to create a Pandas DataFrame containing the date and closing price for each day. We will use the last 900 days of stock price data. Therefore, in order to have the close prices of the four stocks in a single DataFrame, we use concat to merge them all.
import requests
import pandas as pd
import numpy as np
#Variables
key = 'your api key'
stocks = ['NVS','AAPL','MSFT','GOOG']
initial_weight = np.array([0.20,0.30,0.30,0.20])
empresas = {}
#Get all prices into a dataframe
for stock in stocks:
prices = requests.get(f'https://financialmodelingprep.com/api/v3/historical-price-full/{stock}?serietype=line&apikey={key}').json()
prices = prices['historical'][-900:]
prices = pd.DataFrame(prices)
empresas[stock] = prices.set_index('date')
empresas[stock] = empresas[stock]['close']
#Concatenate each of the dataframes into a single dataframe
portfolio = pd.concat(empresas, axis=1)
To conclude the portfolio return section, we can also calculate the cumulative returns of the portfolio by using cumprod. Check out the following link if you want to understand a bit more how that works.
Cumulative_returns_daily = (1+return_stocks).cumprod()
Cumulative_returns_daily.tail(5)
We can visualise cumulative returns as well by plotting the porfolio_daily_returns column.
Cumulative_returns_daily['portfolio_daily_returns'].plot()
Great it seems that the portfolio performs pretty well. We have achieved, for example, a cumulative return of around 127% which is not bad at all. The biggest driver of the excellent return was Microsoft with a cumulative return of around 315%. In the next section, we will have a look at the portfolio risk.
As mentioned above, we are going to calculate portfolio risk using variance and standard deviations. Remember that the standard deviation of daily returns is a common measure to analyse stock or portfolio risk.
We can calculate the standard deviation of a portfolio using three elements:
Portfolio weight array
Portfolio covariance matrix
Transpose of portfolio weight array
Therefore, we need to calculate the covariance matrix since the portfolio weight is given. First, we calculate the daily covariance and then we annualise it by multiplying for 252 (i.e. 252 are more or less the trading days in a year). We use iloc in order to remove the last column (total portfolio returns) from our calculation.
matrix_covariance_portfolio = return_stocks.iloc[:,:-1]
matrix_covariance_portfolio = (matrix_covariance_portfolio.cov())*252
matrix_covariance_portfolio
Having calculated the portfolio covariance, we can calculate the standard deviation which will indicate the risk of our portfolio:
portfolio_variance = np.dot(initial_weight.T,np.dot(matrix_covariance_portfolio, initial_weight))
#standard deviation (risk of portfolio)
portfolio_risk = np.sqrt(portfolio_variance)
portfolio_risk
0.23489504797086014
Finally, after all this matrix operations, we see that the risk of the portfolio is around 23.48%.
We have calculated the portfolio returns and risk for our four stocks. For example, the portfolio cumulative return was of around 127% with a risk of 23%. As next steps, it will be interested to know if we could achieve a similar return lowering the risk. We can do that by optimising our portfolio.
Sep 11, 2023 - Rajnish Katharotiya
Price to Earnings is one of the key metrics use to value companies using multiples. The P/E ratio and other multiples are relative valuation metrics and they cannot be looked at in isolation. One of the problems with the P/E metric is the fact that if we are in the peak of a business cycle, earni...
Sep 11, 2023 - Rajnish Katharotiya
Price-to-Earnings ratio is a relative valuation tool. It is used by investors to find great companies at low prices. In this post, we will build a Python script to calculate Price Earnings Ratio for comparable companies. Photo by Skitterphoto on Pexels Price Earnings Ratio and Comparable Compa...
Oct 17, 2023 - Davit Kirakosyan
Shares of VMware (NYSE:VMW) witnessed a sharp drop of 12% intra-day today due to rising concerns about China's review of the company's significant sale deal to Broadcom. Consequently, Broadcom's shares also saw a dip of around 4%. Even though there aren’t any apparent problems with the proposed solu...