From Single Stocks to Diversified Portfolios: A Practical Guide to Risk and Return

No of Post Views:

32 hits

Welcome to the fascinating world of financial data analysis! Whether you’re a seasoned investor or just starting, understanding performance and risk of your investments is crucial. In this article, we’ll start with individual stocks then move to evaluating a diversified portfolio. This will equip you with the foundational knowledge and practical Python skills to make informed financial decisions.

The Building Blocks: Understanding Single Asset Returns

Before we can run, we must first learn to walk. In the context of financial analysis, this means mastering the calculation of returns for a single asset. Let’s start with a familiar name: General Electric (GE).

A Quick Recap: Calculating Cash and Percentage Returns

Imagine you bought 100 shares of GE ten years ago. To calculate your cash return, you would use a simple formula:

Formula for calculating cash return on an investment, showing the equation with variables for number of shares and share prices.

Where:

  • \(r_f\) is the final cash return
  • \(p_f\) is the final price per share
  • \(p_i\) is the initial price per share

Let’s use Python to fetch historical data and calculate.

import datetime
import yfinance as yfin

# Define the time period
end_GE = datetime.date(2024, 12, 31)
start_GE = end_GE - datetime.timedelta(365 * 10)

# Download historical data for GE
price_GE = yfin.download(["GE"], start_GE, end_GE)["Close"]
initialPrice_GE = price_GE.iloc[0]
finalPrice_GE = price_GE.iloc[-1]

# Calculate the cash return for 100 shares
cashReturn_GE = (finalPrice_GE - initialPrice_GE) * 100

# Convert to scalar floats for printing
initialPrice_GE_scalar = float(initialPrice_GE)
finalPrice_GE_scalar = float(finalPrice_GE)
cashReturn_GE_scalar = float(cashReturn_GE)


print(
    f"With an initial investment of ${initialPrice_GE_scalar * 100:.2f}, "
    f"the cash return of this investment would be "
    f"(${finalPrice_GE_scalar:.3f} - ${initialPrice_GE_scalar:.3f}) * 100 = ${cashReturn_GE_scalar:.3f}"
)
With an initial investment of $10093.53, the cash return of this investment would be ($167.543 - $100.935) * 100 = $6660.785

While cash return is useful, percentage return provides a more standardized measure of performance. The formula is just as straightforward:

Mathematical formula for percentage return in financial analysis, showing the calculation based on final and initial prices.

This simple calculation forms the basis of our analysis. Now, let’s expand this concept to a portfolio of assets.

The Power of Two: Calculating Portfolio Returns

Investing in a single stock can be risky. A more common approach is to build a portfolio of multiple assets. Let’s consider a simple two-stock portfolio consisting of Meta (formerly Facebook) and Chipotle (CMG).

Determining Your Stakes: Asset Weights

To calculate the return of a portfolio, we first need to calculate the weight of each asset. The weight is simply the proportion of the total portfolio’s value that each asset represents.

Let’s assume we bought 100 shares of both Meta and Chipotle five years ago. We can calculate the initial weights as follows:

# Define the time period
start_stocks = datetime.date(2020, 9, 20)
end_stocks = datetime.date(2025, 9, 20)

# Download historical data
prices_stocks = yfin.download(["META", "CMG"], start_stocks, end_stocks)["Close"]
initialMETA = prices_stocks.META.iloc[0]
initialCMG = prices_stocks.CMG.iloc[0]

# Calculate the initial weights
METAWeight = initialMETA / (initialMETA + initialCMG)
CMGWeight = 1 - METAWeight # The weights must sum to 1

print(f"The initial weight of META was {METAWeight:.2f} and CMG was {CMGWeight:.2f}")
The initial weight of META was 0.91 and CMG was 0.09

The Combined Effect: Portfolio Return Formula

The return of a portfolio is the weighted average of the returns of its individual assets. For our two-stock portfolio, the formula is:

Formula for calculating portfolio returns, illustrating the weighted average of returns from two assets.

Where:

  • \(w_1\) and \(w_2\) are the weights of Meta and Chipotle, respectively.
  • \(R_1\) and \(R_2\) are the returns of Meta and Chipotle, respectively.

Let’s calculate the individual and portfolio returns using Python:

finalMETA = prices_stocks.META[-1]
finalCMG = prices_stocks.CMG[-1]

# Calculate individual percentage returns
returnMETA = 100 * (finalMETA - initialMETA) / initialMETA
returnCMG = 100 * (finalCMG - initialCMG) / initialCMG

# Calculate the portfolio return
portfolioReturn = (returnMETA * METAWeight) + (returnCMG * CMGWeight)

print(f"The return for META was {returnMETA:.2f}% and for Chipotle was {returnCMG:.2f}%")
print(f"The total portfolio return was {portfolioReturn:.2f}%")
The return for META was 215.39% and for Chipotle was 62.95% 

The total portfolio return was 201.82%

As you can see, the portfolio’s return is a blend of the individual returns, influenced by their respective weights.

Beyond Returns: Quantifying Portfolio Risk with Variance

While high returns are desirable, they often come with high risk. In finance, one of the most common measures of risk is variance, which quantifies the volatility of returns.

The Math Behind the Risk: Portfolio Variance Formula

For a two-asset portfolio, the variance is calculated as follows:

Mathematical formula for portfolio variance showing asset weights, variances, and covariance.

Where:

  • \(w_1\) and \(w_2\) are the asset weights.
  • \(σ_1^2\) and \(σ_2^2\) are the variances of the individual assets.
  • \(Cov_1^2\) is the covariance between the two assets, which measures how they move relative to each other.

This formula can be extended to portfolios with any number of assets using matrix algebra. In Python, we can express this as:

Mathematical formula for portfolio variance illustrated with weights and covariance matrix.

Let’s calculate the annual variance of our Meta and Chipotle portfolio.

import numpy as np

# Use slightly different weights for this example
weights_stocks = np.array([0.77, 0.23])

# Calculate daily returns
returns_stocks = prices_stocks.pct_change()

# Calculate the annualized covariance matrix
covariance_stocks = 252 * returns_stocks.cov()

# Calculate the portfolio variance
variance_stocks = np.dot(weights_stocks.T, np.dot(covariance_stocks, weights_stocks))

print(f"The portfolio variance is {variance_stocks:.4f}")
The portfolio variance is 0.0915

The Diversification Effect: Comparing Variances

A key principle of modern portfolio theory is that diversification can reduce risk. Let’s see this in action by comparing our portfolio’s variance to the variances of the individual stocks.

# Calculate individual annualized variances
individual_variances = returns_stocks.var() * 252
print(individual_variances)
Ticker
CMG     0.102976
META    0.190175

You’ll notice that the portfolio’s variance is lower than the variance of either individual stock. This is the magic of diversification at work! As the two stocks are not perfectly correlated, their movements offset each other. This results in a smoother, less volatile portfolio.

The Holy Grail: Measuring Risk-Adjusted Returns with the Sharpe Ratio

A high return is great, but what if it comes with gut-wrenching volatility? The Sharpe Ratio helps us answer this by measuring the return of an investment per unit of risk.

The formula is:

Formula for calculating the Sharpe Ratio, displaying the components: Portfolio Return, Risk Free Rate, and Portfolio Standard Deviation.

The standard deviation is simply the square root of the variance and is often used as a measure of risk. The risk-free rate is the return on an investment with zero risk, such as a government bond. For simplicity, we’ll assume a risk-free rate of 0.

A Sharpe Ratio above 1 is generally considered good. Let’s calculate it for our stock portfolio.

import math

# Annualized portfolio return
annual_return = (portfolioReturn / 100) / 5 # Assuming a 5-year period

# Annualized portfolio standard deviation
annual_std_dev = math.sqrt(variance_stocks)

# Calculate the Sharpe Ratio
sharpe_ratio_stocks = annual_return / annual_std_dev
print(f"The Sharpe Ratio of the stock portfolio is {sharpe_ratio_stocks:.4f}")
The Sharpe Ratio of the stock portfolio is 1.3346

A New Frontier: Analyzing Cryptocurrencies

The principles we’ve discussed are not limited to stocks. Let’s apply them to the exciting world of cryptocurrencies, specifically Bitcoin (BTC) and Ethereum (ETH).

Crypto Portfolio: Returns and Risk

Let’s assume a portfolio with 5 BTC and 100 ETH over a five-year period. We’ll follow the same steps as before to calculate the returns, variance, and Sharpe Ratio.

# Define the time period
start_crypto = datetime.date(2020, 9, 20)
end_crypto = datetime.date(2025, 9, 20)

# Download historical data
prices_crypto = yfin.download(["BTC-USD", "ETH-USD"], start_crypto, end_crypto)["Close"]
prices_crypto = prices_crypto.rename(columns={"BTC-USD": "Bitcoin", "ETH-USD": "Ethereum"})

# Calculate initial and final values
initialBTC_val = 5 * prices_crypto.Bitcoin[0]
initialETH_val = 100 * prices_crypto.Ethereum[0]
finalBTC_val = 5 * prices_crypto.Bitcoin[-1]
finalETH_val = 100 * prices_crypto.Ethereum[-1]

# Calculate weights
BTCWeight_crypto = initialBTC_val / (initialBTC_val + initialETH_val)
ETHWeight_crypto = 1 - BTCWeight_crypto

# Calculate returns
returnBTC_crypto = 100 * (finalBTC_val - initialBTC_val) / initialBTC_val
returnETH_crypto = 100 * (finalETH_val - initialETH_val) / initialETH_val
portfolioReturn_crypto = (returnBTC_crypto * BTCWeight_crypto) + (returnETH_crypto * ETHWeight_crypto)

# Calculate variance (annualized for 365 days)
weights_crypto = np.array([BTCWeight_crypto, ETHWeight_crypto])
returns_crypto = prices_crypto.pct_change()
covariance_crypto = 365 * returns_crypto.cov()
variance_crypto = np.dot(weights_crypto.T, np.dot(covariance_crypto, weights_crypto))

# Calculate Sharpe Ratio
annual_return_crypto = (portfolioReturn_crypto / 100) / 5
annual_std_dev_crypto = math.sqrt(variance_crypto)
sharpe_ratio_crypto = annual_return_crypto / annual_std_dev_crypto

print(f"The crypto portfolio return was {portfolioReturn_crypto:.2f}%")
print(f"The crypto portfolio variance is {variance_crypto:.4f}")
print(f"The Sharpe Ratio of the crypto portfolio is {sharpe_ratio_crypto:.4f}")
The crypto portfolio variance is 0.4076
The Sharpe Ratio of the crypto portfolio is 3.1865

A Tale of Two Portfolios: Stocks vs. Crypto

On comparing the results, we find that the cryptocurrency portfolio exhibits higher returns but also higher variance (risk) than the stock portfolio. Despite the significantly higher risk, crypto portfolio has a better Sharpe ratio. This comparison underscores the importance of considering both risk and return when evaluating investments.

Conclusion: Your Journey Begins

In this article, we’ve laid the groundwork for understanding and analyzing financial assets. We’ve moved from the simple calculation of single-stock returns to the more nuanced evaluation of portfolio risk and performance. You’ve learned how to use Python to fetch and analyze real-world financial data, and you’ve seen the power of diversification.

This is just the beginning of your journey. In next article, we’ll move deeper into the concept of diversification, exploring how it can be quantified and optimized to build more resilient and efficient portfolios. Stay tuned!


Leave a Reply

Discover more from SimplifiedZone

Subscribe now to keep reading and get access to the full archive.

Continue reading

Discover more from SimplifiedZone

Subscribe now to keep reading and get access to the full archive.

Continue reading