Portfolio Simple Returns

In this article I will show you how to write a python program for finance. This program will show you how to compute portfolio simple returns, daily returns, volatility, variance (risk), co-variance, and stock correlation.

The idea is to create a fictional portfolio containing the 5 best performing tech stocks, Facebook, Amazon, Apple, Netflix, and Google also known as FAANG.

I will also give our portfolio some weights, so 40% of the money invested in this fictional portfolio will be in Facebook, 10% in Amazon, 30% in Apple, 10% in Netflix and 10% in Google.

If you prefer not to read this article and would like a video representation of it, you can check out the YouTube Video below. It goes through everything in this article with a little more detail, and will help make it easy for you to start developing your own program, or you can use both as supplementary materials for learning !

# Start Programming:

I will start by stating what I want this program to do. Again the idea is to create a fictional portfolio containing the 5 best performing tech stocks, Facebook, Amazon, Apple, Netflix, and Google also known as FAANG and compute the portfolio simple returns, daily returns, volatility, variance (risk), co-variance, and stock correlation.

`#Description: This is a python program for finance. #This program will show you how to compute portfolio simple returns, #daily returns, variance, co-variance, and volatility etc.`

# Import The Libraries & Packages

Next import some of the libraries that will be used within this program. We will use the `datetime` library to get the date. The library `pandas_datareader` will be used to get the stock price. The library `pandas` will be used for analysis. The library `numpy` will be used for high level mathematical functions and matrices. The library `matplotlib.pyplot` will be used for graphing, and the style of the graph will be the same style used for the website fivethirtyeight.com, this is achieved by the statement `plt.style.use('fivethirtyeight')` .

`# Import the librariesfrom datetime import datetimeimport numpy as npimport pandas as pdimport pandas_datareader as webimport matplotlib.pyplot as pltplt.style.use('fivethirtyeight')`

# Get The Stock Symbols

Get the stock symbols of the stock that will be in this fictional portfolio and store them in a list. Remember that this portfolio will be using Facebook, Amazon, Apple, Netflix & Google stock also known as “FAANG”.

Amazon symbol = AMZN

Apple symbol = AAPL

Netflix symbol = NFLX

`# Get the stock symbols in your portfoliostockSymbols = ["FB", "AMZN", "AAPL", "NFLX", "GOOG"]`

# Get The Start & End Dates Of The Portfolio

Now let’s get the start date and end date of the portfolio. I am choosing January 1st , 2013 to be the starting date because the Facebook stock wasn’t public until mid 2012 and I want a full year of stock data from Facebook.

`#Get the stock starting datestockStartDate = '2013-01-01'`

The ending date of the portfolio will be whatever the current date is, so I will get today's date and format it accordingly. Then I will print the date just to make sure that it is in the correct format ‘YYYY-mm-dd’

`# Get todays date and format it in the form YYYY-MM-DD today = datetime.today().strftime('%Y-%m-%d')print(today)`

# Get The Number Of Assets In The Portfolio

In this fictional portfolio the number of assets is 5, but maybe later the number of stocks within the portfolio will change and if it does I want a robust way of getting the number of assets in the portfolio. So I’ll do that now.

`# Get the number of assests in the portfolio numAssets = len(stockSymbols) # Print the number of assests in your portfolio print('You have '+ str(numAssets)+ ' assets in your portfolio')`

# Get The Stock Price(s) For The Portfolio

First I will create a function to get the stock Adjusted Close price.

`# Create a function to get the stock price(s) of the portfolio def getMyPortfolio(stocks= stockSymbols, start = stockStartDate, end = today, col='Adj Close'):     data =  web.DataReader(stocks, data_source='yahoo', start=start, end=end)[col]     return data`

Next I will test the function by storing the values in a variable and showing the results.

`# Get the stock portfolio Adj. Close price my_stocks = getMyPortfolio(stockSymbols)# Show my stocksmy_stocks`

# Visually Show The Stock/Portfolio Price(s)

First I want to create a function to visualize the stock in the portfolio.

`# Create a function to visualize the stock/portfoliodef showGraph(stocks= stockSymbols,start=stockStartDate, end=today, col='Adj Close'):    # Create the title   title = 'Portfolio ' + col + ' Price History'    #Get the stocks  my_stocks = getMyPortfolio(stocks= stocks, start=start, end=end, col = col)    # Visualize the price history  plt.figure(figsize=(12.2,4.5))   # Loop through each stock and plot the Adj Close for each day  for c in my_stocks.columns.values:    plt.plot( my_stocks[c],  label=c)    plt.title(title)  plt.xlabel('Date',fontsize=18)  plt.ylabel(col +' Price USD (\$)',fontsize=18)  plt.legend(my_stocks.columns.values, loc='upper left')  plt.show()`

Now that I’m done creating the function, I want to test and show the results.

`# Show the adjusted close price of FAANG                              showGraph(stockSymbols)`

# Analyze The Stocks/Portfolio

Time to analyze the stocks /portfolio and get some measurements. I want to first calculate and show the stock daily simple returns.

`# Calculate Simple Returnsdaily_simple_returns = my_stocks.pct_change(1)daily_simple_returns`

Show the stock correlation. Correlation is used to determine when a change in one variable can result in a change in another. A correlation value of 1 means two stocks have a perfect positive correlation. If one stock moves up while the other goes down, they would have a perfect negative correlation, noted by a value of -1. The correlation will always have a measurement value between -1 and 1.

`# Show the stock correlationdaily_simple_returns.corr()`

Show the co-variance matrix for the daily simple returns. Co-variance can tell how the stocks move together.

`# Show the co-variance matrix for simple returnsdaily_simple_returns.cov()`

The diagonal entries of the co-variance matrix are the variances and the other entries are the co-variances. The co-variance of two stocks tells you how likely they are to increase or decrease simultaneously.

Show the variance. Variance (σ²) in statistics is a measurement of the spread between numbers in a data set. The higher the variance of an asset price, the higher risk the asset bears along with a higher return and a higher volatility. The lower the variance of an asset price, the lower risk the asset bears along with a lower return and a lower volatility.

`# Show the variancedaily_simple_returns.var()`

Get the volatility or square root of variance also known as standard deviation and print it. You can see from the picture below that Google is the least volatile and Netflix is the most volatile and therefore Google is not as risky as the rest of the stocks while Netflix is the riskiest stock in the portfolio.

`# Print the standard deviationprint("The Stock Volatility:")daily_simple_returns.std()`

Now visualize the stocks daily simple returns / volatility.

`# Visualize the stocks daily simple returns / volatility plt.figure(figsize=(12,4.5)) #Set the figure size (width, height)# Loop through each stock and plot the simple returns for each dayfor c in daily_simple_returns.columns.values:  plt.plot(daily_simple_returns.index, daily_simple_returns[c], lw=2, label=c)# Place the legend in the upper left corner with font size of 10plt.legend(loc='upper right', fontsize=10)plt.title('Volatility')plt.ylabel('Daily Simple Returns') #Label the Y-axis simple returnsplt.xlabel('Date')plt.show()`

Show the mean / average / expected daily simple return. As expected the stock that gives the highest return is Netflix and the lowest return is given by Google.

`# Show the mean / average of the daily simple returndailyMeanSimpleReturns = daily_simple_returns.mean()# Print the daily mean simple returnprint("The daily mean simple return: ")print(dailyMeanSimpleReturns)`

Calculate and print the expected portfolio daily performance using random weights. Exactly 40% of the money invested in this fictional portfolio will be in Facebook, 10% in Amazon, 30% in Apple, 10% in Netflix and 10% in Google.

`# Calculate the expected portfolio daily performance with weights# 40% FB, 10% AMZN, 30% AAPL, 10% NFLX, 10% GOOGrandomWeights = np.array([0.4, 0.1, 0.3,0.1,0.1])portfolioSimpleReturn = np.sum(dailyMeanSimpleReturns*randomWeights) # Print the daily expected portfolio returnprint("The daily expected portfolio return: "+str(portfolioSimpleReturn))`

Get the yearly simple return. This can be calculated by taking the portfolio simple return calculation and multiplying it by 253 since there are approximately 253 trading days in a year on average for NASDAQ and NYSE.
The number 253 was calculated from 365.25 (days on average per year) * 5/7 (proportion work days per week) — 6 (weekday holidays) — 3*5/7 (fixed date holidays) = 252.75 ≈ 253.

`# Print the expected annual portfolio simple returnprint("Expected annualised portfolio simple return : "+ str(portfolioSimpleReturn * 253))`

Calculate and show the growth of the investment over this particular period of time. This can easily be achieved by calculating the daily cumulative returns.

`# Calculate the growth of our investmentdailyCumulSimplReturn = (daily_simple_returns+1).cumprod()# Show the cumulative simple returndailyCumulSimplReturn`

Visually show the daily cumulative returns.

`# Visualize the daily cumulative simple returnsfig = plt.figure(figsize=(12.2,4.5))for c in dailyCumulSimplReturn.columns.values:  plt.plot(dailyCumulSimplReturn.index, dailyCumulSimplReturn[c], lw=2, label=c)# Place the legend in the upper left corner with font size of 10plt.legend(loc='upper left', fontsize=10)plt.xlabel("Date")plt.ylabel("Growth of \$1 investment")plt.title("Daily Cumulative Simple Returns")plt.show()`

We can see from this chart that if we had invested \$1 in Netflix in Jan. 2013 , and sold it sometime between the year 2018 and 2019, we would have made 30 times our initial investment.

That’s it, we are done creating this program !

If you are also interested in reading more on Python one of the fastest growing programming languages that many companies and computer science departments use then I recommend you check out the book Learning Python written by Mark Lutz’s. Also you can see the full code in this article here.