Moving average is a simple, technical analysis tool. Moving averages are usually calculated to identify the trend direction of a stock or to determine its support and resistance levels. It is a trend-following—or lagging—indicator because it is based on past prices.
There are various types of moving averages, like SMA & EMA so I tried to create a moving average indicator in which I have plotted 2 moving averages with the help of historical data.
A simple moving average (SMA) is a calculation that takes the arithmetic mean of a given set of prices over the specific number of days in the past; for example, over the previous 15, 30, 100, or 200 days.
Exponential moving averages (EMA) is a weighted average that gives greater importance to the price of a stock on more recent days, making it an indicator that is more responsive to new information.
# Load the necessary packages and modules
from pandas_datareader import data as pdr
import matplotlib.pyplot as plt
import yfinance
import pandas as pd
# Simple Moving Average
def SMA(data, ndays):
SMA = pd.Series(data['Close'].rolling(ndays).mean(), name = 'SMA')
data = data.join(SMA)
return data
# Exponentially-weighted Moving Average
def EWMA(data, ndays):
EMA = pd.Series(data['Close'].ewm(span = ndays, min_periods = ndays - 1).mean(),
name = 'EWMA_' + str(ndays))
data = data.join(EMA)
return data
# Retrieve the Nifty data from Yahoo finance:
data = pdr.get_data_yahoo("^NSEI", start="2020-01-01", end="2021-03-19")
data = pd.DataFrame(data)
close = data['Close']
# Compute the 50-day SMA for NIFTY
n = 50
SMA_NIFTY = SMA(data,n)
SMA_NIFTY = SMA_NIFTY.dropna()
SMA = SMA_NIFTY['SMA']
# Compute the 200-day EWMA for NIFTY
ew = 200
EWMA_NIFTY = EWMA(data,ew)
EWMA_NIFTY = EWMA_NIFTY.dropna()
EWMA = EWMA_NIFTY['EWMA_200']
# Plotting the NIFTY Price Series chart and Moving Averages below
plt.figure(figsize=(9,5))
plt.plot(data['Close'],lw=1, label='NSE Prices')
plt.plot(SMA,'g',lw=1, label='50-day SMA (green)')
plt.plot(EWMA,'r', lw=1, label='200-day EWMA (red)')
plt.legend(loc=2,prop={'size':11})
plt.grid(True)
Here is the output of my program, moving average of 50-days SMA and 200 days EWMA from
1st January 2020 to March 2021.
And here is the screenshot of the moving average from my trading portal.
The program which I compiled is giving the exact result as my trading portal is giving
which means my calculations in the program are executed correctly
Comments
Post a Comment