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.
Nov 25, 2023 6:39 AM - Parth Sanghvi
Choosing the Right Valuation Method: DCF vs. Comparable Companies Analysis Introduction: Valuation methods play a pivotal role in determining the fair value of a company, aiding investors in making informed investment decisions. Two commonly used methods, DCF Valuation and Comparable Companies A...
Dec 25, 2023 2:31 AM - Parth Sanghvi
Introduction: The Discounted Cash Flow (DCF) model stands as a cornerstone in investment analysis, offering a robust framework for estimating the intrinsic value of an investment. In this comprehensive guide, we delve into the fundamentals of DCF analysis, providing step-by-step instructions, key...
Jan 4, 2024 1:56 AM - Parth Sanghvi
The Discounted Cash Flow (DCF) model remains a cornerstone in financial analysis, offering a strategic way to assess the intrinsic value of an investment. With advancements in technology, the integration of Big Data and Artificial Intelligence (AI) presents a transformative approach to enhance the p...