Get Started

Calculating portfolio returns

In order to build and backtest a portfolio, you have to be comfortable working with the returns of multiple assets in a single object.

In this exercise, you will be using a pandas DataFrame object, already stored as the variable StockReturns, to hold the returns of multiple assets and to calculate the returns of a model portfolio.

The model portfolio is constructed with pre-defined weights for some of the largest companies in the world just before January 2017:

Company Name Ticker Portfolio Weight
Apple AAPL 12%
Microsoft MSFT 15%
Exxon Mobil XOM 8%
Johnson & Johnson JNJ 5%
JP Morgan JPM 9%
Amazon AMZN 10%
General Electric GE 11%
Facebook FB 14%
AT&T T 16%

Note that the portfolio weights should sum to 100% in most cases

This is a part of the course

“Introduction to Portfolio Risk Management in Python”

View Course

Exercise instructions

  • Finish defining the numpy array of model portfolio_weights with the values according to the table above.
  • Use the .mul() method to multiply the portfolio_weights across the rows of StockReturns to get weighted stock returns.
  • Then use the .sum() method across the rows on the WeightedReturns object to calculate the portfolio returns.
  • Finally, review the plot of cumulative returns over time.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Finish defining the portfolio weights as a numpy array
portfolio_weights = np.array([0.12, 0.15, 0.08, 0.05, 0.09, 0.10, 0.11, ____, ____])

# Calculate the weighted stock returns
WeightedReturns = StockReturns.____(portfolio_weights, axis=____)

# Calculate the portfolio returns
StockReturns['Portfolio'] = WeightedReturns.____(axis=____)

# Plot the cumulative portfolio returns over time
CumulativeReturns = ((1+StockReturns["Portfolio"]).cumprod()-1)
CumulativeReturns.plot()
plt.show()
Edit and Run Code

This exercise is part of the course

Introduction to Portfolio Risk Management in Python

IntermediateSkill Level
4.5+
11 reviews

Evaluate portfolio risk and returns, construct market-cap weighted equity portfolios and learn how to forecast and hedge market risk via scenario generation.

Level up your understanding of investing by constructing portfolios of assets to enhance your risk-adjusted returns.

Exercise 1: Portfolio composition and backtestingExercise 2: Calculating portfolio returns
Exercise 3: Equal weighted portfoliosExercise 4: Market-cap weighted portfoliosExercise 5: Correlation and co-varianceExercise 6: The correlation matrixExercise 7: The co-variance matrixExercise 8: Portfolio standard deviationExercise 9: Markowitz portfoliosExercise 10: The efficient frontierExercise 11: Sharpe ratiosExercise 12: The MSR portfolioExercise 13: The GMV portfolio

What is DataCamp?

Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.

Start Learning for Free