Hi MLEnthusiasts! Today, we’ll be learning the concept of logarithmic rate of return and how to calculate it using python.
So, let’s get started by understanding the concept of Logarithmic Rate of Return.
As time progresses, the investments that we take part in increase and earn a compounded return. For bonds, the compound interest is fixed but for stocks, it varies. To calculate this continuously compounded interest, natural logarithm function is used by investors.
For bonds, the formula of log return is given by ln(1 + stated rate of interest)
For stocks, this becomes
The output of this formula results in the continuously compounded rate of return for the given time period.
Let’s begin our analysis by importing the required packages.
#Numpy is the package for scientific computing with python. Array computations are made very easy by using this package.
import numpy as np
#Functions from pandas_datareader.data and pandas_datareader.wb extract data from various Internet sources into a pandas DataFrame.
from pandas_datareader import data as wb
#Using pyplot, we can get interactive plots and generate programmatic plots
import matplotlib.pyplot as plt
Now, let’s extract the historical prices for Procter & Gamble company from yahoo finance using DataReader.
#Importing the data
PG = wb.DataReader('PG', data_source='yahoo', start='1995-1-1')
#Displaying the head of the dataframe PG. head() displays first 5 rows by default.
PG.head()
#pandas.Dataframe.shift(# lags)
#Using shift(1), we can get the row just above the present row. Here, # lags is 1.
#log() is a function given in numpy package in python. It calculates the natural log of the value given inside it.
PG['Log Return'] = np.log(PG['Adj Close']/PG['Adj Close'].shift(1))
#print() function prints the value inside it on the console.
print(PG['Log Return'])
Plotting the Simple Return series using matplotlib.pyplot
PG['Log Return'].plot(figsize=(8,5))
plt.show()
Calculating Daily Average Returns¶
Daily Average Returns are given by computing the mean of the log rate of return series.
daily_log_returns = PG['Log Return'].mean()
daily_log_returns
Calculating Annual Average Returns¶
Annual Average Returns are given by computing the mean of the log rate of return series and then multiplying the value by 250 since 250 days exist in a business day system.
annual_log_returns = PG['Log Return'].mean() * 250
annual_log_returns
Annual average returns percent for PG is given by the following code.
print(str(round(annual_log_returns*100, 2)) +' %')
So, guys, this was the second tutorial on how to apply python in the field of finance and trading. Stay tuned for more tutorials on this.