
INTRODUCTION:
Investment Analysis and Portfolio Management has been one of the key areas of interest among all sorts of investors, portfolio managers since long.
Investment Analysis involves evaluating different classes of financial instruments across sectors, markets, geographies and asset classes. It includes analyzing the past historical data like % Daily Return, 20 DMA, 50 DMA (Daily Moving Average), Cumulative Returns, Weighted Returns, Bollinger’s Bands etc in equities, the % change, yields, cumulative total returns, total market cap, z spread etc in bonds) to understand the performance so far as well as to come up with models to predict/forecast future performance, manage risks and adjust the investments for higher yields.
In this particular post we would be focusing on understanding some of the techniques that can be applied on the historical prices to understand how the price movements have been historically and take some decisions based on that.
The focus of this article is only to showcase the different technical indicators that can be plotted based on historical pricing data using Python code. One is advised to do proper research and study before taking any sort of decisions based on these indicators.
We would be using data for the stock Maruti Suzuki available via Yahoo Finance using the yfinance module. We would be plotting charts fpr the following techniques/technical indicators:
- % Daily Returns
- Simple Moving Average
- Exponential Weighted Moving Average
- Cumulative Total Returns
- KDE Plot
- Bollinger’s Band
- Standard Deviation for Risk Analysis
- Annualized Expected Returns
So let’s get started.
% Daily Returns:
This tells us how much we would gain/lose if we bought the stock today and sold it tomorrow. This is a useful analytics to measure the volatility of the stock and helps us to weigh in the risk factor involved if the price movements are extremely volatile. It gives the % of return on a daily basis. Daily return is calculated using the following formula:
Rt = (Pt/Pt-1) -1
Here Pt is the price at time t and Pt-1 is the price at t-1.
Thus it gives the % of return on a daily basis. Let us go ahead and plot the % Daily Return.
# import the required libraries
import yfinance as yf
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import matplotlib.style as style
style.use('seaborn-poster') #sets the size of the charts
style.use('ggplot')
stock_ticker = 'MARUTI.BO'
start_date = '2019-04-05'
end_date = '2020-04-05'
price_field = 'Adj Close'
# fetch the data for the required duration
# the fetched data has Date column set as the DateTimeIndex by default
data = yf.download(stock_ticker, start=start_date, end=end_date)
# Fill in the missing data using forward fill and backward fill
data.fillna(method='ffill', inplace=True)
data.fillna(method='bfill', inplace=True)
# create a final dataframe df_final
# assign the Adj Close as one of the columns in Data Frame
df_final = data[[price_field]]
df_daily_change = df_final.pct_change(1)
# plot the % Daily Return
df_daily_change.plot(figsize = (16,8), title = stock_ticker)

Simple Moving Average :
Moving Average is technique that takes the average price over a defined time period. For eg: 20 day MA will take the average of price values for duration of 20 days. Similarly we can have 30 day MA, 50 day MA and so on. Moving Average helps in filtering out the noise and get a high level picture of price movements. The higher the duration we take the smoother the curve becomes.
# import the required libraries
import yfinance as yf
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import matplotlib.style as style
style.use('seaborn-poster') #sets the size of the charts
style.use('ggplot')
stock_ticker = 'MARUTI.BO'
start_date = '2019-04-05'
end_date = '2020-04-05'
price_field = 'Adj Close'
period = 20 # consider for a 20 Day Moving Average
# fetch the data for the required duration
# the fetched data has Date column set as the DateTimeIndex by default
data = yf.download(stock_ticker, start=start_date, end=end_date)
# Fill in the missing data using forward fill and backward fill
data.fillna(method='ffill', inplace=True)
data.fillna(method='bfill', inplace=True)
# create a final dataframe df_final
# assign the Adj Close as one of the columns in Data Frame
df_final = data[[price_field]]
# CAlculate and assign the 20 Day Moving Average for each of the price points
df_final[str(price_field) + ' : ' + str(period) + ' Day Moving Average'] = df_final.rolling(window=period).mean()
# plot the Price and Mving Average
df_final.plot(figsize = (16,8), title = stock_ticker)

Exponential Weighted Moving Average :
Exponential Moving Average is a technique that also takes the average price over a defined period of time but the prices are weighted. In SMA equal weight is given to all prices whereas in case of EWMA, the prices that are closer to the current date are given more weight than the ones that are further. This helps to get more precise forecasting based on the recent prevailing prices.
# import the required libraries
import yfinance as yf
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import pandas as pd
import matplotlib.style as style
style.use('seaborn-poster') #sets the size of the charts
style.use('ggplot')
stock_ticker = 'MARUTI.BO'
start_date = '2019-04-05'
end_date = '2020-04-05'
price_field = 'Adj Close'
period = 250 # give more weights to the recent dates. 250 is the number of business days in a year
# fetch the data for the required duration
# the fetched data has Date column set as the DateTimeIndex by default
data = yf.download(stock_ticker, start=start_date, end=end_date)
# Fill in the missing data using forward fill and backward fill
data.fillna(method='ffill', inplace=True)
data.fillna(method='bfill', inplace=True)
# create a final dataframe df_final
# assign the Adj Close as one of the columns in Data Frame
df_final = data[[price_field]]
df_final_ewm = df_final.ewm(span=250).mean() # since daily data considered hence taking 250
df_final_ewm.columns = 'EWM ' + df_final_ewm.columns
df_final = pd.merge(df_final, df_final_ewm, left_index=True, right_index=True)
# plot the Price and Mving Average
df_final.plot(figsize = (16,8), title = stock_ticker)

Cumulative Total Returns:
Cumulative Returns is the aggregate return that signifies the total change in price of a stock from the day it was purchased to the current day. Cumulative Returns is calculated using the following formula:

# import the required libraries
import yfinance as yf
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import warnings
warnings.filterwarnings("ignore")
import matplotlib.style as style
style.use('seaborn-poster') #sets the size of the charts
style.use('ggplot')
stock_ticker = 'MARUTI.BO'
start_date = '2016-04-05'
end_date = '2020-04-05'
price_field = 'Adj Close'
# fetch the data for the required duration
# the fetched data has Date column set as the DateTimeIndex by default
data = yf.download(stock_ticker, start=start_date, end=end_date)
# Fill in the missing data using forward fill and backward fill
data.fillna(method='ffill', inplace=True)
data.fillna(method='bfill', inplace=True)
# create a final dataframe df_final
# assign the Adj Close as one of the columns in Data Frame
df_final = data[[price_field]]
df_daily_change = df_final.pct_change(1)
df_cumulative_return = ((1 + df_daily_change).cumprod())
df_cumulative_return = df_cumulative_return * 100
# plot the Cumulative Return in %
df_cumulative_return.plot(figsize = (16,8), title = stock_ticker)

Stay tuned for further updates to this post.
Go ahead and run the above piece of code in your favorite python IDE and Voila you can see the chart plotted.
See you until next time. Happy Learning !
